#include "test.h"

int main(int argc, char* argv[])
{
	char InputDesc[] = "matrix D, matrix Dm, matrix Dp, matrix MX, matrix L0, matrix L, arrayi Mask, arrayi ipl, arrayi dpl";
	char OutputDesc[] = "matrix Df, matrix Dmf, matrix Dpf, matrix MXF, matrix L0F, matrix LF, arrayi ipl";
	FILE* input;
	MemoryManager mem;
	matrix Dm, Dp, MX, L0, L, D;
	int *Mask, *ipl, *dpl, *Filled;
	int MaskCount, ipCount, dpCount, ResFilled[8], i;
	pn2acpn_r result;
	
	/*Initialize the filled mask that will be used with the result display*/
	for (i = 0; i < 8; i++)
	{
		ResFilled[i] = 1;
	}
	
	/*Get the input stream. If there was a command line argument, treat it as a 
	filename and attempt to open it for read access, terminating on failure.
	Otherwise set stdin as the input stream.*/
	if (! (input = ParseCmdLine(argc, argv)))
	{
		return 0;
	}
	
	/*Initialize the memory manager. We don't know how many matrices and arrays
	we'll need so just pick a nice round number as the initial address block size
	and use the default additional block size.*/
	mem = CreateMemoryManager(5, 5, 0, 0);
	
	/*Attempt to parse a problem from the file and fill all the problem parts.
	Continue doing so until a fatal input error or a quit command is encountered.*/
	while(ParseStructure(input, InputDesc, &Filled, &mem, &D, &Dm, &Dp, &MX, &L0, &L, &Mask, &MaskCount, &ipl, &ipCount, &dpl, &dpCount))
	{
		/*If D was given, fill Dm and Dp appropriately.*/
		FillDmDp(Filled, &D, &Dm, &Dp, &mem);
		/*Display the problem.*/		
		DisplayStructure(InputDesc, Filled, &D, &Dm, &Dp, &MX, &L0, &L, Mask, MaskCount, ipl, ipCount, dpl, dpCount);
		
		/*Get the solution.*/
		result = pn2acpn(Filled[1] ? &Dm : 0, Filled[2] ? &Dp : 0, Filled[6] ? Mask : 0, Filled[3] ? &MX : 0, Filled[4] ? &L0 : 0, Filled[5] ? &L : 0, Filled[7] ? ipl : 0, ipCount, Filled[8] ? dpl : 0, dpCount);
		
		/*Display the solution. Show Dm and Dp only if there are self-loops and
		D only if there are not self-loops.*/
		if (HasSelfLoops(&Dm, &Dp))
		{
			ResFilled[0] = 0;
			ResFilled[1] = 1;
			ResFilled[2] = 1;
		}
		else
		{
			ResFilled[0] = 1;
			ResFilled[1] = 0;
			ResFilled[2] = 0;
		}
		printf("Solution:\n");
		DisplayStructure(OutputDesc, ResFilled, &result.Df, &result.Dmf, &result.Dpf, &result.MXF, &result.L0F, &result.LF, result.iplf, result.iplfCount);
		printf("---------------------------------------------------------------------------\n");
		FreeMemory(&mem);
		DeallocatePn2acpn(&result);
		mem = CreateMemoryManager(5, 5, 0, 0);
	}	
	FreeMemory(&mem);
	return 0;
}
