/*
    This file is part of Page Layout Detection Tools.

    This code is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This code is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this code; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <formats/tifffact.h>
#include <util/bitutil.h>
#include <tiff.h>
#include <tiffio.h>

namespace pagetools{

TiffFactory::TiffFactory(const char *path)
:path_(path){
}

CntPtr<BWImage> 
TiffFactory::create(){
    TIFF* tif = TIFFOpen(path_, "r");
    if (tif) {
	    uint32 imagelength, imagewidth;
	    tdata_t buf;
	    uint32 row;

	    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &imagelength);
        TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &imagewidth);
        uint16 bpp, photometric, fillorder;
        TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bpp);
        if(bpp!=1){
            return 0; // Not a monochrome image
        }
        TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric);
        TIFFGetField(tif, TIFFTAG_FILLORDER, &fillorder);


        uint32 ssize=TIFFScanlineSize(tif);
        CntPtr<BWImage> retval=CntPtr<BWImage>(new BWImage(imagewidth, imagelength, ssize));
        unsigned char padmask=0xFF<<((imagewidth+7)%8);
        uint8 *r;
        for (row = 0; row < imagelength; row++){
            buf=r=retval->scanline(row);
	        TIFFReadScanline(tif, buf, row);
            unsigned int col;
            if(photometric!= PHOTOMETRIC_MINISWHITE){
                for(col=0; col<ssize; col++){
                    r[col]^=0xFF; // Invert the image
                }
            }
            if(fillorder!= FILLORDER_MSB2LSB){
                const unsigned char *inv=BitUtil::invbits();
                for(col=0; col<ssize; col++){
                    r[col]=inv[r[col]]; // Change the bit order
                }
            }
            r[ssize-1]&=padmask; // Zero trailing bits
        }


        TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
        retval->setBitorder((fillorder==FILLORDER_MSB2LSB) ? BWImage::MSB2LSB : BWImage::LSB2MSB);

        TIFFClose(tif);
        return retval;
    }
    return 0;
}

}//namespace pagetools
