//
//  PRGrayscaleFilter.m
//  PRICE
//
//  Created by Riccardo Mottola on Mon Dec 23 2002.
//  Copyright (c) 2002-2005 Carduus. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under the terms of the version 2 of the GNU General Public License as published by the Free Software Foundation.
// This program 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.


#import "PRGrayscaleFilter.h"
#import <math.h>


@implementation PRGrayscaleFilter

- (PRImage *)filterImage:(PRImage *)srcImage
{
    NSBitmapImageRep *srcImageRep;
    PRImage          *destImage;
    NSBitmapImageRep *destImageRep;
    int              w, h;
    int              x, y;
    unsigned char    *srcData;
    unsigned char    *destData;
    unsigned char    *p1;
    int              bytesPerPixel;
    
    
    /* get source image representation and associated information */
    srcImageRep = [srcImage tiffRep];
    
    w = [srcImageRep pixelsWide];
    h = [srcImageRep pixelsHigh];
    bytesPerPixel = [srcImageRep bitsPerPixel] /8;
    
    /* if the image is already greyscale... */
    if ([srcImageRep hasAlpha])
    {
        if ([srcImageRep samplesPerPixel] == 2)
            return srcImage;
    }
    else
    {
        if ([srcImageRep samplesPerPixel] == 1)
            return srcImage;
    }
    
    /* allocate destination image and its representation */
    destImage = [[PRImage alloc] initWithSize:NSMakeSize(w, h)];
    destImageRep = [[NSBitmapImageRep alloc]
                    initWithBitmapDataPlanes:NULL
                    pixelsWide:w
                    pixelsHigh:h
                    bitsPerSample:8
                    samplesPerPixel:1
                    hasAlpha:NO
                    isPlanar:NO
                    colorSpaceName:NSCalibratedWhiteColorSpace
                    bytesPerRow:0
                    bitsPerPixel:0];
    
    srcData = [srcImageRep bitmapData];
    destData = [destImageRep bitmapData];
    
    /* execute the actual filtering */
    for (y = 0; y < h; y++)
        for (x = 0; x < w; x++)
        {
            p1 = srcData + bytesPerPixel * (y * w + x);
            destData[y*w + x] = (unsigned char)rint((p1[0] + p1[1] + p1[2]) / 3);
        }
    
    [destImage addRepresentation:destImageRep];
    [destImageRep release];
    [destImage autorelease];
    return destImage;
}

@end
