//==============================================================================
//
// pgmstat.c
//
// use:
// pgmstat file.pgm
//
//==============================================================================

#include <stdio.h>
#include "pgm.h"

double sqrt(double);

int main(int nArg, char** ppArg)
{
	int i;
	int nW, nH; // image width and height
	int nB;    // image brightness
	byte* pIm;  // pointer to image matrix
	int nSize;  // image size in bytes
	double s1=0., s2=0.;
	int nMin= 32767, nMax=-32768;
	
	if(nArg==1) 
	{
		puts("calculation of image standard statistics");
		puts("pgmstat file.pgm");
		exit(1);
	}

	ReadPGM(ppArg[1], &pIm, &nW, &nH);
	
	nSize = nW * nH;
	
	for(i=0; i<nSize; i++)
	{
		nB = pIm[i];
		if(nB < nMin) nMin = nB;
		if(nB > nMax) nMax = nB;
		s1 = s1 + (double) nB;
		s2 = s2 + (double) nB * nB;
	}

	s1 = s1 / nSize;
	s2 = (s2 - nSize*s1*s1)/(nSize-1);
	s2 = sqrt(s2);
  
	printf("min=%d   max=%d    average=%f   stddev=%f\n", nMin, nMax, s1, s2);
	
	free(pIm);
	
	return 0;
}