#ifndef TEXT_LINE_MAX
#define TEXT_LINE_MAX         800
#endif


#ifndef     PI
#define     PI                3.14159265358979323846
#define     PI_180            0.01745329252
#endif

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fftw3.h>
#include "mrcfile.c"

void help()
{
    printf("preProcess parameter\n######\n");
    printf("-input : projection file\n######\n");
    //printf("-tiltfile : tilt file\n######\n");
    printf("-output : preProcessed projection file\n######\n");
    //printf("-subtractModeOnly : subtract mode only, 1 for yes ; 0 for no, default as 1. If it is set to 1, then tiltfile is not used.\n######\n");
    printf("-help : for help\n");
}


double minusmode(float *in , int nx , int ny)
{
    int graylevel = 256;
    double edgeRate = 0.1;
    double min,max,step;
    int xedge = nx*edgeRate;
    int yedge = ny*edgeRate;
    int i,j,index;
    int maxindex;
    min = max = in[yedge*nx+xedge];
    for (j = yedge ; j < ny - yedge ; j++)
        for (i = xedge ; i < nx - xedge ; i++)
        {
            index = j*nx+i;
            if (in[index] < min)
                min = in[index];
            if (in[index] > max)
                max = in[index];
        }
    step = (max-min)/(double)graylevel;
    int *hist = (int *)malloc(graylevel*sizeof(int));
    memset(hist,0,graylevel*sizeof(int));
    for (j = yedge ; j < ny - yedge ; j++)
        for (i = xedge ; i < nx - xedge ; i++)
        {
            index = j*nx+i;
            hist[(int)floor((((double)in[index]-min)/step))]++;
        }
    max = -1000;
    for (i = 0 ; i < graylevel ; i++)
        if (max < hist[i])
        {
            max = hist[i];
            maxindex = i;
        }
    double mode = maxindex*step+min;
    for (i = 0 ; i < nx*ny ; i++)
        in[i] -= mode;
    free(hist);
    return mode;
}


//targetSum = Sum_standard/cos(thita_standard);
//return sum/cos(thita);
double normalize(float *in,int nx,int ny,float angle,double target)
{
	double max,min;
	max = -10000;
	min = 10000;
	int i,j;
	int size = nx*ny;
	/*for (i = 0 ; i < size ; i++)
	{
		if (max < in[i])
			max = in[i];
		if (min > in[i])
			min = in[i];
	}
	for (i = 0 ; i < size ; i++)
		in[i] = (in[i] - min)/(max - min);*/
	double sum = 0;
	for (i = 0 ; i < size ; i++)
		sum+=in[i];
	if (fabs(target + 1) > 0.000001) // target != -1
	{
		double factor = target*cos(angle/180.0*3.1415926)/sum;
		printf("cos %f factor %f\n",cos(angle/180.0*3.1415926),factor);
		for (i = 0 ; i < size ; i++)
			in[i] *= factor;
		sum = 0;
		for (i = 0 ; i < size ; i++)
			sum+=in[i];
	}
	return sum/cos(angle/180.0*3.1415926);
}


