//
//  NSImageFromPPM.m
//  FaceCrop
//
//  Created by Andrew Salamon on 10/10/06.
//  Copyright 2006 Machine Perception Laboratory, University of California San Diego.. All rights reserved.
//

#import "NSImageFromPPM.h"


@implementation NSImage(NSImageFromPPM)
- (id)initWithContentsOfPPMFile:(NSString *)fileName
{
	NSTask *convert = [[NSTask alloc] init];
	
	NSString *ppmtobmp = [[NSBundle mainBundle] pathForAuxiliaryExecutable:@"ppmtobmp"];
	NSPipe *pipe = [NSPipe pipe];
	NSFileHandle *output = [pipe fileHandleForReading];
	
	[convert setLaunchPath:ppmtobmp];
	[convert setArguments:[NSArray arrayWithObject:fileName]];
	[convert setStandardOutput:pipe];
	[convert launch];
//	[convert waitUntilExit];
	
	NSMutableData *ppmData = [NSMutableData data];
	NSData *data = [output availableData];
	
	while( ( data != nil ) && ( [ data length] != 0 ) )
	{
		[ppmData appendData:data];				
		data = [output availableData];
	}
	
	if( [ppmData length] > 0 )
	{
		self = [self initWithData:ppmData];
	}
	else
	{
		[self release];
		self = nil;
	}
	
	[convert release];
	return self;
}
@end
