#!/usr/bin/perl -w
# $Id: mail2tex.pl,v 1.1 2003/01/14 13:26:28 oliver Exp $
# $Log: mail2tex.pl,v $
# Revision 1.1  2003/01/14 13:26:28  oliver
# Initial revision
#

sub tex_format (string) {
    my ($string) = @_; 
    $string =~ s/'(.*?)'/"`$1"'/g;               #`' <- (make emacs font lock mode happy)
    $string =~ s/"([^`'].*?)"([^`'])/"`$1"'$2/g; #'
    $string =~ s/"([^`'])/""$1/g;                #"'` <- (make emacs font lock mode happy)
    $string =~ s/&/\\&/g;    
    $string =~ s(/~)(/\~{ })g; 
    $string =~ s(> )(\\newline\n\$>\$ )g; 
    $string =~ s(_(.*?)_)(\\emph{$1})g;  

    return $string;  
};

sub tex_print (string) {
    my ($string) = @_; 
    print ( &tex_format($string));
    return;
};

sub tex_print_paragraph (string) {
    my ($string) = @_; 
    $string  = &tex_format ($string);
    if (length($string) < 72) {$string = "\\noindent " . $string};  
    print $string . "\n\n";
    return;
};

    
sub tex_print_header {
    my ($subj, $hfrom, $from, $date, $to) = @_;
    &tex_print ("\\subsection{$subj}\n" . 
		"\\mailheader[$hfrom]%\n\t{$from}%\n\t{$to}%\n\t{$date}%\n\t{$subj}\n");
    return;
};


sub tex_document_header {
    print <<'EOL';
\documentclass[a4paper,12pt,german]{article}
\usepackage{babel,array}

%%% \mailheader [from(envelope)] from to date subject  
\newcommand{\mailheader}[5][]{%
  \par
  {\tt 
  \begin{tabular}{>{\bf}l<{}l}
  From: & #2\\
  To:   &  #3\\
  Date: &  #4\\
  Subject: &  #5
  \end{tabular}\\
  \rule{0mm}{2\parskip}
}}

\begin{document}

EOL

    return;
};

sub tex_document_end {
    print <<'EOL';
\end{document}

EOL
    return;
}


$hfrom_re = '^From (.*@.*$)';    


&tex_document_header;

SCAN: while (<>) {
     if (/$hfrom_re/ .. /^$/) {
	 chomp;
	 s/$hfrom_re/$1/           &&  do {$hfrom = $_}; 
	 s/^From: *(.*$)/$1/       &&  do {$from = $_}; 
	 s/^Date: *(.*$)/$1/       &&  do {$date = $_}; 
	 s/^To: *(.*$)/$1/         &&  do {$to = $_};
         s/^Subject: *(.*$)/$1/    &&  do {$subject = $_};
	 $print_header = 1;
	next SCAN;
    };

    if ($print_header) {
	$print_header = 0;
	&tex_print_header ($subject, $hfrom, $from, $date, $to);
	&tex_print ("\n");
    };

    # weedout 
    next SCAN if (m(^GMX -) ||
		  m(GMX Tipp) ||
		  m(http://www.gmx) ||
	          m(Machen Sie Ihr Hobby) ||
		  m(^http://profi) ); 

    do { chomp; 
	 # modify: put already in tex syntax
	 s(^-- *$)(--\\newline);
	 $paragraph .= ($_ . " "); 
	 next SCAN } unless /$ *^/; 

    &tex_print_paragraph ($paragraph);
    $paragraph = '';
};



&tex_document_end;
