#!/usr/bin/perl
# $Id: make_latex_report,v 1.51 2017/06/22 10:11:02 sofc Exp $
my $VERSION = 2.1;
my $PROGRAM = $0;
use RFC::Rig;
use RFC::Header;
use RFC::Main;
use AFM qw();
use LATEX;
use strict;
use Carp;
use warnings;
chdir;
my $debug = 0;
my $test = 0;
my $edit = 0;
my $inter = 0;
my $do = 1;
my $remake = 0;
my $short = 0;
for my $string (@ARGV)
{
    if ($string =~ /--version/)
    {
	warn "$PROGRAM is: $VERSION\n";
	exit 0;
    }
    if ($string =~ /--debug/)
    {
	$debug = 1;
    }
    if ($string =~ /--test/)
    {
	$test = 1;
    }
    if ($string =~ /--edit/)
    {
	$edit = 1;
    }
    if ($string =~ /--inter/)
    {
	$inter = 1;
    }
    if ($string =~ /--remake/)
    {
	$remake = 1;
    }
    if ($string =~ /--short/)
    {
	$short = 1;
    }
}

my $rig = 0;
if (@ARGV) 
{
    my $rigno = $ARGV[0];
    $rigno =~ /(\d+)/;
    $rig = $1;
}
my $r = RFC::Rig->new($rig);
$r->check_run;

