#! /usr/bin/perl

##
## FILE:  rescale
## DESC:  take two ASCII charts and match their scales for generating graphs
##

$min = 1.0e50;  # some big number
$max = 0.0;     # some small number

if (@ARGV != 2) {
	print STDERR "usage: rescale <chart1> <chart2>\n";
	exit(1);
}

$chart1 = $ARGV[0];
$chart2 = $ARGV[1];

@chart1 = &readchart($chart1);
@chart2 = &readchart($chart2);

&writechart($chart1, @chart1);
&writechart($chart2, @chart2);

sub readchart {
	local($chart) = @_;
	local(@chart);
	local(@fields);
	local($line);

	open(CHART, $chart) || die "unable to open $chart: $!\n";

	## read to the first blank line
	while (<CHART>) {
		push(@chart, $_);
		last if /^$/;
	}

	## read the column titles
	push(@chart, scalar(<CHART>));

	## read data fields until a blank line is encountered
	while (<CHART>) {
		chop($line = $_);
		push(@chart, $_);
		last if /^$/;

		@fields = split(/\t/, $line);
		shift @fields;		## discard first field

		for (@fields) {
			$min = $_ if $_ < $min;
			$max = $_ if $_ > $max;
		}
	}

	## read the rest of the file
	while (<CHART>) {
		push(@chart, $_);
	}

	close(CHART);

	return @chart;
}

sub writechart {
	local($chart, @chart) = @_;
	local($tmpfile) = ($chart . ".rescale");
	local($line);

	open(CHART, ">" . $tmpfile) || die "unable to create $tmpfile: $!\n";

	## first line gets min and max
	chop($line = shift @chart);
	print CHART $line, "\t", $min, "\t", $max, "\n";

	## write out the rest of the chart
	for (@chart) {
		print CHART $_;
	}

	close(CHART) || die "unable to close $tmpfile: $!\n";

	rename($tmpfile, $chart)
		|| die "unable to replace $chart with $tmpfile: $!\n";
}
