/*!
 Targa Image Code
 Image diff code

Bob Kuehne, rpk@blue-newt.com, 09/2005
*/

#include "image.h"
#include <string>
#include <stdio.h>

static void write_u16(FILE* f, int i)
{
    unsigned char b;
    b = i & 0xff;
    fwrite(&b,1,1,f);
    b = (i>>8) & 0xff;
    fwrite(&b,1,1,f);
}

bool diffImage( const char* img0, const char* img1, unsigned int width, unsigned int height,
                unsigned int & npix, unsigned int &maxdiff )
{
    bool isdiff = false;
    unsigned int npixdiff = 0;
    unsigned int maxcolordiff = 0;
    unsigned int colordiff[ 4 ];

    for( unsigned int jj=0; jj<height; jj++ )
    {
        for( unsigned int ii=0; ii<width; ii++ )
        {
            unsigned int anydiff = 0;
            for( unsigned int kk=0; kk<4; kk++ )
            {
                unsigned int offset = ii*4 + jj*width*4;
                colordiff[ kk ] = img0[ offset ] - img1[ offset ];
                if ( colordiff[ kk ] != 0 ) anydiff += colordiff[ kk ];
            }
            if ( anydiff != 0 )
            {
                npixdiff++;
                maxcolordiff = ( maxcolordiff > anydiff ) ? maxcolordiff : anydiff;
            }
        }
    }
    
    npix = npixdiff;
    maxdiff = maxcolordiff;
    
    return( isdiff );
}


bool saveTGA( std::string name, const char* img, int width, int height)
{
	if (!img)
		return false;

	FILE* f = fopen( name.c_str(),"wb" );

	if (!f)
		return false;

	unsigned char b;

	// ID length, 0 = no ID
	b = 0; fwrite(&b,1,1,f);

	// Color Map type. 0 = no color map
	b = 0; fwrite(&b,1,1,f);

	// Image type, 3 = uncompressed black and white
	b = 2; fwrite(&b,1,1,f);

	// Color Map Specification, 5 bytes zero
	b = 0;
	fwrite(&b,1,1,f);
	fwrite(&b,1,1,f);
	fwrite(&b,1,1,f);
	fwrite(&b,1,1,f);
	fwrite(&b,1,1,f);

	// X-origin
	write_u16(f,0);

	// Y-origin
	write_u16(f,0);

	// Width
	write_u16(f,width);

	// Heigth
	write_u16(f,height);

	// Pixel Depth
	b = 32; fwrite(&b,1,1,f);

	// Image Descriptor, 0x20 = first pixel is top left
	// 0x08 = 8 attribute = alpha bits
	b = 0x08; fwrite(&b,1,1,f);

	// write image data
	fwrite(img,width*height,4,f);

	if (fclose(f))
		return false;

	return true;
}
