#!/usr/bin/perl -w
# $Id$
# Dieses Script (latex-rlist) 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 data from an sql database
# and converts it to a latex-table

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


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

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


# ===========================================================================
# 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 %refrig = &coldformix::get_refrig();
my %oils  = &coldformix::get_oils();
my %symbols  = &coldformix::get_symbols();
my %units  = &coldformix::get_units();

# create lists of oils used for a certain type
my @oil_hfkw_mix = &get_usable_oils("hfkw_mix");
my @oil_fckw_hfckw = &get_usable_oils("fckw_hfckw");
my @oil_kw = &get_usable_oils("kw");
my @oil_nh3_r723 = &get_usable_oils("nh3_r723");


my @exp_symbols=();

if (not -e "../data/refrig/latex") {
    system("install -d ../data/refrig/latex");
}

if (not -e "../data/refrig/latex/generated-$lang") {
    system("mkdir ../data/refrig/latex/generated-$lang");
}


# Variables 
my $latex_line="";
my $name;
my $name_latex;
my $structure_mixture="";
my @comp_list=();
my $temp_comp;
my $temp_comp_mpercent;
my $i;
my $vapour_point_1;
my $temperature_glide_value;
my $temperature_glide_at;
my $temperature_glide;
my $critical_temp;
my $odp;
my $gwp;
my $safety_group;
my $mak;
my $oil;
my @oil=();
my $range;
my @range=();
my $hashref;

my $is_cool_good;
my $is_refrig;

# Keep all the lines in this lists, to sort later
my @cool_good_lines=();
my @refrig_lines=();


############################################################
# Reading the Database

# which order?

