/*
 *  ImageWriter.m
 *  PIDShapeDumper
 *
 *  Created by Alexander Strange on Sun Dec 15 2002.
 *  Copyright (c) 2002 __MyCompanyName__. All rights reserved.
 *
 */

#import "ImageWriter.h"
#import "Dumper.h"

static BOOL internal_write_bitmap_planar(unsigned short *planes[5],unsigned long theId,unsigned char color_table, void *collection, unsigned long coll_size);

void write_bitmap_to_file(void *collection,unsigned short theId,NSString *fileName, unsigned long coll_size, unsigned long color_table)
{
    struct collection_header *coll = (struct collection_header*)collection;
    struct low_level_shape_header *lls = offset_of_lls_header(coll,theId) + (long)coll;
    unsigned char *pixels = offset_of_pixel_data(coll,theId) + coll->pixel_data_offset + (long)coll;
    unsigned short *planes[5];
    NSBitmapImageRep *img = [NSBitmapImageRep alloc];
    NSData *data;
    img = [img initWithBitmapDataPlanes:NULL pixelsWide:lls->width pixelsHigh:lls->height bitsPerSample:16 samplesPerPixel:4 hasAlpha:YES isPlanar:YES colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:0 bitsPerPixel:0];
    [img getBitmapDataPlanes:(unsigned char **)&planes];

    if ((long(pixels) - long(coll)) >= coll_size) goto exit;

    internal_write_bitmap_planar(planes,theId,color_table,collection,coll_size);

    data = [img TIFFRepresentation];
    [data writeToFile:[fileName stringByExpandingTildeInPath] atomically:YES];
    
    goto exit;
exit:
	[img release];
    return;
}

static BOOL internal_write_bitmap_planar(unsigned short *planes[5],unsigned long theId,unsigned char color_table, void *collection, unsigned long coll_size) {
    struct collection_header *coll = (struct collection_header*) collection;
    struct low_level_shape_header *lls = (struct low_level_shape_header*) (collection + coll->low_level_offset + (sizeof(struct low_level_shape_header) * theId));
    unsigned char *pixels = collection + coll->pixel_data_offset + lls->pixel_offset;
    unsigned short *r = planes[0],*g = planes[1], *b = planes[2], *a = planes[3];
    ColorSpecPtr colors = coll->colors;
    unsigned long m = (lls->width * lls->height) << 8, coff = coll->color_count * color_table;
    const unsigned long precalc_coff = coff - 2;

    do
    {
	ColorSpecPtr ccolor = colors++;
	unsigned long p = *pixels++, p2 = p + coff;
	if ((p - long(collection)) >= coll_size) return NO;

	*r++ = ccolor->rgb.red;
	*g++ = ccolor->rgb.green;
	*b++ = ccolor->rgb.blue;
	*a++ = (p==2)?0:65535;

    } while (m--);
    return YES;
}