package mp;
use Encode;

#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 open OUT=>':encoding(iso-8859-1)';
# use HTML::Latex;

require Exporter;

my $thesaurus_path = "/mpbin/thesaurus.pl";
my $mp_path = "/home/mp/new_site";
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",
	      decendencia => "Descendentes",
	      casamento => "Casamento",
	      namoro => "Namoro",
	      identificacao => "Indentificação",
	      oficio => "Ofício",
	      pprofissional => "Percurso Profissional",
	      antepassados => "Antepassados",
	      ascendencia => "Antepassados");

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

my $meta="";
my @meta=();

# identificacao

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

sub _pai{
    my $hist = shift;
    (ctxt(1) =~ m/^($hist)$/) ? 1 :
	(ctxt(2) =~ m/^($hist)$/) ? 2 : 
	    (ctxt(3) =~ m/^($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 $path = shift;

  my $pai=_pai($hist);
  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 => "$path/$id.$idh.html" )
	      : ( id => $id, url =>(($q eq "hv")? "$path/$id.bi.html"
                                            : "$path/$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;
  my $opts = shift;

  $OPTID = $optid;
  $FILE = $filename;

  $path = $opts->{url_prefix};

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

	       '-outputenc' => 'ISO-8859-1',
	       '-default'   => sub{if($q =~ /^($hist)$/){&ph($path)}
				   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($hist)]{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($path);},
	       #     '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($hist)]{"ref"}},$a);"" },
	      );
  dt($filename,%handler)->[0];

}

sub historiasDeVida2catalog{
  my $filename = shift;
  my $optid = shift;
  my $depoente = "unamed";
  #my $meta=  "";
  my $rel="";
  $OPTID=$optid;
  $FILE=$filename;

  my %handler=(
       '-outputenc' => 'ISO-8859-1',
       '-default'      => sub{""},

	# 'p'             => sub{ toxml },

       'meta'          => sub{$meta=$c},
       'depoente'      => sub{
	   $c =~ s/\n/ /g;
	   $c =~ s/\s+/ /g;
	   $depoente = $c ; 
       },
       # 'nascimento'    => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
       # 'entrevistador' => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
       'oficio'  => sub{if($v{titulo}){
                         $rel.="\t<rel tipo='profissao'>$v{titulo}</rel>\n";}
                       },
       # 'data'     => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
       # 'projecto' => sub{$q = ucfirst($q); "<ul><li><b>$q:</b> $c</li></ul>"},

       );
  
  
  dt($filename,%handler).
  return "<entry id=\"$optid\">
  <autor tipo=\"depoente\">$depoente</autor>
  <relations>
$rel
  </relations>
</entry>";

}

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

  my %handler=(
	       '-outputenc' => 'ISO-8859-1',
	       '-default'      => sub{""},

	       'entrevista'    => sub{"$c"},
		# 'p'             => sub{ toxml },

	       'meta'          => sub{"$c"},
	       'depoente'      => sub{
		   $c =~ s/\n/ /g;
		   $c =~ s/\s+/ /g;
		   "<autor tipo=\"depoente\">$c</autor>";
	       }
	       # 'nascimento'    => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
	       # 'entrevistador' => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
	       # 'profissao'     => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
	       # 'data'          => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
	       # 'projecto'      => sub{$q = ucfirst($q); "<ul><li><b>$q:</b> $c</li></ul>"},

	       # 'pergunta'      => sub{"<b>$c</b>"},
	       #'resposta'      => sub{"<blockquote>$c</blockquote>"},
	       );
  
  
  return "<entry id=\"$optid\">".
      dt($filename,%handler).
	  "</entry>";

}


sub hv2xmlcatalog{
  my $f=shift;
  my $optid = shift;
  my $optattr = 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,$optattr))] , "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 $counter = 0;
  my %h = (
	   '-outputenc' => 'ISO-8859-1',
	   '-default'   => sub{ strong($q).": $c". br},
	   'fotos'      => sub{
	     my $close = "";
	     $close = "</tr>" if ($counter % 2);
	     "<table width='100\%'>$c$close</table>"},
	   'quando'     => sub{strong($q).": $c$v{data}". br},
	   #     'onde' => sub{"<br>$q:$c"},
	   'foto' => sub{
	     my $res = "";
	     $counter ++;
	     if ($counter % 2) {
	       $res .= "<tr>";
	     }
	     $res .= td(
	"<table><tr><td><a href=\"_Sm_$v{ficheiro}.jpg\"><img style=\"border: solid thin #000000\" src=\"_Tn_$v{ficheiro}.jpg\"></a></td><td>$c</td></tr></table>");

	     unless ($counter %2) {
	       $res .= "</tr>";
	     }
	     return $res;
	   },# remember $v{ficheiro}
	   'facto' => sub{blockquote($c)},
	   'autor' => sub{"<strong>Fotógrafo:</strong> <i>$c</i><br>" },
	   'legenda' => sub{blockquote($c)},
	   'quem' => sub{if ($c && $c !~ /^\s*$/) {"<br>$q:$c"} else {""}},
	  );
  dt(shift,%h);
}

