//
//  EXPPlotElement.m
//  XMLTest
//
//  Created by Ashley on 21/05/2007.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "EXPPlotElement.h"
#import "PLTMatrix.h"
#import "PLTMatrixColumnView.h"
#import "EXPModel.h"
#import "EXPStateElement.h"
#import "EXPAuxiliaryElement.h"

@implementation EXPPlotElement

- (id) init
{
	[super init];
	_grid = NO;
	_legend = NO; 
	_plotTitle = nil;
	_style = @"lines";
	_xlabel = nil;
	_ylabel = nil;
	_lineTitles = [[NSMutableArray alloc] init];
	return self;
}

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

- (BOOL) grid
{
	return _grid;
}

- (void) setLegend:(BOOL)legend
{
	_legend = legend;
}

- (BOOL) legend
{
	return _legend;
}

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

- (id) plotTitle
{
	return _plotTitle;
}

- (void) setXlabel:(id)xlabel
{
	[xlabel retain];
	[_xlabel release];
	_xlabel = xlabel;
}

- (id) xlabel
{
	return _xlabel;
}

- (void) setYlabel:(id)ylabel
{
	[ylabel retain];
	[_ylabel release];
	_ylabel = ylabel;
}

- (id) ylabel
{
	return _ylabel;
}

- (void) setStyle:(id)style
{
	[style retain];
	[_style release];
	_style = style;
}

- (id) style
{
	return _style;
}

- (void) addLineTitle:(id)title
{
	[_lineTitles addObject:title];
}

- (id) lineTitles
{
	return _lineTitles;
}

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

- (BOOL) plot:(double *)points nLines:(int)nLines nPoints:(int)nPoints
{
	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) {
		return NO;
	}
	
	NSTask *pipeTask;
	NSFileHandle *writeHandle;

	pipeTask = [[NSTask alloc] init];
	NSPipe *newPipe = [NSPipe pipe];
	writeHandle = [newPipe fileHandleForWriting];
	
    [pipeTask setStandardInput:newPipe]; 
    [pipeTask setLaunchPath:gnuplotPath];
    [pipeTask launch];
	[gnuplotPath release];

	[self writeLn:@"set term aqua" topipe:writeHandle];

	NSString *style = [[NSString alloc] initWithFormat:@"set style data %@", [self style]];
	[self writeLn:style topipe:writeHandle];
	[style release];

	if ([self xlabel]!=nil) {
		NSString *xlabel = [[NSString alloc] initWithFormat:@"set xlabel '%@'", [self xlabel]];
		[self writeLn:xlabel topipe:writeHandle];
		[xlabel release];
	}
	
	if ([self ylabel]!=nil) {
		NSString *ylabel = [[NSString alloc] initWithFormat:@"set ylabel '%@'", [self ylabel]];
		[self writeLn:ylabel topipe:writeHandle];
		[ylabel release];
	}
	
	if ([self grid]) {
		[self writeLn:@"set grid" topipe:writeHandle];
	}
	
	
	if ([self legend]) {
		[self writeLn:@"set key on" topipe:writeHandle];
	} else {
		[self writeLn:@"set key off" topipe:writeHandle];
	}
	
	NSString *title = [self plotTitle];
	if (title!=nil) {
		NSString *str = [[NSString alloc] initWithFormat:@"set title '%@'", title];
		[self writeLn:str topipe:writeHandle];
		[str release];
	}
	
	NSArray *lineTitles = [self lineTitles];
	NSMutableString *line = [[NSMutableString alloc] initWithString:@"plot"];
	int k;
	for(k=1; k<nLines; k++) {
		if (k>1) {
			[line appendString:@","];
		}
		[line appendString:@" '-'"];
		NSString *lineTitle = [lineTitles objectAtIndex:k];
		if ([lineTitle length]>0) {
			NSString *str = [[NSString alloc] initWithFormat:@" title '%@'", lineTitle];
			[line appendString:str];
			[str release];
		}
	}
//	printf("%s\n", [line UTF8String]);
	[self writeLn:line topipe:writeHandle];
	[line release];
	
	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 topipe:writeHandle];
			[line release];
		}
		[self writeLn:@"e" topipe:writeHandle];
	}
	
	[writeHandle closeFile];
	[pipeTask release];
	
	return YES;
}

- (NSString *)elementType
{
	return @"plotter";
}

- (void) dealloc
{
	[_plotTitle release];
	[_xlabel release];
	[_ylabel release];
	[_style release];
	[_lineTitles release];
	[super dealloc];
}

@end