#!c:/perl/bin/perl.exe
################################################################################
##        ELXTOMML - Perl script for replacing LaTeX math to MathML           ##
##        using MathJax scripts                                               ##
################################################################################
##                                                                            ##
##   This script is an add-on program to the electronic publishing package    ##
##   which includes LaTeX style package ELXfinal (elxfinal) which             ##
##   in its turn expands and modifies the standard LaTeX  article.sty.        ##
##   The script uses HTML file generated by elxpaper.pl script and sends to   ##
##   output two files, basic HTML with numberred placeholders instead of      ##
##   math fragments (both inline and display types) and math file containing  ##
##   only extracted math with corresponding numberred placeholders.  The      ##
##   latter uses MathJax to convert TeX math notations to MathML ones.        ##
##                                                                            ##
################################################################################
##   Written by Vitaly Nechitailenko,            e-mail: vnechita@gmail.com   ##
##   Version 2.0,  September 2019                    Last update 03.09.2019   ##
################################################################################

require 'elxfinal.cfg'  ||  die "ELXFINAL configuration file not found! \n";
require 'elxtomml.cfg'  ||  die "ELXTOMML configuration file not found! \n";

$infile = $ARGV[0];
print "I N F I L E + $infile\n";   ####################################>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$outfile = $infile;
$opsdir = $ARGV[1];
$lct = $ARGV[2];

@names = split(/\./,$outfile);
$errfile = $names[0]."-s.err";
$leninput = length($infile);            ##      Marker for cutting the tail of main file

##############################################################print "$errfile\n";

## The naming of files in the current version is specified to the naming accepted  
## for online journals published by GC RAS. The following naming fragment may be
## changed if necessary

$identname = $names[0];
$htmlname = $identname."_tex\.html";    ## file with TeX placeholders only
$mmlname = $identname."_mml\.html";     ## TeX math for MathJax

$epubname = $opsdir."\/".$identname."\.xhtml";     ## HTML file after MML substitutions
$modname = $epubname;
##$modname = $identname."\.xhtml";     ## HTML file after MML substitutions

unlink ($mmlflag);
#open (FLAG, "<$mmlflag")  ||  die "Cannot open $mmlflag file for reading.";
#$flag_value = <FLAG>;
#print "FLAG value = $flag_value  at the start of elxtomml.pl script.\n";
#close (FLAG);
open (FLAG, ">$mmlflag")  ||  die "Cannot open $mmlflag file for writing.";
###\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\print FLAG "FLAG_OFF\n";
close (FLAG);

print "   Converting $infile to \.xhtml\. Please wait. . .";

open (IN, "<$infile") || die "Cannot open $infile file.";
open (ERR, ">$errfile")  || die "Cannot open $errfile file.";
open (HTM, ">$htmlname") || die "Cannot open $htmlname file.";
open (MML, ">$mmlname")  || die "Cannot open $mmlname file.";
$errcount = 0;
$inlinecnt = 0;
$displaycnt = 0;
@inlarray = ();
@disarray = ();
####print ERR "\nidentname = $identname     names = $names[0]\n\n";

##    Header for TeXtoMML input file  ++++++++++++++++++++++++++++++++++ H E A D E R  TeXtoMML ++++++++++++++++++++++

