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

use English;



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



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

#print STDERR "**********************  I got:\n\n" . $file . "\n"; 

## transform it

$file =~ s/(\\begin{graph}.*?\\end{graph})/processGraph($1)/sge;

# print output
print $file; 


###############
# end of MAIN
###############

sub processGraph {
    my ($block) = @_;

    # to make it easier to put matrices in labels
    $block =~ s/(\[\w+=[^"\]]+)(\[[^\]]+\])([^"\]]+\])/$1.store($2).$3/ge;
#    $block =~ s/\[\w+=([^"\]]+)(\[[^\]]+\])/$1$2 HELLOOOOOOOOOOOOOOOOOOO/g;

    $block = storeMathModes($block);  
#print STDERR "in 20esc:\n $block\n";

    $block =~ s/\[label=((?!${EASYLATEXSTORE_RESERVED_WORD})[^,"\]]+)([,\]])/[label=\$$1\$$2/g;
#    $block =~ s/\[label=([^"\]]+)\]/[label=\$$1\$]/g;
#    $block =~ s/\[label=([^\]]+)\]/[label=\$$1\$]/g;
#    $block =~ s/\[label=\$([^\]]+)(,[^\]=]*=[^\]]*)\$\]/[label=\$$1\$$2]/g;
#    $block =~ s/\[label=\$([^\]]+)(,[^\]=]*=[^\]]*)\$\]/[label=\$$1\$$2]/g;
    
    
$block =~ s/=/\\=/g;
#$block =~ s/\[([^]]+=[^]]+)]/\\[$1\\]/g;

$block =~ s/^(.*\S.*)(?<!;)(<!{)\n/$1;\n/mg;
$block =~ s/;//;  # remove the ; we just added to "\begin{graph};"

# default size limit, to keep graph from being bigger than the page
#

if (! ($block =~ /size\\=/i))
{$block =~ s/\\begin{graph}/\\begin{graph}    size="6,10";/}

$block = unstoreMathModes($block);

# print STDERR "escapeInsideGraph: $block\n";



    return $block;
}




######################
# "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};
}

