#!/usr/bin/perl

use strict;

my $GNUPLOTPath = 'D:\Programs\gnu\gnuplot4.4\binary\pgnuplot.exe';
my $TempPath    = "temp.txt";
my $Terminal    = 'wxt';
my $OutputPath  = "output.png";
#my $OutputPath  = "";

#my $PlotFunction  = "splot";
#my $Function      = "sin(x,y)";
my $PlotFunction  = "plot";
my $Function      = "sin(x)";
my $PlotOption    = "with p ps 3 pt 4"; # line|dot|impulse|w p p[oint]s[ize] 3 p[oint]t[ype] 4 l[ine]w[idth] 3
my $Title         = 'Test Graph';
my ($XMin, $XMax) = (-1, 1);
my ($YMin, $YMax) = (0.001, 1);
my ($ZMin, $ZMax) = (-1, 1);
my $XPlotType     = 'linear';
my $YPlotType     = 'log';

if($ARGV[0] eq 'boot') {
	system($GNUPLOTPath);
}
elsif($ARGV[0] ne '') {
	$PlotFunction = $ARGV[0];
}

if($OutputPath =~ /\.pdf$/i) {
	$Terminal    = 'pdf';
}
elsif($OutputPath =~ /\.ps$/i) {
	$Terminal    = 'postscript';
}
elsif($OutputPath =~ /\.(jpeg|jpg)$/i) {
	$Terminal    = 'jpeg';
}
elsif($OutputPath =~ /\.(emf|wmf)$/i) {
	$Terminal    = 'emf';
}
elsif($OutputPath =~ /\.(gif|cgm|dxf|eepic|fig|hpgl|latex|bm|png|tgif|tpic)$/i) {
	$Terminal    = $1;
}
#print "OutputPath: $OutputPath\n";

open(OUT, ">$TempPath");
print OUT "reset\n";
if($OutputPath eq '') {
	print OUT "set terminal $Terminal\n";
}
else {
	print OUT "set terminal $Terminal\n";
	print OUT "set output \"$OutputPath\"\n";
}
print OUT "set title '$Title'\n";
if($XPlotType eq 'log') {
	print OUT "set logscale x\n";
}
if($YPlotType eq 'log') {
	print OUT "set logscale y\n";
}
#print OUT "set xrange [$XMin:$XMax]\n";
#print OUT "set yrange [$YMin:$YMax]\n";
#print OUT "set zrange [$ZMin:$ZMax]\n";
print OUT "$PlotFunction [$XMin:$XMax] [$YMin:$YMax] [$ZMin:$ZMax] $Function $PlotOption\n";
#print OUT "$PlotFunction $Function $PlotOption\n";
if($OutputPath eq '') {
}
else {
	print OUT "exit\n";
}
close(OUT);

#gnuplot -persist -e "set title 'Sine curve'; plot sin(x)"
#ファイルのコマンドを実行する前に、ユーザ定義変数 a と s をセットする: 
#gnuplot -e "a=2; s='file.png'" input.gpl
my $cmd;
if($OutputPath eq '') {
#	$cmd = "$GNUPLOTPath \"$TempPath\"";
	$cmd = "$GNUPLOTPath -persist \"$TempPath\"";
}
else {
	$cmd = "$GNUPLOTPath  \"$TempPath\"";
}
system($cmd);
