#!/usr/bin/env perl
#
#
# lsl.pl filename 
#
# Do a linear fit on x,y data, plot and report results
#
# filename points to a text file in which each line contains
# two numbers (input and output) separated by white space. 
#
# The output is a color eps file "filename.ls.eps" containing the plot.
#
# The program will also report the equation and R2.
#

use IPC::Open2;
use FileHandle;

if ($#ARGV<0 || $#ARGV>0) {
    print STDERR "lsl.pl filename\n";
    exit(-1);
}

$filename = $ARGV[0];

system "cp $filename matlabinput.txt";

open2(MATOUT,MATIN,"matlab -display none");
MATOUT->autoflush(1);
MATIN->autoflush(1);

print MATIN "load('matlabinput.txt');\n";
print MATIN "x=matlabinput(:,1);\n";
print MATIN "y=matlabinput(:,2);\n";
print MATIN "path(path,'/afs/cs/project/cmcl-pdinda-3/TOOLS');\n";
print MATIN "[r2,m,b] = leastsquaresline(x,y)\n";
print MATIN "yp = m*x+b;\n";
print MATIN "plot(x,y,'b.',x,yp,'r.');\n";
print MATIN "xlabel('input');\n";
print MATIN "ylabel('output');\n";
print MATIN "t = sprintf('leastsquares on $filename, yp=%gx+%g R2=%g',m,b,r2);\n";
print MATIN "title(t);\n";
print MATIN "print -depsc $filename.ls.eps\n";
print MATIN "quit;\n";

@linesout = <MATOUT>;
close(MATOUT);
close(MATIN);

$globout = join("",@linesout);
#print $globout;
$globout =~ /r2 =.*\n.*\n(.*)/;
$r2 = $1;
$r2 =~ s/\s+//g;
$globout =~ /m =.*\n.*\n(.*)/;
$m = $1;
$m =~ s/\s+//g;
$globout =~ /b =.*\n.*\n(.*)/;
$b = $1;
$b =~ s/\s+//g;

print "Figures written to $filename.ls.eps\n";
print "model is:  y = $m*x + $b  (R2=$r2)\n";

system "rm -f matlabinput.txt";