# Reading the entrys
foreach my $name (keys %refrig) {
   my $hashref = $refrig{$name};
#while (my ($name, $hashref) = each %refrig) {
   # empty the lists and variables
   print "Working on refrigerant: $name \n";
   @oil=();
   @range=();
   $structure_mixture="";

   #========================================
   # reading values
   $name_latex=$refrig{$name}{'latex'};

   if (not defined $refrig{$name}{'gwp'}){
      $gwp="";
   } elsif ($refrig{$name}{'gwp'}==-1) {
      $gwp = "-";
   } else {
      $gwp = $refrig{$name}{'gwp'};
   }

   if (not defined $refrig{$name}{'odp'}){
      $odp="";
#      $odp=&coldformix::strip($odp);
   } elsif ($refrig{$name}{'odp'}==-1) {
      $odp = "-";
   } else {
      $odp = $refrig{$name}{'odp'};
      $odp=&coldformix::strip($odp);
   }

   $vapour_point_1=$refrig{$name}{'evap_1bar'};
   $vapour_point_1=&coldformix::strip($vapour_point_1);

   $critical_temp=$refrig{$name}{'critical_temp'};
   $critical_temp=&coldformix::strip($critical_temp);

   #========================================
   # deciding if its a mixture or not
   if ($refrig{$name}{'structural_formula'} eq "na"){
       # its a mixture
       print "   $name (mixture)\n";
       # read components in a list
       for ($i=1; $i<7; $i++){
	   if (defined $refrig{$name}{"comp_$i"}) {
               $temp_comp=$refrig{$name}{"comp_$i"};
               $temp_comp=$refrig{$temp_comp}{'latex'};
           } else {
               $temp_comp="na";
           }
           if (defined $temp_comp and $temp_comp ne "na") {
             $temp_comp_mpercent=$refrig{$name}{"comp_mpercent_$i"};
             if (not defined $temp_comp_mpercent){
	         $temp_comp_mpercent="na";
             } else {
                $temp_comp_mpercent=$refrig{$name}{"comp_mpercent_$i"};
             }
             if (defined $temp_comp 
                and $temp_comp ne "na"
                and defined $temp_comp_mpercent
                and $temp_comp_mpercent ne "na"
                ){
        	    if ($structure_mixture ne ""){
                        $structure_mixture="$structure_mixture"." \\par ";
		    }
                    if ($temp_comp_mpercent ne "na"){
                       $temp_comp_mpercent=&coldformix::strip($temp_comp_mpercent);
		    }
                    # replace . with , in percentage value
                    $temp_comp_mpercent=~s/\./,/g;
                    $structure_mixture="$structure_mixture".
                                       "$temp_comp".
                                       "\\,--$temp_comp_mpercent\\,\\%";
             }      
	   }
        }
   } else {
       # its not a mixture
       $structure_mixture="$refrig{$name}{'structural_formula'}";
   }
   

   #========================================
   # deciding if it has a glide
   if (defined $refrig{$name}{'temperature_glide_value'}){
      $temperature_glide=$refrig{$name}{'temperature_glide_value'};
      if ($refrig{$name}{'temperature_glide_value'}==0) {
         $temperature_glide="0";
      }
   } else {
      $temperature_glide="";
   }

   $temperature_glide_at=$refrig{$name}{'temperature_glide_at'};


   #========================================
   # reading if safety_group
    if (not defined $refrig{$name}{'safety_group'}){
      $safety_group="";
    } else {
      $safety_group=$refrig{$name}{'safety_group'};
    }

   #========================================
   # reading if MAK
    if (not defined $refrig{$name}{'mak'}){
      $mak="";
    } else {
      $mak=$refrig{$name}{'mak'};
    }


   #========================================
   # oil
    my $oil_group="";
    if (defined $refrig{$name}{'oil_group'}) {
	$oil_group=$refrig{$name}{'oil_group'};
        #print "   Oil Group of $name is $oil_group\n";
	if ($oil_group eq "hfkw_mix"){
            @oil = @oil_hfkw_mix;
        } elsif ($oil_group eq "fckw_hfckw"){
            @oil = @oil_fckw_hfckw;
        } elsif ($oil_group eq "kw"){
            @oil = @oil_kw;
        } elsif ($oil_group eq "nh3_r723"){
            @oil = @oil_nh3_r723;
        } else {
            @oil = (); 
        }
   } else {
       $oil_group="";
   }

   # creating a String from the oil-list
   $oil=&coldformix::format_list(",\\,",@oil);


   #========================================
   # range
   # reading the range in a list
   if ($refrig{$name}{'climatic_cooling'}){
      push @range, "K";   
   }

   if ($refrig{$name}{'normal_cooling'}){
      push @range, "N";   
   }

   if ($refrig{$name}{'deep_cooling'}){
      push @range, "T";   
   }

   # creating a String from the range-list
   $range=&coldformix::format_list(",\\,",@range);


   # ========================================
   # writing a line from the entry
   $latex_line="$name_latex & ".
               "$structure_mixture & ".
               "$vapour_point_1 & ".
               "$temperature_glide& ".
               "$critical_temp & ".
               "$odp & ".
               "$gwp & ".
               "$safety_group & ".
               "$mak & ".
#               "$oil & ".
               "@oil & ".
               "$range ".
               "\\tabularnewline \\hline";

   if ($refrig{$name}{'visible'}==1){
       print "Name: $name \n";
       push @refrig_lines, $latex_line;
   } else {
       print "Name: $name is not visible, skipping ...\n";
   }

} # end reading the entrys








############################################################
# printing the refrig-table
#open(LATEXOUT,">../data/refrig/latex/generated-$lang/refrig.tex");


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

open(LATEXOUT,">../coldformix-generated/$lang/latex/refrig-$lang.tex");

print LATEXOUT "\\begin{landscape}\n";

print LATEXOUT "\\begin{longtable}{",
                                  "|l",
                                  "|p{30mm}",
                                  "|D{.}{,}{4.1}",
                                  "|D{.}{,}{2.1}",
                                  "|D{.}{,}{4.2}",
                                  "|D{.}{,}{2.3}",
                                  "|D{.}{,}{5.0}",
                                  "|c",
                                  "|D{.}{,}{4.0}",
                                  "|l",
                                  "|l",
                                  "|} \\hline\n";


