//==============================================================================
//
// pgmdown2.c
//
// use:
// pgmdown2  file.pgm result.pgm
//
//==============================================================================

#include <stdio.h>
#include "pgm.h"


//==============================================================================
int main(int nArg, char** ppArg)
{
	int i, j;
	int nW, nH; // image width and height
	int nB;     // image brightness
	byte* pIm;  // pointer to image matrix
	int nSize;  // image size in bytes
	byte* pIm2;  // pointer to second image matrix 
	int nX, nY;
	
	if(nArg==1) 
	{
		puts("two times image downsampling  ");
		puts("pgmdown2  file.pgm result.pgm");
		exit(1);
	}
	
	ReadPGM(ppArg[1], &pIm,  &nW, &nH);
	
	nSize = nW * nH;
	pIm2 = (byte*) malloc(nSize/4); 
	
	for(nY=0; nY<nH; nY=nY+2)
	{
		for(nX=0; nX<nW; nX=nX+2)
		{
			i = nY*nW + nX;
			nB = pIm[i]+pIm[i+1]+pIm[i+nW]+pIm[i+nW+1];
			nB = (nB +2)/4;
			pIm2[nY*nW/4+nX/2] = nB;
		}
	}
	
	WritePGM(ppArg[2], pIm2, nW/2, nH/2);
	
	free(pIm2);
	free(pIm);
	
	return 0;
}