#!/usr/local/bin/perl

## Input parameters

$input = $ARGV[0];

## Open input/output files

unless (open(INPUT, $input))  {
  die "\nCan't find input file: $input\n\n";
}

while (<INPUT>)  {
  @input_data = (@input_data,$_);
}

close(INPUT);

## Search/Replace/Convert routine

$length = @input_data;

unless (open(OUTPUT, ">" . $input))  {
  die "\nCan't open output file: $input for writing\n\n";
}

for ($i=0;$i<=$length;$i++)  {
  $a = $input_data[$i];
  study($a);
  $a =~ s/\\casefrac\s?{/\\frac{/g;
  $a =~ s/\\casefrac\s?{/\\frac{/g;
  $a =~ s/\\approx\b/\\HCode{ <mo>&ap\;<\/mo> }/g;
  $a =~ s/\\sub\s?{/_{/g;
  $a =~ s/\\sub\s?{/_{/g;
  $a =~ s/\\super\s?{/^{/g;
  $a =~ s/\\super\s?{/^{/g;
  $a =~ s/\\deq\b/\\HCode{ <mover><mo>=<\/mo><mstyle scriptlevel="3"><mi>def<\/mi><\/mstyle><\/mover> }/g;
  $a =~ s/\\inxx{[^}]*}//g;
  $a =~ s/\\inxx{[^}]*}//g;
  if ($a =~ /\\inxx{[^}]*\n/)  {
    $a =~ s/\\inxx{[^}]*//g;
    $input_data[$i+1] =~ s/^[^}]*}//g;
  }

  # Get rid of \boxeq command: replace with \begin{equation} ... \end{equation}
  if ($a =~ /\\l?(ll)?(lll)?s?(ss)?(sss)?boxeq\s*{/)  {
    $a =~ s/\\l?(ll)?(lll)?s?(ss)?(sss)?boxeq\s*{/\\begin{equation}/g;
    $length_limit = 6;
    for ($m=0;$m<$length_limit;$m++)  {
      if ($input_data[$i+$m] =~ /^\s*(\\label{[^}]*})?\s*}\s*\n+\s*$/)  {
        $input_data[$i+$m] = $1 . "\n\\end{equation}\n";
        $m = $length_limit;
      }
    }
  }

  $length_limit = 6;

  if ($a =~/\\specialeps/)  {
    $a =~ /^\s*\\specialeps\s*{([^{}]*)}\s?{([^{}]*)}\s?({?[^\n]*\n$)/;
    $directory = $1;
    $file_name = $2;
    $caption = $3;
    for ($m=1;$m<$length_limit;$m++)  {
      if ($input_data[$i+$m] =~ /}[^{}]*}/  ||  $input_data[$i+$m] =~ /^[^{}]*}/)  {
        $input_data[$i+$m] =~ /}([^{}\n]*\n)/;
        $caption = $caption . $`;
        $input_data[$i+$m] = "\n" . $1;
        $m = $length_limit;
      }  else  {
        $caption = $caption . $input_data[$i+$m];
        $input_data[$i+$m] = "\n";
      }
    }
    $caption =~ s/^\n*\s*\n*{/{/g;
    $a = "\\begin{figure}\n\\begin{center}\n\\includegraphics{FIGS/" . $directory . "/" . $file_name . "}\n";
    $a = $a . "\\end{center}\n\\caption" . $caption . "}\\label{" . $file_name . "}\n\\end{figure}\n";
  }

  print OUTPUT $a;
}

close(OUTPUT);






