//
//  ImageCompare.m
//  Hootenanny
//
//  Created by Noah Sorscher on 11/11/04.
//  Copyright 2004 __MyCompanyName__. All rights reserved.
//

#import "ImageCompare.h"


@implementation NSImage (compare)


typedef struct _RGBAPixel
{
	unsigned char redByte, greenByte, blueByte, alphaByte;	
} RGBAPixel;


- (NSComparisonResult)compareA:(NSImage *)otherImage
{
    NSSize this = [self size], that = [otherImage size];
    if (this.width != that.width || this.height != that.height) return NSOrderedAscending;
    NSBitmapImageRep *rep1 = [[self representations] objectAtIndex:0];
    NSBitmapImageRep *rep2 = [[otherImage representations] objectAtIndex:0];
    if ([rep1 samplesPerPixel] == 4 && [rep2 samplesPerPixel] == 4) {
        RGBAPixel *pixels1 = (RGBAPixel *)[rep1 bitmapData];
        RGBAPixel *pixels2 = (RGBAPixel *)[rep2 bitmapData];
        int row, col, rows = [rep1 pixelsHigh], cols = [rep1 pixelsWide];
        for (row = 0; row < rows; row++) {
            for (col = 0; col < cols; col++) {
                RGBAPixel thisPixel = pixels1[row*cols+col];
                RGBAPixel thatPixel = pixels2[row*cols+col];
                if (thatPixel.alphaByte > thisPixel.alphaByte) return NSOrderedAscending;
                else if (thatPixel.alphaByte < thisPixel.alphaByte) return NSOrderedDescending;
            }
        }
        return NSOrderedSame;
    }
    return NSOrderedAscending;
}

@end
