#include <stdio.h>
#include <math.h>

/*
 * Include the header for the libpicio routines
 */
#include <pic.h>

Pic *in;
Pic *out;

void map_pixels(float a, float b)
{
    int i;
    float val;
    /*
     * This is how many pixel samples there are in the image.
     * We want to apply a mapping to each one equally.
     */
    int size = in->nx * in->ny * in->bpp;


    printf("Mapping pixels using %fv + %f\n", a, b);


    for(i=0; i<size; i++)
    {
	val = a*((float)in->pix[i]) + b;
	if( val > 255 ) val = 255;
	if( val < 0   ) val = 0;

	out->pix[i] = (int)rint(val);
    }
}




main(int argc, char **argv)
{
    if( argc < 5 )
    {
	printf("usage: tifflmap a b <in.tiff> <out.tiff>\n");
	exit(1);
    }

    /*
     * Read in the file named by argv[3].
     * tiff_read will allocate the space for it.
     */
    in = tiff_read(argv[3], NULL);
    if( !in )
    {
	printf("Unable to open input file '%s'\n", argv[3]);
	exit(1);
    }

    /*
     * Tell the user the basic statistics of our image.
     * NOTE: Having just used tiff_read, in->bpp will always be 3.
     */
    printf("Read a %dx%d TIFF image (%d bytes per pixel)\n",
	   in->nx, in->ny, in->bpp);

    /*
     * Allocate a Pic to hold our output picture in
     */
    out = pic_alloc(in->nx, in->ny, in->bpp, NULL);

    map_pixels(atof(argv[1]), atof(argv[2]));


    /*
     * Write the picture out to the file named by argv[4]
     */
    if( !tiff_write(argv[4], out) )
	printf("Unable to write output to file '%s'\n", argv[4]);
}

