#!/usr/local/bin/perl
#!/usr/perl/perl5/bin/perl

$doma_root = "/home/p/pumuckel/cslib2000/doma_root/";
$doma_url = "http://www.cs.tu-berlin.de/~pumuckel/cslib2000/doma_url_root/";
$doma_url_root = "/home/p/pumuckel/cslib2000/doma_url_root/";

$doma_root = $ENV{'DOMA_ROOT'};
$doma_url = $ENV{'DOMA_URL'};
$doma_url_root = $ENV{'DOMA_URL_ROOT'};

# Wie es aussieht, sind 3 Durchlaeufe notwendig
# 1. Felder auswerten, Indexeintragungen durchfuehren,
#    HTML-Rohform herstellen, Umlaute HTML-gerecht kodieren,
#    das Produkt ist in jeder Weise HTML-konform (bis auf Referenzen)
#    (dies soll den Einsatz von SGMLS f"ur die nachfolgenden Schritte
#    nicht verbauen: ein Pass statt zweien, Wandlung nach HTF, ...)
# 2. NAME-Attribute in Referenzenverzeichnis (des umfassenden
#    Dokuments) eintragen,
#    (sp"ater vielleicht: TITLE- und INDEX-Attribute auswerten)
# 3. HREF-, SRC-, ACTION-, Attribute durch Nachschlagen aufl"osen oder 
#    ersatzweise inaktiven
#    'Anquor' erzeugen, (unterschiedliche Handhabung von A-, FORM-, IMG-,
#    INPUT-Elementen)
#    Elementen), offenene Referenzen melden (das Ausgangsfile
#    dieses Schrittes ist ein gutes Zwischenformat fuer die
#    Dokumentenerzeugung zur Laufzeit: Referenzen werden nur zur
#    Lieferung aufgel"ost)
# /<[aA]\s*(name|NAME|Name)\s*=\s*\"([^"]*)\"[^>]*>([^<]*)<\/[aA]>/
#  $name=$2; # eventuell Umlaute rueckgaengig machen
#  $text=$3;

sub uml{
  local($a) = @_;
  if( $field{'encoding'} eq "latex" ){
    $a=~s/\"\"/@#\$%123/g;
    $a=~s/\"a/\&auml;/g;
    $a=~s/\"u/\&uuml;/g;
    $a=~s/\"o/\&ouml;/g;
    $a=~s/\"U/\&Uuml;/g;
    $a=~s/\"A/\&Auml;/g;
    $a=~s/\"O/\&Ouml;/g;
    $a=~s/\"s/\&szlig;/g;
    $a=~s/@#\$%123/\"/g;
  }elsif( $field{'encoding'} eq "iso" ){
#char *ASC_TAB[] = { "Ae", "Oe", "Ue", "ae", "oe", "ue", "sz" }; 
#/* 0xc4, 0xd6, 0xdc, 0xe4, 0xf6, 0xfc, 0xdf */
#char *ISO_TAB[] = {"\304", "\326", "\334", "\344", "\366", "\374", "\337" };
    $a=~s/\xe4/\&auml;/g;
    $a=~s/\xf6/\&ouml;/g;
    $a=~s/\xfc/\&uuml;/g;
    $a=~s/\xc4/\&Auml;/g;
    $a=~s/\xd6/\&Ouml;/g;
    $a=~s/\xdc/\&Uuml;/g;
    $a=~s/\xdf/\&szlig;/g;
  }else{
    die "unknown encoding $field{'encoding'}";
  };
  return $a;
}

