// Negate.cpp : Defines the entry point for the console application.
#include "stdafx.h"

#ifdef _MSC_VER
#pragma hdrstop
#endif

using namespace std;

#include "../../Kernel/kernelincludes.h"
#include "../../Multilevel/Blif.h"
#include "../../Multilevel/Signal.h"
#include "../../Multilevel/Node.h"
#include "../../Multilevel/Network.h"


void Help()
{
	cout << "Syntax: Negate source.pla dest.blif" << endl;
	cout << "    Appends inverters to the PLA outputs and produces Blif." << endl;
}

void AppendInverters( Network &net )
{
	unsigned int i;
	SoPLA *inv;

	inv = new SoPLA(1, true);
	inv->AppendTerm("0");
	
	for ( i = 0; i < net.outputs(); i++ ) {
		inv->setIName(0, net.getOName(i));
		net.setOName( i, net.getOName(i) + "_neg" );
		inv->setName(net.getOName(i));
		net.AddNode(Node(*inv));
	}
	delete inv;
}


int main(int argc, char* argv[])
{
    PLA source;
    Blif *dest;
	Network *net;
	char *src_file = NULL;
	char *dest_file = NULL;
	int i;


	cout << "Negate 1.0, (c) May 2010 by Petr Fiser" << endl;
	if ( argc < 3 ) {
        Help();
        exit(1);
    }

	try {
		i = 1;
		while ( i != argc ) {
			if ( argv[i][0] != '-' && src_file == NULL ) src_file = argv[i];
			else if ( argv[i][0] != '-' && dest_file == NULL ) dest_file = argv[i];
/*
			else if ( argv[i][0] != '-' && src_file != NULL && dest_file != NULL ) fanin = atoi(argv[i]);
			else if ( strcmp( argv[i], "-g" ) == 0 ) {
				i++;
				groupfilen = argv[i];
			}
*/
			else {
				Help();
				exit(1);
			}
			i++;
		}
	} catch (...) {
        Help();
        exit(1);
    }

	if ( src_file == NULL || dest_file == NULL ) {
        Help();
        exit(1);
    }

	try {
		source.LoadPLA(src_file);
	} catch (IOException e) {
			cerr << e.GetMsg() << endl;
			exit(1);
	}

	if ( source.getINames().empty() ) source.NameVars();
	net = new Network(source);
	net->SetModel("pla");

	AppendInverters(*net);

	dest = net->ToBlif();
	dest->SaveBlif(dest_file);
	delete dest;
	return 0;
}
