#include <stdio.h>
#include <stdint.h>

int main()
{
	FILE *fi, *fb, *fout;
	float data[4];
	float label;
	float dummy;
	uint8_t orig[512*512];
	uint8_t result[512*512*3];
	int x1, x2;
	uint16_t xmin, ymin, xmax, ymax;
	uint8_t value;
	uint8_t Red, Green, Blue;
	
	fi = fopen("000100_512x512_bgr.y", "r");
	fb = fopen("stats_tool_out_eve.bin", "rb");
	fout = fopen("markedBoxes.ppm", "w");
	
	fread(&orig[0], 512 * 512, sizeof(uint8_t), fi);
	
 	for(x1 = 0; x1 < 512; x1 ++)
	{
		for(x2 = 0; x2 < 512; x2 ++)
		{
			value = orig[(x1 * 512) +  x2];
			result[(x1 * 512 * 3) + (x2 * 3)]= value;
			result[(x1 * 512 * 3) + (x2 * 3) + 1] = value;
			result[(x1 * 512 * 3) + (x2 * 3) + 2] = value;			
		}
	} 
	
	for(x2 = 0; x2 < 20; x2 ++)
	{
		fread(&dummy, 1, sizeof(float), fb);
		
		fread(&label, 1, sizeof(float), fb);
		
		fread(&dummy, 1, sizeof(float), fb);
		
		fread(&data[0], 4, sizeof(float), fb);
		
		xmin = (uint16_t)(data[0] * 512);
		ymin = (uint16_t)(data[1] * 512);
		xmax = (uint16_t)(data[2] * 512);
		ymax = (uint16_t)(data[3] * 512);
		
		// printf("data[3] = %f, ymax = %d\n", data[3], ymax);
		
		// printf("%f - (%f, %f)  (%f, %f) - %f\n", label, data[0], data[1], data[2], data[3], dummy);
		printf("%d - (%d, %d)  (%d, %d) - %f\n\n", (uint8_t)label, xmin, ymin, xmax, ymax, dummy);
		
		if(label == 1)
		{
			Red = 255;
			Green = 0;
			Blue = 0;
		}
		
		if(label == 2)
		{
			Red = 0;
			Green = 255;
			Blue = 0;
		}
		
		if(label == 3)
		{
			Red = 0;
			Green = 0;
			Blue = 255;
		}
		
		for(x1 = xmin; x1 <= xmax; x1 ++)
		{
			result[(ymin * 512 * 3) + (x1 * 3)] = Red;
			result[(ymin * 512 * 3) + (x1 * 3) + 1] = Green;
			result[(ymin * 512 * 3) + (x1 * 3) + 2] = Blue;
		}
		
		for(x1 = xmin; x1 <= xmax; x1 ++)
		{
			result[(ymax * 512 * 3) + (x1 * 3)] = Red;
			result[(ymax * 512 * 3) + (x1 * 3) + 1] = Green;
			result[(ymax * 512 * 3) + (x1 * 3) + 2] = Blue;
		}
		
		for(x1 = ymin; x1 <= ymax ; x1 ++)
		{
			result[(x1 * 512 * 3) + (xmin * 3)] = Red;
			result[(x1 * 512 * 3) + (xmin * 3) + 1] = Green;
			result[(x1 * 512 * 3) + (xmin * 3) + 2] = Blue;
		}
		
		for(x1 = ymin; x1 <= ymax ; x1 ++)
		{
			result[(x1 * 512 * 3) + (xmax * 3)] = Red;
			result[(x1 * 512 * 3) + (xmax * 3) + 1] = Green;
			result[(x1 * 512 * 3) + (xmax * 3) + 2] = Blue;
		}
	}
	
	fprintf(fout, "P3 512 512 255 ");
	for(x1 = 0; x1 < 512 * 512 * 3; x1 ++)
		fprintf(fout, "%d ", result[x1]);
	
	fclose(fi);
	fclose(fb);
	fclose(fout);
	
	return 1;
}
