/**
 * \file main_optimum.c
 * \brief This file is used to profile the clusterflow
 *
 * \date Jun 10, 2009
 * \author Alexander Pimenov
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "global.h"
#include "g12buffer.h"
#include "integral.h"
#include "ppm.h"
#include "flow.h"



int main (int argC, char **ArgV)
{

	// Load two images
	if (argC <=1 || argC >3)
	{
		printf("Wrong usage. Should be called as:\n"
			   "  simulate_pc <directory with imageXXXX_c0.pgm files> [<settings file>]\n");
		return EXIT_FAILURE;
	}

	char dataPath[200];
	strncpy(dataPath, ArgV[1], sizeof(dataPath));
	strncat(dataPath, "/image%04i_c0.pgm", sizeof(dataPath));


	char path[200];

	int count = 1;
	sprintf(path, dataPath, count);
	G12Buffer *I1 = g12BufferCreateFromPPM(path);
	if (I1 == NULL)
	{
		printf("Could not open the input file %s", path);
		return EXIT_FAILURE;
	}
	count++;
	sprintf(path, dataPath, count);
	G12Buffer *I2 = g12BufferCreateFromPPM(path);
	if (I2 == NULL)
	{
		printf("Could not open the input file %s", path);
		return EXIT_FAILURE;
	}
	count++;

	printf("Images Loaded\n");
	fflush(stdout);

	integralBuffer *II1 = integralBufferCreateFromG12(I1);
	integralBuffer *II2 = integralBufferCreateFromG12(I2);

/*	FILE *Outgrid = fopen("out.txt","wt");
	fprintf(Outgrid, "# Data for parameters selection\n");
	fprintf(Outgrid, "# \t a \t b \t c\n");*/

	int max = 0;
	double ma,mb,mc;
	double a,b,c;
	for (a = 0.0; a < 0.3; a+=0.1)
	{
		char s[100];
		snprintf(s,100, "out-%lg.txt", a);
		FILE *Outgrid = fopen(s,"wt");
		fprintf(Outgrid, "# Data for parameters selection\n");
		fprintf(Outgrid, "# \t a \t b \t c\n");

	//a = 0.03;
		for (b = 0.000; b < 0.006; b+=0.001)
		{
			for (c = 0; c < 0.0025; c+=0.0006)
			{
				FlowBuffer *flow1;
				FlowBuffer *flow;
				flow1 = calculateTheFlow(II1, II2, a, b, c, 7, 1);
				flow = filterFlow(flow1, 1, 1, 100, 100);
				int dense = flowCountDensity(flow);
				if (dense > max)
				{
					max = dense;
					ma = a;
					mb = b;
					mc = c;
				}
				printf("Flow : %d min: %lf, %lf, %lf \n", dense ,a,b,c);
				fprintf(Outgrid, "%lf \t %lf \t %lf \t %d \n", a,b,c, dense);


				flowBufferDelete(flow);
				flowBufferDelete(flow1);
			}
		}
		fclose(Outgrid);
	}
	printf("Flow done: %d max: %lf, %lf, %lf \n", max ,ma,mb,mc);

}
