import config
import global tiffio, stdio, stdlib, math, stdint
import image

Image *def load_tiff_luminance(char const *filename):
    TIFF *tif = TIFFOpen(filename, "r")
    if not tif: return None
    int32_t w, h
    size_t npixels
    uint32 *raster

    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w)
    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h)
    
    npixels = w * h
    raster = _TIFFmalloc(npixels * sizeof (uint32))
    B *luminance = None

    if raster:
        if TIFFReadRGBAImage(tif, w, h, raster, 0):
            luminance = ALLOCATE(w * h * sizeof *luminance)
            for int j = 0; j < h; j++:
                for int i = 0; i < w; i++:
                    float r = (raster[i + w * j] >> 0x00) & 0xff
                    float g = (raster[i + w * j] >> 0x08) & 0xff
                    float b = (raster[i + w * j] >> 0x10) & 0xff
                    float y = 0.299 * r + 0.587 * g + 0.114 * b
                    if y > 255: y = 255
                    luminance[i + w * (h - 1 - j)] = y
        _TIFFfree(raster)

    TIFFClose(tif)
    Image *image = image_new_b(luminance, w, h)
    image_set_path(image, filename, True)
    return image

def save_tiff_luminance(char const *filename, Image *luminance):
    B *data = luminance->data.b
    int w = luminance->w
    int h = luminance->h
    TIFF *tif = TIFFOpen(filename, "w")

    TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, w)
    TIFFSetField(tif, TIFFTAG_IMAGELENGTH, h)
    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8)
    TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 1)
    TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, h)
    TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, 1)

    TIFFWriteEncodedStrip(tif, 0, data, w * h);

    TIFFClose(tif)

def save_tiff_rgb(char const *filename, Image *image):
    TIFF *tif = TIFFOpen(filename, "w")

    TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, image->w)
    TIFFSetField(tif, TIFFTAG_IMAGELENGTH, image->h)
    TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8)
    TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3)
    TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, image->h)
    TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, 2)
    TIFFSetField(tif, TIFFTAG_PLANARCONFIG, 1)

    TIFFWriteEncodedStrip(tif, 0, image->data.rgb, image->w * image->h * 3);

    TIFFClose(tif)
