#!/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

$wordRE = '\w+';

$file = storeUntouchables($file);

#print STDERR "stored file: $file\n\n";

$file =~ s/(^|\W)(${wordRE})\^(\w$wordRE)(\W|$)/$1$2^{$3}$4/mg;
$file =~ s/(^|\W)(${wordRE})_(\w$wordRE)(\W|$)/$1$2_{$3}$4/mg;
$file = unstoreUntouchables($file);

# print output
print $file; 




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

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

    $file =~ s/(\\documentclass{.*?})/store($1)/egs;
    $file =~ s/\\documentclass{([^}]+)}/'\\documentclass{' . store($1) . '}'/egs;



    return $file;
}

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

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

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

    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}.' ';
}




