package mp;

#use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
use CGI qw/:standard/;
use XML::DT ;
use bytes;
use DB_File;
use Fcntl ;
use MLDBM qw(DB_File);
use Data::Dumper;
use HTML::Latex;

require Exporter;

my $thesaurus_path = "/mpbin/thesaurus.pl";
my $mp_path = "/home/mp/new_site/MuseuDaPessoa";
my $thesaurus_op = 't';

sub set_thesaurus_path{ $thesaurus_path = shift || $thesaurus_path}

sub set_mp_path{ $mp_path = shift || $mp_path}

@ISA = qw(Exporter AutoLoader);
@EXPORT = qw();

$VERSION = '0.04';

my %htits = ( hv => "História de vida",
	      infancia => "Infância",
	      familia => "Família",
	      casamento => "Casamento",
	      namoro => "Namoro",
	      identificacao => "Indentificação",
	      oficio => "Ofício",
	      pprofissional => "Percurso Profissional",
	      antepassados => "Antepassados");

my $hist = join('|',qw{
 h hv
 infancia familia casamento namoro oficio pprofissional antepassados
}); 

# identificacao

my $FILE = "?";
my $OPTID = "-1";

sub _pai{
  (ctxt(1) =~ /^($hist)$/) ? 1 :
    (ctxt(2) =~ /^($hist)$/) ? 2 : 
      (ctxt(3) =~ /^($hist)$/) ? 3 : 0;
}

sub _geracao{ scalar grep {/^($hist)$/} @dtcontext ; }

sub _getid{ $dtatributes[-2]{id} || $OPTID ||
	      die "falta id na historia de vida $FILE;\n"
	    }

sub ph {
  my $pai=_pai();
  my $idh = ++ $dtatributes[-1]{idh};
  my $id = _getid();

  my $rel= [
	    (map {+{tipo =>"about",name=>$_}} (split(/\s*[,;]\s*/, $v{tipo}))),
	    ($v{tipo} ? () : (+{tipo => "IOF", name => lcfirst($htits{$q})})),
	    ($v{onde} ? (+{tipo => "onde", name => $v{onde}}):()),
	    @{$v{meta}{rel}},
	    (map {+{tipo =>"profissao",name=>lcfirst($_)}} @{$v{meta}{profissao}})
	   ];

  my $a= +{ 
    ($v{tipo} ? (tipo => [split(/\s*[,;]\s*/, $v{tipo})])
              : (tipo => $q)),
    ($pai ? ( id => "$id.$idh", url => "$id.$idh.html" )
	      : ( id => $id, url =>(($q eq "hv")? "$id.bi.html"
                                            : "$id.monobloco.html"))),
    ($v{meta} ? (%{$v{meta}}) : ()), 
    ($v{historias} ? (historias => $v{historias}) : ()), 
    ($v{onde} ? (onde => $v{onde}):()),
    ($v{data} ? (data => $v{data}):()),
    ($v{"ref"} ? ("ref" => $v{"ref"}):()),
    ($v{tit}  ? (title => $v{tit})
	          : (title => $htits{$q}. 
		                  ($v{depoimento}?"- $v{depoimento}":""))),
    rel => $rel
  };

  if ($pai==0) { $a; } 
  else { push(@{ $dtatributes[$pai]{historias} },$a); ""; }
}

sub hv2catalog{
  my $filename = shift;
  my $optid = shift;
  $OPTID=$optid;
  $FILE=$filename;

  my %handler=(
	       -type=>{meta => MMAPON("rel","autor"),
		       mp   => "SEQ" },

	       '-outputenc' => 'ISO-8859-1',
	       '-inputenc'  => 'ISO-8859-1',
	       '-default'   => sub{if($q =~ /^($hist)$/){&ph}
				   else {
				     $c;
				   }
				 },
	       #     'biografia' => sub{"$q:$c"},
	       #     'pergunta' => sub{"$q:$c"},
	       #     'projecto' => sub{"$q:$c"},
	       'meta' => sub{ $dtatributes[1]{meta}=$c; "" },
	       'rel' => sub { +{tipo => $v{tipo} || "about", name => $c} },
	       'destaque' => sub{ $dtatributes[1]{destaque}=$c; $c },
	       'profissao' => sub{ [split(/\s*[,;]\s*/, $c)]},
	       'autor' => sub{
		 if ($v{tipo}=~/^depo/i) {
		   $dtatributes[_pai()]{depoimento}=$c;
		 }
		 ;
		 +{%v,name=>$c}},
	       'nascimento' => sub{+{%v}}, # remember $v{data},$v{onde}
	       #     'hv' => sub{ print Dumper(&ph)},
	       #     'h'  => \&ph,
	       #     'resposta' => sub{"$q:$c"},
	       #     'br' => sub{"$q:$c"},
	       'foto' => sub{""}, # remember $v{href}
	       'oficio' => sub{ $v{tit} = "Ofício de $v{nome}";
				$v{tipo} = $v{nome};
				$q="h";
				&ph;},
	       #     'data' => sub{"$q:$c"},
	       #     'expressao' => sub{"$q:$c"},# remember $v{significado}
	       #     'mp' => sub{ $c},
	       #     'mp' => sub{$c},
	       'ref' => sub {my $a= +{tipo => $v{tipo} || "referência", name => $c};
			     push(@{$dtatributes[_pai()]{"ref"}},$a);"" },
	      );
  dt($filename,%handler)->[0];

}

