#!/usr/bin/perl


#getting equation
print "Please enter the equation you would like graphed:\nZ= ";
$eqn = <STDIN>;

#creating new derive program
$old = './derive.cpp';
$new = './derive.cpp.bak';
open(OLD, $old);
@line = <OLD>;
close(OLD);
open(NEW, ">$new");
for($i=0; $i<8 ; $i++)
{
	print NEW $line[$i];
}
#removing newline, outputing equation
chop($eqn);
print NEW "	ex Z = $eqn;\n";
for($i=9; $line[$i]; $i++)
{
	print NEW $line[$i];
}

system("mv derive.cpp derive.orig");
system("mv derive.cpp.bak derive.cpp");
#finding derivatives
system("g++ -lginac -oderive derive.cpp");
system("./derive");

$original = './calc.cpp';
$temp = './calc.cpp.bak';
open(SOURCE, $original);
@line = <SOURCE>;
close(SOURCE);
open(DEST, ">$temp");

#Outputting first part of source
for($i = 0; $i < 31; $i++)
{
	print DEST $line[$i];
}

#Ouputing Derivitives
open(DERIVS, '.deriv');
@derive = <DERIVS>;
close(DERIVS);
print DEST "#define Z(x,y)	$eqn\n";
print DEST "#define dZdx(x,y)	$derive[0]";
print DEST "#define dZdy(x,y)	$derive[1]";

#outputting remained of source
for($i=34; $line[$i]; $i++)
{
	print DEST $line[$i];
}
close(DEST);

system("mv calc.cpp calc.orig");
system("mv calc.cpp.bak calc.cpp");
system("g++ calc.cpp -lGL -lGLU -lglut -o calc");
system("./calc");