my $testno = $r->session;
if ( scalar(@ARGV) > 1 ) 
{
    my $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
my $analytic_dir = '/home/http/cgi-bin/analytic/';
my $name = 'rig'.$rig;
my $continue = 1;
our $inffile = &get_path.'report_information.txt';

if (!$remake)
{
    warn("######## Input Author name: (q for quit, RETURN for none) ######\n");
    while ($continue)
    {
	my $str = <STDIN>;
	chomp $str;
	if ($str =~ /([\s\w\{\}\\\.]+)/)
	{
	    $name = ucfirst($1);
	    $continue = 0;
	}
	if ($str =~ /^q$/)
	{
	    warn("###### Ok exiting ######\n");
		exit;
	}
	if ($str =~/^\s*$/)
	{
	    warn("###### Using default author: $name ########\n");
		$continue = 0;
	}
    }
    unlink($inffile);
    &write_old_info('AUTHOR',$name);
}
else
{
    $name = &get_old_info('AUTHOR');
}

my $title = 'Cell test report for '.$rig.'test'.$testno;

$continue = 1;

if (!$remake)
{
    warn("#######  Input Title: (q for quit, RETURN for none)  #####\n");
    while ($continue)
    {
	my $str = <STDIN>;
	chomp $str;
	if ($str =~ /([\d\s\w]+)/)
	{
	    chomp $str;
	    $str =~/([\d\w\s]+)/;
	    $title = $1;
	    $continue = 0;
	}
	if ($str =~ /q/)
	{
	    warn("###### Ok exiting ######\n");
		exit;
	}
	if ($str =~/^\s*$/)
	{
	    $continue = 0;
	    warn("###### Using default title: $title ######\n");
	    }
    }
    &write_old_info('TITLE',$title);
}
else
{
    $title = &get_old_info('TITLE');
}
$title .= ' (short version)' if ($short);

#####################################################
#### End header information Begin writing report ####
#####################################################

my $g_proc_data_loc = get_cv('MDRIVE','location');
my $g_mount_data_loc = get_cv('MDRIVE','mountloc');
my $g_umount_data_loc = get_cv('MDRIVE','unm_loc');
my $cell = &get_cell;
my $othernr = &get_other_nr();
my $psdir = &get_psdir;
my $ivpsdir = &get_ivpsdir;
my $server = `/bin/hostname`;

print &latex_header($title,$name);
my $impedance = &is_impedance;
if ($impedance =~ /YES/)
{
    my $cmd = "/usr/local/bin/get_impedance_data $rig $testno";
    system($cmd);
    &make_impedance if (!$remake);
}

print '\section{Data information}',"\n\n";

my $program = &input_information_new('Program for the cell (DK/RR/..)','PROJECT');
my $sistercells = &input_information('Sister cells to tested cell','SISTERC');
my $dataplacement = $psdir;
$dataplacement =~ s/\/ps\//\//;
$dataplacement = $dataplacement." on ".$server;

my $procesdata = &input_information("Processed data location (Mdrev),\nuse X: for $g_proc_data_loc\n",'PROC');
if ($procesdata =~ /^X\:/) {$procesdata =~ s/^X\:/$g_proc_data_loc/};

my $picturemount = &input_information("Location of images of mounting,\nuse X: for $g_mount_data_loc\nuse Y: for $g_proc_data_loc\nuse Z: for $procesdata\n",'MOUNT');
if ($picturemount =~ /^X\:/) {$picturemount =~ s/^X\:/$g_mount_data_loc/};
if ($picturemount =~ /^Y\:/) {$picturemount =~ s/^Y\:/$g_proc_data_loc/};
if ($picturemount =~ /^Z\:/) {$picturemount =~ s/^Z\:/$procesdata/};

my $picturedismount = &input_information("Location of images of dismounting,\nuse X: for $g_umount_data_loc\nuse Y: for $g_proc_data_loc\nuse Z: for $procesdata\n",'DMOUNT');
if ($picturedismount =~ /^X\:/) {$picturedismount =~ s/^X\:/$g_umount_data_loc/};
if ($picturedismount =~ /^Y\:/) {$picturedismount =~ s/^Y\:/$g_proc_data_loc/};
if ($picturedismount =~ /^Z\:/) {$picturedismount =~ s/^Z\:/$procesdata/};

my $posttest = &input_information("Post test analysis,\nuse X: for $g_proc_data_loc\nuse Z: for $procesdata\n",'POST');
if ($posttest =~ /^X\:/) {$posttest =~ s/^X\:/$g_proc_data_loc/};
if ($posttest =~ /^Z\:/) {$posttest =~ s/^Z\:/$procesdata/};
my $keywords = &input_information_new('Keywords from cell production','KEYWORDS');
my $tkeyword = 0;
$tkeyword = 1 if length($keywords) > 700;
my $testplan = &input_information_new('Test plan','TESTPLAN');
my $ttestplan = 0;
$ttestplan = 1 if (length($testplan) > 700);
my $testresult = &input_information('Test result','TESTRESULT');
my $comments = &input_information('Comments on test','COMMENTS');
my $impedansst = '';
if ($impedance =~ /YES/)
{
    $impedansst = $psdir;
    $impedansst =~ s/\/ps\//\/impedance\//;
    $impedansst .= " on ".$server;
}


print &start_table('Cell information and data location','p{4 cm}','p{12 cm}');
print &hline;
print &row('Program:',$program);
print &hline;
my $c = $cell;
$c =~ s/\\_/_/g;
print &row('Cell nr.',$c);
print &hline;
print &row('Other test numbers.',$othernr);
print &hline;
print &row("Sister cells",$sistercells);
print &hline;
print &row("Rig nr.",$rig);
print &hline;
print &row("Test nr.",$testno);
print &hline;
print &row("Raw data",$dataplacement);
print &hline;
print &row("Processed data",$procesdata);
print &hline;
print &row("Mounting photos",$picturemount);
print &hline;
print &row("Dismounting photos",$picturedismount);
print &hline;
if ($impedance =~ /YES/)
{
    print &row("Impedance data",$impedansst);
    print &hline
}
print &row("Post test analysis",$posttest);
print &hline;
if ($tkeyword)
{
    print &row("Production keywords:",'See section '.&ref('keyword'));
}
else
{
    print &row("Production keywords:",$keywords);
}
print &hline;
if ($ttestplan)
{
    print &row("Test plan:",'See section '.&ref('testplan'));
}
else
{
    print &row("Test plan:",$testplan);
}
print &hline;
print &row("Test result",$testresult);
print &hline;
print &row("Comments on test",$comments);
print &hline;
print &end_table('datalocation');


###### Prints the overview text ######
my $fuelflowvar = &is_fuel_var;
my $airflowvar = &is_air_var;
my $fueltemp = &get_fueltemp;
my $airtemp = &get_airtemp;
my $tempvar = &is_tempvar;
my $isiv = &is_iv; 
my $isleak = &is_leak;
 
print "\%start\n";
my $f = &get_path . 'manual_info.txt';
if (-e($f))
{
    open INH, $f or die "could not open file $f\n";
    while(!eof(INH))
    {
	my $st = <INH>;
	print $st;
    }
    close INH;
}
print "\%end\n\n\n";

print "Table ",&ref('overview-tabel')," ",&pref('overview-tabel')," shows the total charge passed through the cell, as well as the minimum resistance and maximum power obtained.\n";
print "The minimum resistances reported in table ",&ref('overview-tabel')," is the lowest resistances measured at 750, 800 and 850 degrees centigrade in dry hydrogen \(no addition of oxygen to the anode gas\).\n";

print "The minimum cell resistance at 750 mV reported in table ",&ref('overview-tabel')," is the lowest cell resistance at 750, 800 and 850\$\\pm\$8 degrees and a gas flow of 24\$\\pm\$1 L\/hour hydrogen (5\\% H\$_2\$O) and 140\$\\pm\$5 L\/hour air.\n";

print "The minimum leak current reported in ",&ref('overview-tabel')," is the lowest leak current for an iv curve at 850\$\\pm\$8 degrees and a gas flow of 24\$\\pm\$1 L\/hour hydrogen (5\\\% H\$_2\$O) and 140\$\\pm\$5 L\/hour air.\n";
print "The leak current calculation assumes that the only leak through the cell is an electronic leak. ";

print "The figures in section ",&ref('Results')," ",&pref('Results')," shows the cell voltage and the temperature during the test, as well as the gas flows.\n\n";
if ($isleak)
{
    print "Section ",&ref('Leak investigation')," ",&pref('Leak investigation')," show the leak current through the cell and cell assembly as a function of fuel and air flow.\n\n";
}

if ($isiv =~ /YES/)
{
    print "Section ",&ref('Representative i-V curves')," ",&pref('Representative i-V curves')," Includes figures of representative i-V curves, both in the beginning and at the end of the test.\n";
    if (($fuelflowvar =~ /YES/i) && ($airflowvar =~ /YES/i))
    {
	print "In section ",&ref('Fuel flow variations in the beginning of the test')," ",&pref('Fuel flow variations in the beginning of the test')," and \n";
	print &ref('Air flow variations in the beginning of the test')," ",&pref('Air flow variations in the beginning of the test')," The effect of differrences in fuel and air flow is shown\n\n\n";
    }
    if (&is_long_term =~ /YES/i)
    {
	print "Section ",&ref('Long term test')," ",&pref('Long term test')," inclueds figures showing the development of the cell resistance (at different current loads) as a function of time.\n\n";
    }
    if ($tempvar =~ /YES/i)
    {
	print "Section ",&ref('Temperatuture variation')," ",&pref('Temperatuture variation')," shows how the temperature of the cell influences the cell resistance.\n\n";
    }
}

if ($impedance =~ /YES/)
{
    print "Section ",&ref('Impedance'),' ',&pref('Impedance')," Contains figures showing some of the impedance spectra obtained.\n\n";
}

my $infofile = &get_path.'info.txt';

####### Prints the reference to the infofile and the command log #####
####### But only if the long version is chosen #######################
if (!$short)
{
    if (-e($infofile))
    {
	print "Appendix ",&ref('infofile')," ", &pref('infofile')," shows the test log\n";
	my $cmdlog = $infofile;
	$cmdlog =~ s/info\.txt/proglog/; 
	if (-e($cmdlog))
	{
	    print " and appendix ",&ref('cmdlog')," ",&pref('cmdlog')," shows the command log for cell $cell.\n\n";
	}
	else
	{
	    print " for cell $cell.\n\n";
	}
    }
    print "Appendix ",&ref('Startup and end')," Contains figures showing the cell voltage, current, temperature and oxygen potential of the inlet and outlet gas at the start and end of the test of cell $cell.\n\n";
    print "Appendix ",&ref('All measured values')," Contains figures showing all measured data channels as a function of test time for cell $cell.\n\n";
}

###################################

my $jdata = &get_path.'jdata';
my $cmd = "/usr/bin/head -n 1 $jdata";
my $startt = `$cmd`;
$startt =~ /\s+([\d\:]+)/;
$startt = $1;
my @startt = split(':',$startt);
$startt = $startt[0];
for (my $x = 1; $x < 3; $x++)
{
    $startt = $startt.':'.$startt[$x];
}
$cmd = "/usr/bin/tail -n 1 $jdata"; 
my $endt = `$cmd`;
$endt =~ /\s+([\d\:]+)/;
$endt = $1;
my @endt = split(':',$endt);
$endt = $endt[0];
for (my $x = 1; $x < 3; $x++)
{
    $endt = $endt.':'.$endt[$x];
}
$cmd = "/usr/bin/tail -n 1 $jdata"; 
my $totalt = `$cmd`;
$totalt =~ /([\d\.]+)/;
$totalt = $1 / 24;
my $totalch = `$cmd`;
if ($totalch =~ /coulomb/)
{
    $totalch =~ /coulomb\s+([\d\.eE\+\-]+)/;
    $totalch = $1;
}
else
{
    $totalch = '';
}
my $totalp = `$cmd`;
if ($totalp =~ /joule/)
{
    $totalp =~ /joule\s+([\d\.eE\+\-]+)/;
    $totalp = $1/1000;
}
else
{
    $totalp = '';
}
my $maxcurrent = &get_max_current;
my $maxpower = &get_max_power;
my $minASR = &get_min_r('ASR_corr',$rig,'850');
my $minRse = &get_min_r('R_secant',$rig,'850');
my $minASR750 = `/usr/local/bin/get_ASR_750 $rig $testno --flow850`;
chomp $minASR750;
if ($minASR750 =~ /\-32768|found/)
{ 
    $minASR750 = 0;
}
my $string = `/usr/local/bin/get_leak_iv $rig $testno --flow`;
my ($minleakin,$minleak,$minleakout) = (0,0,0);
($minleakin,$minleak,$minleakout) = split(/\s+/,$string) if ($string && $string =~ /\d/);
if ($minleak =~ /\-32768/)
{ 
    $minleak = 0;
}
if ($minleakin =~ /\-32768/)
{ 
    $minleakin = 0;
}
if ($minleakout =~ /\-32768/)
{ 
    $minleakout = 0;
}

print &start_table('Overview of test','l','l');
print &hline;
print &row("Test period: yyyy:mm:dd - yyyy:mm:dd","$startt - $endt");
print &hline;
print &row("Total test time",sprintf("%6.1f days",$totalt));
print &hline;
if ($totalch > 10000)
{
    $totalch = $totalch / 1000;
    $totalch = sprintf("%8.1f kC",$totalch);
}
else
{
    $totalch = sprintf("%8.1f C",$totalch);
}
print &row("Total charge passed:",$totalch);
print &hline;
print &row("Total energy produced:",sprintf("%6.1f kJ",$totalp));
print &hline;
print &row("Maximum current, maximum power",sprintf("%5.1f A  %5.2f W",$maxcurrent,$maxpower));
print &hline;
print &hline;
print &row("850 C",' ');
print &hline;
if ($minleak > 0)
{
    $minleak = sprintf("%8.3f A",$minleak);
}
else
{
    $minleak = ' ';
}
print &row("Minimum cell leak current (if electronic leak):",$minleak);
print &hline;
if ($minleakin > 0)
{
    $minleakin = sprintf("%8.3f A",$minleakin);
}
else
{
    $minleakin = ' ';
}
print &row("Minimum O2in leak current (if electronic leak):",$minleakin);
print &hline;
if ($minleakout > 0)
{
    $minleakout = sprintf("%8.3f A",$minleakout);
}
else
{
    $minleakout = ' ';
}
print &row("Minimum O2out leak current (if electronic leak):",$minleakout);
print &hline;
if (defined($minRse) && $minRse && $minRse > 0)
{
    $minRse = sprintf("%8.3f",$minRse).' $\Omega$*cm$^2$';
}
else
{
    $minRse = ' ';
}
print &row("Minimum cell resistance (secant resistance):",$minRse);
print &hline;
if (defined($minASR) && $minASR && $minASR > 0)
{
    $minASR = sprintf("%8.3f",$minASR).' $\Omega$*cm$^2$';
}
else
{
    $minASR = ' ';
}
print &row("Minimum cell resistance (corrected for FU):",$minASR);
if (defined($minASR750) && $minASR750 && $minASR750 > 0)
{
    $minASR750 = sprintf("%8.3f",$minASR750).' $\Omega$*cm$^2$';
}
else
{
    $minASR750 = ' ';
}
print &row("Minimum cell resistance at 750 mV (corrected for FU):",$minASR750);
print &hline;
$minASR = &get_min_r('ASR_corr',$rig,'800');
$minRse = &get_min_r('R_secant',$rig,'800');
$minASR750 = `/usr/local/bin/get_ASR_750 $rig $testno --flow800`;
chomp $minASR750;
if ($minASR750 && $minASR750 =~ /\-32768|found/)
{ 
    $minASR750 = 0;
}
print &hline;
print &row("800 C",' ');
print &hline;
if (defined($minRse) && $minRse && $minRse > 0)
{
    $minRse = sprintf("%8.3f",$minRse).' $\Omega$*cm$^2$';
}
else
{
    $minRse = ' ';
}
print &row("Minimum cell resistance (secant resistance):",$minRse);
print &hline;
if (defined($minASR) && $minASR && $minASR > 0)
{
    $minASR = sprintf("%8.3f",$minASR).' $\Omega$*cm$^2$';
}
else
{
    $minASR = ' ';
}
print &row("Minimum cell resistance (corrected for FU):",$minASR);
if (defined($minASR750) && $minASR750 && $minASR750 > 0)
{
    $minASR750 = sprintf("%8.3f",$minASR750).' $\Omega$*cm$^2$';
}
else
{
    $minASR750 = ' ';
}
print &row("Minimum cell resistance at 750 mV (corrected for FU):",$minASR750);
print &hline;
$minASR = &get_min_r('ASR_corr',$rig,'750');
$minRse = &get_min_r('R_secant',$rig,'750');
$minASR750 = `/usr/local/bin/get_ASR_750 $rig $testno --flow750`;
chomp $minASR750;
if ($minASR750 =~ /\-32768|found/)
{ 
    $minASR750 = 0;
}
print &hline;
print &row("750 C",' ');
print &hline;
if (defined($minRse) && $minRse && $minRse > 0)
{
    $minRse = sprintf("%8.3f",$minRse).' $\Omega$*cm$^2$';
}
else
{
    $minRse = ' ';
}
print &row("Minimum cell resistance (secant resistance):",$minRse);
print &hline;
if (defined($minASR) && $minASR && $minASR > 0)
{
    $minASR = sprintf("%8.3f",$minASR).' $\Omega$*cm$^2$';
}
else
{
    $minASR = ' ';
}
print &row("Minimum cell resistance (corrected for FU):",$minASR);
if (defined($minASR750) && $minASR750 && $minASR750 > 0)
{
    $minASR750 = sprintf("%8.3f",$minASR750).' $\Omega$*cm$^2$';
}
else
{
    $minASR750 = ' ';
}
print &row("Minimum cell resistance at 750 mV (corrected for FU):",$minASR750);
print &hline;
print &hline;
print &row('\bf{Experiemnts}',' ');
print &hline;
my $file = $ivpsdir;
$file = &get_path.'iv/ivtable';
my @list = ();
if (-e $file)
{
    open MYIN,'<',$file or die "Could not open file $file for reading!\n";
    @list = <MYIN>;
    close MYIN;
}
my $totaliv = scalar(@list);

print &row("Total number of i-V curves run:",' '.$totaliv);
print &hline;
my $longterm = &is_long_term;
print &row("Long term test under constant conditions",' '.$longterm);
print &hline;
if ($longterm =~ /YES/)
{
    my $file = &get_path.'degradation';
    my $str = `/bin/cat $file`;
    $str =~ /Degradation: (\-*\d+)/;
    my $degr = $1+0;
    $str =~ /Start: (\d+)/;
    my $startt = $1;
    $str =~ /End: (\d+)/;
    my $endt = $1;
    print &row("Degradation rate ($startt h - $endt h)",$degr.' $\mu$V/h');
    print &hline;
    $file = &get_path.'degradation_300_1500.txt';
    if (-e($file))
    {
	open MYIN, '<', $file or die "Could not open file $file $!";
	while (my $str = <MYIN>)
	{
	    if ($str =~ /^(\d+).*\: ([\-\.\d]+) myV/)
	    {
		my $time = $1;
		my $degr = $2;
		$degr =~ /(\-*\d+)/;
		$degr = $1;
		$str =~ /\((\d+)/;
		my $startt = $1;
		$str =~ /(\d+) h\)/;
		my $endt = $1;
		print &row("Degradation rate during first $time hours ($startt - $endt h)",$degr.' $\mu$V/h');
		&hline;
	    }
	}
	close MYIN;
    }
}
if ($tempvar =~ /yes/i)
{
    my $Ea = `/usr/local/bin/get_Ea.pl $rig $testno`;
    chomp $Ea;
    $Ea =~ s/Ea:\s*//; 
    print &row("Activation energy at 750 mV",$Ea);
    print &hline;
}
print &row("Impedance spectroscopy",' '.$impedance);
print &hline;
if ($impedance)
{
    my $count = 0;
    my $f = &get_path.'impedance/imp_data';
    if (-e $f)
    {
	open MYIN,'<',$f or die "Could not open file $f $!";
	while (<MYIN>)
	{
	    $count++;
	}
	close MYIN;
    }
    print &row("Number of impedance spectra",' '.$count);
    print &hline;
}
my $fingerprint = &is_fingerprint;
print &row("Fingerprint investigation",' '.$fingerprint);
print &hline;

print &end_table('overview-tabel');


if ($impedance =~/YES/)
{
    &get_imp_numbers('impedance_numbers','numbers of impedance spectra to be included in long term test figure:') if (!$remake);
    &get_imp_numbers('drywet850.txt','numbers of 2 impedance spectra aquired in moist (5% H2O) and wet (20% H2O) hydrogen at 850 C:') if (!$remake);
    &get_imp_numbers('drywet750.txt','numbers of 2 impedance spectra aquired in moist (5% H2O) and wet (20% H2O) hydrogen at 750 C:') if (!$remake);
}

###### Print long information which could not be in table #####

if ($tkeyword)
{
    print '\subsection{Production keywords}',"\n";
    print '\label{keyword}',"\n";
    $keywords =~ s/\_/\\\_/g;
    print $keywords;
    print "\n\n";
}

if ($ttestplan)
{
    print '\subsection{Testplan}',"\n";
    print '\label{testplan}',"\n";
    $testplan =~ s/\_/\\\_/g;
    print $testplan;
    print "\n\n";
}



print '\clearpage'."\n";
print &my_section('Results');


$file =  $psdir.'cell_voltage.eps';
&print_figure($file,"Cell voltage for cell $cell.",'Cell_volt',0.75);
print "\n\n";


$file = $psdir.'multi.ps';
if (-e $file)
{
    &print_figure($file,"Overview of test history and gas flows for cell $cell.",'history',0.85);    
}

print '\clearpage'."\n";

#### Inserting leak figures ###
if ($isleak)
{
    my $leakdir = &get_path.'leak/';
    my $leakpsdir = $leakdir.'ps/';
    print &my_section('Leak investigation');
    print "Figure ",&ref('leak_h2_var')," and ",&ref('leak_air_var')," shows the leak current as a function of hydrogen and air flow. Only positive leak currents are reported, so in case one or more of the different leaks are missing it may be due to negative leaks.\n\n";
    my $h2file = $leakpsdir.'leak_h2var.ps';
    my $airfile = $leakpsdir.'leak_airvar.ps';
    if (-e $h2file  && -s $h2file)
    {
	my $f = $leakdir.'constair';
	my $line = `/usr/bin/head -1 $f`;
	my $temp = 0;
	if ($line && $line =~ /\s+T\s+(\d+)/)
	{
	    $temp = $1+0;
	}
	&print_figure($h2file,"Leak current as a function of hydrogen flow at $temp C.",'leak_h2_var',0.9);
    }
    if (-e $airfile  && -s $airfile)
    {
	my $f = $leakdir.'consth2';
	my $line = `/usr/bin/head -1 $f`;
	my $temp = 0;
	if ($line && $line =~ /\s+T\s+(\d+)/)
	{
	    $temp = $1+0;
	}
	&print_figure($airfile,"Leak current as a function of air flow at $temp C.",'leak_air_var',0.9);
    }
    print '\clearpage'."\n";
}


if ($isiv =~ /YES/)
{
    print &my_section('Representative i-V curves');
    $file = $psdir.'iv-fig4.ps';
    my $file2 = $psdir.'ASR-fig4.ps';
    if (-e $file  && -s $file)
    {
	my $temp = &get_temp_fig($file2);
	&print_figure($file,"i-V curves obtained at $temp C at the beginning and end of the test of cell $cell \(best i-V curve also shown\).",'first-best-last-iv');     
	my $fig = &ref('first-best-last-iv');
	if (-e $file2  && -s $file2)
	{
	    my $fig = &ref('first-best-last-iv');
	    &print_figure($file2,"Area specific cell resistance corrected for fuel utilisation for the i-V curves shown in figure $fig.",'first-best-last-ASR');    
	}
    }    
### indsaet tabel #####
    print '\clearpage'."\n";
    my $ivtabel = &get_path.'iv/ivtable.tex';
    if (-e $ivtabel  && -s $ivtabel)
    {
	my $show = 0;
	my $count = 0;
	open MYIN,'<',$ivtabel or die "Could not open ivtable $ivtabel";
	while (my $line = <MYIN>)
	{
	    if ($line =~ /\\begin\{sidewaystable\}/)
	    {
		$show = 1;
	    }
	    print $line if ($show);;
	    if ($line =~ /\\end\{sidewaystable\}/)
	    {
		$show = 0;
		$count++;
		if ($count > 4)
                {
                    print '\clearpage'."\n";
                    $count = 0;
                }
	    }
	}
	close MYIN;
    } 
    if ($fuelflowvar =~ /YES/)
    {
	print &my_subsection('Fuel flow variations in the beginning of the test');
	
	$file = $psdir.'iv-H_2.ps';
	$file2 = $psdir.'ASR-H_2.ps';
	my $temp = &get_fueltemp;
	my $time = &get_fueltime;
	my $fig1 = &ref('history');
	my $airflow = &get_air_fuelvar;
	if ($airflow =~ /\d+\.\d+/)
	{
	    $airflow =~ /(\d+\.\d)/;
	    $airflow = $1;
	}
	$airflow = $airflow. ' L/h';
	my $timestr = "The data was obtained after $time hours \(figure $fig1\).";
	if (-e $file  && -s $file)
	{
	    &print_figure($file,"i-V curves obtained at diferent hydrogen flows at $temp C at the beginning of the test of cell $cell. $timestr The airflow was $airflow.",'iv-var-h2flow',0.95);    
	    my $fig = &ref('iv-var-h2flow');
	    if (-e $file2  && -s $file2)
	    {
		&print_figure($file2,"Area specific cell resistance corrected for fuel utilisation for the i-V curves shown in figure $fig. $timestr The airflow was $airflow.",'ASR-var-h2flow');
	    }
	}
	$file = $ivpsdir.'fuel_flow_variation_R_imax_etc.ps';
	if (-e $file  && -s $file)
	{
	    &print_figure($file,"Secant resistance at different hydrogen flows cor cell $cell. The temperature is $temp C. $timestr The airflow was $airflow.",'R-plot-h2flow');
	}
    }
    
    if ($airflowvar =~ /YES/i)
    {
	print &my_subsection('Air flow variations in the beginning of the test');
	my $fig1 = &ref('history');
	$file = $psdir.'iv-Air.ps';
	$file2 = $psdir.'ASR-Air.ps';
	my $time = &get_airtime;
	my $timestr = "The data was obtained after $time hours \(figure $fig1\).";
	my $temp = &get_airtemp;
	my $fuelflow = &get_fuel_airvar;
	if ($fuelflow =~ /\d+\.\d+/)
	{
	    $fuelflow =~ /(\d+\.\d)/;
	    $fuelflow = $1;
	}
	$fuelflow = $fuelflow . ' L/h';
	
	if (-e $file  && -s $file)
	{
	    &print_figure($file,"i-V curves obtained at diferent air flows at $temp C at the beginning of the test of cell $cell. $timestr The hydrogen flow was $fuelflow.",'iv-var-Airflow',0.95);    
	    my $fig = &ref('iv-var-Airflow');
	    if (-e $file2  && -s $file2)
	    {
		&print_figure($file2,"Area specific cell resistance corrected for fuel utilisation for the i-V curves shown in figure $fig. $timestr  The hydrogen flow was $fuelflow.",'ASR-var-Airflow');    
	    }
	}
	$file = $ivpsdir.'air_flow_variation_R_imax_etc.ps';
	if (-e $file  && -s $file)
	{
	    &print_figure($file,"Secant resistance at different air flows cor cell $cell. The temperature is $temp C. $timestr  The hydrogen flow was $fuelflow.",'R-plot-airflow');
	}
    }

    ###### dry and wet i-v curves ######
    print '\clearpage'."\n";
    $file = &get_path.'iv/drywet-iv';
    if (-e $file  && -s $file)
    {
	print &my_subsection('i-V curves in moist and wet hydrogen');
	$file = $psdir.'iv-drywet.ps';
	if (-e $file  && -s $file)
	{
	    &print_figure($file,"i-V curves at obtained in hydrogen with aproximately 5\\\% and 20\\\% water).",'iv-drywet',0.9);
	}
	$file = $psdir.'R_s-drywet.ps';
	if (-e $file && -s $file)
	{
	    &print_figure($file,"Secant resistance for the i-V curves shown in figure ".&ref('iv-drywet').".",'Rs-drywet');
	}
	$file = $psdir.'ASR-drywet.ps';
	if (-e $file && -s $file)
	{
	    &print_figure($file,"Area specific cell resistance corrected for fuel utilisation for the i-V curves shown in figure ".&ref('iv-drywet').".",'ASR-drywet');
	}
    }
    ##### Temperature variation ####
    if ($tempvar =~ /YES/i)
    {
	print &my_section('Temperatuture variation');
	my $fuelflow = &get_temp_fuel;
	if ($fuelflow =~ /\d+\.\d+/)
	{
	    $fuelflow =~ /(\d+\.\d)/;
	    $fuelflow = $1;
	}
	my $airflow = &get_temp_air;
	if ($airflow =~ /\d+\.\d+/)
	{
	    $airflow =~ /(\d+\.\d)/;
	    $airflow = $1;
	}
	$file = $psdir.'iv-temp-var.ps';
	my $flowst = "The hydrogen flow was $fuelflow L/h and the airflow was $airflow L/h.";
	if (-e $file && -s $file)
	{
	    &print_figure($file,"i-V curves obtained at different temperatures. $flowst",'iv-temp-var');
	}
	
	$file = $psdir.'ASR-temp-var.ps';
	if (-e $file && -s $file)
	{
	    my $fig = &ref('iv-temp-var');
	    &print_figure($file,"Area specific cell resistance corrected for fuel utilisation obtained at different temperatures \(same i-V curves as in figure $fig\).",'ASR-temp-var');
	}
	$file = $ivpsdir.'arrhenius_rminvalues.ps';
	if (-e $file && -s $file)
	{
	    &print_figure($file,"Fuel utilisation corrected cell resistance as a function of temperature for cell $cell. $flowst. Note that the activation energ is calculated based on the minimum cell resistance at each temperature.",'Arrenius');
	}
    }
    print '\clearpage'."\n";
}




###### Long term test #############

if (&is_long_term =~ /YES/)
{
    print &my_section('Long term test');
    my $file = &get_path.'degradation';
    my $str = `/bin/cat $file`;
    $str =~ /Start: (\d+)/;
    my $st = $1+0;
    $str =~ /h End: (\d+)/;
    my $et = $1+0;
    $str =~ /Start: ([\d\.\-]+) mV/;
    my $sU = $1+0;
    $str =~ /End: ([\d\.\-]+) mV/;
    my $eU = $1+0;
    $str =~ /Degradation: ([\d\.\-]+)/;
    my $degr = $1+0;
    my $dt = $et - $st;
    my $tot = int($totalt);
    my $current = &get_current_at_time($st);
    my $area = &AFM::get_config_value_old($rig,'area',$testno);
    $area = &AFM::get_usercv_test($rig,$testno,'main','cell_area') unless ($area);
    my $cd = $current / $area;
    $cd = &format_number($cd,2);
    print "The cell was tested for $tot days and the degradation rate was $degr \$\\mu\$V/h as determined between $st and $et hours. The cell voltage was $sU mV in the beginning and $eU after $dt hours at $cd A/cm\$\^2\$\n";  
    
    $file = 'multi-res-at_current*';
    my $command = "/bin/ls $psdir".$file;
    my @files = `$command`;
    for my $str (@files)
    {
	$file = $str if ($str =~ /current_\d+_\d+\.ps/);
    }
    chomp $file;
    $file =~ /current_(\d+_\d+)/;
    $current = $1;
    $current =~ s/_/\./;
    if (-e($file))
    {
	&print_figure($file,"Secant cell resistance at density of $current A/cm\$\^2\$ as a function of time",'R-vs-tid-multi',0.85); 
    }
    print '\clearpage'."\n";
}

##### Impedance section added in version 2 #####

if ($impedance =~ /YES/)
{
    my $dir = &get_path.'impedance/';
    my $impdir = $dir;
    open MYIN,'<',$impdir.'imp_data' or die "Could not open file ".$impdir.'imp_data '.$!;
    my @lines = <MYIN>;
    close MYIN;
    print &my_section('Impedance');
    print "This appendix contains some of the impedance spectra obtained for cell $cell.\n\n";
    print "Be advised that the Rp values given is the real part of the measured impedance at the lowest frequency. If the impedance curve does not teerminate at the real axis, the Rp value given will be wrong!\n\n";
    $dir = $dir.'ps/';
    my $area = &AFM::get_usercv_test($rig,$testno,'main','cell_area');
    $area = &AFM::get_config_value_old($rig,'area',$testno) unless ($area);
    my $dw850 = $impdir.'drywet850.txt';
    if (-e($dw850))
    {
	my @list = `/bin/cat $dw850`;
	my @flist = ();
	for my $st (@list)
	{
	    chomp $st;
	    my $str = $lines[$st-1];
	    $str =~ /^\s*([\w\.\-\:]+)\s+/;
	    push @flist, $1;
	}
	if (-d $analytic_dir)
	{
	    my $cmd = "/usr/local/bin/celltest/imp_multiplot_analytic.pl $rig $testno $area ";
	    $cmd .= $flist[0].' "['.$list[0].'] 850 C - H2 \(5%H2O\)" ';
	    $cmd .= $flist[1].' "['.$list[1].'] 850 C - H2 \(20%H2O\)"';
	    system($cmd);
	}
	else
	{
	    my $cmd = "/usr/local/bin/impedance_multiplot.pl $rig $testno $area".'ASRDEC4lines ';
	    $cmd .= $flist[0].' "\['.$list[0].'\] 850 C, H_2 (5\%H_2O)" ';
	    $cmd .= $flist[1].' "\['.$list[1].'\] 850 C, H_2 (20\%H_2O)" --BV';
	    system($cmd);
	}
	for (my $x = 0; $x < @flist; $x++)
	{
	    $flist[$x] =~ /^([\w\.\-\:]+)\.\w+$/;
	    $flist[$x] = $1;
	}
	my $psfile = $dir.$flist[0].$flist[1].'-impedance.ps';
	if (-d $analytic_dir)
	{
	    if (-e($psfile))
	    {
		&print_figure_imp_new($psfile,'Impedance spectra for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 850 C. Numbers in square brackets denote the impedance spectrum used.','imp-dw-850',0.9);
	    }
	    $psfile = $dir.$flist[0].$flist[1].'-bode.ps';
	    if (-e($psfile))
	    {
		&print_figure_imp_new($psfile,'Bode plot for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 850 C. Numbers in square brackets denote the impedance spectrum used.','bode-dw-850',0.9);
	    }
	}
	else
	{
	    if (-e($psfile))
	    {
		&print_figure_imp($psfile,'Impedance spectra for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 850 C. Numbers in square brackets denote the impedance spectrum used.','imp-dw-850',0.9);
	    }
	    $psfile = $dir.$flist[0].$flist[1].'-bode.ps';
	    if (-e($psfile))
	    {
		&print_figure_imp($psfile,'Bode plot for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 850 C. Numbers in square brackets denote the impedance spectrum used.','bode-dw-850',0.9);
	    }
	}
    }   
    print '\clearpage'."\n";
    my $imptable = $impdir.'impedancetable.tex';
    if (-e($imptable))
    {
	my $show = 0;
	open MYIN,'<',$imptable or die &errorlog("Could not open $imptable");
	my @tlines = <MYIN>;
	close MYIN;
	for (my $x = 0; $x < scalar(@tlines); $x++)
	{
#	    $tlines[$x] =~ s/_/\\_/g;
	    if ($tlines[$x] =~ /\\begin\{sidewaystable\}/)
	    {
		$show = 1;
	    }
	    print $tlines[$x] if ($show);
	    if ($tlines[$x] =~ /\\end\{sidewaystable\}/)
	    {
		$show = 0;
		print '\clearpage',"\n";
	    }
	}
    }
    warn "##### Creating impedance plot for constant current ####\n"; 
    my $freqs = &input_information('frequencies (xxxx:xxxx:xxx... ), return for default','IMPFREQS');
    $cmd = "/usr/local/bin/plot_current_imp.pl $rig $testno $freqs";
    system($cmd);
    my $psfile = $impdir.'ps/impedance_vs_time.ps';
    if (-e($psfile))
    {
	my $factor = 1/$area;
	&print_figure_imp($psfile,'Impedance data for cell '.$cell.' at current densities above '.$factor.' A/cm$^2$. Note that the data points are not at the exact threshold frequencies, but for the first frequency below.','imp-current',0.9);
	print '\clearpage'."\n";
    }
    my $dw750 = $impdir.'drywet750.txt';
    if (-e($dw750))
    {
	my @list = `/bin/cat $dw750`;
	my @flist = ();
	for my $st (@list)
	{
	    chomp $st;
	    my $str = $lines[$st-1];
	    $str =~ /^\s*([\w\.\-\:]+)\s+/;
	    push @flist, $1;
	}
	if (-d $analytic_dir)
	{
	    my $cmd = "/usr/local/bin/celltest/imp_multiplot_analytic.pl $rig $testno $area ";
	    $cmd .= $flist[0].' "['.$list[0].'] 750 C - H2 \(5%H2O\)" ';
	    $cmd .= $flist[1].' "['.$list[1].'] 750 C - H2 \(20%H2O\)"';
	    system($cmd);
	}
	else
	{
	    my $cmd = "/usr/local/bin/impedance_multiplot.pl $rig $testno $area".'ASRDEC4lines ';
	    $cmd .= $flist[0].' "\['.$list[0].'\] 750 C, H_2 (5\%H_2O)" ';
	    $cmd .= $flist[1].' "\['.$list[1].'\] 750 C, H_2 (20\%H_2O)" --BV';
	    system($cmd);
	}
	for (my $x = 0; $x < @list; $x++)
	{
	    $flist[$x] =~ /^([\w\-\:\.]+)\.\w+$/;
	    $flist[$x] = $1;
	}
	my $psfile = $dir.$flist[0].$flist[1].'-impedance.ps';
	if (-d $analytic_dir)
	{
	    if (-e($psfile))
	    {
		&print_figure_imp_new($psfile,'Impedance spectra for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 750 C. Numbers in square brackets denote the impedance spectra used.','imp-dw-750',0.7);
	    }
	    $psfile = $dir.$flist[0].$flist[1].'-bode.ps';
	    if (-e($psfile))
	    {
		&print_figure_imp_new($psfile,'Bode plot for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 850 C. Numbers in square brackets denote the impedance spectrum used.','bode-dw-750',0.7);
	    }
	}
	else
	{
	    if (-e($psfile))
	    {
		&print_figure_imp($psfile,'Impedance spectra for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 750 C. Numbers in square brackets denote the impedance spectra used.','imp-dw-750',0.7);
	    }
	    $psfile = $dir.$flist[0].$flist[1].'-bode.ps';
	    if (-e($psfile))
	    {
		&print_figure_imp($psfile,'Bode plot for cell '.$cell.' in hydrogen with 5 and 20 \% H$_2$O at 850 C. Numbers in square brackets denote the impedance spectrum used.','bode-dw-750',0.7);
	    }	    
	}
    }   
    my $ltimp = $impdir.'impedance_numbers';
    if (-e($ltimp))
    {
	my @list = `/bin/cat $ltimp`;
	my @flist = ();
	my @ftime = ();
	for my $st (@list)
	{
	    chomp $st;
	    my $str = $lines[$st-1];
	    $str =~ /^\s*([\w\.\-\:]+)\s+/;
	    push @flist, $1;
	    $str =~ /Time\:(\d+)/;
	    push @ftime,$1; 
	}
	if (-d $analytic_dir)
	{
	    my $cmd = "/usr/local/bin/celltest/imp_multiplot_analytic.pl $rig $testno $area ";
	    for (my $x = 0; $x < @list; $x++)
	    {
		$cmd .= $flist[$x].' "['. $list[$x] .'] '.$ftime[$x]. 'h" ';
	    }
	    system($cmd);
	}
	else
	{
	    my $cmd = "/usr/local/bin/impedance_multiplot.pl $rig $testno $area".'ASRDEC4lines ';
	    for (my $x = 0; $x < @list; $x++)
	    {
		$cmd .= $flist[$x].' "\['. $list[$x] .'\] '.$ftime[$x]. 'h" ';
	    }
	    $cmd .= '--BV';
	    system($cmd);
	}
	for (my $x = 0; $x < @flist; $x++)
	{
	    $flist[$x] =~ /^([\w\-\:\.]+)\.\w+$/;
	    $flist[$x] = $1;
	}
	my $psfile = $dir.$flist[0].$flist[1].'-impedance.ps';
	if (-d $analytic_dir)
	{
	    if (-e($psfile))
	    {
		&print_figure_imp_new($psfile,'Impedance spectra for cell '.$cell.' at different times durring the test. Numbers in square brackets denote the impedance spectra used.','imp-lt',0.7);
	    }
	    $psfile = $dir.$flist[0].$flist[1].'-bode.ps';
	    if (-e($psfile))
	    {
		&print_figure_imp_new($psfile,'Bode plot for cell '.$cell.' at different times durring the test. Numbers in square brackets denote the impedance spectra used.','bode-lt',0.7);
	    }
	}
	else
	{
	    if (-e($psfile))
	    {
		&print_figure_imp($psfile,'Impedance spectra for cell '.$cell.' at different times durring the test. Numbers in square brackets denote the impedance spectra used.','imp-lt',0.7);
	    }
	    $psfile = $dir.$flist[0].$flist[1].'-bode.ps';
	    if (-e($psfile))
	    {
		&print_figure_imp($psfile,'Bode plot for cell '.$cell.' at different times durring the test. Numbers in square brackets denote the impedance spectra used.','bode-lt',0.7);
	    }	    
	}
    }   
    print '\clearpage'."\n";
}

########### Exit if short version #####
if ($short)
{
    print &end_document;
    exit;
}

##############  Printing appedix #########

print '\clearpage'."\n";
my $app = 0;
if (-e($infofile))
{
    $app = 1;
    print "\n\n",'\appendix',"\n\n";
    my $server = `/bin/hostname`;
    print &my_section("Cell information file for cell $cell",'infofile');
    print "The file is located at $infofile on $server\n\n";
    print '\vspace{1cm}',"\n";
    print '\begin{verbatim}',"\n";
    open MYCMD,'<',$infofile or die "Could not open file '$infofile' $!";
    my @lines = <MYCMD>;
    close MYCMD;
    my $count = 0;
    for my $st (@lines)
    {
	$count++;
	if ($count > 1000)
	{
	    print '\end{verbatim}',"\n";
	    print '\clearpage'."\n";
	    print '\begin{verbatim}',"\n";
	    $count = 0;
	}
	chomp $st;
	chomp $st;
	next unless ($st);
	$st =~ s/_/\_/g;
	while (length($st) > 70)
	{	    
	    $st =~ s/(.{70})//;
	    print $1,"\n";
	}
	print $st,"\n";
    }
    print '\end{verbatim}',"\n";
}
    
$infofile =~ s/info\.txt/proglog/; 
if (-e($infofile))
{
    print &my_section("Command log for cell $cell",'cmdlog');
    print "The file is located at $infofile on $server\n\n";
    print '\vspace{1cm}',"\n";
    print '\begin{verbatim}',"\n";
    open MYCMD,'<',$infofile or die "Could not open file '$infofile' $!";
    my @lines = <MYCMD>;
    close MYCMD;
    my $count = 0;
    for my $st (@lines)
    {
	$count++;
	if ($count > 1000)
	{
	    print '\end{verbatim}',"\n";
	    print '\clearpage'."\n";
	    print '\begin{verbatim}',"\n";
	    $count = 0;
	}
	chomp $st;
	chomp $st;
	next unless ($st);
	$st =~ s/_/\_/g;
	while (length($st) > 70)
	{	    
	    $st =~ s/(.{70})//;
	    print $1,"\n";
	}
	print $st,"\n";
    }
    print '\end{verbatim}',"\n";
}

print '\clearpage'."\n";

#### Making impedance section and plots #####
if ($impedance =~ /YES/)
{
    my $dir = &get_path.'impedance/';
    my $impdir = $dir;

    if (!$app)
    {
	$app = 1;
	print "\n\n",'\appendix',"\n\n";
    }
    my $cmd = "/bin/cat $impdir".'imp_data'; 
    my @lines = `$cmd`;
    print &my_section('Detailed impedance data');
    print "This appendix contains some of the impedance spectra obtained for cell $cell.\n\n";

    print "Be advised that the Rp values given is the real part of the measured impedance at the lowest frequency. If the impedance curve does not teerminate at the real axis, the Rp value given will be wrong!\n\n";

    $dir = $dir.'ps/';
    my %h = ();
    my $impnumber = &get_path.'impedance/impedance_numbers';
    if (-e($impnumber))
    {
	open MYIN,'<',$impnumber or die &errorlog("Could not open $impnumber");
	my @impnumbers = <MYIN>;
	close MYIN;
	for my $st (@impnumbers)
	{
	    $h{$st} = $st;
	}
    }
    $impnumber = &get_path.'impedance/drywet850.txt';
    if (-e($impnumber))
    {
	open MYIN,'<',$impnumber or die &errorlog("Could not open $impnumber");
	my @impnumbers = <MYIN>;
	close MYIN;
	for my $st (@impnumbers)
	{
	    $h{$st} = $st;
	}
    }
    $impnumber = &get_path.'impedance/drywet750.txt';
    if (-e($impnumber))
    {
	open MYIN,'<',$impnumber or die &errorlog("Could not open $impnumber");
	my @impnumbers = <MYIN>;
	close MYIN;
	for my $st (@impnumbers)
	{
	    $h{$st} = $st;
	}
    }
    my @impnumbers = ();
    for my $key (sort keys %h)
    {
	push @impnumbers,$key;
    }
    my @files = `$cmd`;
    my $cc = 0;
    my $count = 3;
    print '\clearpage'."\n";
    for my $n (@impnumbers)
    {
	$n += 0;
	if ($count > 3)
	{
	    print '\clearpage'."\n";
	    $count = 0;
	}
	if ($cc == 1)
	{
	    my $imptable = $impdir.'impedancetable.tex';
	    if (-e($imptable))
	    {
		my $show = 0;
		open MYIN,'<',$imptable or die &errorlog("Could not open $imptable");
		my @tlines = <MYIN>;
		close MYIN;
		for (my $x = 0; $x < scalar(@tlines); $x++)
		{
#		    $tlines[$x] =~ s/_/\\_/g;
		    if ($tlines[$x] =~ /\\begin\{sidewaystable\}/)
		    {
			$show = 1;
		    }
		    print $tlines[$x] if ($show);
		    if ($tlines[$x] =~ /\\end\{sidewaystable\}/)
		    {
			$show = 0;
			print '\clearpage'."\n";
		    }
		}
	    }
	    print '\clearpage'."\n";
	}
	$lines[$n-1] =~ /\s*([\d\w\.]+)/;
	my $name = $1;
	my $file = &get_path.'impedance/ps/'.$name;
	$file =~ s/\.i2b/\-impedance\.ps/i;
	chomp $file;
	if (-e($file))
	{
	    my $info_str = '';
	    my $f = &get_path.'impedance/'.$name;
	    open MYIN,'<',$f or die &errorlog("Could not open $f");
	    my @list = <MYIN>;
	    close MYIN;
	    for (my $z = 0; $z < 7 ; $z++)
	    {
		if ($list[$z] =~ /\#(.*)$/)
		{
		    my $s = $1;
		    chomp $s;
		    $info_str = $info_str.$s;
		}
	    }
	    $info_str = 'Info: '.$info_str.'.' unless ($info_str eq '');
	    chomp $name;
	    my $flowst =  $lines[$n-1];
	    $flowst =~ s/_/\\_/g;
	    chomp $flowst;
	    &print_figure_imp($file,"Impedance spectra for cell $cell (file nr $n, $flowst). $info_str",$name,0.7);
	}
	$count++;
	$cc++;
    }
}


print '\clearpage'."\n";

if (!$app)
{
    $app = 1;
    print "\n\n",'\appendix',"\n\n";
}
print &my_section('Startup and end');

$file =  $psdir.'cell_voltage.eps';
&print_figure($file,"Cell voltage versus time for cell $cell,(same as figure".&ref('Cell_volt'),'cell_volt2',0.9);

$file = $psdir.'multi-emf_0_50.ps';
if (-e($file))
{
    &print_figure($file,"Cell voltage, temperature and oxygen potential of the inlet and outlet gas during the first 50 hours of the test of $cell.",'start-emf',0.85);
}

$cmd = "/bin/ls -1B $psdir".'multi-emf*';
my @files = `$cmd`;
my $countfig = 0;
for my $str (@files)
{
    $countfig++;
    if ($str =~ /multi-emf_\d+_0/)
    {
	chomp $str;
	if (-e($str))
	{
	    &print_figure($str,"Cell voltage, temperature and oxygen potential of the inlet and outlet gas during the end of the test of $cell.",'end-emf'.$countfig,0.85);
	} 
    }
}

print '\clearpage'."\n";
print &my_section('long term test');

$file = $psdir.'Akk_Pt_Voltage.eps';
if (-e($file))
{
    &print_figure($file,"Voltage difference between Akk and metal foil on the anode side for cell $cell.",'Akk_Pt_volt',0.75);
}
else
{
    print ".\n\n";
}

$file = $psdir.'inplane_V_hydrogen.eps';
if (-e($file))
{
    &print_figure($file,"In-plane voltage along the metal foil on the hydrogen side of the cell $cell.",'in_plane_hydrogen',0.7);    
}
print "\n\n";

$file = $psdir.'multi-emf.ps';
if (-e($file))
{
    &print_figure($file,"Overview of test history and oxygen potentials for cell $cell.",'multi_emf',0.85);    
}

$file = $psdir.'multi-sec-res-start.ps';
if (-e($file))
{
    &print_figure($file,"Cell resistance at low current as a function of time",'Rstart-vs-tid-multi',0.85); 
}

$file = $psdir.'multi-sec-res-min.ps';
if (-e($file))
{
    &print_figure($file,"Minimum cell resistance as a function of time",'Rmin-vs-tid-multi',0.85); 
}
    

print '\clearpage'."\n";

if ($fuelflowvar =~ /YES/)
{
    $file = $psdir.'iv-H_2.ps';
    my $file2 = $psdir.'ASR_H_2.ps';
    my $temp = &get_fueltemp;
    my $time = &get_fueltime;
    my $fig1 = &ref('history');
    my $airflow = &get_air_fuelvar;
    if ($airflow =~ /\d+\.\d+/)
    {
	$airflow =~ /(\d+\.\d)/;
	$airflow = $1;
    }
    $airflow = $airflow. ' L/h';
    my $timestr = "The data was obtained after $time hours \(figure $fig1\).";
    print &my_section('Fuel flow variation');
    $file = $psdir.'H_2_var_Airflow.ps';
    if (-e($file))
    {
	&print_figure($file,"Cell voltage at different current densities and hydrogen flows in the beginning of the test of cell $cell at $temp C. $timestr The airflow was $airflow.",'cell-volt-h2flow');
    }
    $file = $ivpsdir.'fuel_flow_variation_R_current.ps';
    if (-e($file))
    {
	&print_figure($file,"Secant resistance at different hydrogen flows and different current densities for cell $cell. The temperature is $temp C. $timestr The airflow was $airflow.",'R-plot-current-h2flow');
    }
    
    $file = $ivpsdir.'fuel_flow_variation_Power.ps';
    if (-e($file))
    {
	&print_figure($file,"Power density for cell $cell at different fuel flows. The temperature is $temp C. $timestr The airflow was $airflow.",'Power-h2flow');
    }
    
}

print '\clearpage'."\n";

if ($airflowvar =~ /YES/i)
{
    my $fig1 = &ref('history');
    $file = $psdir.'iv-Air.ps';
    my $file2 = $psdir.'ASR_Air.ps';
    my $time = &get_airtime;
    my $timestr = "The data was obtained after $time hours \(figure $fig1\).";
    my $temp = &get_airtemp;
    my $fuelflow = &get_fuel_airvar;
    if ($fuelflow =~ /\d+\.\d+/)
    {
	$fuelflow =~ /(\d+\.\d)/;
	$fuelflow = $1;
    }
    $fuelflow = $fuelflow . ' L/h';
    print &my_section('Air flow variation');
    $file = $psdir.'Air_var_H2flow.ps';
    if (-e($file))
    {
	&print_figure($file,"Cell voltage at different current densities and air flows in the beginning of the test of cell $cell at $temp C. $timestr  The hydrogen flow was $fuelflow.",'cell-volt-airflow');
    }
    $file = $ivpsdir.'air_flow_variation_R_current.ps';
    if (-e($file))
    {
	&print_figure($file,"Secant resistance at different air flows and different current densities for cell $cell. The temperature is $temp C. $timestr  The hydrogen flow was $fuelflow.",'R-plot-current-airflow');
    }
    $file = $ivpsdir.'air_flow_variation_Power.ps';
    if (-e($file))
    {
	&print_figure($file,"Power density for cell $cell at different air flows. The temperature is $temp C. $timestr The hydrogen flow was $fuelflow.",'Power-airflow');
    }
}

print '\clearpage'."\n";

if ($tempvar =~ /YES/i)
{
    my $fuelflow = &get_temp_fuel;
    if ($fuelflow =~ /\d+\.\d+/)
    {
	$fuelflow =~ /(\d+\.\d)/;
	$fuelflow = $1;
    }
    my $airflow = &get_temp_air;
    if ($airflow =~ /\d+\.\d+/)
    {
	$airflow =~ /(\d+\.\d)/;
	$airflow = $1;
    }
    $file = $psdir.'iv-temp-var.ps';
    my $flowst = "The hydrogen flow was $fuelflow L/h and the airflow was $airflow L/h.";
    print &my_section('Variation in temperature');
    $file = $ivpsdir.'temp_variation.ps';
    if (-e($file))
    {
	&print_figure($file,"Minimum area specific cell resistance as a function of temperature for cell $cell $flowst" ,'R-vs-temp');
    }
}

print '\clearpage'."\n";
print &my_section('All measured values');
$cmd = '/bin/ls -1 '.$psdir.'all/*.ps';
@list = `$cmd`;
my $count = 0;
for my $f (@list)
{
    chomp $f;
    $f =~ /([\w\-]+)\.ps$/;
    my $txt = $1;
    $txt =~ s/_//g;
    if (-e($f))
    {
	&print_figure($f,'','all_'.$f,0.9);
    }
    $count++;
    if ($count > 1)
    {
	$count = 0;
	print '\clearpage'."\n";
    }
    else
    {
	print '\vspace{1 cm}',"\n";
    }
}

print &end_document;

exit;

################################
### Normal functions  ##########
################################

sub make_impedance
{
    $cmd = "/usr/local/bin/get_impedance_data $rig $testno";
    system($cmd);
    $cmd = "/usr/local/bin/impedance_html.pl $rig $testno > /dev/null";
    system($cmd);
}


sub is_fingerprint
{
    my $res = 'YES';
    $res = ' ' unless (&is_iv);
    $res = ' ' unless (&is_fuel_var);
    $res = ' ' unless (&is_air_var);
    $res = ' ' unless (&is_tempvar);
    return $res;
}

sub is_iv
{
    my $file = &get_path.'iv/ivtable';
    return '' unless (-e $file);
    open MYIN,'<',$file or die "Coud not open file $file!\n";
    my @lines = <MYIN>;
    close MYIN;
    return 'YES' if (@lines > 0);
    return '';
}

sub is_fuel_var
{
    my $res = '';
    my $file = &get_path.'iv/ivtable_H_2_variation';
    return '' unless (-e $file);
    open MYIN,'<',$file or die "Coud not open file $file!\n";
    my @lines = <MYIN>;
    close MYIN;
    return 'YES' if (@lines > 0);
    return '';
}

sub get_air_fuelvar
{
    my $file = &get_path.'iv/plot_ivtable_sort_Air_constant/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /\s+air\s+([\d\.]+)/)
    {
	return $1;
    }
    return ' ';
}

sub get_fueltemp
{
    my $file = &get_path.'iv/plot_ivtable_sort_Air_constant/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /T_center\s+(\d+)/)
    {
	return $1;
    }
    return ' ';
}

sub get_fueltime
{
    my $file = &get_path.'iv/plot_ivtable_sort_Air_constant/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /(\d+)/)
    {
	return $1;
    }
    return ' ';
}

sub is_air_var
{
    my $file = &get_path.'iv/ivtable_Air_variation';
    return '' unless (-e $file);
    open MYIN,'<',$file or die "Coud not open file $file!\n";
    my @lines = <MYIN>;
    close MYIN;
    return 'YES' if (@lines > 0);
    return '';
}

sub get_fuel_airvar
{
    my $file = &get_path.'iv/plot_ivtable_sort_H_2_constant/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /\s+h2\s+([\d\.]+)/)
    {
	return $1;
    }
    return ' ';
}

sub get_airtemp
{
    my $file = &get_path.'iv/plot_ivtable_sort_H_2_constant/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /T_center\s+(\d+)/)
    {
	return $1;
    }
    return ' ';
}

sub get_airtime
{
    my $file = &get_path.'iv/plot_ivtable_sort_H_2_constant/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /(\d+)/)
    {
	return $1;
    }
    return ' ';
}

sub is_long_term
{
    my $file = &get_path.'degradation';
    my $res = ' ';
    if (-e($file)) {$res = 'YES';};
    return $res;
}

sub is_tempvar
{
    $file = &get_path.'iv/tempvariation';
    return '' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my @test = <MYIN>;
    close MYIN;
    return 'YES' if (@test > 1);
    return '';
}

sub get_temp_air
{
    my $file = &get_path.'iv/plot_tempvariation/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /\s+air\s+([\d\.]+)/)
    {
	return $1;
    }
    return ' ';
}

sub get_temp_fuel
{
    my $file = &get_path.'iv/plot_tempvariation/rstartvalues';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    my $test = <MYIN>;
    close MYIN;
    if ($test =~ /\s+h2\s+([\d\.]+)/)
    {
	return $1;
    }
    return ' ';
}




sub is_iv_const_fu
{
    my $res = ' ';
    $file = &get_path.'info.txt';
    return ' ' unless (-e $file);
    open MYIN ,'<', $file or die "Coudld not open file $file";
    while ((!$res) && (my $test = <MYIN>))
    {
	$res = 'YES' if ($test =~ /constant fuel ut/i);
    }
    return $res;
}


sub is_impedance
{
    ##### Search impedance dir for i2b files ####
    my $res = ' ';
    my $dir = &get_path.'impedance';
    my @r = `/bin/ls -1 $dir/*.i2b`;
    $res = 'YES' if (@r);
    @r = `/bin/ls -1 $dir/*.I2B`;
    $res = 'YES' if (@r);
    return $res;
}

sub is_currentint
{
    return ' ';
}

sub is_ocvst
{
    return ' ';  
}

sub is_other_exp
{
    my $res = &input_information('other experiements performed on this cell','OTHER');
    return $res;
}

sub is_leak
{
    my $res = 0;
    my $leakdir = &get_path.'leak/';
    if (-d($leakdir))
    {
	$res = 1;
    }
    return $res;
}

sub get_cell
{
    my $file = &get_path.'info.txt';
    my $res = `/bin/cat $file`;
    my $name = '';
    if ($res =~ /(?:Cell|Sample) number\s+:\s+([\w\-]+)/i)
    {
	$name = $1;
    }
    $name =~ s/_/\\_/g;
    return $name;
}

sub get_other_nr()
{
    my @l = ();
    my $file = &get_path.'info.txt';
    open INF,'<',$file or die "Could not open file $file $!\n";
    while (<INF>)
    {
	next unless (@l || (/^Alternate test/));
	last if (/^[\s\t]*$/);
	push @l,$_ if (/\w/);
    }
    close INF;
    my @r = ();
    foreach (@l)
    {
	if (/:[\s\t]*(.*)/)
	{
	    push @r, $1;
	}
    }
    my $str = join(', ',@r);
    $str = ' ' unless ($str);
    return &quote_chrs($str);
}

sub get_temp_fig()
{
    my $file = shift;
    $file =~ s/\/ps\//\/txt\//;
    $file =~ s/\.\w+$/\.txt/;
    my $res = 'XXX';
    if (-e($file))
    {
	$res = `/bin/cat $file`;
	$res =~ /Temperature\s*:\s*(\d+)/;
	$res = $1;
    }
    return $res;
}

sub get_time_fig()
{
    my $file = shift;
    $file =~ s/\/ps\//\/txt\//;
    $file =~ s/\.\w+$/\.txt/;
    my $res = '0';
    if (-e($file))
    {
	$res = `/bin/cat $file`;
	$res =~ /Time\s*:\s*(\d+)/;
	$res = $1;
    }
    return $res;
}

sub get_path
{
    my $dir = $RFC::Header::publicdir.'rig'.$r->name.'/'.$r->name.'test'.$testno.'/';
#    my $dir = $AFM::publicdir.'rig'.$rig.'/'.$rig.'test'.$testno.'/';
    return $dir;
}

sub get_psdir
{
    my $dir = &get_path.'ps/';
    return $dir;
}

sub get_ivpsdir
{
    my $dir = &get_path.'iv/ps/';
}


sub input_information($)
#############################################################################
### Gets user information from standard in and writes to report info file ###
### If the remake bit is set it reads the info from the report info.file  ###
#############################################################################
{
    my $string = shift;
    chomp $string;
    my $key = shift;
    if (!$remake)
    {
	my $ret = undef;
	warn "###################################################\nInput $string\n###################################################\n";
	    my $cont = 1;
	while ($cont)
	{
	    my $inp = <STDIN>;
	    if ($inp =~/^\s*$/)
	    {
		$cont = 0;
		$ret = ' ';
	    }
	    if ($inp =~ /[\w\d]+/)
	    {
		$inp =~ /([\w\s\d\.\,\-\+\:\/\;\\\(\)]+)/;
		$ret = $1;
		$ret =~ s/\\/\//g;
		$ret =~ s/\;/\\\;/g;
		$cont = 0;
	    }
	}
	$ret = &write_old_info($key,$ret) if (defined($key));
	$ret = ' ' unless ($ret);
	return &quote_chrs($ret);
    }
    else
    {
	return &quote_chrs(&get_old_info($key)) if (defined($key));
    }
}


sub input_information_new($)
#########################################################
#### This function is a wrapper for input_information ###
#### It scans the info file for the keywords before   ###
#### calling input_information and uses the info from ###
#### info.txt instead if found                        ###
#########################################################
{
    my $sting = shift;
    my $key = shift;
    if (!$remake)
    {
	my $file = &get_path.'info.txt';
	if (-e $file)
	{
	    open MYIN,'<',$file or die "Could not open file $file\n";
	    while (my $str = <MYIN>)
	    {
		if ($str =~ /^$key\s*\#\s*(.*)/)
		{
		    my $result = $1;
		    $result = &write_old_info($key,$result) if (defined($key));
		    close MYIN;
		    $result = ' ' unless ($result);
		    return &quote_chrs($result);
		}
	    }
	    close MYIN;
	    return &quote_chrs(&input_information($string,$key));
	}
	else
	{
	    return &quote_chrs(&input_information($string,$key));
	}
    }
    else
    {
	return &quote_chrs(&get_old_info($key)) if (defined($key));
    }
}


sub quote_chrs($)
{
    my $str = shift;
    $str =~ s/[^\\]\%/\\\%/g;
    $str =~ s/[^\\]\#/\\\#/g;
#    $str =~ s/[^\\]_/\\\_/g;
    $str =~ s/[^\\]\$/\\\$/g;
    $str =~ s/[^\\]\&/\\\&/g;
    $str =~ s/\r/\r/g;
    return $str;
}

sub get_imp_numbers()
{
    my $file = shift;
    my $text = shift;
    my $impnumbers = &input_information($text);
    my @nr = split(/\s+/,$impnumbers);
    my $dir = &get_path.'impedance/';
    my $impfile = $dir.$file;
    unlink $impfile if (-e($impfile));
    if (@nr)
    {
	open (OUT , '>', $impfile) or die "Could not open file $impfile for writing!\n";
	for my $st (@nr)
	{
	    print OUT $st,"\n";
	}
	close (OUT);
    }
}




sub get_max_current
{
    my $file = &get_path.'jdata';
    my $header = `/usr/bin/head -1 $file`;
    my @headern = split(/\s+/,$header);
    my $col = 0;
    for (my $x = 0; $x < scalar(@headern); $x++)
    {
	if ($headern[$x] =~ /current/)
	{
	    $col = $x+2;
	}
    }
    my $cmd = "awk '{if(min==\"\"){min=max=\$$col}; if(max<\$$col){max=\$$col}; if(\$$col< min) {min=\$$col};} END {print min \"\\n\" max}' $file";
    my ($min,$max) = `$cmd`;
    return $max;
}

sub get_max_power
{
    my $file = &get_path.'iv/ivtable';
    return 0 unless (-e $file);
    open MYIN, '<', $file or die "Could not open file $file for reading!\n";
    my @lines = <MYIN>;
    close MYIN;
    my $power = 0;
    for my $header (@lines)
    {
	my @headern = split(/\s+/,$header);
	my $coli = 0;
	my $colu = 0;
	for (my $x = 0; $x < scalar(@headern); $x++)
	{
	    if ($headern[$x] =~ /cmax/)
	    {
		$coli = $x+1;
	    }
	    if ($headern[$x] =~ /Voltage_at_max_current/)
	    {
		$colu = $x+1;
	    }
	}
	my $localP = $headern[$coli] * $headern[$colu] / 1000;
	if ($localP > $power)
	{
	    $power = $localP;
	}
    }    
    return $power;
}

sub get_min_r($$)
{
    my $mode = shift;
    my $rig = shift;
    my $t = shift;
    my $file = &get_path.'iv/plotdata/rminvalues';
    return '' unless (-e $file);
    open MYIN ,'<', $file or die "Could not open file $file for reading!\n";
    my @lines = <MYIN>;
    close MYIN;
    my @values;
    my $o2cutoff = &AFM::get_usercv_test($rig,$testno,'gas_o2','cutoff_report');
    $o2cutoff = &AFM::get_config_value_old($rig,'o2_cutoff',$testno) unless ($o2cutoff);
    my $ch4cutoff = &AFM::get_usercv_test($rig,$testno,'gas_ch4','cutoff_report');
    $ch4cutoff = &AFM::get_config_value_old($rig,'ch4_cutoff',$testno) unless ($ch4cutoff);
    for my $line (@lines)
    {
	$line =~ /o2\s+([\d\.\-]+)/;
	my $o2 = $1;
	$line =~ /T_OCV_measure\s+(\d+)/;
	my $temp = $1;
	$line =~ /ch4\s+([\d\.\-]+)/;
	my $ch4 = $1;
	if (($o2 < $o2cutoff) && ($ch4 < $ch4cutoff) && ($temp < $t + 7) && ($temp > $t - 7))
	{
	    push @values, $line;
	}
    }
    my $rmin = 1000000;
    for my $header (@values)
    {
	my @headern = split(/\s+/,$header);
	my $coli = 0;
	for (my $x = 0; $x < scalar(@headern); $x++)
	{
	    if ($headern[$x] =~ /$mode/)
	    {
		$coli = $x+1;
	    }
	}
	my $localR = $headern[$coli];
	if (($localR > 0) && ($localR < $rmin))
	{
	    $rmin = $localR;
	}
    }    
    if ($rmin == 1000000)
    {
	$rmin = 0;
    }
    return $rmin;
}


sub get_current_at_time($)
{
    my $file = &get_path.'jdata';
    open MY_DATA ,'<', $file or die "Could not open jdata file $file!!\n";
    my $notfound = 1;
    my $res = 0;
    while (($notfound) && (!eof(MY_DATA)))
    {
	my $str = <MY_DATA>;
	my @list = split(/\s+/,$str);
	if ($list[0] > $_[0])
	{
	    $notfound = 0;
	    $str =~ /current\s+([\-\d\.]+)/;
	    $res = $1+0;
	}
    }
    close (MY_DATA);
    return $res;
}

sub format_number($$)
{
    my $number = $_[0];
    my $digits = $_[1];
    my $res = $number;
    if ($number =~ /(\-*\d+\.\d{$digits})\d*([eE][\-\+]\d+)/)
    {
	$res = $1.$2;
	return $res;
    }
    if ($number =~ /(\-*\d+\.\d{$digits})\d*/)
    {
	$res = $1;
	return $res;
    }
}


################################
###  Latex functions  ##########
################################

sub ref($)
{
    my $res =  '\ref{'.$_[0].'}';
    return $res;
}

sub pref($)
{
    my $res =  '(page \pageref{'.$_[0].'})';
    return $res;
}


sub print_figure($$$)
{
    my $caption = undef;
    my $figure = $_[0];
    my $label = undef;
    my $width = 0.6;
    if (scalar(@_) > 1) 
    {
	$caption = $_[1];
    }
    if (scalar(@_) > 2) 
    {
	$label = $_[2];
    }
    if (scalar(@_) > 3) 
    {
	$width = $_[3];
    }
    print "\n";
    print '\begin{figure}[htbp]',"\n";
    print '   \abovecaptionskip=0pt',"\n";
    print '   \begin{center}',"\n";
    print '   \includegraphics[width=',$width,' \linewidth]{',$figure,"\}\n";
    my $server = `/bin/hostname`;
    chomp $server;
    $figure =~ s/_/\\_/g;
    $caption = $caption . "\\newline File: $figure on $server.";
    print '   \end{center}',"\n";
    print '   \caption{'.$caption."\}\n";
    if (defined($label))
    {
	print '   \label{'.$label."\}\n";
    }
    print '\end{figure}',"\n";
}

sub print_figure_imp($$$)
{
    my $caption = undef;
    my $figure = $_[0];
    my $label = undef;
    my $width = 0.7;
    if (scalar(@_) > 1) 
    {
	$caption = $_[1];
    }
    if (scalar(@_) > 2) 
    {
	$label = $_[2];
    }
    if (scalar(@_) > 3) 
    {
	$width = $_[3];
    }
    print "\n";
    print '\begin{figure}[htbp]',"\n";
    print '   \abovecaptionskip=0pt',"\n";
    print '   \begin{center}',"\n";
    print '   \includegraphics[width=',$width,' \linewidth, bb=50 50 554 410, clip=]{',$figure,"\}\n";
    my $server = `/bin/hostname`;
    chomp $server;
    $figure =~ s/_/\\_/g;
    $figure =~ s/\/ps\//\/ps\/ \\newline / if (length($figure) > 70);
    $caption = $caption . "\\newline File: $figure on $server.";
    print '   \end{center}',"\n";
    print '   \caption{'.$caption."\}\n";
    if (defined($label))
    {
	print '   \label{'.$label."\}\n";
    }
    print '\end{figure}',"\n";
}

sub print_figure_imp_new($$$)
{
    my $caption = undef;
    my $figure = $_[0];
    my $label = undef;
    my $width = 0.7;
    if (scalar(@_) > 1) 
    {
	$caption = $_[1];
    }
    if (scalar(@_) > 2) 
    {
	$label = $_[2];
    }
    if (scalar(@_) > 3) 
    {
	$width = $_[3];
    }
    print "\n";
    print '\begin{figure}[htbp]',"\n";
    print '   \abovecaptionskip=0pt',"\n";
    print '   \begin{center}',"\n";
    if (-d $analytic_dir)
    {
	print '   \includegraphics[angle=-90,width=',$width,' \linewidth]{',$figure,"\}\n";
    }
    else
    {
	print '   \includegraphics[width=',$width,' \linewidth, bb=50 50 554 410, clip=]{',$figure,"\}\n";
    }
    my $server = `/bin/hostname`;
    chomp $server;
    $figure =~ s/_/\\_/g;
    $figure =~ s/\/ps\//\/ps\/ \\newline / if (length($figure) > 70);
    $caption = $caption . "\\newline File: $figure on $server.";
    print '   \end{center}',"\n";
    print '   \caption{'.$caption."\}\n";
    if (defined($label))
    {
	print '   \label{'.$label."\}\n";
    }
    print '\end{figure}',"\n";
}


sub get_old_info($)
{
    my $ret = '';
    my $key = shift;
    open TXT, '<', $inffile or die "Could not open file $inffile\n";
    while (my $str = <TXT>)
    {
        if ($str && $str =~ /^$key\s+\#\s+(.*)/)
        {
            $ret = $1;
            chomp $ret;
            next;
        }
        next unless ($ret);
        last if ($str && $str =~ /^\w+\s+\#/);
        $ret .= $str;
    }
    close(TXT);
    $ret =~ s/\.?[\s\t]*[\r\n][\r\s\n\t]*[\r\n]/\. /g;
    $ret =~ s/[\s\t]+/ /g;
    $ret =~ s/[\r\n]+/ /g;
    $ret = ' ' unless ($ret);
    return $ret;
}

sub write_old_info($$)
{
    my $key = shift;
    my $string = shift;
    chomp $string;
    open TXT, '>>', $inffile or die "Could not open file $inffile\n"; 
    print TXT "$key  \# $string\n";
    close(TXT);
    my $ret = $string;
    $ret =~ s/\.?[\s\t]*[\r\n][\r\s\n\t]*[\r\n]/\. /g;
    $ret =~ s/[\s\t]+/ /g;
    $ret =~ s/[\r\n]+/ /g;
    return $ret;
}


sub my_section($)
{
    my $s = shift;
    my $ref = $s;
    $ref =~ /([\w\s\-]+)/;
    $ref = $1;
    $ref = shift if (@_);
    return &section($s,$ref);
}

sub my_subsection($)
{
    my $s = shift;
    my $ref = $s;
    $ref =~ /([\w\s\-]+)/;
    $ref = $1;
    $ref = shift if (@_);
    return &subsection($s,$ref);
}

