#!/usr/bin/perl -w
# vi:set nowrap ts=4:
#
# $Id: plot_maker.pl,v 0.0 2002/09/06 19:54:54 nicb Exp $
#
# This perl script has been designed to plot the roller_tables.c tables
# It was written in blind-mode by Nicola Bernardini (nicb@centrotemporeale.it)
# under directions given by Davide Rocchesso (rocchesso@sci.univr.it)
#
use strict;
#use Term::Gnuplot ':ALL';
use FileHandle;
use Roller;
#
# main is at the end
#
sub term_open($)
{
	my ($term_desc) = @_;
	my $path = "| gnuplot";
	my $result = new FileHandle($path);
	#my $result = \*STDOUT;

	die("$path not found") unless defined($result);

	$result->printf("set term %s;\n", $term_desc);

	return $result;
}
sub term_close($)
{
	my ($fh) = @_;

	$fh->close();
}
sub plot_labels($$$)
{
	my ($h, $xlab, $ylab) = @_;

	$h->printf("set xlabel '%s';\nset ylabel '%s'\n", $xlab, $ylab);
}
sub term_start_plot($$$$)
{
	my ($h, $title, $xlab, $ylab) = @_;

	plot_labels($h, $xlab, $ylab);
}
sub term_end_plot($)
{
	my ($h) = @_;

	$h->print("e\n");
}
sub _plot($$$)
{
	my ($handle, $r_x, $r_y) = @_;
	my $end = scalar(@{$r_x});

	for (my $i = 0; $i < $end; ++$i)
	{
		$handle->printf("%08.6f %08.6f\n", $r_x->[$i], $r_y->[$i]);
	}

	term_end_plot($handle);
}
sub plot($$$$$$)
{
	my ($handle, $r_x, $r_y, $title, $x_label, $y_label) = @_;
	my $end = scalar(@{$r_x});

	plot_labels($handle, $x_label, $y_label);

	$handle->printf("plot '-' title '%s' w lines\n", $title);

	_plot($handle, $r_x, $r_y);
}
sub two_plots($$$$$$$$$)
{
	my ($h, $r_x1, $r_y1, $title1, $r_x2, $r_y2, $title2, $xl, $yl) = @_;

	plot_labels($h, $xl, $yl);
	$h->printf("plot '-' title '%s' w lines", $title1);
	$h->printf(", '-' title '%s' w lines\n", $title2);

	_plot($h, $r_x1, $r_y1);
	_plot($h, $r_x2, $r_y2);
}
#
# main
#
	my $inct = 0.01;# linear increment to express the curve in parametric form
	my $tmax = 0.5; # maximum value of the parameter (for parametric curve), in meters

	my $index      = Roller::build_index($tmax, $inct);
	my $parametric = Roller::build_parametric($index, $Roller::tdipmax);
	my $pincs      = Roller::build_pinc($index, $parametric);
	my $pslopes    = Roller::build_pslope($index, $parametric);
	my $p          = Roller::build_p($pincs);
	my $sigma      = Roller::build_sigma($pslopes, $Roller::gravity);
	my $ptilde     = Roller::build_ptilde($p, $sigma, $Roller::h, $Roller::damping);

	#my $fh = term_open("postscript eps enhanced color");
	my $fh = term_open("postscript enhanced color");

	plot($fh, $index, $parametric, "y(t)", "m", "m");
	two_plots($fh, $p, $sigma, "sigma=f(p)", $ptilde, $sigma,
		"sigma=f1(ptilde)", "m", "m/s^2");
	two_plots($fh, $index, $p, "p(t)", $index, $ptilde, "ptilde(t)", "m", "m");

	term_close($fh);
#
# end of main
#