sub hv2xmlcatalog{
  my $f=shift;
  my $optid = shift;
  $OPTID=$optid;
  $FILE=$f;
  my $ct = { seq       => {
			   rel       => "relations",
			   ref       => "references",
                           historias => "subhists"
			  },
             allattbut => {
			   autor        => "name",
                           pai          => "title",
                           subhistorias => "title",
                           ref          => "name" ,
			   rel          => "name"
			  },
             att       => {
			   entry => ["id"],
                           autor => ["tipo"],
			  }
	   };
  my $t= _2xml( [ _cat2onelevcat(hv2catalog($f,$optid))] , "entry",0,$ct);
  $t =~ s/\&/\&amp;/g;
  $t;
}

sub hv2dbfilecatalog{
  my $f=shift;
  my $dbfilename=shift;
  my $optid = shift;

  $OPTID=$optid;
  $FILE=$f;    

  $x= tie %h,  MLDBM , $dbfilename, O_RDWR|O_CREAT, 0644, $DB_BTREE or die $! ;
  my @a=_cat2onelevcat(hv2catalog($f,$optid));
  for (@a) {
    print "\nprocessing '$_->{id}'\n";
    print Dumper($_);
    $h{$_->{id}} = $_ if $_->{id};
  }

  untie %h;     
}



sub _cat2onelevcat{
  my $t=shift;
  my $h=$t->{historias};
  my %base = %$t;
  my @ind = (); 

  if ($h) {
    $base{subhistorias} = [ map {+{ "id" => $_->{id},
				    "title"=> $_->{title},
				    "url" => $_->{"url"} } } @$h ];
    delete $base{historias};
    push(@ind, +{%base},
	 (map { my $a=+{%$_, pai =>{"id" => $t->{id},
				    "title"=> $t->{title},
				    "url" => $t->{"url"} }}; 
		_cat2onelevcat($a) } @$h));
  } else {
    push(@ind, +{%base});
  }
 
  @ind; 
}

sub _2xml{
  my ($t,$tag,$ind,$ct)=@_;
  my $r = "";
  my $att = "";
  my $i= " " x $ind;

  if (ref($t) eq "HASH") {
    if ($ct->{allattbut}{$tag}) { 
      my $cont=$t->{$ct->{allattbut}{$tag}};
      delete $t->{$ct->{allattbut}{$tag}};
      for (keys %$t) {
	$att .= " $_='$t->{$_}'";
      }
      $r = "\n$i<$tag$att>$cont</$tag>";
    } else {
      if ($ct->{att}{$tag}) { 
	for (@{$ct->{att}{$tag}}) {
	  $att .= " $_='$t->{$_}'"; 
	  delete $t->{$_};
	}
      }
      for my $k (sort keys %$t) {
	$r .= _2xml($t->{$k},$k,$ind + 3,$ct );
      }
      $r= "\n$i<$tag$att>$r\n$i</$tag>";
    }
  } elsif (ref($t) eq "ARRAY") {
    if ($ct->{seq}{$tag}) {
      for (@$t) {
	$r .= _2xml($_,$tag,$ind + 3,$ct );
      }
      $r = "\n$i<$ct->{seq}{$tag}>$r\n$i</$ct->{seq}{$tag}>" ;
    } else {
      for (@$t) {
	$r .= _2xml($_,$tag,$ind,$ct );
      }
    }
  } else {
    $r = "\n$i<$tag>$t</$tag>";
  }

  $r;
}

