#import "JFIFBitmap.h"
#import "nxJfif.h"
#import "jfifNx.h"
#import <c.h>
#import <libc.h>

// This subclass extends NXBitmapImageRep.  Specifically, this class may
// be initialized from a jpeg stream and may create a jpeg stream.  Really
// just an object-oriented interface to write_jfif() and read_jfif().

@implementation JFIFBitmap

- writeJFIF:(NXStream *)stream usingQuality:(int)quality
{
    // write_jfif only processes bitmaps with eight bits per sample
    if ([self bitsPerSample] != 8) {
        return(nil);
    }
    // the bitsPerPixel argument allows you to specify the alpha component
    // the bytesPerRow argument allows you to specify row padding
    write_jfif(stream, [self data], [self pixelsWide], [self pixelsHigh],
        [self  samplesPerPixel], [self bitsPerSample], [self bitsPerPixel],
        [self bytesPerRow], quality);
    return(self);
}

- readJFIF:(NXStream *)stream
{
    unsigned char *data;
    int width, height, bps, spp;
    NXColorSpace colorSpace;

    read_jfif(stream, &data, &width, &height, &bps, &spp);
    if (spp == 3) {
        colorSpace = NX_RGBColorSpace;
    } else if (spp == 1) {
        colorSpace = NX_OneIsWhiteColorSpace;
    }
    [self initData:data pixelsWide:width pixelsHigh:height bitsPerSample:bps
    samplesPerPixel:spp hasAlpha:NO isPlanar:NO colorSpace:colorSpace
    bytesPerRow:(width * spp * bps) / 8 bitsPerPixel:spp * bps];
    return(self);
}

- free
{
    if (jfifData != NULL) {
        free(jfifData);
    }
    return([super free]);
}

@end