int main(argc,argv)
int argc;
char *argv[];
{
    char infile[1000],anglefile[1000],outfile[1000];
    int radius;
    int i,j,k;
    int paraNum = 4;
    int *paraMark = (int *)malloc(paraNum*sizeof(int));
    // read Parameter
    i = 1;
    memset(paraMark,0,paraNum*sizeof(int));
    paraMark[3] = 1;
    int subtractModeOnly = 1;
    while (i < argc)
    {
        if (argv[i][0] == '-')
        {
            if (strcmp(argv[i]+1,"input") == 0)
            {
                i++;
                sscanf(argv[i],"%s",infile);
                i++;
                paraMark[0] = 1;
            }
            else if (strcmp(argv[i]+1,"tiltfile") == 0)
            {
                i++;
                sscanf(argv[i],"%s",anglefile);
                i++;
                paraMark[1] = 1;
            }
            else if (strcmp(argv[i]+1,"output") == 0)
            {
                i++;
                sscanf(argv[i],"%s",outfile);
                i++;
                paraMark[2] = 1;
            }
            else if (strcmp(argv[i]+1,"subModeOnly") == 0)
            {
                i++;
                sscanf(argv[i],"%d",&subtractModeOnly);
                i++;
                paraMark[3] = 1;
            }
            else if (strcmp(argv[i]+1,"help") == 0)
            {
                i++;
                help();
                return;
            }
            else
                i++;
        }
        else
            i++;
    }
    if (!(paraMark[0] && paraMark[2]))
    {
	printf("parameter error!\n Please use -help to see the manual\n");
	return;
    }
    else if (!subtractModeOnly && !paraMark[1])
    {
	printf("parameter error!\n tiltfile is needed for normalization. Please use -help to see the manual\n");
	return;
    }
    {
        printf("parameter:\n");
        printf("input : %s\n",infile);
	if (paraMark[1])
        	printf("tiltfile : %s\n",anglefile);
        printf("output : %s\n",outfile);
        //printf("subModeOnly : %d\n",subtractModeOnly);
    }
    // end of read Parameter
    //------------------------------------end of read anglefile
    float *indata;

    int i1,j1,k1;
    MrcHeader  *inhead, *outhead;
    FILE *fin, *fout;
    if((fin=fopen(infile,"r"))==NULL)
    {

        printf("\nCannot open file '%s' strike any key exit!",infile);
        exit(1);
    }

    if((fout=fopen(outfile,"w+"))==NULL)
    {
        printf("\nCannot open file '%s' strike any key exit!",outfile);
        exit(1);
    }


    inhead=(MrcHeader *)malloc(sizeof(MrcHeader));
    outhead=(MrcHeader *)malloc(sizeof(MrcHeader));

    mrc_read_head(fin,inhead);
    memcpy(outhead,inhead,sizeof(MrcHeader));
    outhead->nx = inhead->nx;
    outhead->nz = inhead->nz;
    outhead->ny = inhead->ny;
    outhead->nzstart = 0;
    mrc_write_head(fout,outhead);
    int nx = inhead->nx;
    int ny = inhead->ny;
    int nz = inhead->nz;

    // MinusMode slice by slice
    indata = (float*)malloc(nx*ny*nz*sizeof(float));
    for (k = 0 ; k < nz ; k++)
    {
        mrc_read_slice(fin, inhead, k, 'z',indata+k*nx*ny);
        printf("slice %d mode %lf\n",k,minusmode(indata+k*nx*ny,nx,ny));
    }
    if (subtractModeOnly)
	for (k = 0 ; k < nz ; k++)
	{
		mrc_add_slice(fout,outhead,indata+k*nx*ny);
	}
    //end of MinusMode slice by slice
    if (!subtractModeOnly)
    {
	FILE *fang;
	if((fang=fopen(anglefile,"r"))==NULL)
   	{
        	printf("\nCannot open file '%s' strike any key exit!",anglefile);
        	exit(1);
    	}
	int Ang_Num = 0;
	float thita[180];
	int minAngIndex;
	double minAng = 90;
    	while (fscanf(fang,"%f",&(thita[Ang_Num]))!=EOF)
   	{
        	thita[Ang_Num] *=-1;
		if (fabs(thita[Ang_Num])<minAng)
		{
			minAng = fabs(thita[Ang_Num]);
			minAngIndex = Ang_Num;
		}
        	Ang_Num++;
    	}
    	fclose(fang);
	double target;
	target = normalize(indata+minAngIndex*nx*ny,nx,ny,thita[minAngIndex],-1);
	for (k = 0 ; k < nz ; k++)
	{
		printf("normalize %f\n",normalize(indata+k*nx*ny,nx,ny,thita[k],target));
		mrc_add_slice(fout,outhead,indata+k*nx*ny);
	}
    }	

    free(inhead);
    free(outhead);
    free(indata);
    fclose(fout);
    mrc_update_head(outfile);

    return 0;
}




