//==============================================================================
//
// pgmimgadds.c
//
// use:
// pgmimgadds file1.pgm file2.pgm result.pgm
//
//==============================================================================

#include <stdio.h>
#include "pgm.h"

int main(int nArg, char** ppArg)
{
	int i;
	int nW1, nH1; // image width and height
	int nW2, nH2; // image width and height
	int nBr;      // image brightness
	byte* pIm1;   // pointer to image matrix 1
	byte* pIm2;   // pointer to image matrix 1
	byte* pIm3;   // pointer to image matrix with sum
	int nSize;    // image size in bytes
	int n;
	
	if(nArg==1) 
	{
		puts("saturated addition of two images");
		puts("pgmimgadds file1.pgm file2.pgm result.pgm");
		exit(1);
	}

	
	ReadPGM(ppArg[1], &pIm1, &nW1, &nH1);
	ReadPGM(ppArg[2], &pIm2, &nW2, &nH2);
	
	if( (nW1!=nW2) || (nH1!=nH2) )
	{
		free(pIm1);  
		free(pIm2);
		return 1;
	}
	
	nSize = nW1 * nH1;
	pIm3 = (byte*) malloc(nSize);
	
	for(i=0; i<nSize; i++)
	{
		n = pIm1[i] + pIm2[i];
		if(n>255)
		{
			printf(".");
			n=255;
		}
		pIm3[i] = n;
	}
	
	WritePGM(ppArg[3], pIm3, nW1, nH1);
	
	free(pIm3);
	free(pIm2);
	free(pIm1);  
		
	return 0;
}