//==============================================================================
//
// pgm1conv3abs.c
//
// use:
// pgm1conv3abs 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; // convolution's coefficients
	int nSum;
	int n;

	if(nArg==1) 
	{
		puts("1-Dim convolution filter with convolution vector 1x3");
		puts("pgmconv13abs coef0 coef1 coef2  file.pgm result.pgm");
		exit(1);
	}

	coef0 = atoi(ppArg[1]);
	coef1 = atoi(ppArg[2]);
	coef2 = atoi(ppArg[3]);
	nSum = coef0 + coef1 + coef2;
	if(nSum == 0) nSum = 1;
	
	ReadPGM(ppArg[4], &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-1]*coef0 +  pIm[i]*coef1 +  pIm[i+1]*coef2;
			n = abs( (n + nSum/2) / nSum);
			if(n>255) n = 255;
			pIm2[i] = (byte) n;
		}
		else
		{
			pIm2[i] = pIm[i];
		}
	}
	
	WritePGM(ppArg[5], pIm2, nW, nH);
	
	free(pIm2);
	free(pIm);
	
	return 0;
}