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

#include "stdafx.h"

using namespace std;

#include "../../Kernel/kernelincludes.h"

int main(int argc, char* argv[])
{
    PLA source;
    PLA *onset, *offset;
	unsigned int i;
	TermList::iterator ti;
	bool ok;
	Term *t;

    cerr << "PLA Split 2.1, (c) December 2008 by Petr Fiser" << endl << endl;
    if ( argc != 4 ) {
		cout << "Syntax: split source.pla onset.pla offset.pla" << endl;
		exit(1);
    }

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

	onset = new PLA( source.inputs(),  source.outputs()/2, source.getType() );
	if ( onset == NULL) throw RuntimeException( "Split: Not enough memory" );
	offset = new PLA( source.inputs(),  source.outputs()/2, source.getType() );
	if ( offset == NULL) throw RuntimeException( "Split: Not enough memory" );

	t = new Term( source.inputs(), source.outputs()/2 );
	if ( t == NULL) throw RuntimeException( "Split: Not enough memory" );
	for ( ti = source.getData()->begin(); ti != source.getData()->end(); ++ti ) {
		ok = false;
		for ( i = 0; i < source.outputs()/2; i++ )
			if ( (*ti).isOM_1(i) ) {
				ok = true;
				break;
			}
		if ( ok ) {
			t->setCube( (*ti).getCube() );
			for ( i = 0; i < source.outputs()/2; i++ )
				t->setOM( i, (*ti).getOM(i) );
			onset->AppendTerm(*t) ;
		}

		ok = false;
		for ( i = 0; i < source.outputs()/2; i++ )
			if ( (*ti).isOM_1(i+source.outputs()/2) ) {
				ok = true;
				break;
			}
		if ( ok ) {
			t->setCube( ti->getCube() );
			for ( i = 0; i < source.outputs()/2; i++ )
				t->setOM( i, ti->getOM(i+source.outputs()/2) );
			offset->AppendTerm(*t) ;
		}
	}

	onset->SavePLA(argv[2]);
	offset->SavePLA(argv[3]);

	delete onset;
	delete offset;
	delete t;

    return 0;
}

