//Test to pull in a P5 and remap it with a function

#include <stdio.h>
#include <stdlib.h>
#include <netpbm/pam.h>

int main(int argc, char *argv[])
{
	char *myname = argv[0];
	if(argc != 3)
	{
		fprintf(stderr,"Usage: %s Function_Spec_File.txt Mask.pgm\n", myname);
		exit(1);
	}
	
	//Read in the mask
	gray **mask; //Pointer to image data
	gray max; //Maxval in image (read)
	int cols, rows; //Dimensions of image (read)
	int y, x; //Indices for manipulation
	FILE *gfp;
	pgm_init(&argc, argv); //Init the ppm library
	
	
	if(gfp == NULL)
	{
		fprintf(stderr,"Could Not Open File %s\n", argv[2]);
		exit(1);
	}
	gfp = fopen(argv[2], "rb");
	mask = pgm_readpgm(gfp, &cols, &rows, &max); //Read an image
	fclose(gfp);

	//Read In the Fns
	int fns;
	// These will usually be sparse, but I don't give enough fucks to do better
	int fnc[256] = {0}; //Points per function
	float *fna[256]={NULL}; //Pointers to lists of points for each function
	FILE *ffp;
	ffp = fopen(argv[1], "r");
	if(ffp == NULL)
	{
		fprintf(stderr,"Could Not Open File %s\n", argv[1]);
		exit(1);
	}
	
	fscanf(ffp, "%d", &fns); //How many functions are specified
	for(int ifc=0; ifc < fns; ifc++)
	{
		int graylev;
		fscanf(ffp,"%d",&graylev); //Get the gray level
		fscanf(ffp,"%d",fnc+graylev); //points for the function for graylevel
		fprintf(stderr,"got %d points for gray level %d\n", fnc[graylev],graylev);
		fna[graylev]=calloc(fnc[graylev],sizeof(float)); //allocate
		for(int pts = 0; pts < fnc[graylev]; pts++) //read points
		{
			fscanf(ffp,"%f",fna[graylev]+pts);
		}
	}
	fclose(ffp);

	
	//Print to see we got what we intended
	for(int i=0;i<256;i++)
	{
		if(fnc[i]!=0)
		{
			fprintf(stderr,"%d : %d :",i, fnc[i]);
			for(int j=0;j<fnc[i];j++)
			{
				fprintf(stderr,"%f ", fna[i][j]);
			}
			fprintf(stderr,"\n");
		}
	}
	
	//Mutate the mask pixel by pixel
		for (y=0; y<rows; y++)
		{
			for (x=0; x<cols; x++)
			{
				//Current pixel has value mask[y][x], look it up
				if(fnc[mask[y][x]] == 0) // Check that there is a function for that channel
				{
					fprintf(stderr,"No function for value %d in mask %s\n", mask[y][x],argv[2]);
					exit(2);
				}
				//DEBUG2 fprintf(stderr,"Swapping pixel [%d, %d] value %d with fn lookup value %d\n",x,y,mask[y][x],fna[mask[y][x]][0]);
				mask[y][x] = fna[mask[y][x]][0]; //Right now just insert the 1st value to check lookups work
			}
		}

	pgm_writepgm(stdout, mask, cols, rows, max, 1); //Write it out
	pgm_freearray(mask, rows); //Cleanup dynamic memory
	return 0;
	
	
	
	return(0);
}