print MML <<EOM;
<!DOCTYPE html>
<html>
<head>
<title>MathJax TeX to MathML Page<\/title>
<script type=\"text\/javascript\">
   function toMathML(jax,callback) \{
      var mml;
      try \{
         mml = jax.root.toMathML(\"\");
      \} catch(err) \{
         if (!err.restart) \{throw err\} \/\/ an actual error
            return MathJax.Callback.After(\[toMathML,jax,callback\],err.restart)\;
         \}
         MathJax.Callback(callback)(mml)\;
      \}
<\/script>

<script type=\"text\/x-mathjax-config\">
//  Composing Form.tarea content
   MathJax.Hub.Config({
      tex2jax\: \{inlineMath: \[\[\"\$\",\"\$\"\],\[\"\\\\(\",\"\\\\)\"\]\]\}
   \})\;
   MathJax.Hub.Queue(
   function () {
      var jax = MathJax.Hub.getAllJax();
                         //alert("jar.length=" + jax.length);
      if (jax.length > 0)  \{
         for (var i = 0; i < jax.length; i++) \{
            var ii = i + 1;
            toMathML(jax[i],function (mml) \{
               var mmlin = document.Form.tarea.value;
                           //alert("eqn=" + ii + "   mmlin=" + mmlin);
               var mmlout = mmlin + \"\\n\\n\" + mml;
                           //alert("eqn=" + ii + "   mmlout=" + mmlout);
               document.Form.tarea.value = mmlout;
   //    Sending form data to localhost after saving last jax fragment 
               if (ii == jax.length)  \{
                  //alert("last fragment added [" + ii + "]");
                  document.Form.submit();
               \}
            \});
         \}
      \}  else  \{
         mmlout = "No math insertions";
         document.Form.tarea.value = mmlout;
         document.Form.submit();
      \}
   \});
</script>
<script type=\"text\/javascript\" 
   src=\"http\:\/\/cdn.mathjax.org\/mathjax\/latest\/MathJax.js\?config=TeX-AMS_HTML-full\">
<\/script>
<link rel=\"stylesheet\" type=\"text\/css\" href=\"css\/elx-online.css\" \/>
<\/head>
<body>
EOM
##    Header for TeXtoMML input file  ============== E N D ================ H E A D E R  TeXtoMML ======================


########print ERR  "Before scanning\n";
##    Scanning input file
##    Now we skip the HTML <head> fragment
while (<IN>)  {
    chop();
    if (/^<title>/)  {
        s/<title>//;
        s/<\/title>//;
        $title = $_;
    }
    if (/^<body/)  {
        goto BODY;
    }
}
BODY:

##    The following file accumulates markers for xhtml files containing MathML fragments
$mathmarks = "mathmarks.tmp";
if (-x $mathmarks)  {
   print "NO MathMarks file\n";
}  else  {
   print "YES MathMarks file\n";
   open (ML, ">>$mathmarks")  ||  die "Cannot open $mathmarks file";
}

##    Replacing links to *.html with the links to  *.xhtml

###>>>print "Replacing links to *.html with the links to  *.xhtml\n";   ########################>>>>>>>>>>>>>>>>>>>>>>

$substmml = "substmml.bat";     ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
open (BAT, "<$substmml")  ||  die  "Cannot open $substmml file.";
$ifi = 0;
while (<BAT>)  {
   chop();
   @parts = split(/ /, $_);
   $sechtml[0][$ifi] = $parts[2];
   $oldlink = $parts[2];
   $newlink = $oldlink;
   $newlink =~ s/\.html/\.xhtml/;
   $sechtml[1][$ifi] = $newlink;
   $ifi += 1;
}
close (BAT);
####  for ($n = 0; $n < $ifi; $n++)  {
####     print ERR "$sechtml[0][$n]  -->  $sechtml[1][$n]\n";
####  }
                                ##===========================================================                                         
$menublock = 0;
$openinllab = 0;
$opendislab = 0;

while (<IN>)  {         ####  Scanning input file
   chop();
##    Removing dynamic menu
   if (/<\!-- Start of dynamics menu -->/)  {
      $menublock = 1;
   }  elsif  (/<\!-- End of dynamics menu -->/)  { 
      $menublock = 0;
      goto SKIPLINE; 
   }          
   if ($menublock == 1)  {
      goto SKIPLINE;
   }
   if (/^<div id=\"div/)  {
      goto SKIPLINE;
   } 
   if (/^<p><!-- Fragment for DIVs --><\/p>/)  {
      goto SKIPLINE;
   }        
   s/ +/ /g;
   s/\\\$/\[dollar\]/g;
   if (length($_) == 0)  {
      goto SKIPLINE;
   }
##    Substitutions missed on previous steps
   s/\`\`/\"/g;
   s/\'\'/\"/g;
   s/<it>/<i>/g;
   s/<\/it>/<\/i>/g;
   
   
   
   if (/^\\begin\{equation/  ||  /^\\begin\{eqnarray/)  {          ##    Opens display math
      $opendislab = 1;
      $displaycnt += 1;
      $_ .= "\\mbox\{\[DISPLAY-".$displaycnt." \]\}\\ ";
      $disarray[$displaycnt] = $_;
      print MML "$_\n";
      $_ = "\[DISPLAY-".$displaycnt." \]";
   }  elsif (/^\\end\{equation/  ||  /^\\end\{eqnarray/)  {        ##    Closes display math
      print MML "$_\n";
      $_ = "";
      $opendislab = 0;
   }  elsif ($opendislab == 1)  {             ##    Saving display math core
      print MML "$_\n";
      $_ = "";
   }  elsif (/\$/)  {   ##    Strings containing math
########      print ERR "\n--------------------------------------\n$_\n";
      $modline = $_;
      @stringsubarray = ();      ##    Temporal array for inline substitutions 
      $subcounter = 0;           ##    Counter of substitutions
      $strscan = 0;

      @symbs = split(//, $modline);       ##    Array of string chars
      $lenstr = @symbs;
      while ($modline =~ /\$/)  {
         $posdolop = index($modline, "\$", $strscan);
         if ($posdolop < 0)  {
            goto OUT;
         }
         $j = $posdolop + 1;
         $oplab = 0;
         while ($j < $lenstr)  {
            if ($symbs[$j] eq "\{")  {
               $oplab += 1;
            }  elsif ($symbs[$j] eq "\}")  {
               $oplab -= 1;
            }  elsif ($symbs[$j] eq "\$" && $oplab == 0)  {       ##    Closing $
               $posdolcl = $j;
##       Processing of inline math  fragment
               $lenmath = $posdolcl - $posdolop + 1;
               $curmath = substr($modline, $posdolop, $lenmath);
               $lenmatfr = length($curmath);
               $inlinecnt += 1;
               $curmath =~ s/^\$/\$\\mbox\{\[INLINE-$inlinecnt \]\}\\ /;
               $curmath =~ s/\[dollar\]/\\\$/g;          ##    Restoring dollar sign inside inline math
               $inlarray[$inlinecnt] = $curmath;         ##    Saving inline math in array
               print MML "$curmath\n";
               $inlplaceholder = "\[INLINE-".$inlinecnt." \]";
               $stringsubarray[$subcounter][0] = $posdolop;
               $stringsubarray[$subcounter][1] = $posdolcl;
               $stringsubarray[$subcounter][2] = $inlplaceholder;
               $stringsubarray[$subcounter][3] = $curmath;
               $subcounter += 1;          
               goto CLOSE;
            }
            $j += 1;
         }
CLOSE:
         $strscan = $posdolop + $lenmatfr + 1;
      }
OUT:

##  T E S T

##    Substitution to $modline from right to left
      if ($subcounter == 0)  {
         print ERR "Program or data error!  Unexpected zero value of inline substitution counter.\n";
         $errcount += 1;
         goto OUTER;
      }
      for ($is = $subcounter - 1; $is >= 0; $is--)  {
         $leftpart = substr($modline, 0, $stringsubarray[$is][0]);      
         $rightpart = substr($modline, $stringsubarray[$is][1]+1);
         $modline = $leftpart.$stringsubarray[$is][2].$rightpart;         
      }

###    print ERR "modline-1 = $modline\n";
      $_ = $modline;
   }
   if (length($_) != 0)  {
      print HTM "$_\n";
   }
SKIPLINE:
}  
close (IN);

###>>>print "END OF SUBSTITUTIONS \n";     ###################################>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

##    End of substitution
##    print "DIS = $displaycnt    INL = $inlinecnt\n";
$totmath = $displaycnt + $inlinecnt;
if ($totmath == 0)  {         ##    No math in fhis file
   print ML "$identname\.html \|\|\| nomath\n";   
}  else  {                    ##    There is math in this file
   print ML "$identname\.html \|\|\| math\n";   
}
close (ML);   

print MML <<EOM;     
<form action=\"http\:\/\/localhost\/cgi-bin\/textomml.pl\" name=\"Form\" method=\"post\">
<textarea name=\"tarea\" type=\"text\" width=\"10\" height=\"10\" value=\"\">
<\/textarea>
<\/form>

<\/body>
<\/html> 
EOM

close(MML);
close(HTM);

##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
########### END OF COMPOSING Files  _mml.html    and   _tex.html  ##################################
##--------------------------------------------------------------------------------------------------
#################################################################################################################################goto OUTER;
###\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\print "File = $infile   displaynt = $displaycnt   inline = $inlinecnt\n";

#########if ($displaycnt > 0 || $inlinecnt > 0)  {
##==================
##    The next line starts default browser (with 'browser_path' defined in config file).
##    Browser downloads $mmlname file which is preprocessed by MathJax via 'cdn.mathjax.org'
##    site in the current release, accumulates converted MML fragments in the html form's 
##    textarea field and automatically sends this form to the local Apache web server 
##    (to /cgi-bin/textomml.pl script).  
##    It produces  the file '/docs/mmlsub.txt'  containing the set of MathML substitutions
##    for $htmlname  file.
   
$comline = $browser_path." ".$mmlname."\n";     ##    Loads $mmlname into default browser
###############################print ERR "COMLINE + $comline\n"; 


###>>>print "COMLINE + $comline\n";      ##################################>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...

system $comline;
##-----------------------------------add pause!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

sleep(2);

##     Waiting for  FLAG  to set ON

REPEAT:
open (FLAG, "<$mmlflag")  ||  die "Cannot open $mmlflag file for reading.";
sleep(1);
$flag_value = <FLAG>;
###>>>print "FLAG value = $flag_value  at waiting cycle of elxtomml.pl script.\n";  #############>>>>>>>>>>>>
close (FLAG);
if ($flag_value =~ /FLAG_ON/ || $flag_value =~ /FLAG_PASS/)  {
   goto CONTINUE;
}  else  {
   goto REPEAT;
}
CONTINUE:

##  $mmlsub_out   is defined in config file  

open (SUB, "<$mmlsub_out")  ||  die "Cannot open $mmlsub_out file.";
$inlcnt = 0;
$discnt = 0;
@inlarray = ();
@disarray = ();
while (<SUB>)  {
   chop();
   @elems = split(/ \|\|\| /, $_);
######   print ERR "\n$elems[0] ||| $elems[1] ||| $elems[2] \n";
  
## Removing comments in MathML substitutions which contain non-utf-8 chars
    $modstr = $elems[2];
########print ERR "\nstr===$modstr\n";        
    $pcostr = 0;
    while ($modstr =~ /<!--/)  {
        $pco = index($modstr, "<!--", $pcostr);
        if ($pco < 0)  {
            goto RCOM;
        }  else  {
            $pcc = index($modstr, "-->", $pco+4);
            if ($pcc < 0)  {
                print ERR "MLLSUB string $_ \ncontains non-closed comment substring\n";
                $errcount += 1;
                goto RCOM;
            }  else  {
##  Here we select comments containing utf-8 chars
                $pcc += 3;
                $leftfrag = substr($modstr, 0, $pco);
                $rightfrag = substr($modstr, $pcc); 
                $midlfrag = substr($modstr, $pco, $pcc - $pco); 
########print ERR "$leftfrag ||| $midlfrag ||| $rightfrag\n";         
                if ($midlfrag =~ /<!-- \&\#\d+\; -->/)  {       ##  Comment contains utf-8, no actions needed
                    $pcostr = $pcc + 1;
                }  else {                                       ##  Removing comment
                    $lemf = length($midlfrag);
                    $midlfrag = "";
                    $pcostr = $pcc + 1 - $lemf;
                }
                $modstr = $leftfrag.$midlfrag.$rightfrag;                    
            }
        }  
#####print ERR "fin===$modstr\n";    
    }
    RCOM:
    $elems[2] = $modstr;

##  Math fragments converted from TeX to MathML  are accumulated to two arrays below
    if ($elems[0] eq "INL")  {
        $inlarray[$elems[1]] = $elems[2];
    }  elsif  ($elems[0] eq "DIS")  {
        $disarray[$elems[1]] = $elems[2];
    }   
}
close(SUB);
#########################################################################################unlink($mmlsub_out);

####$comline = "tskill  firefox";
####system $comline;


##    Substitutions
open (HTM, "<$htmlname")  ||  die "Cannot open $htmlname file.";
open (MOD, ">$modname")  ||  die "Cannot open $modname file.";

##    Header for TeXtoHTML output file

######<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
######\"http\://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
print MOD <<EOM;

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head><title>$title</title>
<meta http-equiv="default-style" content="text/html; charset=utf-8"/>
<link rel=\"stylesheet\" type=\"text\/css\" href=\"css\/elx-online.css\" \/>
</head>
<body>
EOM

#############################################################&flush (MOD);

$ssslabel = 0;

while (<HTM>)  {
   chop();
   
################   print ERR "INI = $_\n";

   if (/\[INLINE/)  {
      $strpnt = 0;
      while (/\[INLINE/)  {
         $posinlop = index($_, "\[INLINE", $strpnt);
         if ($posinlop < 0)  {
            goto INL;
         }
         $posinlcl = index($_, " \]", $posinlop+1); 
         $leftfrag = substr($_, 0, $posinlop);
         $rightfrag = substr($_, $posinlcl+2);
         $lenmid = $posinlcl - $posinlop + 2;
         $middlefrag = substr($_, $posinlop, $lenmid);
         $middlefrag =~ s/\[INLINE-//;
         $middlefrag =~ s/ \]//;
         $middlefrag *= 1;
         $_ = $leftfrag.$inlarray[$middlefrag].$rightfrag;
         $strpnt = $posinlop + 7;
      }
INL:      
   }      
   if (/\[DISPLAY/)  {
      $strpnt = 0;
      while (/\[DISPLAY/)  {
         $posdisop = index($_, "\[DISPLAY", $strpnt);
         if ($posdisop < 0)  {
            goto DIS;
         }
         $posdiscl = index($_, " \]", $posdisop+1);            
         $leftfrag = substr($_, 0, $posdisop);
         $rightfrag = substr($_, $posdiscl+2);
         $lenmid = $posdiscl - $posdisop + 2;
         $middlefrag = substr($_, $posdisop, $lenmid);
         $middlefrag =~ s/\[DISPLAY-//;
         $middlefrag =~ s/ \]//;
         $middlefrag *= 1;
########         print ERR "middlefrag = $middlefrag\n";
         $_ = $leftfrag.$disarray[$middlefrag].$rightfrag;
         $strpnt = $posdisop + 7;
      }
DIS:      
   }      


##  Cleaning XHTML files                     ## C L E A N I N G    X H T M L

##  Removing links to popup footnotes
##  Sample:  <a href="refsdir-545/foot01" title="Click on for more info" alt="Click on for more info"  onClick="javascript:showlayer('divfoot01');return false;"><sup><b><font color="#A52A00">[1]</font></b></sup></a>
##         Removing [ onClick="javascript:showlayer('divfoot ] 

    $strfrag = " onClick=\\\"javascript\\\:showlayer\\\(\\\'divfoot";

    if ($_ =~ /$strfrag/)  {
            ##############   print ERR "$_\n";
        $lookpos = 0;
        while (/$strfrag/)  { 
            $foopenpos = index($_, "<a href=\"refsdir", $lookpos);
            if ($foopenpos < 0)  {
                print ERR "Something wrong in footnote format.\n";
                $errcount += 1;
                goto SKIPFOOT;
            }
            $foclospos = index($_, "\]<\/font><\/b><\/sup><\/a>", $lookpos+17) + 22;
            if (foclospos < 0)  {
                print ERR "Something wrong in footnote format.\n";
                $errcount += 1;
                goto SKIPFOOT;
            }            

            ###############    print ERR "FOOTNOTE:  foopenpos = $foopenpos       foclospos = $foclospos\n";
            
            $leftpart = substr($_, 0, $foopenpos);
            $lenmid = $foclospos - $foopenpos;
            $middlepart = substr($_, $foopenpos, $lenmid); 
            $rightpart = substr($_, $foclospos);
            
            ###############    print ERR "middlepart = $middlepart\n";

##  Extracting ref+foot directory name

            @folink = split(/\" title=\"Click on for more info/, $middlepart);
            $foolink = $folink[0];
            $foolink =~ s/<a href=\"//;
            $foolink .= "\.html"; 
           
            $mergedline = $leftpart."|||".$middlepart."|||".$rightpart;
            
            ###############       print ERR "MERGEDLINE =   $mergedline\n\n";
            $footstring = "";            
            open (FOOT, "<$foolink")  ||  die "Cannot open $foolink  file.";
            while (<FOOT>)  {
                chop();
                $footstring .= " ".$_;
            }            
            close (FOOT);
            
            ###############       print ERR "\n FOOT = $footstring\n";
            
            @newfrg = split(/<font face=\"Verdana\" size=\"-1\">/, $footstring);
            @addfrg = split(/<\/font><\/body>/, $newfrg[1]); 
            $foottext = $addfrg[0];
            
            ####print ERR "FOOTTEXT = $foottext\n";            
            
            $mergedline = $leftpart."|||".$middlepart."|||".$rightpart;
            
            $correctedline = $leftpart." (<span class=\"footnote\"> ".$foottext."<\/span>) ".$rightpart; 
            
            ####print ERR "correctedline = $correctedline\n\n"; 
            
            $_ = $correctedline;  
        }            
    }
SKIPFOOT:

##  Removing links to popup references
##  Sample:  <a href="#babk04" onClick="javascript:showlayer('divbabk04');return false;">2004</a>
##         Removing [ onClick="javascript:showlayer('div                nusi97');     return false;"] 
   $strfrag = " onClick=\\\"javascript\\\:showlayer\\\(\\\'div";
   $finfrag = "return false\\\;\\\"";
   if ($_ =~ /$finfrag/)  {
####            print ERR "$_\n";
      s/ onClick=\"javascript\:showlayer\(\'div/<remove>/g;
      s/ onClick=\"OpenWinAlt\(\'/<remove>/g;
      s/return false\;\"/<\/remove>/g;
####            print ERR "$_\n";
      @parts = split(/<remove>/, $_);
      $nelm = @parts;
##print ERR "nelm = $nelm\n"; 
      for ($ip = 1; $ip < $nelm; $ip++)  {
         @frags = split(/<\/remove>/, $parts[$ip]);
         $parts[$ip] = $frags[1];
      }
      $_ = join("", @parts);
####            print ERR "$_\n---\n";
   }

##    Replacing links to *.html with the links to  *.xhtml   
   
   for ($n = 0; $n < $ifi; $n++)  {
      $hlink = $sechtml[0][$n];
      $xlink = $sechtml[1][$n]; 
      s/$hlink/$xlink/g;      ##    Replacing internal links to html files to correspondong links toxhtml files
   }   

##    Replacing external link to image with the local one   
   
   if (/<img title=\"Powered by MathJax\" src=\"http\:\/\/www.mathjax.org\/badge.gif\" border=\"0\" alt=\"Powered by MathJax\" \/>/)  {
      s/<img title=\"Powered by MathJax\" src=\"http\:\/\/www.mathjax.org\/badge.gif\" border=\"0\" alt=\"Powered by MathJax\" \/>/<img src=\"images\/mathjax-badge.jpg\" alt=\"Powered by MathJax\" \/>/;
   }
   if (/-tables/ || /-figures/)  {
      s/ target=\"\_new\">/>/g; 
   }  
   print MOD "$_\n";
   
   if (/<span class=\"texweb\">Generated from LaTeX source by /  &&  $leninput == 17)  {
            print MOD "</body></html>\n";
            ####print "CURRENT FILE = $rootfile\n";
            goto REMDIV;            ##      This stops copying DIV fragment
   }
}
REMDIV:
close(HTM);
####print ERR "---------------------------------\n";
########################################################################################################################################################################close(ERR);
   unlink($htmlname);
   unlink($mmlname);
#####################################################################&flush (MOD);
close(MOD);
#######}

###      Adding table environment to numberred equations
open (MOD, "<$modname")  ||  die  "Cannot open $modname file for reading";
$ixh = 0;
@xhtml = ();
while (<MOD>)  {
   chop();
   $xhtml[$ixh] = $_;
   $ixh += 1;
}
close (MOD);
##===##===##  print ERR "\n";
open (MOD, ">$modname")  ||  die  "Cannot open $modname file for writing";
for ($ix = 1; $ix <= $ixh; $ix++)  {
##===##===##  print ERR "$xhtml[$ix]\n";
   $_ = $xhtml[$ix];
   if (/<p> <a accesskey=\"eqn/)  {
##    Extract current number
###      print ERR "====$_\n";
      print MOD "$_\n";
###      print ERR "<table class=\"disp\"><tr><td>\n";
      print MOD "<table class=\"disp\"><tr><td>\n";
      $curnum = $_;
      $curnum =~ s/<p> <a accesskey=\"eqn//; 
      $curnum = substr($curnum, 0, 3);
      $curnum *= 1;
       ###print ERR "Label = $curnum\n";
      $ix += 1;
      $_ = $xhtml[$ix];  

###  Some corrections to equation numbers made 5 December 2015      
      $poslabtrop = index($_, "<mtable><mlabeledtr><mtd id=\"mjx-eqn-", 0);
      $poslabtrcl = index($_, "\)<\/mtext><\/mtd>", $poslabtrop) + 15;
      
      $leftpart = substr($_, 0, $poslabtrop);
      $leftpart .= "<mtable><mtr>";      
      $rightpart = substr($_, $poslabtrcl);      
  
      if (/<mtd id=\"mjx-eqn-/)  {
          $mjxeqnop = index($_, "<mtd id=\"mjx-eqn-", 0);
          $mjxeqncl = index($_, "<\/mtext><\/mtd>", $mjxeqnop); 
          $mjxfrag = $mjxeqncl - $mjxeqnop + 14;
##          print ERR "open =  $mjxeqnop     close = $mjxeqncl    length = $mjxfrag\n";  
      }  
      $mjxleft = substr($_, 0, $mjxeqnop);
      $mjxmidl = substr($_, $mjxeqnop, $mjxfrag);
##  Replacing equation numbers (correction of 5 December 2015 ###############################################################      
      $mjxmidl =~ s/\(//; 
      $mjxmidl =~ s/\)//;       
      $mjxmidl =~ s/<mtext>.+<\/mtext>/<mtext>\&\#xA0\;<\/mtext>/;       
      $mjxrigh = substr($_, $mjxeqncl+14);
 ##     print ERR "$mjxleft\n";
 ##     print ERR "$mjxmidl\n";
 ##     print ERR "$mjxrigh\n\n";
      $_ = $mjxleft.$mjxmidl.$mjxrigh;
###      print ERR "$_\n\n";    
      print MOD "$_\n";
#####  old version      print MOD "</td><td class=\"tla\">($curnum)<\/td><\/tr><\/table>\n";          
      print MOD "</td><td class=\"tla\">($curnum)<\/td><td><\/td><\/tr><\/table>\n";          
   }  else  {
      print MOD "$_\n";
   }
}   
close (MOD); 
 
if ($lct eq "rus")   {          ##  This requires recoding to UTF-8
    ##  print ERR "\nPlace to call ICONV program\n";
    ##  print ERR "MODNAME = $modname \n\n";
    $identtemp = $identname."\.xhtml";
    $identout = $opsdir."\/".$identtemp;
    $comiconv = $iconv_path." -f cp1251 -t utf-8 ".$modname." > ".$identtemp;
    ##  print ERR "comiconv = $comiconv\n"; 
    system $comiconv;
    
    open (CONV, "<$identtemp")  ||  die  "Cannot open $identtemp file for reading";
    open (FINA, ">$identout")   ||  die  "Cannot open $identout file for writing";   
    while (<CONV>)  {
        chop();
        if (length($_) > 0)  {
            print FINA "$_\n";
        }
    }
    close (CONV);
    close (FINA);
    unlink($identtemp);
} 

   
close (ERR);
sleep(2);                  ###         Waiting for 2 secs

OUTER:

if ($errcount > 0)  {
    print "done\nProgram ELXTOMML was abnormally closed while converting $infile  file!  errcount = $errcount  See error log file \[$errfile\].\n";
} else  {
    ###unlink($errfile);
}

#####################################################################################################

