// LinearPowerFlow.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


#include "VectorJI.h"

#include "mylibrary.h"
#include "TopologyReaderLPF.h"


#include <iostream>
using std::cout;
using std::endl;

TopologyReaderLPF topoReader;
Config conf;
std::ifstream confFile;
vector<CircuitElement*> circElements;
char* confFilename = nullptr;


#define PI 3.1415


int main(int argc, char* argv[])
{
	int maxn = 100;
	double toll = 1.0e-6;
	double alfa = 1;
	TopologyReaderLPF topoReader;
	Config conf;
	std::ifstream confFile;
	vector<CircuitElement*> circElements;
	char* confFilename = nullptr;
	

	for (int i = 1; i < argc; i++) {
		if (!std::string(argv[i]).compare("-nl") || !std::string(argv[i]).compare("--netlist")) {
			if (++i >= argc) {
				std::cerr << "missing parameter for -nl/--netlist" << std::endl;
				std::cin.get();
				exit(1);
			}
			confFilename = argv[i];
		}
		else {
			std::cerr << "unknown / invalid parameter " << argv[i] << std::endl;
			std::cin.get();
			exit(1);
		}
	}
	if (!confFilename) {
		std::cerr << "no netlist file given" << std::endl;
		std::cin.get();
		exit(1);
	}

	confFile.open(confFilename);

	if (topoReader.readConfig(confFile, conf) != 0) {
		std::cin.get();
		exit(1);
	}

	topoReader.parseConfig(conf, circElements, maxn, toll, alfa);

	if (circElements.size() == 0) {
		std::cerr << "failed to parse netlist" << std::endl;
		std::cin.get();
		exit(1);
	}

	int maxNode = 0;
	for (std::vector<CircuitElement*>::iterator it = circElements.begin(); it != circElements.end(); ++it) {
		if ((*it)->getMaxNode() > maxNode)
			maxNode = (*it)->getMaxNode();
	}

	LPF_Sim newSim(maxNode);

	for (std::vector<CircuitElement*>::iterator it = circElements.begin(); it != circElements.end(); ++it) {
		newSim.AddModelToList((*it));
	}



	// Initialize and Matrix Stamp
	newSim.Init();
	cout << "\tInit Completed" << endl;
	newSim.P.A.printMatrix();
	newSim.P.B.printMatrix();
	cout << "\tEntering Main Power Flow Loop" << endl;
	// Main Simulation Loop
	ComplexMatrix Vini(maxNode + 1, 1);
	Complex One(1, 0);
 
	for (int i = 1; i <= maxNode + 1; i++)
			Vini.set(i, 1,One);

	newSim.Solve(Vini, maxn, toll, alfa);
	cout << "\tOut of the Loop" << endl;

    return 0;
}