
/* Performs histogram equalization of the 
 * imageIn, in the area (x1,y1) to (x2,y2)
 */

void Hist_Eq(BYTE * imageIn, BYTE * imageOut)
{
  
  float N=width*height;
  unsigned int n[HL];
  int i;
  float cumprob=0.0;
  float s[HL];
    
  memset(n, 0, (int)HL*sizeof(unsigned int));
  memset(s, 0, (int)HL*sizeof(float));

  for (i=0; i<width*height; i++)
      (n[ imageIn[i] ])++;

  for (i=0; i<HL; i++)
    {
      cumprob += (float)n[i]/N;
      s[i] = cumprob*((float)HL-1.001);
    } 

  for (i=0; i<width*height; i++)
      imageOut[i] = (BYTE) s[ imageIn[i] ];

  /*
  save_hist(n, imageOut,x1, y1, x2, y2);
  */
}



/*
 * saves the old and new histograms to a file 
 */

void save_hist(unsigned int *n, BYTE *imageOut, 
	       int x1, int y1, int x2, int y2)
{

  int i,j;
  unsigned int k[HL];
  
  FILE        *fp = NULL;
  
  memset(k, 0, (int)HL*sizeof(unsigned int));
  
  for (i=x1; i<=x2; i++)
  for (j=y1; j<=y2; j++)
    (k[ imageOut[j*width+i] ])++;
  
  fp = fopen("hist.txt","w");
  for (i=0;i<(int)HL;i++)
    fprintf(fp, "%d:%d:%d\n", i,n[i],k[i]);
  fclose(fp);
  
}

void Hist_Eq_Col(BYTE *imageIn, BYTE *imageOut)
{

  float N=width*height;
  unsigned int nr[HL], ng[HL], nb[HL];
  int i;
  float cumprob_r=0.0, cumprob_g=0.0, cumprob_b=0.0;
  float sr[HL], sg[HL], sb[HL];

  memset(nr, 0, (int)HL*sizeof(unsigned int));
  memset(ng, 0, (int)HL*sizeof(unsigned int));
  memset(nb, 0, (int)HL*sizeof(unsigned int));
  memset(sr, 0, (int)HL*sizeof(float));
  memset(sg, 0, (int)HL*sizeof(float));
  memset(sb, 0, (int)HL*sizeof(float));
  
  for (i=0; i<width*height; i++)
    {
      (nr[ imageIn[ 3*i    ] ])++;
      (ng[ imageIn[ 3*i +1 ] ])++;
      (nb[ imageIn[ 3*i +2 ] ])++;
    }
  
  /*
  fp = fopen("hist.txt","w");
  for (i=0;i<(int)HL;i++)
    fprintf(fp, "%d:%d:%d:%d\n", i,nr[i],ng[i],nb[i]);
  fclose(fp);
  */

  for (i=0; i<HL; i++)
    {
      cumprob_r += (float)nr[i]/N;
      sr[i] = cumprob_r*((float)HL-1.001);

      cumprob_g += (float)ng[i]/N;
      sg[i] = cumprob_g*((float)HL-1.001);

      cumprob_b += (float)nb[i]/N;
      sb[i] = cumprob_b*((float)HL-1.001);
    }
  
  for (i=0; i < width*height; i++)
    {
      imageOut[3*i  ] = (BYTE) sr[ imageIn[3*i  ] ];
      imageOut[3*i+1] = (BYTE) sg[ imageIn[3*i+1] ];
      imageOut[3*i+2] = (BYTE) sb[ imageIn[3*i+2] ];
    }
  
}