sub translate {
  local($a) = @_;
  $a=~s/\$glos\/([^"]*)/\.\/\1\.html/g;
  return $a;
}

sub ascii_uml {
  local($a) = @_;
  if( $field{'encoding'} eq "latex" ){
    $a=~s/\"a/ae/g;
    $a=~s/\"u/ue/g;
    $a=~s/\"o/oe/g;
    $a=~s/\"U/Ue/g;
    $a=~s/\"A/Ae/g;
    $a=~s/\"O/Oe/g;
    $a=~s/\"s/ss/g;
  }elsif( $field{'encoding'} eq "iso" ){
    $a=~s/\xe4/ae/g;
    $a=~s/\xf6/oe/g;
    $a=~s/\xfc/ue/g;
    $a=~s/\xc4/Ae/g;
    $a=~s/\xd6/Oe/g;
    $a=~s/\xdc/Ue/g;
    $a=~s/\xdf/ss/g;
  }else{
    die "unknown encoding $field{'encoding'}";
  };
  return $a;
}

sub filyfy {
  local($a) = @_;
  if( $field{'encoding'} eq "latex" ){
    $a=~s/\"a/ae/g;
    $a=~s/\"u/ue/g;
    $a=~s/\"o/oe/g;
    $a=~s/\"U/ue/g;
    $a=~s/\"A/ae/g;
    $a=~s/\"O/oe/g;
    $a=~s/\"s/ss/g;
    $a=~s/([A-Z])/\l\1/g;
    $a=~s/ /_/g;
  }elsif( $field{'encoding'} eq "iso" ){
    $a=~s/\xe4/ae/g;
    $a=~s/\xf6/oe/g;
    $a=~s/\xfc/ue/g;
    $a=~s/\xc4/ae/g;
    $a=~s/\xd6/oe/g;
    $a=~s/\xdc/ue/g;
    $a=~s/\xdf/ss/g;
    $a=~s/([A-Z])/\l\1/g;
    $a=~s/ /_/g;
  }else{
    die "unknown encoding $field{'encoding'}";
  };
  return $a;
}

sub sortyfy {
  local($a) = @_;
  if( $field{'encoding'} eq "latex" ){
    $a=~s/\"a/ae/g;
    $a=~s/\"u/ue/g;
    $a=~s/\"o/oe/g;
    $a=~s/\"U/ue/g;
    $a=~s/\"A/ae/g;
    $a=~s/\"O/oe/g;
    $a=~s/\"s/ss/g;
    $a=~s/([A-Z])/\l\1/g;
    $a=~s/ //g;
  }elsif( $field{'encoding'} eq "iso" ){
    $a=~s/\xe4/ae/g;
    $a=~s/\xf6/oe/g;
    $a=~s/\xfc/ue/g;
    $a=~s/\xc4/ae/g;
    $a=~s/\xd6/oe/g;
    $a=~s/\xdc/ue/g;
    $a=~s/\xdf/ss/g;
    $a=~s/([A-Z])/\l\1/g;
    $a=~s/ //g;
  }else{
    die "unknown encoding $field{'encoding'}";
  };
  return $a;
}

#print do filyfy ('"ubergro"ser Alphabetischer Katalog'), "\n";
#print do sortyfy ('"ubergro"ser Alphabetischer Katalog'), "\n";
 

#dbmopen(field,'db',0666);

while (<>) {
    chop;
    if( $text ){
      if( $field{'class'} eq 'cslib2000-glossar-eintrag' ){
        if( /^\*\s*([^:]*):\s*/ ){
          $rest=$';
          $tag=$1;
#        $rest=do translate ($rest);
          $tag = do uml($tag);
          $rest=do uml ($rest);
          print dest <<EOF
<p>

<em>$tag:</em> $rest
EOF
        }
        elsif( /^(\s*)?$/ ){
           print dest "\n";
        }else{
#          print dest do translate (do uml ($_)),"\n";
          print dest do uml ($_),"\n";
        }
      }elsif($field{'class'} eq 'cslib2000-referat' ){
        print dest do uml($_),"\n";
      }else{
        die "doma: unknown class $field{'class'}\n"
      } 
    }elsif( $html_cover_mode ){
      if( /^\.\.\.end/ ){
        $html_cover_mode = 0;
      }else{
        $html_cover_line[++$#html_cover_line] = $_;
      }
    }elsif( $abstract_mode ){
      if( /^\.\.\.end/ ){
        $abstract_mode = 0;
      }else{
        $abstract_line[++$#abstract_line] = $_;
      }
    }elsif( $literature_mode ){
      if( /^\.\.\.end/ ){
        $literature_mode = 0;
      }else{
        $literature_line[++$#literature_line] = $_;
      }
    }else{
      if( /^([^:]*):\s*(.*)/ ){
        $name = $1;
        $value = $2;
        if(     $name eq "title"){
          $field{$name} = $value;
          $index[$index_cnt++] = $value;
        }elsif( $name eq "index"){
          $index[$index_cnt++] = $value;
        }elsif( $name eq "mail-to" ||
                $name eq "autor" ){
          local ($varname) = $name;
          $varname =~ s/-/_/g;
          $value =~ s/\"/\\\"/g;
          eval "\$field_$varname[++\$#field_$name] = \"$value\"";
        }else{
          $field{$name} = $value;
        }
      }elsif( /^html-cover\.\.\./ ){
        $html_cover_mode = 1;
      }elsif( /^abstract\.\.\./ ){
        print "abstract...\n";
        $abstract_mode = 1;
      }elsif( /^literature\.\.\./ ){
        $literature_mode = 1;
      }elsif( /^text\s*$/ || /^text\.\.\./ ){
        $text=1;
        print "text...\n";
        if( $field{'class'} eq "cslib2000-glossar-eintrag" ){
          $filestem=do filyfy ($field{'title'});
          $destination=$filestem.".1";
          $this_url="${doma_url}glossar/$filestem.html";
          unless (open(dest, ">".$destination)) {
            print STDERR "Can't open $filename: $!\n";
            die;
          };
          $dest_title=do uml ($field{'title'});
          $ascii_title=do ascii_uml($field{'title'});
          print dest <<EOF
<HTML>
<head>
<title>CSLIB2000-Glossar: $ascii_title</title>
<body>
<h1>$dest_title</h1>
<hr>
EOF
        }elsif( $field{'class'} eq 'cslib2000-referat' ){
          print "name: ", $field{'name'}, "\n";
          if( $field{'name'} eq "" ){
            $filestem=do filyfy ($field{'title'});
          }else{
            $filestem=$field{'name'};
          };
          $destination=$filestem.".1";
          $this_url="${doma_url}referate/$filestem.html";
          unless (open(dest, ">".$destination)) {
            print STDERR "Can't open $filename: $!\n";
            die;
          };
          $dest_title=do uml ($field{'title'});
          $ascii_title=do ascii_uml($field{'title'});
          print dest <<EOF
<HTML>
<HEAD>
<Title>CSLIB2000-Referat: $ascii_title</Title>
</HEAD>
<BODY>

<A NAME="Referat">
<H1>Kurzreferat zum Projekt CSLIB2000</H1>
</A>

<H2>$dest_title</H2>
EOF
;
          foreach (@html_cover_line){
            print dest do uml($_), "\n";
          };

          print dest <<EOF
<H2>Formalien</H2>

<DL>
  <DT><STRONG>Thema</STRONG>
  <DD>$dest_title

  <DT><STRONG>Gruppennummer/Gruppenname</STRONG>
  <DD>$field{'group-number'}/$field{'group-name'}

  <DT><STRONG>Gruppenmitglieder</STRONG>
EOF
;
          print dest "  <DD>";
          print dest do uml( join(', ', (@field_autor) ) ), "\n";
          print dest <<EOF
  <DT><STRONG>Kontakt</STRONG>
  <DD>
EOF
;
          $contacts = join( ',', @field_mail_to );
          $contacts_short = $contacts;
          $contacts_short =~ s/@[^,]*//g;
          $url_title = $ascii_title;
          $url_title =~ s/ /+/g;
          print dest <<EOF
<a href="http://www.cs.tu-berlin.de/cgi/sendmail?$contacts&fixed=to,subject&subject=CSLIB2000-Referat:+$url_title">$contacts_short</a>

  <DT><STRONG>Zusammenfassung</STRONG>
  <DD>
EOF
;
          foreach (@abstract_line){
            print dest do uml($_), "\n";
          };

          if( $field{'slides-url'} ne "" ){
            print dest <<EOF
  <DT><STRONG>Vortragsfolien</STRONG>
  <DD>Die <A HREF="$field{'slides-url'}">Vortragsfolien</A>
werden gesondert zur Verf&uuml;gung gestellt.
EOF
;
          };

          print dest <<EOF

  <DT><STRONG>Literatur</STRONG>
  <DD>
EOF
;
          foreach (@literature_line){
            print dest do uml($_), "\n";
          };

          print dest <<EOF
  <DT><STRONG>Glossar</STRONG>
  <DD>Die Erl&auml;uterung von Fachbegriffen erfolgt direkt durch
    Hyperlink in das <A HREF="\$glosind/top">Gemeinsame CSLIB2000-Glossar</A>.
</DL>
<HR>
EOF
        }else{
          die "doma: unknown class $field{'class'}\n";
        }
      }
    }
}

if( $field{'class'} eq 'cslib2000-glossar-eintrag' ){
  $contacts = join( ',', @field_mail_to );
  $contacts_short = $contacts;
  $contacts_short =~ s/@[^,]*//g;

  print dest <<EOF
  </p>

  <hr>

  <address>
  Betreuung dieses Eintrags im
  <a href="\$glosind/top">CSLIB2000-Glossar</a>: 
  <a href="http://www.cs.tu-berlin.de/cgi/sendmail?$contacts&fixed=to,subject&subject=CSLIB2000-Glossareintrag:+$filestem">$contacts</a>
  </address>
  </body>
  </html>
EOF
  ;
}elsif( $field{'class'} eq 'cslib2000-referat' ){
  print dest <<EOF;
</BODY>
</HTML>
EOF
};

close dest;

# ---------------------------------------------------------------------------
# Pass 2: fehlt

# Konsistenter Zugriff auf die Objekte per URL
# $url_root=http://www.cs.tu-berlin.de/~ul/csliblv/www # fuer Serverzugriff
# $url_root=file:/home/p/pumuckel/cslib2000/html       # fuer Viewerzugriff

# Eindeutiger Zugriff auf die Objekte per Pfad (= Id)
# $path_root = ~ul/csliblv/www/
# $path_root = ~pumuckel/cslib2000/html/
# this_path = ~ul/csliblv/www/referate/die_klassische_bibliothek
# this_path = ~ul/csliblv/www/glossar/unselbststaendig
# full_path = ~ul/csliblv/www/glossar/sammelwerk
# 

sub rel_url{
  local ($this_url, $dest_url) = @_;

  local ($this, $that, $this_protocol, $dest_protocol,
         $this_server, $dest_server);

#   print $this_url, "  ", $dest_url, "\n";
  ($this_protocol,$this) = split(':', $this_url, 2);
  ($dest_protocol,$dest) = split(':', $dest_url, 2);

  if( $this_protocol eq $dest_protocol ){
    if( $this_protocol eq "http" ){
      ($b, $b, $this_server,$this) = split('/', $this, 4);
      ($b, $b, $dest_server,$dest) = split('/', $dest, 4);
      if( $this_server ne $dest_server ){
        return $dest_url;
      }
    }else{
      return $dest_url;
    }
    @this_compo = split('/', $this, 9999);
    @dest_compo = split('/', $dest, 9999);
    while( $this_compo[0] eq $dest_compo[0] ){
      @this_compo = @this_compo[1..($#this_compo)];
      @dest_compo = @dest_compo[1..($#dest_compo)];
    }
#    print "***", $#this_compo,  '../' x $#this_compo, join('/',@dest_compo), "\n";
    return '../' x $#this_compo. join('/',@dest_compo);
  }else{
    return $dest_url;
  }
}

sub reference_lookup{
  local($full_path, $this_url) = @_;

  local ($slots);

  $slots{'referencable'} = 1;
# $id1 = $full_path - $root_path;
# $id2 = $this_path - $root_path;
# $url1 = root_url + id1;
# $url2 = root_url + id2;
# $rel_url = url1 - url2 = id1 - id2
# glossar/sammelwerk - glossar/unselbststaendige = sammelwerk
# glossar/sammelwerk - referate/klassische = ../glossar/sammelwerk
# referate/klassische/einleitung - glossar/sammelwerk = ../referate/klassische
#                                     ../referat/klassische/einleitung
#  $rel_url = $full_path;
  
  if( $full_path =~ /(.*)\/glossar\/(.*)/ ){
      $slots{'url'} = do rel_url($this_url, "${doma_url}glossar/$2.html");
      $slots{'semantic'} = "glossar";
  }elsif( $full_path =~ /(.*)\/referate\/([^\/]*)\/(.*)/ ){
      $slots{'url'} = do rel_url($this_url, "${doma_url}referate/$2.html#$3");
      $slots{'semantic'} = "zitieren";
  }elsif( $full_path =~ /(.*)\/glossarindex\/(.*)/ ){
      $slots{'url'} = do rel_url($this_url, "${doma_url}glossarindex/$2.html");
      $slots{'semantic'} = "index";
  }elsif( $full_path =~ /(.*)\/literatur\/(.*)/ ){
      $slots{'url'} = do rel_url($this_url, "${doma_url}literatur/sammlung.html#$2");
      $slots{'semantic'} = "literatur";
  }elsif( $full_path =~ /(.*)\/sendmail\?/ ){
      print ">>>>>>>>>>>>. $full_path\n";
      $slots{'url'} = "$full_path";
      $slots{'semantic'} = "sendmail";
  }elsif( $full_path =~ /^#(.*)/ ){
      $slots{'url'} = "#$1";
      $slots{'semantic'} = "this";
  }else{
      $slots{'url'} = "$full_path";
      $slots{'semantic'} = "extern";
  }
  return %slots;
}

# ---------------------------------------------------------------------------
# Pass 3: Kurzreferenzen ersetzen

%shortref_map = (
  'glos', "${doma_root}glossar",
  'ref', "${doma_root}referate",
  'glosind', "${doma_root}glossarindex",
  'lit', "${doma_root}literatur"
);

open(pass3in, "<".$filestem.".1");
#open(pass3out, ">".$filestem.".html");
if( $field{'class'} eq 'cslib2000-glossar-eintrag' ){ 
  open(pass3out, ">".$doma_url_root."glossar/".$filestem.".html");
}elsif( $field{'class'} eq 'cslib2000-referat' ){ 
  open(pass3out, ">".$doma_url_root."referate/".$filestem.".html");
  print ">".$doma_url_root."referate/".$filestem.".html\n";
};

while(<pass3in>){
  chop;
  $rest = $_;

  while(1){
    if( $rest=~/<[aA](.*)(href|HREF|Href)\s*=\s*\"([^"]*)\"([^>]*)>([^<]*)<\/[aA]>/ ){
      $before=$`;
      $other1 = $1;
      $href = $3;
      $other2 = $4;
      $hyper = $5;
      $rest = $';

      $full_path = "";
      if( $href=~/\$([^\/]*)(\/?)/ ){
        $full_path = $shortref_map{$1}.$2.$';
      }elsif( $href=~/\#(.*)/ ){
        $url = $href;
        print pass3out "$before<A $other1 HREF=\"$url\" $other2>$hyper</A>";
      }else{
        $full_path = $href;
      }
      if( $full_path ne ""){
        print $full_path, "\n";
        %obj = do reference_lookup($full_path, $this_url); # $this_path
        if( $obj{'referencable'} ){
          $url = $obj{'url'};
          if( $obj{'semantic'} eq "glossar" ){
            $symbol = '<img src="../gifs/glossarr.gif">';
          }elsif( $obj{'semantic'} eq "zitieren" ){
            $symbol = '<img src="../gifs/cite.gif">';
          }elsif( $obj{'semantic'} eq "index" ){
            $symbol = '<img src="../gifs/index.gif">';
          }elsif( $obj{'semantic'} eq "sendmail" ){
            $symbol = '<img src="../gifs/mail.gif">';
          }elsif( $obj{'semantic'} eq "literatur" ){
            $symbol = '<img src="../gifs/literature.gif">';
          }elsif( $obj{'semantic'} eq "extern" ){
            $symbol = '<img src="../gifs/web.gif">';
          }else{
            $symbol = "";
          }
          print pass3out "$before$symbol<A $other1 HREF=\"$url\" $other2>$hyper</A>";
        }else{
          print pass3out "$before<U>$hyper</U>";
        }
      }
      next;
    }else{
      print pass3out $rest, "\n";
      last;
    }
  }
}

close pass3in;
close pass3out;

# ---------------------------------------------------------------------------
# Indexeintrag

print "---\n";

if( $field{'class'} eq 'cslib2000-glossar-eintrag' ){
  $filename = $filestem.".html";
  $indexdir= $doma_root."glossarindex";

  foreach $x (@index){
    $sortname=do sortyfy ($x);
    print "Index -- ", $sortname, "\n";
  #  $sortname=m/(.).*/;
  #  $first=$1;
    $first=substr($sortname, 0, 1);
    print $first, "\n";
    unless (open(indexfile, ">>".$indexdir."/".$first.".index")) {
      print STDERR "Can't open indexfile\n";
    };
    print $indexdir."/".$first.".index", "\n";
    $rurl = do rel_url($doma_url."glossarindex/$first".".index", $this_url);
    print indexfile $sortname, "\t", 
                  do uml ($x), "\t", $rurl, "\n";
    close indexfile;  
  }
}

print "Filename: ", do filyfy ($field{'title'}), "\n";
#foreach $x  (%field){
#  print '>>>>>>',$x,"\n";
#};