sub fotos2html{
  my $filename = shift;

  my %handler=(
    '-outputenc' => 'ISO-8859-1',
    '-inputenc' => 'ISO-8859-1',
    '-default'   => sub{strong($q).": $c". br},
     'fotos' => sub{ "<table width='100\%' >$c</table>"},
     'quando' => sub{strong($q).": $c$v{data}". br},
#     'onde' => sub{"<br>$q:$c"},
     'foto' => sub{
         Tr(
           td({align=>"right",width=>'160'},a({ href=> "_Sm_$v{ficheiro}.jpg"},
               img({src=>"_Tn_$v{ficheiro}.jpg"}))),
           td({align=>'left'},small($c))
         ) },# remember $v{ficheiro}
     'facto' => sub{blockquote($c)},
     'quem' => sub{if ($c && $c !~ /^\s*$/) {"<br>$q:$c"} else {""}},
   );
  dt($filename,%handler);     
}

sub hv2html {

  my $filename = shift;
  my $ddir = shift;
  my $optid = shift;
  $OPTID=$optid;

  my ($depoente,%autores,$versao,$biografia,%nas,$proj,$data,$prof,$hcount,@hist,$escritor);

  my $hv = 0;
  my $id = 0;
  pathdt($filename,(
		'-inputenc'=>'ISO-8859-1',
    		'-default'=>sub{""},
		    'hv'=>sub{$hv = 1;$id=_getid()},
		    'mp/h'=>sub{$id=_getid()}));
  #			'hv'=>sub{$id=$v{id}}));
  
  if ($hv) {
      open BI, ">$ddir/$id.bi.html" or die("...");
  }
      open BLOCO, ">$ddir/$id.monobloco.html" or die("...");
  my %data = ();
  my %handler=(
	       '-outputenc' => 'ISO-8859-1',
	       '-inputenc'  => 'ISO-8859-1',
	       '-default'   => sub{print STDERR "$q\n";""},
	       'nota'       => sub{ "" }, #ignore;
	       'biografia'  => sub{$biografia=$c},
	       'pergunta'   => sub{p(b($c))},
	       'projecto'   => sub{$data{Projecto} = $c;""},
	       'data'       => sub{$data{Data}     = $c;""},
	       'versao'     => sub{$data{'Versão'}   = $c;""},
	       'nascimento' => sub{
               $data{Nascimento} = 
			    (($v{data} ne "")?$v{data}.(exists($v{onde})?" em $v{onde}":""):"");
			},
	       'profissao'  => sub{thesaurus_link($c)},
	       '//meta/profissao' => sub{$data{'Profissão'} = $c;""},
	       'mp/h/meta'  => sub{
		 my $html;
		 if ($escritor && !$depoente) { $depoente = $escritor }
		 $html.= hhead($depoente);
		 $html.= h2($depoente);
		 $html.= blockquote($biografia);

		 $html.="<ul>";
		 for (sort keys %data) { $html.=li(b("$_: ").$data{$_}); }
		 for (sort keys %autores) { $html.=li(b("$_: ").$autores{$_}); }
		 $html.="</ul>";

		 "$html<p><a name=\"0\">";
	       },
	       'hv/meta'    => sub{
		 my $html;
		 $html.= hhead($depoente);
		 $html.= h2($depoente);
		 $html.= blockquote($biografia);

		 $html.="<ul>";
		 for (sort keys %data) { $html.=li(b("$_: ").$data{$_}); }
		 for (sort keys %autores) { $html.=li(b("$_: ").$autores{$_}); }
		 $html.="</ul>";

		 print BI $html if ($hv);
		 "$html<p><a name=\"0\">__INDICE__";
	       },
	       'p' => sub{toxml},
	       'r' => sub{$q='em';toxml},
	       'h' => sub{

#            $id=_getid() if inctxt("mp");

		 $hist[++$hcount]={tipo=>$v{tipo},tit=>$v{tit}};
		 open H, ">$ddir/$id.$hcount.html" or die("...");
		 print H hhead("$v{tit}");

		 # Colocar aqui os tipos e links para o thesaurus e afins

		 print H h2($v{tit});
 		 print H "<p align=\"right\">";
		 print H thesaurus_link($v{tipo});
		 print H "</p>\n";
		 print H blockquote($c);
		 print H "<div align=\"right\"><i>$depoente</i></div>";
		 print H "<br>";

		 unless(inctxt("mp")) {
		 	print H "<div align=\"right\">";
		 	print H "[<a href=\"$id.",$hcount-1,".html\">&lt;&lt;</a>]" if $hcount>1;
		 	print H " [<a href=\"$id.bi.html\">Índice</a>] ";
		 	print H "[<a href=\"$id.",$hcount+1,".html\">&gt;&gt;</a>]</div>";
		}


		 print H hfoot();
		 close H;
		 a({name=>$hcount}) . a({href=>"$id.monobloco.html#0"},h3($v{tit})) . blockquote($c);
	       },		# remember $v{tit},$v{tipo}
	       'h/meta'    => sub{
		 my $html;
		 # $html.= hhead($depoente);
		 # $html.= h2($depoente);

		 $html.="<ul>";
		 for (sort keys %data) { $html.=li(b("$_: ").$data{$_}); }
		 for (sort keys %autores) { $html.=li(b("$_: ").$autores{$_}); }
		 $html.="</ul>";

		 "$html<p><a name=\"0\">";
	       },

	       'hv/meta'    => sub{
		 my $html;
		 $html.= hhead($depoente);
		 $html.= h2($depoente);
		 $html.= blockquote($biografia);

		 $html.="<ul>";
		 for (sort keys %data) { $html.=li(b("$_: ").$data{$_}); }
		 for (sort keys %autores) { $html.=li(b("$_: ").$autores{$_}); }
		 $html.="</ul>";

		 print BI $html if ($hv);
		 "$html<p><a name=\"0\">__INDICE__";
	       },
	       'p' => sub{toxml},
	       'r' => sub{$q='em';toxml},
	       'h' => sub{

#            $id=_getid() if inctxt("mp");

		 $hist[++$hcount]={tipo=>$v{tipo},tit=>$v{tit}};
		 open H, ">$ddir/$id.$hcount.html" or die("...");
		 print H hhead("$v{tit}");

		 # Colocar aqui os tipos e links para o thesaurus e afins

		 print H h2($v{tit});
 		 print H "<p align=\"right\">";
		 print H thesaurus_link($v{tipo});
		 print H "</p>\n";
		 print H blockquote($c);
		 print H "<div align=\"right\"><i>$depoente</i></div>";
		 print H "<br>";

		 unless(inctxt("mp")) {
		 	print H "<div align=\"right\">";
		 	print H "[<a href=\"$id.",$hcount-1,".html\">&lt;&lt;</a>]" if $hcount>1;
		 	print H " [<a href=\"$id.bi.html\">Índice</a>] ";
		 	print H "[<a href=\"$id.",$hcount+1,".html\">&gt;&gt;</a>]</div>";
		}


		 print H hfoot();
		 close H;
		 a({name=>$hcount}) . a({href=>"$id.monobloco.html#0"},h3($v{tit})) . blockquote($c);
	       },		# remember $v{tit},$v{tipo}

	       'infancia|familia|casamento|namoro|identificacao|oficio|pprofissional|antepassados' => sub{
		 if ($q ne "identificacao") {
		   my $f="";
		   $f = " - $v{nome}" if $q eq "oficio";
		   $hist[++$hcount]={tipo=>$q,tit=>"$htits{$q}$f"};
		   open H, ">$ddir/$id.$hcount.html" or die("...");
		   print H hhead("$htits{$q}$f");

		   # Colocar aqui os tipos e links para o thesaurus e afins
		   print H "<table bgcolor=\"#dddddd\" align=\"right\"><tr><td>";
		   print H thesaurus_link($q);
		   print H "</td></tr></table>\n";

		   print H h3("$htits{$q}$f").blockquote($c);
		   print H "<div align=\"right\"><i>$depoente</i></div>";
		   print H "<br>";
		   print H "<div align=\"right\">";
		   print H "[<a href=\"$id.",$hcount-1,".html\">&lt;&lt;</a>]" if $hcount>1;
		   print H " [<a href=\"$id.bi.html\">Índice</a>] ";
		   print H "[<a href=\"$id.",$hcount+1,".html\">&gt;&gt;</a>]</div>";
		   print H hfoot();
		   close H;
		   a({name=>$hcount}).a({href=>"$id.monobloco.html#0"},h3("$htits{$q}$f")).blockquote($c);
		 } else {
		   h3($htits{$q}).blockquote($c);
		 }
	       },
	       'autor' => sub{
		   if ($v{tipo}=~/escritor/i) {
		       $escritor = $c;
		   }
		   if ($v{tipo}=~/depoente/i) {
		       $depoente = $c;
		   } else {
		       $autores{$v{tipo}} = $c;
		   }
	       },
	       'resposta' => sub{"<p>$c</p>"},
	       'br' => sub{"</p><p>"},
	       'rel' => sub{
		 thesaurus_link($c);
	       },
	       'versos' => sub{ "<pre>$c</pre>" },
	       'foto' => sub{
		 p({align=>"center"},
                   a({href=>"../fotos/_Sm_$v{href}.jpg"},
                     img({src=>"../fotos/_Tn_$v{href}.jpg"})),br,small($c))},
	       'expressao' => sub{i($c)}, # remember $v{significado}
	       'destaque' => sub{em($c)},
	       'mp' => sub{
		 my $ss = "";
		 my $i;
		 if ($hv) {
		     print BI b("Documento Completo:"),a({href=>"$id.monobloco.html"},"&gt;&gt;"),br,br;
		     print BI b("Histórias:"),"<ul>";
		 }
		 $ss .= b("Histórias:")."<ul>";
		 for ($i=1;$i<=$#hist;++$i) {
		   print BI li(a({href=>"$id.$i.html"},$hist[$i]->{tit}));
		   $ss .= li(a({href=>"$id.monobloco.html#$i"},$hist[$i]->{tit}));
		 }
		 $ss .= "</ul>";
		 print BI "</ul>" if ($hv);

		 $c=~s/__INDICE__/$ss/;
		 print BLOCO $c;
	       },
	       'ref' => sub{thesaurus_link($c)},	# remember $v{tipo}
	       'hv' => sub{
		 if (exists($v{tit})) {
		   for ($c) {
		     s!</TITLE>! - $v{tit}</TITLE>!;
		     s!</H2>!</H2><H3>--- $v{tit}</H3>!;
		   }
		 }
		 "$c"},
	      );
  pathdt($filename,%handler);

  if ($hv) {
      print BI hfoot();
      close BI;
  }
  print BLOCO hfoot();
  close BLOCO;

}

