#!/usr/bin/perl -w
# $Id$
# Dieses Script (latex-rtables) wurde von Rdiger Beck erstellt
# Es ist freie Software
# Bei Fehlern wenden Sie sich bitte an mich.
# jeffbeck@web.de  oder  jeffbeck@gmx.de

# thist script reads a vapour-table from coolpack-output
# and converts it to a latex-table

# die Formelzeichen aus der Datenbank holen ???? Todo

# Bibliotheken
use strict;
use DBI;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
use File::Find;
use coldformix;
# ==========================================================================


# Dirty Hack, but works (- 3 in multiple Places takes away the Last 3 colums)


# Choose the Language: de, en
my $lang="de";


# Choose the Unit-System: si_symbol,
my $unit_system = "si_symbol";


my %symbols  = &coldformix::get_symbols();
my %units  = &coldformix::get_units();
my %refrig  = &coldformix::get_filename_refrigerants();
my %temperature_values=(); # values to print

my $symbol="";
my $number=0;
# ===========================================================================
# Optionen verarbeiten
# ==========================================================================
# Parsen der Optionen
my $testopt=GetOptions(
           "lang|l=s" => \$lang,
           "unit_system|u=s" => \$unit_system
          );


print "Language: $lang \n";
print "Unit_System: $unit_system \n";

# Prfen, ob Optionen erkannt wurden, sonst Abbruch
&coldformix::check_options($testopt);



my $boxed_line=0;
my $i;
my $column_width="16mm";

#
if (not -e "../coldformix-generated/$lang/latex") {
    system("install -d ../coldformix-generated/$lang/latex");
}
if (not -e "../coldformix-generated/$lang/rtables") {
    system("install -d ../coldformix-generated/$lang/rtables");
}


#my %refrigerants = &coldformix::get_refrigerants;

# This hash should be generated by querying the Database
# using the given language



my %mapping = qw(
     T            t
     P            p_abs{1}
     Vl           v_liquid
     Vg           v_gas
     Hl           h_liquid
     Hg           h_gas
);
 

#v_liquid
#v_gas
#h_liquid
#h_gas

my $rtables_dir="../coldformix-source/data/rtables";

my @filelist=();
# ???????????
#my @filelist=("r134a.dat");


my $latex_head="";

   opendir(DIR, $rtables_dir) || die "Kann $rtables_dir nicht ffnen: $!";
   while (defined (my $file = readdir(DIR))) {
       # Eintrag verarbeiten
       if (not $file eq "." and
          not $file eq ".." and
          not $file eq "CVS" and
          not $file=~/~/) {
          push (@filelist, $file);
       }
   }








print "##### Working on this files: @filelist \n";