sub historiaDeVida2html {
	my $filename = shift;
	my $depoente = "unnamed";
    my %handler = (
    '-outputenc' => 'ISO-8859-1',
#    '-default'   => sub{"<$q>$c</$q>"},
     'depoente' => sub{$depoente=$c; $c},# 1
     'infancia' => sub{h3("Infância").$c},# 1
     'sonhos' => sub{h3("Sonhos").$c},# 1
     'historiaDeVida' => sub{$c},# 1
     'ascendencia' => sub{h3("Ascendência").$c},# 1
     'educacao' => sub{h3("Educação").$c},# 1
     'oficio' => sub{h3("Ofício". ($v{titulo}? " de $v{titulo}":"")).$c},# 1
     'identificacao' => sub{h3("Identificação").$c},# 1
     'br' => sub{"<br/>"},# 16
);
    my $entrevista = dt($filename,%handler); 
    return "<h2>$depoente</h2>$entrevista";
}

sub ESCRIBA2html {
    my $filename = shift;
    my $depoente = "unnamed";
    my %handler=(
		 '-outputenc' => 'ISO-8859-1',
		 '-default'      => sub{"<font color=\"#ff0000\">$q unknown</font>"},

		 'COMENTARIOS' => sub{""},
		 'TEXTO' => sub{"</ul>$c"},# 1
		 'PALCHAVE' => sub{"<em>$c</em>"},# 1
		 'TRANSCRICAO/DATA' => sub{"#$c"},# 3
		 'DATA' => sub{"<li><b>Data:</b> $c</li>"},
		 'CATEGORIA' => sub{"<li><b>Categoria:</b> $c</li>"},# 1
		 'TITULO' => sub{""},# 1
		 'MULTIMEDIA' => sub{""},# 1
		 'TRANSCRICAO' => sub{
		     $c =~ m!#\s*(\S+?)\s*#!;
		     my $link = $1;
		     my $data = $';
		     $c = $`;
		     $c =~ s/<LINK>/<a href="mailto:$link">/;
		     "$c ($data)</li>";
		 },
		 'TRANSCRICAO/AUTOR' => sub{
		     "<li><b>Transcrição:</b> <LINK>$c</a>"
		     },# 1
		 'TRANSCRICAO/EMAIL' => sub{
		   "#$c";
		 },# 1
		 'AUTOR' => sub{
		   $c
		 },
		 'AUTOR/NOME' => sub{
		     $depoente = "$c";
		     "<li><b>Depoente:</b> $c</li>"
		     },# 1
		 'resposta' => sub{"<blockquote>$c</blockquote>"},# 38
		 'DESCRICAO' => sub{""},# 1
		 'AUDIO' => sub{""},# remember $v{Formato}# 1
		 'pergunta' => sub{"<p><b>$c</b></p>"},# 38
		 'EPOCA' => sub{""},# 1
		 'EMAIL' => sub{"$c"},# 1
		 'DOCUMENTO' => sub{"$c"},# 1
		 'LOCAL' => sub{"<li><b>Local:</b> $c</li>"},# 1
		 'ESCRIBA' => sub{"<ul>$c"},# remember $v{VERSAO}# 1
		 'FICHEIRO' => sub{"$q:$c"},# 1
		 );
    my $entrevista = pathdt($filename,%handler); 
    return "<h2>$depoente</h2>$entrevista";
}

sub ESCRIBA2catalog{
  my $filename = shift;
  my $optid = shift;
  $OPTID=$optid;
  $FILE=$filename;
  my $autor = "<autor tipo=\"depoente\">unnamed</autor>";
  my %handler=(
	       '-outputenc' => 'ISO-8859-1',
	       '-default'      => sub{""},

	       'ESCRIBA'    => sub{"$c"},
		# 'p'             => sub{ toxml },
	       '//AUTOR/NOME' => sub{
		 $c =~ s/\n/ /g;
		 $c =~ s/\s+/ /g;
		 $autor = "<autor tipo=\"depoente\">$c</autor>";
	       },# 1

	       );

  pathdt($filename,%handler).
  return "<entry id=\"$optid\">$autor</entry>";
}



sub entrevista2html {
    my $filename = shift;

    my $depoente = "unnamed";
    my %handler=(
		 '-outputenc' => 'ISO-8859-1',
		 '-default'      => sub{"<font color='#ff0000'>$q unknown</font>$c"},

		 'entrevista'    => sub{"$c"},
		 'p'             => sub{ toxml },

		 'meta'          => sub{"<ul>$c</ul>"},
		 'depoente'      => sub{
		     $depoente = $c;
		     $q = ucfirst($q); 
		     "<li><b>$q:</b> $c</li>"},
		 'expressao'     => sub{
		   my $significado = $v{sgnificado};
		   "  <acronym title=\"$significado\">$c</acronym>   "
		 },
		 'nascimento'    => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
		 'entrevistador' => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
		 'profissao'     => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
		 'biografia'     => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
		 'data'          => sub{$q = ucfirst($q); "<li><b>$q:</b> $c</li>"},
		 'projecto'      => sub{$q = ucfirst($q); "<ul><li><b>$q:</b> $c</li></ul>"},

		 'pergunta'      => sub{"<b>$c</b>"},
		 'resposta'      => sub{"<blockquote>$c</blockquote>"},




		 );
    my $entrevista = dt($filename,%handler); 
    return "<h2>$depoente</h2>$entrevista";
}

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;

  if (`cat $filename|grep DOCTYPE` =~ m!mp\.dtd!) {
    open BI, ">$ddir/$optid.bi.html" or die ("...");
    print BI dt($filename,
		(
		 '-outputenc' => 'ISO-8859-1',
		 '-default' => sub{
		     "<font color='#ff0000'>unknown tag: $q (".join(",",keys %v).")\n";
		 },
		 'identificacao' => sub {
		     "<h3><a name=\"#identificacao\">Identificação</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },
		 'percursoprofissional' => sub {
		     "<h3><a name=\"#pprofissional\">Percurso Profissional</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },
		 'casa' => sub {
		     "<h3><a name=\"#casa\">Casa</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },
		 'descendencia' => sub {
		     "<h3><a name=\"#descendencia\">Descendência</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },
		 'ascendencia' => sub {
		     "<h3><a name=\"#ascendencia\">Ascendência</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },
		 'educacao' => sub {
		     "<h3><a name=\"#educacao\">Educação</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },

		 'infancia' => sub {
		     "<h3><a name=\"#infancia\">Infância</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },
		 'politica' => sub {
		     "<h3><a name=\"#politica\">Política</a></h3>".
			 "<blockquote>$c</blockquote>";
		 },
		 'historia' => sub { # quando e titulo
		     (($v{titulo})?
		      "<h3><a name=\"#historia\">Evento Histórico - $v{titulo}</a></h3>":
		      "<h3><a name=\"#historia\">Evento Histórico</a></h3>").
			  "<blockquote>$c</blockquote>";
		 },
		 'oficio' => sub {
		     (($v{titulo})?
		      "<h3><a name=\"#oficio\">Ofício - $v{titulo}</a></h3>":
		      "<h3><a name=\"#oficio\">Ofício</a></h3>").
			  "<blockquote>$c</blockquote>";
		 },
		 'lazer' => sub {
		     (($v{actividades})?
		      "<h3><a name=\"#lazer\">Lazer - $v{actividades}</a></h3>":
		      "<h3><a name=\"#lazer\">Lazer</a></h3>").
			  "<blockquote>$c</blockquote>";
		 },

		 'episodio' => sub {
		     "<h3>$v{titulo}</h3><blockquote>$c</blockquote>"
		 }, # titulo and termo
		 'foto' => sub {
		     "<a href='../fotos/_Sm_$v{ficheiro}.jpg'>".
			 "<img align='right' src='../fotos/_Tn_$v{ficheiro}.jpg'></a>"
		 }, # ficheiro
		 'p' => sub { toxml },
		 'mp' => sub { "$c" },
		 'ref' => sub{thesaurus_link($c)},	# remember $v{tipo}
		 'lugar' => sub { toxml }, #titulo, onde
		 )
		);
    close BI;
  } else {
    pathdt($filename,(
		      '-outputenc'=>'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("...");
    } else {
      symlink("$id.monobloco.html","$ddir/$id.bi.html");
    }
    open BLOCO, ">$ddir/$id.monobloco.html" or die("...");
    my %data = ();
    my %handler=(
		 '-outputenc' => 'ISO-8859-1',
		 '-default'   => sub{
		   print STDERR "Unkown tag: $q\n\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|ascendencia|educacao' => 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       => "agbookheader", 
              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',
    '-default'  => sub{$c},
    '-pcdata'   => sub{
           #$c = encode("iso-8859-1", $c) if Encode::is_utf8($c);
            $c =~ s/â\x80¦/.../g;
					   $c =~ s/\$/\\\$/g;
					   $c =~ s/\%/\\\%/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;
         my $img=$v{href} || $v{ficheiro} ;
         if(-e "$dirhist/fotos/__$img.pdf") {$foto = "$dirhist/fotos/__$img";}
         elsif(-e "$img.pdf"){$foto = "$img";}
         elsif(-e "$img.jpg"){$foto = "$img.jpg";}
         elsif(-e "fotos/$img.pdf"){$foto = "fotos/$img";}
         elsif(-e "fotos/$img"){$foto = "fotos/$img";}
         elsif(-e "fotos/$img.jpg"){$foto = "fotos/$img.jpg";}
         else {$foto = "NAO ENTCONTREI $dirhist/fotos/\\_\\_$img.pdf"}
         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($hist)]{_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{tit},
                         $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 entrevista2latex{
  my ($opt,@h)=@_;
  my %opt = ( size       => "agbookheader", 
              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 $meta;
  #my @meta = ();

  my ($dirhist, $history);

  my %handler=(
	       '-outputenc'=> '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;
         my $img=$v{href} || $v{ficheiro} ;
         if(-e "$dirhist/fotos/__$img.pdf") {$foto = "$dirhist/fotos/__$img";}
         elsif(-e "$img.pdf"){$foto = "$img";}
         elsif(-e "$img.jpg"){$foto = "$img.jpg";}
         elsif(-e "fotos/$img.pdf"){$foto = "fotos/$img";}
         elsif(-e "fotos/$img.jpg"){$foto = "fotos/$img.jpg";}
         else {$foto = "NAO ENTCONTREI $dirhist/fotos/\\_\\_$img.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";""},
	       'depoente'    => sub{
		 $titulogeral= $titulo=$c;
	       },
	       'entrevista'      => sub{ mkchap($opt{compact})} ,
	       
	       '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 ESCRIBA2latex{
  my ($opt,@h)=@_;
  my %opt = ( size       => "agbookheader", 
              tit        => "Histórias de vida", 
              autor      => "Museu da Pessoa",
              compact    => "normal",
              tipo       => "article",
              projecto   => "",
              %$opt );

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

  my ($dirhist, $history);

  my %handler=(
	       '-outputenc'=> '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;
         my $img=$v{href} || $v{ficheiro} ;
         if(-e "$dirhist/fotos/__$img.pdf") {$foto = "$dirhist/fotos/__$img";}
         elsif(-e "$img.pdf"){$foto = "$img";}
         elsif(-e "$img.jpg"){$foto = "$img.jpg";}
         elsif(-e "fotos/$img.pdf"){$foto = "fotos/$img";}
         elsif(-e "fotos/$img.jpg"){$foto = "fotos/$img.jpg";}
         else {$foto = "NAO ENTCONTREI $dirhist/fotos/\\_\\_$img.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";""},
	       'depoente'    => sub{
		 $titulogeral= $titulo=$c;
	       },
	       'entrevista'      => sub{ mkchap($opt{compact})} ,
	       
	       '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{}

\\providecommand{\\chaptermark}[1]{\\markboth{ \\thechapter.\\ #1}{}}
\\providecommand{\\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
\\newpage
{\\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',
         'project'    => sub{$project = $c },
        ));
  return $project;
}

sub h_tit {
  my $file = shift;
  my $title;
  pathdt($file, (
         '-outputenc' => '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',
		 'p'          => sub{ toxml },
		 'sinopse'    => sub{ $c 
				      },
		 '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 "<h2>$v{title}</h2><div align=\"right\"><a href=\"_index_.html\">$project</a></div>";
			 print T "$c";
			 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{
		   "<i>$c</i><ul>"
		 },
		 '-default'   => sub{ toxml; },
		));

  close D;

  select STDOUT;
}

sub livro2latex{
  my ($opt,$if)=@_;
  my %opt = ( compact=>"normal", tipo => "book", size  => "agbookheader", %$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;
}

sub biografia_bi {
  my $filename = shift;
  my %handler=(
	    #'-outputenc' => 'ISO-8859-1',
	    '-default'   => sub{ "" },
	    'bi' => sub{ "$c" },
	    'biografia' => sub{$c },
	    );
  return dt($filename,%handler);
}

sub bi2html {
  my $biname = shift;
  my $bi = loadBI($biname);
  my %DATA = (%$bi);
  my $tmpl = HTML::Template->new(filename => search_template('bi.tmpl'),
				 die_on_bad_params => 0);
  $tmpl->param(%DATA);
  return $tmpl->output;
}

sub mp2rels {
  my $file = shift;
  my @k = qw/mp p verso sonhos quotidiano resposta estrofe poema
             pergunta foto episodio/;
  my @rels = ();
  dt($file,
     -default => sub {
       unless(grep{$_ eq $q}@k) {
	 print STDERR "MP2RELS: $q\n";
       }
     },
     ref => sub {
       $q = "rel";
       push @rels, toxml
     }
    );
  return @rels;
}

sub bi2catalog {
  my $biname = shift;
  my $filename = shift;
  my $id = shift;
  my $data = shift;
  my $bi = loadBI($biname);

  print STDERR "\n\n BI is \n------------------",Dumper($bi),"-----------\n\n";

  my $title = $bi->{titulo} || $bi->{depoente};
  my @rels = mp2rels($filename);
  my $rels = join("\n",
		  (map { "<rel>$_</rel>" } @{$bi->{rel}}),
		  @rels);
  $rels =~ s/\&/\&amp;/g;
  return <<"EOCAT";
 <entry id="$id">
  <title>$title</title>
  <url>$data->{url_prefix}</url>
  <project>$bi->{projecto}</project>
  <rel tipo="about">Museu da Pessoa</rel>
  $rels
 </entry>
EOCAT
}


sub search_template {
  my $filename = shift;
  my $tries = shift || 10;
  return $filename if (-f $filename);
  return undef unless $tries;
  return search_template("../$filename", $tries-1);
}


#####################
sub loadBI {
  my $filename = shift;
  my @meses = qw/Janeiro Fevereiro Março Abril Maio Junho Julho Agosto Setembro Outubro Novembro Dezembro/;
  my %handler =
    ( -type => {
		bi => MMAPON('rel'),
	       },
      #-outputenc=>'ISO-8859-1',
      'data' => sub { [$v{dia},$v{mes},$v{ano}] }, #remember 'dia', 'mes', 'ano'
      'nascimento' => sub {
        my $mes = $v{mes};
        $mes = $meses[$v{mes}-1] if $mes =~ m!\d!;
	"$v{onde}, $v{dia} de ".$mes." de $v{ano}" #TODO: HANDLE NOT COMPLETES
      }, #remember 'dia', 'mes', 'ano', 'onde'
      'foto' => sub { $v{ficheiro} }, #remember 'ficheiro'
      #      'depoente' => sub {}, #remember 'estadocivil'
      -default => sub {$c},
    );

 
  chomp(my $path = `pwd`); 
  die ("Missing file: $path/$filename\n") unless -f $filename;
  my $ans = dt($filename, %handler);

  return $ans;
}

sub mp2html {

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

  my $files = toHTML($filename);
  my $bi = loadBI("bi.xml");

  my %DATA = (%$bi);
  $DATA{FULLSTORY} = $files->{main};
  $DATA{FULLLINK} = "$optid.mb.html";
  $DATA{BILINK} = "../_index_.html";

  my $tmplfile = search_template("monobloco.tmpl");
  if ($tmplfile) {
    my $tmpl = HTML::Template->new(filename=>$tmplfile,
				   die_on_bad_params => 0);
    $tmpl->param(%DATA);
    open MB, ">$ddir/$optid.mb.html";
    print MB $tmpl->output;
    close MB;
  }

  for (keys %$files) {
    next if $_ eq "main";
    next if $_ eq "css";
    next if $_ eq "index";
    my $tmplfile = search_template("historia.tmpl");
    if ($tmplfile) {
      my $tmpl = HTML::Template->new(filename => $tmplfile,
				     die_on_bad_params => 0);
      my $story = $files->{$_};
      $story =~ s!#sec0!../_index_.html!;
      $tmpl->param(%DATA, STORY => $story);
      open MB, ">$ddir/$optid.sec$_.html" or die;
      print MB $tmpl->output;
      close MB;
    }
  }

  open MB, ">$ddir/$optid.index" or die;
  my $index = $files->{index};
  $index =~ s!#(sec)(\d+)!$ddir/$optid.sec$2.html!g;
  print MB $index;
  close MB;

}


sub toHTML {
  my $filename = shift;

  our $cgi = q!http://alfarrabio.di.uminho.pt/mpbin!;

  our ($i,$j) = (0,0);

  our @index = ();
  our @subindex = ();

  our %files;

  my %handle =
    (
     #-outputenc=>"ISO-8859-1",
     'rel'      => sub {$c}, #remember 'tipo'
     'ref'      => sub {$c}, #remember 'tipo'
     'destaque' => sub {$c}, #remember 'tipo'
     'midia'    => sub {$c}, #remember 'tipo'

     'tema'     => sub {$c}, #remember 'termo', 'titulo', 'onde', 'quando'
     'expressao' => sub {
       "<a href=\"$cgi/glossario?w=$c\">$c</a>"
     }, #remember 'significado'

     'foto' => sub {"<div class=\"foto\"><a href=\"../fotos/_Sm_$v{ficheiro}.jpg\"><img src=\"../fotos/_Tn_$v{ficheiro}.jpg\"></a><br>$c</div>"}, #remember 'ficheiro'
     'nota'     => sub {$c},

     #POEMA
     'poema'    => sub { "<div class=\"poema\">$c</div>" },
     'estrofe'  => sub { "<p style=\"text-indent: 0\">$c</p>" },
     'verso'    => sub { "$c<br/>" },

     'mp'       => sub {
       my $title = "<b>Índice</b><a name=\"sec0\">&nbsp;</a>\n";
       my $index = "$title<ul>".join("\n",map {"<li>$_</li>"} @index)."</ul>";
       $files{index} = $index;
       "$index $c"
     },

     'pergunta' => sub { "<p style=\"text-indent: 0\"><i><b>MP: </b>$c</i></p>"},
     'resposta' => sub { "<p>$c</p>"},

     'avaliacao' => sub {$c},
     'evento' => sub {$c}, #remember 'ano', 'mes', 'dia', 'local', 'eixo', 'titulo', 'descricao'

     'p' => sub { toxml },

     '/mp/episodio' => sub { section("") }, #'termo', 'titulo', 'onde', 'quando'
     '//*/*/episodio' => sub { subsection("") },

     'ascendencia' => sub {
       section("Ascendência")}, #remember 'titulo','onde','quando','origempaterna','origemmaterna'
     'descendencia' => sub { section("Descendência") }, #remember 'titulo', 'onde', 'quando', 'numerofilhos'

     'lazer'          => sub { section("Lazer")   }, #remember 'titulo', 'onde', 'quando', 'actividades'

     'filosofiavida'        => sub { section("Filosofia de Vida")},#remember 'titulo','onde','quando'
     'costumes'             => sub { section("Costumes")     }, #remember 'titulo', 'onde', 'quando'
     'percursoprofissional' => sub { section("Percurso Profissional")},#remember 'titulo','onde','quando'
     'casa'                 => sub { section("Casa")},#remember 'titulo','onde','quando'
     'namoro'               => sub { section("Namoro")       }, #remember 'titulo', 'onde', 'quando'
     'pessoas'              => sub { section("Pessoas")      }, #remember 'titulo', 'onde', 'quando'
     'migracao'             => sub { section("Migração")     }, #remember 'titulo', 'onde', 'quando'
     'lugar'                => sub { section("Lugar")        }, #remember 'titulo', 'onde', 'quando'
     'sonhos'               => sub { section("Sonhos")       }, #remember 'titulo', 'onde', 'quando'
     'historia'             => sub { section("História")     }, #remember 'titulo', 'onde', 'quando'
     'politica'             => sub { section("Política")     }, #remember 'titulo', 'onde', 'quando'
     'identificacao'        => sub { section("Identificação")}, #remember 'titulo', 'onde', 'quando'
     'infancia'             => sub { section("Infância")     }, #remember 'titulo', 'onde', 'quando'
     'quotidiano'           => sub { section("Quotidiano")   }, #remember 'titulo', 'onde', 'quando'
     'educacao'             => sub { section("Educação")     }, #remember 'titulo', 'onde', 'quando'
     'religiao'             => sub { section("Religião")     }, #remember 'titulo', 'onde', 'quando'
     'casamento'            => sub { section("Casamento")    }, #remember 'titulo', 'onde', 'quando'
     ## OFICIO ##
     'oficio'               => sub { section("Ofício")       }, #remember 'titulo', 'onde', 'quando'

     'actividade' => sub { subsection("Actividade")          }, #remember 'titulo'
     'carreira'   => sub { subsection("Carreira")            }, #remember 'titulo'
     'salario'    => sub { subsection("salário")             }, #remember 'titulo'
     'orgulho'    => sub { subsection("Orgulho")             }, #remember 'titulo'
     'relacoes'   => sub { subsection("Relações na Empresa") }, #remember 'titulo'
     'admissao'   => sub { subsection("Admissão")            }, #remember 'titulo', 'quando'
     'saida'      => sub { subsection("Saída")               }, #remember 'titulo', 'quando'
     ## EOFICIO ##
    );

  $files{main} = pathdt($filename, %handle);

  return \%files;

  sub get_attr {
    my $str = shift;
    my $att = shift;
    my %v = @_;
    if (exists($v{$att})) {
      my $c = $v{$att};
      return eval $str;
    } else {
      return "";
    }
  }

  sub section {
    my $type = shift;
    $type = "$type&nbsp;&nbsp;" if ($type);
    $i++;
    my $title = "$type ".get_attr('"<i>$c</i>"', 'titulo', %v);
    push @index, "<a href=\"#sec$i\">$title</a>";

    my $index = "";
    if (@subindex) {
      $index = "<ul>".join("\n",map {"<li>$_</li>"} @subindex)."</ul>";
    @subindex = ();
      $j = 0;
    }

    my $return = "<a name=\"sec$i\">&nbsp;</a><div class=\"top\"><a href=\"#sec0\"><img src=\"/mpessoa/images/index.gif\"></a></div><b class=\"title\">$title</b>$index$c";

    $files{$i} = $return;
    return $return;
  }

  sub subsection {
    my $type = shift;
    $type = "$type&nbsp;&nbsp;" if ($type);
    $j++;
    my $title = "$type ".get_attr('"<i>$c</i>"', 'titulo', %v);
    push @subindex, "<a href=\"#sec$i.$j\">$title</a>";
    "<a name=\"sec$i.$j\">&nbsp;</a><b class=\"subtitle\">$type ".get_attr('"&nbsp;&nbsp;<i>$c</i>"', 'titulo', %v)."</b>$c";
  }
}

sub mp2latex {
  my $filename = shift;
  my $bi = loadBI("bi.xml");


my %handler =
  (
   -pcdata => sub{
 #$c = encode("iso-8859-1", $c) if Encode::is_utf8($c);
            $c =~ s/â\x80¦/.../g;
                       $c =~ s/\$/\\\$/g;
                       $c =~ s/\%/\\\%/g;
                       $c =~ s/\&/\\&/g;


     #$c =~ s/\s"/ ``/g;
     #$c =~ s/"\s/'' /g;
     $c =~ s/" /"\\ /g;
     $c =~ s/_/\\_/g;

     $c = '\subsection*{O 25 de Abril}' if $c =~ m!^\s*25 de abril\s*$!i;

     $c;
   },
   #-outputenc=>"ISO-8859-1",
   'rel' => sub {$c}, #remember 'tipo'
   'ref' => sub {$c}, #remember 'tipo'

   'expressao' => sub { "\\emph{$c}"}, #remember 'significado'

   'poema' => sub { "\n\\begin{quote} $c \\end{quote}\n\n" },
   'verso' => sub { "\\textit{$c}\\\\" },
   'estrofe' => sub{ "$c" },

   'tema' => sub {$c}, #remember 'termo', 'titulo', 'onde', 'quando'
   'foto' => sub {
     chomp(my $path = `pwd`);
   "\n\\begin{figure}\\begin{center}\n\\includegraphics[width=.9\\textwidth]{$v{ficheiro}}\n\\end{center}\n\\vskip 2mm\n$c\n\\end{figure}\n";
   }, #remember 'ficheiro'
   'nota' => sub {$c},

   'resposta' => sub { "\\indent $c\n\n" },
   'pergunta' => sub { "\\noindent \\textbf{MP: }$c\n\n" },

   'mp' => sub {$c},
   'destaque' => sub {$c}, #remember 'tipo'
   'evento' => sub {$c}, #remember 'ano', 'mes', 'dia', 'local', 'eixo', 'titulo', 'descricao'

   'midia' => sub {$c}, #remember 'tipo'


   'p' => sub { "$c\n\n"},

   'admissao' => sub { texsubsection("Admissão") }, #remember 'titulo', 'quando'
   'carreira' => sub { texsubsection("Carreira") }, #remember 'titulo'
   'orgulho'  => sub { texsubsection("Orgulho")  }, #remember 'titulo'
   'salario'  => sub { texsubsection("Salário")  }, #remember 'titulo'
   'actividade'=>sub { texsubsection("Actividade")},#remember 'titulo'
   'relacoes' => sub { texsubsection("Relações") }, #remember 'titulo'
   'saida'    => sub { texsubsection("Saída") }, #remember 'titulo', 'quando'

   '/mp/episodio' => sub { texsection($v{titulo}||"Episódio") }, #remember 'termo', 'titulo', 'onde', 'quando'
   '//*/*/episodio' => sub { texsubsection($v{titulo}||"Episósio").'\vskip 5mm' },

   'ascendencia' => sub { texsection($v{titulo}||"Ascendência")
			}, #remember 'titulo', 'onde', 'quando', 'origempaterna', 'origemmaterna'
   'descendencia' => sub { texsection($v{titulo}||"Descendência")
			 }, #remember 'titulo', 'onde', 'quando', 'numerofilhos'

   'percursoprofissional' => sub { texsection($v{titulo}||"Percurso Profissional") }, #remember 'titulo', 'onde', 'quando'
   'lazer' => sub { texsection($v{titulo}||"Lazer") }, #remember 'titulo', 'onde', 'quando', 'actividades'
   'costumes' => sub { texsection($v{titulo}||"Costumes")}, #remember 'titulo', 'onde', 'quando'
   'filosofiavida' => sub { texsection($v{titulo}||"Filosofia de Vida")}, #remember 'titulo', 'onde', 'quando'
   'namoro' => sub { texsection($v{titulo}||"Namoro")}, #remember 'titulo', 'onde', 'quando'
   'oficio' => sub { texsection($v{titulo}||"Ofício")}, #remember 'titulo', 'onde', 'quando'
   'educacao' => sub { texsection($v{titulo}||"Educação")}, #remember 'titulo', 'onde', 'quando'
   'religiao' => sub { texsection($v{titulo}||"Religião")}, #remember 'titulo', 'onde', 'quando'
   'casamento' => sub { texsection($v{titulo}||"Casamento")}, #remember 'titulo', 'onde', 'quando'
   'casa' => sub { texsection($v{titulo}||"Casa")}, #remember 'titulo', 'onde', 'quando'
   'pessoas' => sub { texsection($v{titulo}||"Pessoas")}, #remember 'titulo', 'onde', 'quando'
   'lugar' => sub { texsection("Lugar")}, #remember 'titulo', 'onde', 'quando'
   'infancia' => sub { texsection($v{titulo}||"Infância")}, #remember 'titulo', 'onde', 'quando'
   'migracao' => sub { texsection($v{titulo}||"Migração")}, #remember 'titulo', 'onde', 'quando'
   'politica' => sub { texsection($v{titulo}||"Política")}, #remember 'titulo', 'onde', 'quando'
   'identificacao' => sub { texsection("Identificação") }, #remember 'titulo', 'onde', 'quando'
   'quotidiano' => sub { texsection($v{titulo}||"Quotidiano") }, #remember 'titulo', 'onde', 'quando'
   'sonhos' => sub { texsection($v{titulo}||"Sonhos") }, #remember 'titulo', 'onde', 'quando'
   'historia' => sub { texsubsection($v{titulo}||"História") }, #remember 'titulo', 'onde', 'quando'

   'avaliacao' => sub { texsection("Avaliação") },
  );

$latex = "";
$latex.= textitle($bi);
$latex.= pathdt($filename, %handler);
$latex.= '\end{document}'."\n";

return $latex;

sub textitle {
  my $bi = shift;
  my $res = "";
  $res.= <<'EOL';
\documentclass[a4paper,portuges]{article}
\lccode`\-=`\-
\defaulthyphenchar=127
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{graphicx}
\usepackage{times} % was aeguill
\usepackage{agbookheader}
\begin{document}
\def\mysection#1{\subsection*{#1}\addcontentsline{toc}{subsection}{#1}}
\def\mysubsection#1{\subsubsection*{#1}\addcontentsline{toc}{subsubsection}{#1}}
EOL
  $res.= "\\title{$bi->{depoente}}\n";
  #$res.= "\\date{$bi->{nascimento}}\n";
  $res.= <<'EOL';
\def\abstractname{}
%\author{Núcleo Português do Museu da Pessoa}
\author{}
\date{}
\maketitle
EOL
if ($bi->{biografia}) {
  $res.= "\\begin{abstract}\n";
  $res.= $bi->{biografia} ;
  $res.= "\\end{abstract}\n";
}
  $res.= "\\vfill\n\\hbox{}\\newpage\n";
  $res.= "\\tableofcontents\n";
  $res.= "\\newpage\n";
  return $res;
}

sub texsection {
  my $type = shift;
  $type = "$type  " if ($type);
  my $title = "\\mysection{$type ".texget_attr('"\\\textit{$c}"', 'titulo', %v)."}\n";
  return $title.$c;
}

sub texsubsection {
  my $type = shift;
  $type = "$type  " if ($type);
  my $title = "\\mysubsection{$type ".texget_attr('"\\\textit{$c}"', 'titulo', %v)."}\n";
  return $title.$c;
}

sub texget_attr {
  my $str = shift;
  my $att = shift;
  my %v = @_;
  if (exists($v{$att})) {
    my $c = $v{$att};
    $c = encode("iso-8859-1", $c) if Encode::is_utf8($c);
    $c =~ s/" /"~/;
    $c =~ s/^"/``/;
    $c =~ s/"$/''/;
    return eval $str;
  } else {
    return "";
  }
}

}


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

ESCRIBA2catalog
ESCRIBA2html
ESCRIBA2latex

_2xml
_cat2onelevcat
_geracao
_getid
_pai

bi2catalog
bi2html

biografia_bi

entrevista2catalog
entrevista2html
entrevista2latex

fotos2html
get_attr
h_tit
hfoot
hhead

historiaDeVida2html
historiasDeVida2catalog

hv2catalog
hv2dbfilecatalog
hv2html
hv2latex
hv2xmlcatalog

loadBI

mkchap
mp2html
mp2latex
mp2rels

ph

search_template
section
set_mp_path
set_thesaurus_path
sinopsis
sinopsis_project
subsection
texget_attr
texsection
texsubsection
textitle
textofinal
thesaurus_link

toHTML

livro2latex