sub hhead {
  my $title = shift;
  return "<HTML>".head(title($title))."<BODY>"; 
}

sub hfoot {
  return "";
#  return <<EOT;
# </body></html>
#EOT
}

sub thesaurus_link {
  my $text = shift;
  my @ts = split /\s*;\s*/, $text;
  return join "\n", map {my $x = $_;s/\s/+/g;"<a href=\"$thesaurus_path?$thesaurus_op=$_\">$x</a>"} @ts;
}

sub hv2latex{
  my ($opt,@h)=@_;
  my %opt = ( size       => "agenda", 
              tit        => "Histórias de vida", 
              autor      => "Museu da Pessoa",
              compact    => "normal",
              tipo       => "article",
              projecto   => "",
              %$opt );

  my $f= $opt{output} || $h[0];
  $f =~ s/\.xml$/.tex/ or $f .= '.tex';

  my ($dirhist, $history);

  my %handler=(
    '-outputenc'=> 'ISO-8859-1',
    '-inputenc'=> 'ISO-8859-1',
    '-default'  => sub{$c},
    '-pcdata'   => sub{$c =~ s/â\x80¦/.../g;$c =~ s/\&/\\&/g;$c },
     'resposta' => sub{"\n\n \\noindent $c\n\n"},
     'pergunta' => sub{"\\mbox{}\\\\[-3mm] {\\bf $c}\n\n"},
     'audio'    => sub{"\\marginpar{{\\scriptsize $v{t1}}}"},
     'data'     => sub{$data="$c";""},
     'hh'       => sub{"{\\small \\textbf{História da história} - $c } \n\n"},
     'ref'      => sub{"\\textbf{$c}\\index{$v{tipo} - $c}\n"},
     'rel'      => sub{"\n\n\\noindent {\\small $c}\n"},
     'biografia'=> sub{push(@destaque,$c); ""},
     'meta'     => sub{
        $meta = ((@meta)
            ? "\n\n" . join('\\\\',@meta)."\n\n"
            :""). $c;
        ""; },
     'p'        => sub{"\n\n$c\n\n"},
     'br'       => sub{"\n\n"},
     'h'        => sub{
       if(inctxt("mp")){ $titulogeral= $titulo = $v{tit}; 
                 $titulo .= " - $v{_escritor}" if $v{_escritor};
                 mkchap($opt{compact});}
       else{ my $tipo=$v{tipo} || $v{t};
        my $tt = $v{tit};
        $tt =~ s/"(.*?)"/\\emph{$1}/g;
        $tt =~ s/'(.*?)'/\\emph{$1}/g;
        
	(_geracao() == 2 ?  "\\subsection{" : "\\subsubsection{") .
        ($v{tit}
          ?"$tt}\n{\\scriptsize $v{data} $v{onde} $v{tipo}}\n\n"
          : ucfirst($tipo) . "}\n{\\scriptsize $v{data} $v{onde}}\n\n").
        $c}}, 

     'projecto' => sub{$proj=$c;push(@meta, "\\textbf{$c}"); "" },
     'nascimento' => sub{push(@meta, "\\textbf{Nascido em} $c $v{onde} $v{data}"); "" },
     'evento'    => sub{
         "\\subsection{$v{tit} ($v{data})}\n $c"},
     'versao'    => sub{"\n\n\\noindent $c\n\n"},
     'versos'    => sub{$c =~ s/\n/\\\\/g;
                        "{\\begin{verse}$c\\end{verse}}\n"},
     'destaque'  => sub{push(@destaque,"...$c...") unless $opt{nodest}; 
                       ($v{tipo})? "" : $c},
     'foto'      => sub{ my $foto;
         if(-e "$dirhist/fotos/__$v{href}.eps")
                 {$foto = "$dirhist/fotos/__$v{href}.eps";}
         elsif(-e "$v{href}.eps"){$foto = "$v{href}.eps";}
         elsif(-e "fotos/$v{href}.eps"){$foto = "fotos/$v{href}.eps";}
         elsif(-e "$v{href}.jpg"){system("jpeg2ps $v{href}.jpg > $v{href}.eps");
                                  $foto = "$v{href}.eps";}
         else                    {$foto = 
                 "NAO ENTCONTREI $dirhist/fotos/\\_\\_$v{href}.eps"}
         if(defined $v{scale}){
             $v{scale} /= 100 if $v{scale} > 2 ;
             "\n\n\\img{$foto}{$v{scale}}\n\n$c\n\n", }
         else { "\n\n\\bigimg{$foto}\n\n$c\n\n"}},
     'profissao'=> sub{$pro="$c";""},
     'autor'    => sub{
        $v{tipo}="$v{role}$v{papel}$v{tipo}";
        delete $v{role};
        delete $v{papel};
        if ($v{tipo} eq "vida" ||
            $v{tipo} eq "vida de"  ||
            $v{role} eq "vida de"  ||
            $v{tipo} eq "depoente"  ||
            $v{tipo} eq "Depoente"  ||
            $v{tipo} eq "vida"
           ) {$titulogeral= $titulo=$c;}
        $dtatributes[_pai()]{_escritor}=$c  if $v{tipo} eq "escritor";
        $v{tipo}="Escrito por"  if $v{tipo} eq "escritor";
        push(@meta,"\\textbf{$v{tipo}} - $c");""},
     'hv'      => sub{ mkchap($opt{compact})} ,
     'mp'      => sub{$c},

     'casamento'     => sub{"\\subsection{$htits{$q}} $c";},
     'identificacao' => sub{"\\subsection{$htits{$q}} $c";},
     'antepassados'  => sub{"\\subsection{$htits{$q}} $c";},
     'oficio'        => sub{"\\subsection{$htits{$q}} $c";},
     'namoro'        => sub{"\\subsection{$htits{$q}} $c";},
     'infancia'      => sub{"\\subsection{$htits{$q}} $c";},
     'familia'       => sub{"\\subsection{$htits{$q}} $c";},
     'pprofissional' => sub{"\\subsection{$htits{$q}} $c";},   

     '-end' => sub{ $c }
  );

  if($opt{justsection}){
      unless ( ($dirhist = $h[0]) =~ s#(.*)/(.*)#$1# ) { $dirhist=".";}
      my $text = dt($h[0],%handler);
      return($text)
  }
  elsif($opt{single})

    { open(F,">$f") or die;
      unless ( ($dirhist = $h[0]) =~ s#(.*)/(.*)#$1# ) { $dirhist=".";}

      my $text = "\\newpage\n". dt($h[0],%handler);
      print F textofinal($titulogeral,
                         $opt{autor},
                         $opt{size},
                         $proj||$opt{projecto},
                         $opt{pre},
                         $opt{tipo}   );
      print F $text;
      print F "\\newpage \\mbox{}\\vfill $opt{end} " if defined $opt{end};
      print F "\n \\end{document}\n";
      close F;
  }                  
  else{
      open(F,">$f") or die;
      print F (textofinal($opt{tit},
                         $opt{autor},
                         $opt{size},
                         $opt{projecto},
                         $opt{pre},
                         $opt{tipo},
                         ));
      for(@h){
        my $historia = $_;
        $historia =~ s/\.xml$//;
        unless ( ($dirhist = $historia) =~ s#(.*)/(.*)#$1# ) {
$dirhist=".";}
        print F "\\newpage\n", ((dt($_,%handler)));
      }
      print F "\\newpage \\mbox{}\\vfill $opt{end} " if defined $opt{end};
      print F "\n \\end{document}\n";
      close F;
  }
}                       

sub textofinal {
  my $t = shift;
  my $a = shift;
  my $size= shift;
  my $projecto = shift;
  my $pre = shift;
  my $page = shift;
  my $pts = (($size =~ s/s$//)? ",10pt":"");
  $projecto = "\\\\\\begin{large}$projecto\\end{large}" if $projecto;

  my $aftertitle= $page eq "article" ? '\vfill':'\newpage';
  my $docclass= $page eq "book" ? 'book':'article';
  my $textofinal = <<".";
\\documentclass[portuges$pts]{$docclass}
\\usepackage{babel}
\\usepackage{$size}
\\usepackage{graphicx}
\\usepackage[latin1]{inputenc}
\\usepackage{t1enc}

\\usepackage{fancyhdr}
\\pagestyle{fancy}
%\\fancyhead[LE,RO]{\\thepage}
%\\fancyfoot{}
\\renewcommand{\\chaptermark}[1]{\\markboth{ \\thechapter.\\ #1}{}}
\\renewcommand{\\sectionmark}[1]{\\markright{ \\thesection.\\ #1}}
%\\rhead{\\nouppercase{\\rightmark}}
%\\lhead{\\nouppercase{\\leftmark}}
\\fancyhead[RO]{\\nouppercase{\\rightmark}}
\\fancyhead[LE]{\\nouppercase{\\leftmark}}
\\fancyhead[RE,LO]{}

\\makeindex
\\begin{document}
\\title{$t}
\\author{$a$projecto}
\\maketitle
$aftertitle
{\\small
\\tableofcontents
}
.
 
  $textofinal .
  ($pre? "\\newpage \\mbox{} \\vfill { \\it $pre} \\vfill \\mbox{} " : "")
}

sub mkchap{
   my $compact = shift;
   $c =~ s!([\$\%])!\\$1!g;
   my $profissao = "";
   $profissao = "\\\\{\\small $pro}" if $pro;
   my $r=  "\\section[$titulo]{$titulo $profissao}\n$meta".
 ((@destaque)?('\vfill ' .join("\n\n",@destaque). '\vfill'):""). 
   ($compact eq "normal" ? "\\newpage\n$c" : "\\mbox{}\\\\\\mbox{}\n$c") ;
   $titulo= $pro = $meta = $biografia = "";
   @destaque = @meta=();
   $r;
}

sub sinopsis_project {
  my $file = shift;
  my $project;
  dt($file, (
         '-outputenc' => 'ISO-8859-1',
         '-inputenc'  => 'ISO-8859-1',
         'project'    => sub{$project = $c },
        ));
  return $project;
}

sub h_tit {
  my $file = shift;
  my $title;
  pathdt($file, (
         '-outputenc' => 'ISO-8859-1',
         '-inputenc'  => 'ISO-8859-1',
         'mp/h'    => sub{$title = $v{tit} },
        ));
  return $title;
}

sub sinopsis {
  my $de = shift;
  my $para = shift || undef;

  if (defined($para)) {
    open D, ">$para" or die ("Cannot open sinopsis file: $!");
    select D;
  }
  my @secs;

  my $count=0;
  my $project;

  print dt($de, (
		 '-outputenc' => 'ISO-8859-1',
		 '-inputenc'  => 'ISO-8859-1',
		 'p'          => sub{ toxml },
		 'sinopse'    => sub{ $c . "</blockquote>"
				      },
		 'section'    => sub{
		     ++$count;
		     my $path ="$para.$count.html";
		     $path = $' if $path =~ /.*\//;
		     if( defined $v{url}){ 
			 "<li><a href=\"$v{url}\">$v{title}</a></li> ";}
		     else {
			 open T, ">$para.$count.html";
			 print T "<blockquote><h2>$v{title}</h2><div align=\"right\"><a href=\"_index_.html\">$project</a></div>";
			 print T "<blockquote>$c</blockquote></blockquote>";
			 close T;
			 "<li><a href=\"$path\">$v{title}</a></li> ";
		     }
		 },
		 'image'      => sub{
		   if ($v{href} =~ m{^(.*)/([^/]+)$}) {
		     $v{href} = "$1/_Tn_$2.jpg";
		   } else {
		     $v{href} =~ m{^([^/]+)$};
		     $v{href} = "fotos/_Tn_$1.jpg";
		   }
			my $l = $v{href};
			$l =~ s/_Tn_/_Sm_/;
		   "<center><a href=\"$l\"><img border=0 src=\"$v{href}\" alt=\"$c\"></a><br><small>$c</small></center>" 
		 },
		 'project'    => sub{
		   $project =$c; "<h2>$c</h2>" },
		 'author'     => sub{
		   if ($c) {
		     "<div align=\"right\"><i>$c</i></div>"
		   }
		 },
		 'date'     => sub{
		   if ($c) {
		     "<div align=\"right\"><i>$c</i></div>"
		   }
		 },
		 'text'       => sub{ "$c</ul>" },
		 'abstract'   => sub{
		   "<blockquote><i>$c</i><ul>"
		 },
		 '-default'   => sub{ toxml; },
		));

  close D if D;

  select STDOUT;
}

sub livro2latex{
  my ($opt,$if)=@_;
  my %opt = ( compact=>"normal", tipo => "book", size  => "agenda", %$opt );
  my $parser = new HTML::Latex();
  my $f= $opt{output} || $if;
  $f =~ s/\.xml$/.tex/ or $f .= '.tex';

  my ($tit,$autor,$proj,$contact) = ("Histórias","Museu da Pessoa","","");
  my %handler=(
    '-outputenc' => 'ISO-8859-1',
     '-default'   => sub{$c},
     'titulo' => sub{$tit = $c; ""},
     'contactos' => sub{$contactos=$c;"\\newpage\\mbox{}\\vfill$c"},
     'sect' => sub{if($v{subtit}){"\\newpage\\chapter[$v{tit} $v{subtit}]{$v{tit}\\\\\\Large{$v{subtit}}}$c"}
                   else{"\\newpage\\chapter{$v{tit}}$c"}},
     'chap' => sub{if($v{subtit}){"\\newpage\\part[$v{tit} $v{subtit}]{$v{tit}\\\\\\Large{$v{subtit}}}$c"}
                   else{"\\newpage\\part{$v{tit}}$c"}},
     'projecto' => sub{$proj=$c;""},
     'p' => sub{"\n$c\n"},
     'hvhtml' => sub{
	 print "$c\n";
        my $latexfile = $parser->parse_string(join("\n",`cat $c`),0);
        $latexfile =~ s/\\includegraphics\[.*?\](.*?\})/\n\n\\img$1\{0.6\}/g;
        $latexfile =~ s/\.png/.png.eps/g;
        "\\newpage\\section[$v{tit}" .  (defined $v{aut} ? " - $v{aut}" : "" ) .  "]{$v{tit}}".
        (defined $v{aut} ? "\\textbf{Escrito por} - $v{aut}\\\\\n\n":"").
        $latexfile;},
     'hv' => sub{
	 print "$c\n";
         "\\newpage\n"
         . hv2latex({justsection=>1,
                     compact=>$opt{compact}, 
                     tipo=>$opt{tipo},
                     size=>$opt{size}},$c)},
     'livro' => sub{
         textofinal($tit,
                    $autor,
                    $opt{size},
                    $proj,
                    undef,
                    $opt{tipo})
         . $c 
         ."\\end{document}\n"},
     'sinopsis' => sub{
         "\\newpage \\mbox{} \\vfill {\\it $c}\\vfill\\mbox{}"},
   );

   my $l=dt($if,%handler);
   open(F, ">$f") or die;
   print F $l;
   close F;
}       
                           

1;

__END__


=head1 NAME

mp - perl module to process Museu da Pessoa documents

=head1 SYNOPSIS

  use mp;
  hv2html(f.xml, dir)
  $a = hv2catalog(f.xml)
  print hv2xmlcatalog(f.xml)

=head1 DESCRIPTION

=head2 C<hv2html>

Builds a set of HTML with all the stories in a mp document, a html index, and
a all-in-one page of the set of stories.

=head2 C<hv2latex>

Builds a latex file with all the stories in a mp document. Many options
available. See also hv2smallbook in exemple directory

 hv2latex({options},inputfile
 options
   justsection   -> returns the latex translation as a section with
       no title page, etc
   output => output file name
   tit   => tiles
   autor => author
   size  => {a5,a6,ag...}
   projecto => project name
   pre   => preambulo
   end   => endpage      

=head2 C<hv2catalog>

Returns a perl struture with the catalogue of all the stories in a document 
following mp.dtd

=head2 C<hv2xmlcatalog>

Returns the XML catalogue of all the stories in a document following mp.dtd

=head2 C<hv2dbfilecatalog>

Returns the XML catalogue of all the stories in a document following mp.dtd

=head2 C<sinopsis>

Passing two file names, uses the first as a XML sinopsis file, processes
it and saves with the second file name.

=head1 AUTHOR

J.Joao Almeida <jj@di.uminho.pt>

Alberto Simoes <albie@alfarrabio.di.uminho.pt>

=head1 SEE ALSO

perl(1).

=cut
