//==============================================================================
//
// pgmconv15abs.c
//
// use:
// pgmconv15abs coef0 coef1 coef2  file.pgm result.pgm
//
//==============================================================================

#include <stdio.h>
#include "pgm.h"

int main(int nArg, char** ppArg)
{
	int i;
	int nW, nH; // image width and height
	int nBr;    // image brightness
	byte* pIm;  // pointer to image matrix
	byte* pIm2; // pointer to result image matrix
	int nSize;  // image size in bytes
	int nX;
	int coef0, coef1, coef2, coef3, coef4; // convolution's coefficients
	int nSum;
	int n;

	if(nArg==1) 
	{	
		puts("1-Dim convolution filter with convolution vector 1x5");
		puts("pgmconv15abs c0 c1 c2 c3 c4 c5    file.pgm result.pgm	");
		exit(1);
	}
	
	coef0 = atoi(ppArg[1]);
	coef1 = atoi(ppArg[2]);
	coef2 = atoi(ppArg[3]);
	coef3 = atoi(ppArg[4]);
	coef4 = atoi(ppArg[5]);
	nSum = coef0 + coef1 + coef2 + coef3 + coef4;
	if(nSum == 0) nSum = 1;
	
	ReadPGM(ppArg[6], &pIm, &nW, &nH);
	
	nSize = nW * nH;
	pIm2 = (byte*) malloc(nSize);
	
	for(i=0; i<nSize; i++)
	{
		nX = i % nW;
		if( (nX>0) && nX<(nW-1) )
		{
			n = pIm[i-2]*coef0  + pIm[i-1]*coef1 +  pIm[i]*coef2 +  pIm[i+1]*coef3 +  pIm[i+2]*coef4;
			n =abs( (n + nSum/2) / nSum);
			if(n>255) n = 255;
			pIm2[i] = (byte) n;
		}
		else
		{
			pIm2[i] = pIm[i];
		}
	}
	
	WritePGM(ppArg[7], pIm2, nW, nH);
	
	free(pIm2);
	free(pIm);
	
	return 0;
}