#!/usr/bin/perl -i.bak

use English;
use Getopt::Declare;

######################
# DEFINE GLOBAL CONSTANTS
######################

use vars qw($EASYLATEX_DIR @TRANSFORM_PATHS $LATEX_HEADER $LATEX_FOOTER $PARTIAL_DOCUMENT);


$DEFAULT_DOCUMENTCLASS = <<'EOF' ;
\documentclass{article}
EOF

$DEFAULT_USEPACKAGE = <<'EOF' ;
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{psfrag}
EOF

@usepackage_list = qw(amsmath amsfonts amssymb psfrag);
%usepackage_options = qw(graphicx dvips);

$BEGIN_DOCUMENT = <<'EOF' ;

\begin{document}

EOF
    
# todo: eliminate DEFAULT_USEPACKAGE
$LATEX_HEADER_FULL = $DEFAULT_DOCUMENTCLASS. $DEFAULT_USEPACKAGE. $BEGIN_DOCUMENT;


$END_DOCUMENT = <<'EOF' ;

\end{document}
EOF


$LATEX_FOOTER = $END_DOCUMENT;


######################
# BEGIN MAIN
######################

#print STDERR "DBG2: " . join(@ARGV);

$argSpecification = q(
		      --partial	              This file is not a full LaTeX document, just a partial one (to be \\include'd, for instance)
		      {$PARTIAL_DOCUMENT = 1;}
		      );


$args = new Getopt::Declare($argSpecification);

if ($PARTIAL_DOCUMENT) {
  #print STDERR 'PARTIAL DBG\n\n';
  exit;
}



undef $INPUT_RECORD_SEPARATOR;
$file = <>;

if (!($file =~ /\\documentclass/))
{
#    $file = $LATEX_HEADER_FULL .  $file . $LATEX_FOOTER;
    $file = $DEFAULT_DOCUMENTCLASS .  $file;
}

if  (!($file =~ /\\begin{document}/))
{

    $file =~ s/(.*\\documentclass{[^}]*}[^\n]*\n)/$1$BEGIN_DOCUMENT/s;
    $file = $file . $END_DOCUMENT;


    ## move usepackages, title, author, newcommand to within preamble
    my @usepackages_in_file;
    while  ($file =~ s/(\\begin{document}.*?)(\\usepackage(\[[^\]]*])?{[^}]+}[^\n]*|\\title{[^}]*}|\\author{[^}]*}|\\newcommand{[^}]*}(?:\[[^\]]*\])?{[^}]*}[^\n]*(?=\n))/$1/sg) {
      $pkg = $2; 
      #push(@usepackages_in_file, $1);      
      $file =~ s/(.*\\documentclass{[^}]*}[^\n]*\n)/$1$pkg\n/s;

    ##NOTE: currently \newcommand is not moved, b/c it was protected from processing in easylatex.pl


    }
}

# TODO: add code to add usepackages
foreach $pkg (@usepackage_list) {
    if  (!($file =~ /\\usepackage(\[[^\]]*])?{$pkg}/))
    {
	if ($usepackage_options{$pkg}) {
	    $opt = $usepackage_options{$pkg};
	    $file =~ s/\\begin{document}/\\usepackage[$opt]{$pkg} %% pkg required by EasyLatex\n\\begin{document}/;
	}
	else {
	    $file =~ s/\\begin{document}/\\usepackage{$pkg} %% pkg required by EasyLatex\n\\begin{document}/;
	
	}
#print STDERR "*********** $pkg";
    }
    
}

if  (!($file =~ /\\usepackage(\[[^\]]*])?{graphicx}/) && !($file =~ /\\documentclass(\[[^\]]*\])?{prosper}/) && !($file =~ /\\dontusepackage{graphicx}/))
{
    $file =~ s/\\begin{document}/\\usepackage[dvips]{graphicx} %% pkg required by EasyLatex\n\\begin{document}/;
    #print STDERR "*********** $pkg";
}


$file =~ s/\\dontusepackage{[^}]+}//g;


print $file;