foreach my $filename (@filelist) {
   $boxed_line=0;
   open(LATEXIN,"<../coldformix-source/data/rtables/$filename");
   my $filename_orig=$filename;
   # create the filename for searches in the database
   my $filename_database=$filename;
   $filename_database=~s/\.dat//g; # i.e.  r134a
   $filename=~s/dat/tex/g;  # i.e. r134a.tex

   my $p_col="";
   my $v2_col="";

   # asking database for values
   %temperature_values=();
   %temperature_values=&temperature_values($filename_database);

#   open(LATEXOUT,">../data/rtables/generated-$lang/$filename");
   open(LATEXOUT,">../coldformix-generated/$lang/rtables/$filename");
   print "Input: $filename_orig \n";
   print "Output: $filename \n";

   # setting the pressure column
   if ($filename_database eq "r1270" or
       $filename_database eq "r13" or
       $filename_database eq "r170" or
       $filename_database eq "r21" or
       $filename_database eq "r22" or
       $filename_database eq "r500" or
       $filename_database eq "r600"){
     $p_col="2.7";
     $v2_col="3.5";
   } elsif ($filename_database eq "r600a") {
     $p_col="3.9";
     $v2_col="3.5";
   } elsif ($filename_database eq "r718") {
     $p_col="3.9";
     $v2_col="6.5";
   } else {
     $p_col="2.5";
     $v2_col="3.5";
   }

   print LATEXOUT "\\begin{longtable}[b]{|D{,}{,}{5.2}|D{,}{,}{${p_col}}",
                  "|D{,}{,}{1.4}|D{,}{,}{$v2_col}|D{,}{,}{4.2}",
                  "|D{,}{,}{4.2}|} \\hline \n";


   print LATEXOUT "\\multicolumn{1}{|c}{\$$symbols{'t_evap'}{'si_symbol'}\$}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{\$$symbols{'p_abs'}{'si_symbol'}\$}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{\$$symbols{'v_liquid'}{'si_symbol'}\$}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{\$$symbols{'v_gas'}{'si_symbol'}\$}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{\$$symbols{'h_liquid'}{'si_symbol'}\$}  & ";
   print LATEXOUT "\\multicolumn{1}{|c|}{\$$symbols{'h_gas'}{'si_symbol'}\$} ";
   print LATEXOUT "\\tabularnewline \n";

   print LATEXOUT "\\multicolumn{1}{|c}{in}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{in}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{in}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{in}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{in}  & ";
   print LATEXOUT "\\multicolumn{1}{|c|}{in} \\tabularnewline \n";

   print LATEXOUT "\\multicolumn{1}{|c}{$units{'temperature'}{'latex_0'}}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{$units{'pressure'}{'latex_1'}}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{$units{'spec_volume'}{'latex_1'}}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{$units{'spec_volume'}{'latex_0'}}  & ";
   print LATEXOUT "\\multicolumn{1}{|c}{$units{'spec_energy'}{'latex_1'}}  & ";
   print LATEXOUT "\\multicolumn{1}{|c|}{$units{'spec_energy'}{'latex_1'}} ";
   print LATEXOUT "\\tabularnewline \\hline \\hline\n";

print LATEXOUT "\\endhead \n\n",
               "      \\hline"," \n";

print LATEXOUT "   \\endfoot ","\n",
               "      \\hline ","\n",
               "   \\endlastfoot ","\n";



   while(<LATEXIN>){
      chomp(); # Returnzeichen abschneiden
      s/\s//g; # Spezialzeichen raus
      if ($_ eq ""){next;} # Wenn Zeile Leer, dann aussteigen
      if(/Refrigerant/){
           # Kltemittel ermitteln
           # vom 2. Grossen R, bis zum ersten komma
           # Todo ????
           next;
        } # 
      if(/^Reference/){next;} # aussteigen
      if(/^T/){
          my @symbols = split(/;/);
          for ($i = 0; $i <= $#symbols - 3; $i++) {
          }
          for ($i = 0; $i <= $#symbols - 3; $i++) {

              # map the found symbols to the name in the database
              if (defined $mapping{$symbols[$i]}) {
                 $symbol = $mapping{$symbols[$i]}; 
	      }

              # Extracting n in {n}, if exists
              if ($symbol=~m/{([0-9])}/) {
                  $number=$1;
                  print "Number of $symbol is $1 \n";
                  # Throwing away {n}
                  $symbol=~s/\{$number\}//;
                  print "Symbol is $symbol \n";
              } else {
                  # when not specified, use 0 as standard
                  $number=0;
              }
 
              $latex_head=&head("$symbol",$number);

	      if ($i==$#symbols - 3) {
              } else {
              }
          }

          next;
      }

      if(/^C/){next;} # aussteigen
      if(/^Copyright/){next;} # aussteigen
      if(/^M.J./){next;} # aussteigen

      # what to do with data-lines
      my @data = split(/;/);

      # taking away unnecessary 0's
      $data[0]=&coldformix::strip($data[0]);
      
      print "Checking if $data[0] must be printed ...\n";
      if (exists $temperature_values{$data[0]}){
          # create the line
          print "   Printing the line for temperature $data[0] \n";
          for ($i = 0; $i <= $#data - 3; $i++) {
              print LATEXOUT "$data[$i]";
              if ($i==$#data - 3) {
                 print LATEXOUT "\\\\ ";
              } else {
                 print LATEXOUT " & "; 
              }    
          }
      
          $boxed_line=$boxed_line+1;
          # print "$boxed_line\n";
          if ($boxed_line==5){
              print LATEXOUT "\\hline  \n";
              $boxed_line=0;
          } else {
              print LATEXOUT "\n";
          }
      }
   }
   print LATEXOUT "\\end{longtable}"."\n";
}


sub temperature_values {
    my ($refrigerant)= @_;
    my $i;
    my $temperature_values=();
    my $min=$refrig{$refrigerant}{'rtables_min'};
    my $max=$refrig{$refrigerant}{'rtables_max'};
    my $step=$refrig{$refrigerant}{'rtables_step'};
    print "Calculating temperature range for $refrigerant : \n";
    print "Min:  $min  \n";
    print "Max:  $max  \n";
    print "Step: $step  \n";
    if ($max==0 and $min==0 and $step==0){
        print "Missing database entries: NO RANGE DEFINED \n\n";
        return $temperature_values
    } else { 
        $i=$min;
        while ($i <= $max) {
            print "$i added to the temperature_values \n";
            $temperature_values{$i}="dummy";
            $i=$i+$step;
        }
        return %temperature_values;
    }
}


sub head {
    my ($name,$number) = @_;
    my $lang_column = "$lang";
    my $latex_column = "latex_"."$number";
    my $description="";
    my $latex_line="";
    if (not defined $symbols{$name}{$lang_column}
        or $symbols{$name}{$lang_column} eq ""){
	$description = "\\textcolor{red}{$symbols{$name}{'de'}(de)}";
	print "Not defined!\n"; 
    } else {
	$description = $symbols{$name}{$lang_column};
    }
    my $unit = $units{$symbols{$name}{'unit'}}{$latex_column};
    print "Looking in column $lang_column for explanation of $name \n";
    print "-> Hit:  $symbols{$name}{$lang_column} \n";
    print "Basic unit of $name is ->  $symbols{$name}{'unit'}\n";
    print "Unit in latex_$number  is ->  $unit \n";

#    print LATEXOUT "\\item [\$$symbols{$name}{$unit_system}\$]:",
#                   " $description in $unit\n";
#    $latex_line="7";
    $latex_line = "\\multicolumn{1}{|c}{\$$symbols{$name}{$unit_system}\$ \\newline in \\newline $unit}"; 
#"\\multicolumn{1}{c}{in}". 
#"\\multicolumn{1}{c}{$unit}";


#    $latex_line = "\$$symbols{$name}{$unit_system}\$".
#                  " \\newline in \\newline $unit";
    return $latex_line;
}

