/**
 * \file tiffloader.c
 * \brief Loads a 12bit TIFF file
 *
 */
#include "tiffloader.h"


G12Buffer* g12BufferCreateFromTiff (char *TIFFname)
{
	TIFF *in;
	in = TIFFOpen(TIFFname, "r");
    if (!in)
    {
            fprintf (stderr, "Can't open %s for reading\n", TIFFname);
			return (G12Buffer *)NULL;
    }
    int h;
    int w;
    uint16_t bps;
    uint16_t spp;
    TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
    TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h);
    TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps);
    TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &spp);

    //TIFFGetField(in, TIFFTAG_IMAGELENGTH, &w);

    printf("Image is [%d x %d] %d * %d \n", w, h, bps, spp);
    if (bps != 16 || !(spp == 3 || spp == 1))
    {
        fprintf (stderr, "Unsupported format %s for reading\n", TIFFname);
    	return NULL;
    }

    G12Buffer *toReturn;
    toReturn = g12BufferCreate(h,w);

    uint16_t *scanline = (uint16_t *) dv_malloc (TIFFScanlineSize(in));

    int i, j;
    for (i = 0; i < h; i++)
    {
    	if (TIFFReadScanline( in, scanline, i, 0 ) < 0 )
    	{
    		fprintf (stderr, "Major unknown error with scanline %d\n", i);
    		return NULL;
    	}

    	for (j = 0; j < w; j++)
    	{
    		// 16 bit to 12 bits
    		toReturn->data[i * w + j] = scanline[j * spp] >> 4;
    	}
    }
    TIFFClose(in);

    return toReturn;
}
