//
//  GPTGraph.m
//  GraphPlot
//
//  Created by Ashley on 16/05/2006.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "GPTGraph.h"

@implementation GPTGraph

- (id) init
{
	[super init];
	
	NSProcessInfo *processInfo = [NSProcessInfo processInfo];
	NSDictionary *environment = [processInfo environment];
	NSString *pathVariable = [environment objectForKey:@"PATH"];
	NSArray *pathDirectories = [pathVariable componentsSeparatedByString:@":"];
	NSString *gnuplotPath = nil;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	int i;
	for(i=0; i<[pathDirectories count]; i++) {
		NSString *directory = [pathDirectories objectAtIndex:i];
		NSString *testPath = [directory stringByAppendingPathComponent:@"gnuplot"];
		if ([fileManager fileExistsAtPath:testPath]) {
			gnuplotPath = [testPath retain];
			break;
		}
	}
	
	if (gnuplotPath==nil) {
		[self release];
		return nil;
	}
	
	_pipeTask = [[NSTask alloc] init];
	NSPipe *newPipe = [NSPipe pipe];
	_writeHandle = [newPipe fileHandleForWriting];
	
    [_pipeTask setStandardInput:newPipe]; 
    [_pipeTask setLaunchPath:gnuplotPath];
    [_pipeTask launch];
	[gnuplotPath release];
	
	_grid = NO;
	_plotTitle = nil;

	return self;
}

- (void) setGrid: (BOOL) grid
{
	_grid = grid;
}

- (BOOL) grid
{
	return _grid;
}

- (void) setPlotTitle:(id)title
{
	[title retain];
	[_plotTitle release];
	_plotTitle = title;
}

- (id) plotTitle
{
	return _plotTitle;
}

- (void) writeLn:(NSString *)line
{
//	printf("%s\n", [line UTF8String]);
	[_writeHandle writeData:[[line stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

- (void) plot:(double *)points nLines:(int)nLines nPoints:(int)nPoints
{
	[self writeLn:@"set style data lines"];
	if ([self grid]) {
		[self writeLn:@"set grid"];
	}
	
	NSString *title = [self plotTitle];
	if (title!=nil) {
		NSString *str = [[NSString alloc] initWithFormat:@"set title '%@'", title];
		[self writeLn:str];
		[str release];
	}
	
	NSMutableString *line = [[NSMutableString alloc] initWithString:@"plot"];
	int k;
	for(k=1; k<nLines; k++) {
		if (k>1) {
			[line appendString:@","];
		}
		[line appendString:@" '-'"];
	}
//	printf("%s\n", [line UTF8String]);
	[self writeLn:line];
	[line release];
	
	int i;
	for(k=1; k<nLines; k++) {
		for (i=0; i<nPoints; i++) {
			NSMutableString *line = [[NSMutableString alloc] initWithFormat:@"%f %f", points[i*nLines], points[i*nLines + k]];
			[self writeLn:line];
			[line release];
		}
		[self writeLn:@"e"];
	}
	
}

- (void) dealloc
{
	[_writeHandle closeFile];
	[_pipeTask release];
	
	[super dealloc];
}

@end