//==============================================================================
//
// pgmhist.c
//
// use:
// pgmhist file.pgm histog.txt result.pgm
//
//==============================================================================

#include <stdio.h>
#include "pgm.h"

#define NHEIGHT  1000
int main(int nArg, char** ppArg)
{
	int i, ii;
	int nW, nH; // image width and height
	int nB;     // image brightness
	byte* pIm;  // pointer to image matrix
	int nSize;  // image size in bytes
	int nn;	
	int nW2, nH2; // image width and height
	byte* pIm2;   // pointer to second image matrix with histogram's graph
	int hist[256];
	FILE *pF;
	int nMax = -1, hh;
	
	if(nArg==1) 
	{
		puts("calculation of image histogram");
		puts("pgmhist file.pgm histog.txt result.pgm");
		exit(1);
	}

	ReadPGM(ppArg[1], &pIm,  &nW, &nH);

	for(i=0; i<256; i++) hist[i] = 0;
	
	nSize = nW * nH;
	
	for(i=0; i<nSize; i++)
	{
		nn = pIm[i]; 
		hist[nn]++;
	}
	
	pF = fopen(ppArg[2], "w");
	for(i=0; i<256; i++) 
	{
		//printf("%3d   %d\n", i, hist[i]);
		fprintf(pF, "%3d   %d\n", i, hist[i]);
		if( nMax < hist[i] ) nMax = hist[i];
	}
	fclose(pF);
	
	printf("histogram max = %d\n", nMax);
	
	nSize = 256 * NHEIGHT;
	pIm2 = (byte*) malloc(nSize);

	for(i=0; i<NHEIGHT; i++)
	{
		nn = NHEIGHT - 1 - i;
//printf("%d  ", i);
		for(ii=0; ii<256; ii++)
		{
			pIm2[i*256 + ii] = 0;
			hh = hist[ii] * NHEIGHT / nMax;
			if(hh >= nn) pIm2[i*256 + ii] = 255;
		}
	}

	WritePGM(ppArg[3], pIm2, 256, NHEIGHT);
	
	free(pIm2);
	free(pIm);
	
	return 0;
}