print LATEXOUT "\\multicolumn{1}{|c}{\\rule{0mm}{5mm}Klte-} &\n",
               "   \\multicolumn{1}{|c}{Strukturformel} &\n",
               "   \\multicolumn{1}{|c}{\$$symbols{'t_evap'}{'si_symbol'}\$} &\n",
               "   \\multicolumn{1}{|c}{\$$symbols{'glide'}{'si_symbol'}\$} &\n",
               "   \\multicolumn{1}{|c}{\$$symbols{'t_crit'}{'si_symbol'}\$} &\n",
               "   \\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c}{Sicher-} &\n",
               "   \\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c|}{} \\tabularnewline[1mm]\n";


print LATEXOUT "\\multicolumn{1}{|c}{mittel} &\n",
               "   \\multicolumn{1}{|c}{oder} &\n",
               "   \\multicolumn{1}{|c}{in} &\n",
               "   \\multicolumn{1}{|c}{in} &\n",
               "   \\multicolumn{1}{|c}{in} &\n",
               "   \\multicolumn{1}{|c}{ODP} &\n",
               "   \\multicolumn{1}{|c}{GWP} &\n",
               "   \\multicolumn{1}{|c}{heits-} &\n",
               "   \\multicolumn{1}{|c}{MAK} &\n",
               "   \\multicolumn{1}{|c}{l} &\n",
               "   \\multicolumn{1}{|c|}{Bereich} \\tabularnewline[1mm] \n";

print LATEXOUT "\\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c}{Bestandteile} &\n",
               "   \\multicolumn{1}{|c}{\$$units{'temperature'}{'latex_0'}\$} &\n",
               "   \\multicolumn{1}{|c}{\$$units{'temperature'}{'latex_1'}\$} &\n",
               "   \\multicolumn{1}{|c}{\$$units{'temperature'}{'latex_0'}\$} &\n",
               "   \\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c}{\\scriptsize 100a} &\n",
               "   \\multicolumn{1}{|c}{gruppe} &\n",
               "   \\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c}{} &\n",
               "   \\multicolumn{1}{|c|}{} \\tabularnewline[1mm] \\hline \\hline \n";

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

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



# sorting the lines
@refrig_lines = sort @refrig_lines;


# print the lines
foreach my $refrig_line (@refrig_lines){
   print LATEXOUT "$refrig_line \n";
}

print LATEXOUT "\\hline\n";
print LATEXOUT "\\end{longtable} \n";

print LATEXOUT "\n";
print LATEXOUT "Quelle der GWP-Angaben:";
print LATEXOUT "\n\n";
print LATEXOUT "\\vspace{2mm}";
print LATEXOUT "\n\n";
print LATEXOUT "\\textbf{1)} VERORDNUNG (EU) Nr. 517/2014 DES EUROPISCHEN PARLAMENTS ",
               "UND DES RATES vom 16.4.2014 ber fluorierte Treibhausgase";
print LATEXOUT "\n\n";
print LATEXOUT "\\textbf{2)} GWP-Werte, die in der VERORDNUNG (EU) Nr. 517/2014 nicht ",
               "aufgefhrt sind stammen aus dem IPCC-Report Nr. 4: ",
               "Climate Change 2013";
print LATEXOUT "\n\n";
print LATEXOUT "\\end{landscape}\n";


close LATEXOUT;


sub get_usable_oils{
    my ($oil_type) = @_;
    my @perfect=();
    my @usable=();
    my @result=();

    while (my ($k,$v) = each %oils){
        if (defined $oils{$k}{$oil_type}){
            if ($oils{$k}{$oil_type}==1){
		push @perfect, $k;
            } elsif ($oils{$k}{$oil_type}==2){
		push @usable, "($k)";
            }
        }
    }
    @perfect = sort @perfect;
    @usable = sort @usable;
    push (@result,@perfect);
    push (@result,@usable);
#    print "Result for $oil_type: @result \n";
    return @result;
}
