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

use English;

use vars qw($EASYLATEXSTORE_RESERVED_WORD @MATH_MODE_SYMBOLS $MATH_MODE_SYMBOL_FILEPATH);

$EASYLATEXSTORE_RESERVED_WORD = 'EASYLATEXSTORE';
use vars qw($StorageIndex @Stored);

$StorageIndex = 0;


## get input
undef $INPUT_RECORD_SEPARATOR;
$file = <>;

## transform it

$file = storeMathModes($file);

if (($file =~ /\\documentclass(\[[^\]]*\])?{article}/) || ($file =~ /\\documentclass(\[[^\]]*\])?{report}/) )
{
    $file =~ s/^====(.*)====\s*$/\\subsubsection*{$1}/mg;
    $file =~ s/^===(.*)===\s*$/\\subsection*{$1}/mg;
    $file =~ s/^==(.*)==\s*$/\\section*{$1}/mg;
}
elsif ($file =~ /\\documentclass(\[[^\]]*\])?{seminar}/)
{
    $file =~ s/^=======(.*)=======\s*$/\\begin{scriptsize}$1\\end{scriptsize}/mg;
    $file =~ s/^=====(.*)=====\s*$/\\begin{small}$1\\end{small}/mg;
    $file =~ s/^====(.*)====\s*$/\\textbf{$1}/mg;
    $file =~ s/^===(.*)===\s*$/\\slidesubheading{$1}/mg;
    $file =~ s/^==(.*)==\s*$/\\slideheading{$1}/mg;

    $file =~ s/^---$/\\smallskip\\hrulefill\\smallskip/mg;
}
elsif ($file =~ /\\documentclass(\[[^\]]*\])?{prosper}/)
{
    $file =~ s/^=======(.*)=======\s*$/\\begin{scriptsize}$1\\end{scriptsize}/mg;
    $file =~ s/^=====(.*)=====\s*$/\\begin{small}$1\\end{small}/mg;
    $file =~ s/^====(.*)====\s*$/\\textbf{$1}/mg;
    $file =~ s/^===(.*)===\s*$/\\begin{large}$1\\end{large}/mg;
    $file =~ s/^==(.*)==\s*$/\\begin{huge}$1\\end{huge}/mg;

    $file =~ s/^---$/\\smallskip\\hrulefill\\smallskip/mg;
}
else {
    $file =~ s/^====(.*)====\s*$/\\subsubsection*{$1}/mg;
    $file =~ s/^===(.*)===\s*$/\\subsection*{$1}/mg;
    $file =~ s/^==(.*)==\s*$/\\section*{$1}/mg;
}


$file = unstoreMathModes($file);

# print output
print $file; 


######################
# "store" subroutines
######################

sub storeMathModes {
    my ($file) = @_;

    ${notSlashRE_begin} = '(^|(?!\\).)';
    ${notSlashRE} = '(?!\\).';

    $file =~ s/(\\begin{align}.*?\\end{align})/store($1)/egs;
    $file =~ s/(\\begin{align\*}.*?\\end{align\*})/store($1)/egs;
    $file =~ s/(\\begin{eqnarray}.*?\\end{eqnarray})/store($1)/egs;
    $file =~ s/(\\begin{eqnarray\*}.*?\\end{eqnarray\*})/store($1)/egs;
    $file =~ s/(\\begin{equation}.*?\\end{equation})/store($1)/egs;
    $file =~ s/(\\begin{equation\*}.*?\\end{equation\*})/store($1)/egs;

    $file =~ s/((?<!\\)\$.*?(?<!\\)\$)/store($1)/egs;

    return $file;
}

sub unstoreMathModes {
    my ($file) = @_;

#    print STDERR "UNSTORE:\n\n".$file;

    while ($file =~ s/${EASYLATEXSTORE_RESERVED_WORD}_(\d+)_${EASYLATEXSTORE_RESERVED_WORD}/$Stored{$1}/egs) {}

    return $file;
}



sub store {
    # got this idea from UseMod
  my ($toBeStored) = @_;

  $Stored{$StorageIndex} = $toBeStored;
#  print STDERR "STORED: $toBeStored\n";

#  print STDERR "REPLACEDW: ".${EASYLATEXSTORE_RESERVED_WORD}.'_' . $StorageIndex . '_'.${EASYLATEXSTORE_RESERVED_WORD};

  return ${EASYLATEXSTORE_RESERVED_WORD}.'_' . $StorageIndex++ . '_'.${EASYLATEXSTORE_RESERVED_WORD};
}


