#!/usr/local/bin/perl
###################################################################################
##       ELXFINAL.PL - PERL script to convert .TEX files to HTML and XML         ##
###################################################################################
##                                                                               ##
##                       VERY IMPORTANT NOTE!!                                   ##
##                                                                               ##
##   This script is a component part of the electronic publishing package which  ##
##   includes LaTeX style package ELXfinal (elxfinal.sty) which expands and      ##
##   modifies the standard LaTeX  article.sty. The script converts source LaTeX  ##
##   file into HTML file compatible with HTML5 and EPUB3 specifications.         ##
##   Conversion process creates also XML meta description of the article         ##
##   compliant with the CrossRef XML schema, ver. 4.3.0.  The script was written ##
##   under assumption that LaTeX file has no TeX errors, i.e. passed through     ##
##   TeXengine with no error messages.                                           ##
##                                                                               ##
##   This version is based essentially on  ELXPAPER package ver. 1.5 which was   ##
##   used in 2012-2017 for generating HTML5 and EPUB3 versions of articles       ##
##   published in Russian Journal of Earth Sciences and other GC RAS journals.   ##
##   The version 2.0 of software contains some corrections and amendments which  ## 
##   are marked with hachtag #NEW<date>                                          ##
###################################################################################
##   Written by Vitaly Nechitailenko,             e-mail: vnechita@gmail.com     ##
##   Version 2.0,  September 2019                     Last update 07.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];
##    The following parameter is used to create only HTML version ($ebook="")
##    or continue process with converting to XHTML ($ebook="-x") with replacing 
##    LaTeX math with MathML substitution and composing all necessary files for 
##    ebook according to ePub3 specifications
$ebook =  $ARGV[1];
if ($ebook ne "-x" && $ebook ne "-z")  {
   $ebook = "";
}
$inclean = "inclean.tex";         ##      File with placeholders in place of \begin{verbatim}  and  \verb+....+
$outclean = "outclean.tex";       ##      File with placeholders in place of \begin{verbatim}  and  \verb+....+
$outfile = $infile;
@names = split(/\./,$outfile);
$outfile1 = $names[0].".1st"; 
$errfile = $names[0].".err";
$tstfile = $names[0].".tst";
$rootdoc = $names[0].".shtml";
$fulldoc = $names[0].".html"; 
$prefile = $names[0].".pre";
$figlist = $names[0].".lof";
$tablist = $names[0].".lot";
$plalist = $names[0].".lop";
$animlist = $names[0].".loa";
$datalist = $names[0].".lod";
$videolist = $names[0].".lov";
$doisuf = $names[0];
$imagedir = "images";
if (length($names[0]) == 9)  {
    $listdirnam = substr($names[0], 6);
} elsif (length($names[0]) == 12)  {
    $listdirnam = substr($names[0], 9);
}
$uniquenumb = $listdirnam;
$reflistdir = "refsdir-".$listdirnam;
$absbodyname = "absbody".$listdirnam."\.html";       ##      Name of abstract body for response page

if (-e $imagedir)  {
    ##print "Directory $imagedir exists, OK!\n";
}  else  {
   mkdir($imagedir, 0777)  ||  die "Cannot create $imagedir directory";
   if (-e $reflistdir)  {
      ##print "New $reflistdir directory created.\n";
   }  else  {
      print "Creation of $reflistdir directory failed!\n";   
   }
}

if (-e $reflistdir)  {
   ##print "Directory $reflistdir exists, OK!\n";
}  else  {
   mkdir($reflistdir, 0777)  ||  die "Cannot create $reflistdir directory";
   if (-e $reflistdir)  {
      ##print "New $reflistdir directory created.\n";
   }  else  {
      print "Creation of $reflistdir directory failed!\n";   
   }
}
##    Copy cross.gif, etc. to the references directory
if (-e $reflistdir)  {
    $aaalink = "basic\/cross.gif";
    $bbblink = $reflistdir."\/cross.gif";
    link($aaalink, $bbblink);
##    Copy cyrchars.txt to the root directory    
    $aaacyr = "basic\/cyrchars.txt";
    $bbbcyr = "cyrchars.txt";
    link($aaacyr, $bbbcyr);
}

####################################################

$abstrnam = "0.shtml";
$absalone = $names[0]."-abs.html";
$refforebook = $names[0]."-ref.tex";
$ebookref = false;
$xmlnam = $names[0].".xml";
$xmlnamcr = $names[0]."-cr.xml";
$xmlnamneb = $names[0]."-crneb.xml";
$auxnam = $names[0].".aux";
$subnam = $names[0];
$hdrnam = $names[0].".hdr";
$refnam = "ref.html";
$refnam0 = "ref0.html";
$connam = $names[0]."-toc.html";
$mapnam = $names[0]."-map.html";
$figsfile = $names[0]."-figures.html";
$tabsfile = $names[0]."-tables.html";
$respage = $names[0]."-res.html";
$subnam = substr($subnam, 3);
$htmnam = "htm".$subnam.".zip"; ##  File containing all HTML components
$symset = $texwebdir."\/symbols.set";
@argmac = ("author", "begin", "caption", "centerline", "cite", "date", "documentstyle", "documentclass", "end", "fbox", "footnote", "footnotemark", "footnotetext", "frame", "hspace", "hspace*", "include", "index", "indexentry", "input", "item", "label", "makebox", "markboth", "markright", "mbox", "newcommand", "newcounter", "pagenumbering", "pageref", "pagestyle", "paragraph", "paragraph*", "parbox", "part", "part*", "renewcommand", "savebox", "sbox", "section", "subsection", "subsubsection", "section*", "subsection*", "subsubsection*","setcounter", "setlength", "special", "subitem", "subparagraph", "subparagraph*", "subsubitem", "thispagestyle", "title", "typein", "typeout", "vspace", "vspace*", "author", "affil", "lefthead", "righthead", "received", "abstract");    

##  Arrays filled in while translating
@contlist = ();
$contitem = 0;
@maplist = ();
$mapitem = 0;
@figlist = ();
$figitem = 0;
$figcount = 0;
@footlist = ();
$footcount = 0;
@tablist = ();
$tabitem = 0;
$tabcount = 0;
@plalist = ();
$plaitem = 0;
$tabcount = 0;
@anilist = ();
$aniitem = 0;
$anicount = 0;
@vidlist = ();
$viditem = 0;
$vidcount = 0;
@datlist = ();
$datitem = 0;
$datcount = 0;
@reflist = ();
$refitem = 0;
$refcount = 0;
@fileconv = ();

##  Formatting published-online date
@elem = localtime(time);
$elem[4] += 1;
for ($ie = 0; $ie < 5; $ie++)  {
	if ($elem[$ie] < 10)  {
		$elem[$ie] = "0".$elem[$ie];
	}
}
$timestamp = $elem[5].$elem[4].$elem[3].$elem[2].$elem[1].$elem[0] + 19000000000000;
$dcyear = $elem[5] + 1900;
$dctime = $dcyear."-".$elem[4]."-".$elem[3]."T".$elem[2]."\:".$elem[1]."\:".$elem[0]."Z";
$nebtime = $dcyear."-".$elem[4]."-".$elem[3]." ".$elem[2]."\:".$elem[1]."\:".$elem[0];

##  Extracting last page number from jobname.aux file
open (AUX, "<$auxnam")  ||  die   "Cannot open $auxnam file.";
while (<AUX>)  {
    chop();
    if (/\\lastpage\{/)  {
        s/\\lastpage\{//;
        s/\}//;
        $lastpage = $_;
    }
        if (/\\lastauth\{/)  {
        s/\\lastauth\{//;
        s/\}//;
        $lastauth = $_;
    }
}

######### A T T E N T I O N ! !  PASS 0 is added for tabulated images  ###############
###########################################################################
##        PASS 0:  Extracting fragments to be converted to float icons   ##
###########################################################################
print "\nPASS  0: Extracting fragments for converting to float icons  . . .";

##    Scanning LaTeX source file and extracting tabular environments for future 
##    converting them to images

$tabulcount = 0;           ##    Counter of tabulars
$tabcnt = 0;               ##    Counter of tables
$tabopenlab = 0;
$figcnt = 0;               ##    Counter of figures
$figopenlab = 0;
$matchpat = 0;
@tabul = ();               ##    Array of tabular parameters  

@verbdisp = ();     ##  Array of extracted verbatim fragments
@verbline = ();     ##  Array of ectracted verb (inline) fractions
$verdis = 0;        ##  Counter of verbatim fragments
$verlin = 0;        ##  Counter of verb fractions               

open (IN, "<$infile") || die "Cannot open $infile file.";
open (ERR, ">$errfile")  || die "Cannot open $errfile file.";
open (TST, ">$tstfile")  || die "Cannot open $tstfile file.";
open (CLEAN, ">$inclean")  || die "Cannot open inclean.tex file."; 

#####print ERR "listdirnam = $listdirnam      absbodyname = $absbodyname\n\n";

#      Loading and processing cyrillic chars
$cyrchars = "cyrchars.txt";
open (CYR, "<$cyrchars")  ||  die   "Cannot open $cyrchars file."; 
$icyr = 0;
while(<CYR>)  {
    chop();
    $ruslist[0][$icyr] = substr($_, 0, 1);
    $ruslist[1][$icyr] = substr($_, 1, 4); 
    $ruslist[1][$icyr] = "\&\#x".$ruslist[1][$icyr]."\;";
####    print ERR "$ruslist[0][$icyr]  --  $ruslist[1][$icyr]\n";
    $icyr += 1;
}
##print ERR "icyr = $icyr\n";

########print ERR "\n------------  I N S I D E   Z E R O   B R A N C H  --------------\n\n"; 

$papidlab = false;   ##    Prefix is not found yet
$reczero = 0;
$verbatimzero = 0;
$joinedtextline = "";
$textmark = false;

while (<IN>)  {
    ###print ERR "===$_";

    if (/\\section\{/)  {
        $textmark = true;
    } 
    if (/\\begin\{references\}/ || /\\noreferences/)  {
            $textmark = false;
    } 
    if ($textmark eq true)  {
        $tail = $_;
        if ($tail =~ /</) {
            $tail =~ s/</\&\#x3C\;/g;
        }
        if ($tail =~ />/) {
            $tail =~ s/>/\&\#x3E\;/g;
        }
        $joinedtextline .= $tail;
    }    
    chop();
    ###    print ERR "++++++++++++++++++++++++ Before if  verbatimzero = $verbatimzero\n"; 
    if (/\\begin\{verbatim\}/ && $verbatimzero == 1)  {     ##      Erroneous \verbatim  structure
        print ERR "\\begin\{verbatim\} occured while verbatimzero was already opened/\n";
        $errcount +=1 ;
    }  elsif (/\\begin\{verbatim\}/)  {                     ##      Starting \verbatim
        $verbatimzero = 1;
        $acverdis = $_."|=|";
        $_ = "";
    }  elsif (/\\end\{verbatim\}/ && $verbatimzero == 0)  { ##      Erroneous \verbatim  structure
        print ERR "\\end\{verbatim\} occured while verbatimzero was not yet opened/\n";
        $errcount +=1;  
    }  elsif (/\\end\{verbatim\}/)  {   
        $verbatimzero = 0;
        $acverdis .= $_;
        $verbdisp[$verdis] = $acverdis;                         ##      array for \verbatimS
        $_ = "\[VERBDISP-".$verdis."\]";                        ##      placeholder for \verbatim command
        $verdis += 1;            
    }  elsif ($verbatimzero == 1)  {
        $acverdis .= $_."|=|";
        $_ = "";        
    }  else  {         ##      Input file without \verbatim fragments
        ##      Extracting verbline fractions 
        if (/\\verb/)  {
            $sspos = 0;
            while (/\\verb/)  {
                $verpos = index($_, "\\verb", $sspos);
                if ($verpos < 0) {
                    print ERR "Error in \\verb fragment, see string\n$_\n";
                    $errcount += 1;
                }  else  { 
                    $sspos = $verpos + 1;
                    $vedel = substr($_, $verpos+5, 1);                  ##      \verb  delimiter
                    $eepos = index($_, $vedel, $verpos+6);
                    $vercom = substr($_, $verpos+6, $eepos-$verpos-6);  ##      \verb  command
                } 
                $verbph = "\(VERBLINE-".$verlin."\)";                   ##      placeholder for \verb command
                $verleft = substr($_, 0, $verpos);
                $verright = substr($_, $eepos+1);
                $_ = $verleft.$verbph.$verright;
                $verbline[$verlin] = $vercom;                           ##      array for \verb commands
                $verlin += 1;
            }
        }

##    Extracting paperid parameter for image prefix
        if (/\\paperid\{/ && $papidlab eq false && $verbatimzero == 0)  {
            $indpos = index($_, "\\paperid\{", 0) + 8;
            &FindMatchBracket($_, $indpos, 1);
            $lenpaind = $nepar - $indpos - 1;    
            $prefix = substr($_, $indpos+1, $lenpaind);
            $prefixsm = $prefix;
            $prefixsm =~ tr/A-Z/a-z/;
####print ERR "\nPREFIX = $prefix    PREFIXSM = $prefixsm\n";
            $papidlab = true;       ##    Prefix is found now
####print ERR   "========================PREFIX = $prefix \n";
        }
        $reczero += 1;            ##  Number of current line
##===========================================================================            print ERR "$_\n";
        s/\\\%/\[percent\]/g;       ##    Substitute marker for \%  Removing comments
        if (/\%/)  {         ##    Current string contains percent sign
            $posper = index($_, "\%", 0);
            if ($posper == 0)  {    ##    Commented full string
                $_ = "";
            }  else  {
                $_ = substr($_, 0, $posper);
            }
        }
        for ($ze = 3; $ze <= 10; $ze++)  {      ##      Start processing floats
            if (/$patopen[$ze]/)  {     ##      Opening float
         ######print ERR "===$_\n";
                $matchpat = $ze;
                if ($ze <= 6)  {        ##      Opening fig strings
                    $figopenlab = 1;
                    $figcnt += 1;
                    if ($figcnt < 10)  {
                        $fnn = "0".$figcnt;
                    }  else  {
                        $fnn = $figcnt;
                    }
                } else {                ##      Closing tab strings
                    $tabopenlab = 1;
                    $tabcnt += 1;
                    if ($tabcnt < 10)  {
                        $tnn = "0".$tabcnt;
                    }  else  {
                        $tnn = $tabcnt;
                    }
                }
            } elsif (/$patclose[$ze]/)  {       ##      Closing float
         ###print ERR "---$_\nze = $ze   matchpat = $matchpat\n";
                if ($matchpat == $ze)  {
                    $matchpat = 0;
                    if ($ze <= 6)  {
                        $figopenlab = 0;
                    } else {
                        $tabopenlab = 0;
                    }
                } else {
                    print ERR "Overlapping floats description \$pathopen = $ze\n";
                    $errcount += 1;
                }
            }
        }

        $mark = 0;     ##
        for ($ze = 11; $ze <= 12; $ze++)  {
            if (/$patopen[$ze]/)  {
                if ($tabopenlab == 0 && $figopenlab == 0)  {    ##    Tabular is outside of float
                    print ERR "TTTTTTTTTTTTTTTTTTTTTTTTTTTTT==  tabul_open_out___$_\n";
                }  elsif ($tabopenlab == 1 && $figopenlab == 1)  {    ## Wrong structure float-tabular
                    print ERR "Wrong structure of float-tabular at PASS 0.\n";
                    $errcount += 1;
                    ###print ERR "tabul_wrong___$_\n";
                    goto TABUL;
                }  elsif ($tabopenlab == 1)  {
                    $curtabulfile = "tabultab".$tnn."\.tex";
                    
                    ###print ERR ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>OPENS curtabulfile = $curtabulfile\n";
                    
                    open (TABUL, ">$curtabulfile")  ||  die "Cannot open $curtabulfile file.";
                    print TABUL <<EOM;
\\documentclass\[twoside,a3\]\{article\}
\\usepackage\[silent,pdf,hyper\]\{elxfinal\}
\\usepackage\{color\}
\\usepackage\{multirow\}
\\usepackage\{hyperref\}
\\textwidth=54pc
\\textheight=90pc

\\begin\{document\}
\\thispagestyle\{empty\}
EOM
                    if ($ze == 12)  {
                    print TABUL "$_\n";
                    }
                }  elsif ($figopenlab == 1)  {
                    $curtabulfile = "tabulfig".$fnn."\.tex";
                    open (TABUL, ">$curtabulfile")  ||  die "Cannot open $curtabulfile file.";
                    print TABUL <<EOM;
\\documentclass\[twoside,a3\]\{article\}
\\usepackage\[silent,pdf,hyper\]\{elxfinal\}
\\usepackage\{color\}
\\usepackage\{multirow\}
\\usepackage\{hyperref\}
\\textwidth=54pc
\\textheight=90pc

\\begin\{document\}
\\thispagestyle\{empty\}
EOM
                    print TABUL "$_\n";
                }
                $tabulcount += 1;       ## Tabular's counter
                ##$matchpat = $ze;
            }
            if (/$patclose[$ze]/)  {
                $tailpos = index($_, "\\end\{tabular", 0);
                $strcb = $tailpos + 12;
                $tailpos = index($_, "\}", $strcb);
                $notail = substr($_, 0, $tailpos+1);
                $_ = $notail;
                if ($ze == 11)  {                
                    print TABUL "$_\n";
                }
                print TABUL "\\end\{document\}\n";
                $figopenlab = 0;
                $tabopenlab = 0;
                close (TABUL);
            }
            if ($tabopenlab == 1 || $figopenlab == 1 )  {
                $mark += 1;
                if ($mark == 1)  {      ##    Marker for preventing double pass
                    s/\[\]/\\\%/g;       ##    Reinstate marker for \%
                    print TABUL "$_\n";
                }
            }
TABUL:
        }
    }
    ###print ERR "---$_\n";
    print CLEAN "$_\n";
}
############################print CLEAN "\n\n End of INCLEAN.TEX file\n\n";
close (IN);
close (CLEAN);

#########################################################goto STOP;

##    Accumulating generated tabulated files
foreach $ffff (<tabul*.tex>)  {
   ###print ERR "====++++====++++ $ffff\n";

##    Names of image files
##    $paperid."-fNN.png"     basic figure image for PDF
##    $paperid."-oNN.png"     screen figure image for HTML 
##    $paperid."-tNN.png"     tabulated figure fragment for HTML
##    $paperid."-thNN.png"    figure's thumbnail

##    $paperid."-toNN.png"    image of tabulated fragment for HTML table
##    $paperid."-tthNN.png"   table's thumbnail

   $fffsh = $ffff;                      ##  tabultab01.tex
   $fffsh =~ s/\.tex//;                 ##  tabultab01
   $ffpdf = $ffff;
   $ffpdf =~ s/\.tex/\.pdf/;
   $ffout = $fffsh;                     ##  tabultab01
   $ffout =~ s/tabultab/-to/;           ##  -to01  for tables
   $ffout =~ s/tabulfig/-t/;            ##  -t01   for figures  
   $ffthumb = $fffsh;                   ##  tabultab01
   $ffthumb =~ s/tabultab/-tth/;        ##  -tth01
   $tdvi = $fffsh."\.dvi";              ##  tabultab01.dvi
   $tlog = $fffsh."\.log";              ##  tabultab01.log
   $tout = $fffsh."\.out";              ##  tabultab01.out
   $taux = $fffsh."\.aux";              ##  tabultab01.aux
   $ttex = $fffsh."\.tex";              ##  tabultab01.tex
   $tpng = $prefixsm.$ffout."\.png";    ##  2015bs016-to.png
   $tpdf = $prefixsm.$ffout."\.pdf";    ##  2015bs016-to.pdf
   $tjpg = $prefixsm.$ffout."\.jpg";    ##  2015bs016-to.jpg
   $thpng = $prefixsm.$ffthumb."\.png"; ##  2015bs016=-tth.png
   
   ####print ERR "tpng = $tpng    tpdf = $tpdf    tjpg = $tjpg    thpng = $thpng\n=================\n";   
  
   if ($ffthumb =~ /tabulfig/)  {
############################################################      unlink ($ttex);
   }  else  {     ##    Do not make thumbnail for tabulated image in figures
   
   ###print ERR "ttex = $ttex       tpng = $tpng\n";  
        $ntsuf = $ttex;
        $ntsuf =~ s/tabultab//;   
        $ntsuf =~ s/\.tex//;
        $ntsuf =~ s/^0//;
        $ntsuf *= 1;
        $ntsuf -= 1;
        $comline1 = $pdflatex." --quiet ".$ffff." > c:\/temp\/null.tmp";              
        system $comline1;
        $comline2 = $imagick."convert -density 300 ".$ffpdf." ".$tpng." > c:\/temp\/null.tmp";      
        system $comline2;
        $comline3 = $imagick."mogrify -trim ".$tpng;
        system $comline3;
        $tabparams[$ntsuf][11] = $tpng;
        &ImageParams($tpng);
        $tabparams[$ntsuf][12] = $sizes[0];                              ##  Screen table image width
        $tabparams[$ntsuf][13] = $sizes[1];                              ##  Screen table image height
        $comline4 = $imagick."convert ".$tpng." -resize 7% ".$thpng." > c:\/temp\/null.tmp";
        system $comline4;
        $tabparams[$ntsuf][14] = $thpng;
        &ImageParams($thpng);
        $tabparams[$ntsuf][15] = $sizes[0];                              ##  Thumb table image width
        $tabparams[$ntsuf][16] = $sizes[1];                              ##  Thumb table image height     
    }

##    unlink ($tdvi);
##    unlink ($tlog);
##    unlink ($tout);
##    unlink ($taux);
###########################################   unlink ($ttex);
}
####################################goto STOP;      ####################!!!!!!!!!!!!!!!!####################

open (CLEAN, "<$inclean")  || die "Cannot open inclean.tex file.";
open (OUTCL, ">$outclean")  || die "Cannot open outclean.tex file for recording."; 

$cntbefore = 0;
$cntafter = 0;
$reflistopen = false;
$refitemopen = false;

while (<CLEAN>)  {
    chop();
    $cntbefore += 1;
    if (/\\begin\{references\}/)  {
        $reflistopen = true;
    } elsif (/\\end\{references\}/ || /\\noreferences/)  {
        $reflistopen = false;
    }
    if (/\\reference\{/)  {
        $refitemopen = true;
    } elsif (/\\endreference\{/)  {
        $refitemopen = false;
    }
    $lenstring = length($_);
    if (($lenstring <= 0) && ($reflistopen eq true) && ($refitemopen eq true)) {
    } else {
        print OUTCL "$_\n";
        $cntafter += 1;
    }      
}

###print OUTCL "\n\ncntbefore = $cntbefore     cntafter = $cntafter\n\n";  
close (OUTCL);
##unlink ($outclean);
###close (ERR);

###############################################################################
##        PASS 1: Numbering input lines and merging to paragraphs            ##
###############################################################################
print "done\nPASS  1: Numbering input lines and merging to paragraphs. . . . . ";    

open (IN, "<$outclean") || die "Cannot open $outclean file.";
open (EBOOK, "<$outclean") || die "Cannot open $outclean file.";    ######################################### REMOVE
open (OUTEB, ">ebooktex.tex") || die "Cannot open ebooktex.tex file.";   #################################### REMOVE 
open (TMP, ">temp.tex")  || die "Cannot open TMP (temp.tex) file.";
open (INT, ">interim.tmp")  || die "Cannot open INT (interim.tmp)file.";
open (TEMP, ">temporal.tex")  || die "Cannot open TEMP (temporal.tex) file.";
###open (TEMPINI, ">temporalini.tex")  || die "Cannot open TEMPINI (temporalini.tex) file.";

# Markers
$equmark = 0;       # equation
$eqnmark = 0;       # eqnarray
$itemark = 0;       # itemize
$enumark = 0;       # enumerate
while (<EBOOK>)  {
    chop();
##      Removing empty lines inside equations and itemization
    if (/\\begin\{equation/) {
        $equmark = 1;
    } 
    if (/\\begin\{eqnarray/) {
        $eqnmark = 1;
    } 
    if (/\\begin\{itemize/) {
        $itemark = 1;
    } 
    if (/\\begin\{enumerate/) {
        $enumark = 1;
    }     
    if (/\\end\{equation/) {
        $equmark = 0;
    } 
    if (/\\end\{eqnarray/) {
        $eqnmark = 0;
    } 
    if (/\\end\{itemize/) {
        $itemark = 0;
    } 
    if (/\\end\{enumerate/) {
        $enumark = 0;
    }     
    $lenn = length($_);    
    if (($lenn == 0) && (($equmark == 1) || ($eqnmark == 1) || ($itemark == 1) || ($enumark == 1))) {
    } else {
        print OUTEB "$_\n";
    }    
}
close(OUTEB);

##  Downloading lists of substitutions
open (SYM1, "<symb01.set")  ||  print "Cannot open symb01.set file.";
$s1 = 0;
while (<SYM1>)  {
    chop();
    s/\t/ /g;
    s/ +/ /g;
    @elms = split(/ /, $_);
    $symb01[$s1][0] = $elms[0];
    $symb01[$s1][1] = $elms[1];
    $s1 += 1;
}
close (SYM1);
open (SYM2, "<symb02.set")  ||  print "Cannot open symb02.set file.";
$s2 = 0;
while (<SYM2>)  {
    chop();
    s/\t/ /g;
    s/ +/ /g;
    @elms = split(/ /, $_);
    $symb02[$s2][0] = $elms[0];
    $symb02[$s2][1] = $elms[1];
    $s2 += 1;
}
close (SYM2);

###print ERR "The first list contains $s1 symbols, the second one $s2 symbols.\n\n";
###print ERR "$symb01[13][0]   [[]]  $symb01[13][1]\n";
###print ERR "$symb02[13][0]   [[]]  $symb02[13][1]\n";
###print ERR "==========================================================================\n";

for ($z = 0; $z < $s1; $z++)  {
####    print ERR "<$symb01[$z][0]>    <$symb01[$z][1]>\n";
}
####print ERR "\n";
for ($z = 0; $z < $s2; $z++)  {
####    print ERR "<$symb02[$z][0]>    <$symb02[$z][1]>\n";
####    print ERR "s1 = $s1   <<>>   s2 = $s2\n";
}
##################################################################################

$errcount = 0;
$recout = 0;
$numbl = 0;
$parcount = 0;
$parmarcount = 0;
$eqnsubpar = 0;

$verbmarker = "false";

while (<IN>)  {
   $recout += 1;            ##  Number of current line
   chop();

##    Replacing \acknowledgement(s)  with \acknowledgment(s)
   if(/\\acknow/) {
       s/\\acknowledgement/\\acknowledgment/g;
   }
   s/ +/ /g;                ##  Replacing multi spaces with single space 
   s/^ //;                  ##  Removing blank spaces at start positions
   s/\\begin ?\{/\\begin\{/g;
   s/\\end ?\{/\\end\{/g;
   ##s/\\begin\{itemize\}/\[itemizeopen\]/g;
   ##s/\\begin\{enumerate\}/\[enumerateopen\]/g;
   ##s/\\end\{itemize\}/\[itemizeclose\]/g;
   ##s/\\end\{enumerate\}/\[enumerateclose\]/g; 
   s/\\item/\[item\]/g;  
##     Temporary replacement of special symbols: <, >, $, %, &, \\
   s/\\\</\<lt \/\>/g;
   s/\\\>/\<gt \/\>/g;
   s/\\-//g;
   s/\\\$/\[dollar\]/g;
   s/\\\&/\[ampersand\]/g;
   s/\\\\/\[linebreak\]/g;
   s/\\permil/\[permil\]/g;
   s/\\ +/ /g;      
####   s/\\\%/\[percent\]/g;
   s/\\\_/\[underscore\]/g; 
###   s/\\deg/\\mbox\{\&\#xB0\;\}/g;
   s/\\deg/\[degree\]/g;   
   ##      Removing comment tails and comment lines
   if (/^\%/)  {
      $_ = "[comment]";
   }
   $perpos = index ($_, "\%");
   if ($perpos > 0)  {
      @parts = split(/\%/, $_);
      $_ = $parts[0];
   } 
##      Removing some non-semantic commands    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
##      This fragment should be replaced with the list of non-semantic macros!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

   while (/\\vspace/)  {
      $vpos = index($_, "\\vspace"); 
      &FindMatchBracket($_, $vpos, 1);   
      $lpart = substr($_, 0, $vpos);
      $rpart = substr($_, $nepar+1);
      $_ = $lpart." ".$rpart;
   }        
   while (/\\hspace/)  {
      $hpos = index($_, "\\hspace"); 
      &FindMatchBracket($_, $hpos, 1);   
      $lpart = substr($_, 0, $hpos);
      $rpart = substr($_, $nepar+1);
      $_ = $lpart." ".$rpart;
   }
   while (/\\enlargethispage/)  {
      $enpos = index($_, "\\enlargethispage"); 
      &FindMatchBracket($_, $enpos, 1);   
      $lpart = substr($_, 0, $enpos);
      $rpart = substr($_, $nepar+1);
      $_ = $lpart." ".$rpart;
   }           

##          Removing empty \tabular arguments and page formatting macros     
   s/\@\{ ?\}//g;      
   s/\\newpage/ /g;
   s/\\clearpage/ /g;
   s/\\pagebreak/ /g;
   s/\\nopagebreak/ /g;
   s/\\linebreak/ /g;
   s/\\nolinebreak/ /g;   
   s/\\fill/ /g;   
   s/\\fil/ /g;  
   s/\\\(/\$/g;
   s/\\\[/\$\$/g;
   s/\\\)/\$/g;
   s/\\\]/\$\$/g;    
   s/ +/ /g;                    ##  Removing extra spaces    

    s/\\begin\{sidewaysfigure/\\begin\{figure/g;
    s/\\begin\{sidewaystable/\\begin\{table/g; 
    s/\\end\{sidewaysfigure/\\end\{figure/g;
    s/\\end\{sidewaystable/\\end\{table/g; 
    s/\\hyperlink +\{/\\hyperlink\{/g;
    s/\\hypertarget +\{/\\hypertarget\{/g;
         
   if (/^(\{\\emergencystretch)/)  {
      $_ = "";
   }
   s/\\begin\{sloppypar\}//g;
   s/\\end\{sloppypar\}//g;   

   $strlen = length($_);    ##  Input string length
   if ($strlen < 1  ||  $_ eq " ")   {
      $SaveIni[$recout][1] = "<empty>";
   }  else  {      
      $SaveIni[$recout][1] = $_;      
   }
   if (($strlen==1) && (/^(\})/))  {
      $SaveIni[$recout][1] = "<empty>";
   }      
   $SaveIni[$recout][0] = "<line=$recout>"; 
}

print TEMP "\nTotal lines = $recout\n";
$recmod = 0;    ##  Corrected counter after removing extra blank lines in math frags    

##########==================================================================
for ($i=1; $i<=$recout; $i++)  {
   $_ = $SaveIni[$i][1];
   
   ## Opening/closing math subparagraph
   if(/\\begin\{equation/ || /\\begin\{eqnarray/) {
      $eqnsubpar = "open";
   } elsif (/\\end\{equation/ || /\\end\{eqnarray/) { 
      $eqnsubpar = "close";
   }      
   
   if ($eqnsubpar eq "open" && $_ eq "<empty>")  {
      ######################################################################################################################################print ERR "Removed!  <<$_>>\n";
   }  else  {
      $recmod += 1;
      $SaveIniMat[$recmod][1] = $_;
   }   
}

##  Corrected SaveIni 
for ($i=1; $i<=$recmod; $i++)  {    
   $SaveIni[$i][1] = $SaveIniMat[$i][1];
}
$recout = $recmod;    

$parlab = false;            ##  Paragraphs' marker: false -- not numberred; true -- numberred
$prelab = true;             ##  Preamble marker:  true -- inside preamble; false -- inside document body
$accum = "";                ##  Accumulated paragraph string
$tail = "";                 ##  Remaining part from previous paragraph
$verbmark = false;

for ($i=1; $i<=$recout; $i++)  {
    $_ = $SaveIni[$i][1];
   
    print TEMP "$SaveIni[$i][1]\n";

    if (/\\begin\{document\}/)  {
        $parlab = true;
        $prelab = false;
    } elsif (/\\begin\{references\}/)  {
        $parlab = false;
    } elsif (/\\end\{references\}/)  {
        $parlab = true;
    }  elsif  (/\\end\{document\}/)  {
        $parlab = false;
        goto ENDSCAN;      
    }   

   if ($i == 1)  {                                  ##  Saving first string
      $SaveIniPar[$parcount][3] = "<p id=\"none\" type=\"preamble\">"; 
      $accum = $_;
      $SaveIniPar[$parcount][0] = $parcount; 
      $SaveIniPar[$parcount][1] = $i; 
   }  else  {                   ##  Consequent strings
      if ($SaveIni[$i][1] eq "<empty>")   {         ##  Empty current string
         if ($SaveIni[$i-1][1] ne "<empty>") { 
            if ($tail ne "")  {               ##  Saving tail
               $accum .= " $tail";
            }
            $SaveIniPar[$parcount][2] = $i - 1;        ##  Last string
            $accum =~ s/\[comment\]//g;
            $accum =~ s/ +/ /g;
            $SaveIniPar[$parcount][4] = $accum;        ##  Accumulated text 
            $tail = "";
            $accum = "";
            $parcount += 1;
         } 
      }  else  {            ##  Non-empty strings 
         if ($SaveIni[$i-1][1] eq "<empty>") {      ##  Fist string of paragraph
            if ($prelab eq true) {                  ##  in the preamble
               $SaveIniPar[$parcount][3] = "<p id=\"none\" type=\"preamble\">"; 
               $accum = $SaveIni[$i][1];
               $SaveIniPar[$parcount][0] = $parcount; 
               $SaveIniPar[$parcount][1] = $i; 
            }  else  {
##=======================================            
##                           Put here algorithm of non-preamble paragraphs (First strings)
##=======================================
                    $SaveIniPar[$parcount][3] = "<p id=\"none\" type=\"indent\">";
                    $accum = $SaveIni[$i][1];                                           ###################### Replace
                    $SaveIniPar[$parcount][0] = $parcount;                              ###################### Replace
                    $SaveIniPar[$parcount][1] = $i;                                     ###################### Replace
                }
            }  else  {
                if ($prelab eq true) {                  ##  in the preamble
                    $accum .= " $SaveIni[$i][1]";
                }  else  {
                    if ($accum =~ /\\begin\{verbatim\}/) {
                        $verbmark = true;
                        $accum .= "<br \/><span class=\"verb\">".$SaveIni[$i][1]."<\/span>";
                    }  elsif ($SaveIni[$i][1] =~ /\\end\{verbatim\}/) {
                        $verbmark = false; 
                    }  elsif (verbmark eq true) {
                        $accum .= "<br \/><span class=\"verb\">".$SaveIni[$i][1]."<\/span>";
                        $accum =~ s/\\begin\{verbatim\}//;
                        $accum =~ s/\\end\{verbatim\}//;
                        $SaveIniPar[$parcount][4] = $accum;        ##  Accumulated text 
                        $tail = "";
                        $accum = "";
                        $parcount += 1;                        
                    }  else  {
                        $accum .= " $SaveIni[$i][1]";
                    }   
                }
            }
        }
    }
} 

ENDSCAN:
     
##  Saving last paragraph. Paragraph here is a part of input text separated by blank lines (para splitter)    
    
$SaveIniPar[$parcount][0] = $parcount;
$SaveIniPar[$parcount][1] = $i + 1;    
$SaveIniPar[$parcount][2] = $i + 1;    
$SaveIniPar[$parcount][3] = "<p id=\"none\" type=\"doc\">";         
$SaveIniPar[$parcount][4] = "$accum";
$parcount += 1;
    
$totpara = $parcount;

for ($k=0; $k<$parcount; $k++)  {       ############  TEST OUTPUT  
    if ($SaveIniPar[$k][4] =~ /\\begin\{verbatim\}/)  {
        print TEMP "VVVV = $SaveIniPar[$k][4]\n";
    }
    print TEMP "===$SaveIniPar[$k][0]   [$SaveIniPar[$k][1]--$SaveIniPar[$k][2]]  $SaveIniPar[$k][3] $SaveIniPar[$k][4]\n"; 
}
close (TEMP);      
 
###############################################################################
##        PASS 2:  Splitting paragraphs to semantical subparagraphs          ##
###############################################################################
print "done\nPASS  2: Splitting paragraphs to semantical subparagraphs . . . . ";     

$parcnt = 0;                            ##  Counter of splitted paragraphs  
$SavePar[$parcnt][0] = $SaveIniPar[0][0];
$SavePar[$parcnt][1] = $SaveIniPar[0][1];
$SavePar[$parcnt][2] = $SaveIniPar[0][2];
$SavePar[$parcnt][3] = $SaveIniPar[0][3];
$SavePar[$parcnt][4] = "";    

$parmarker = true;          
                
##########print TMP "++++ $SavePar[$parcnt][0]  $SavePar[$parcnt][1]  $SavePar[$parcnt][2]  $SavePar[$parcnt][3]  $SavePar[$parcnt][4]\n";

##@@@print TEMP "\n\n====================================================================\nSTEP BY STEP\n";

for ($i = 0; $i < $totpara; $i++)  {  
    $strcheck = 0;
    $openlab = 0;
    $_ = $SaveIniPar[$i][4];

##  Replacing display math in dollar signs, i.e. $$ math_expression $$
##  with \begin{eqnarray*} math_expression \end{eqnarray*}

    while (/\$\$/)  {
        ####print ERR "$_\n";
        $posmath = index($_, "\$\$", $strcheck);
        ####print ERR "posmath = $posmath\n";         
        if ($openlab == 0)  {
            ####print ERR  "Opening... \n";
            s/\$\$/\\begin\{eqnarray\*\}/;
            $openlab = 1;
            $strcheck = $posmath + 2;
        }  else  {
            ####print ERR  "Closing... \n";
            s/\$\$/\\end\{eqnarray\*\}/;
            $openlab = 0;
            $strcheck = $posmath + 2; 
        }
    }
##  Checks for non-paired double dollar signs
    @elems = split(/\$\$/, $_);
    $frags = @elems;
    if ($frags > 1)  {
        print ERR "String $parcnt  contains $frags fragments separated by \$\$\b";
        $errcount += 1;
    } 
##  Blocking dollar as currency sign
#########################################################################    s/\\\$/<dollar>/g;
    if (/\\usepackage/) {
        if (/verbose/) {
            $dialogue = true;     ##  If true the program asks to add extra utf-8 substitution for diacritical chars
        }  else  {
            $dialogue = false;         
        }  
##          The default value for paragraph counter is nopar
        if (/par/) {
            if (/nopar/)  {
                $parmarker = false;
            } else {
                $parmarker = true;
            }
        }  else  {
            $parmarker = false;
        }
    } 
####    print ERR   "dialogue = $dialogue    parmarker = $parmarker\n"; 
     
##@@@print TEMP "\n$SaveIniPar[$i][0]   [$SaveIniPar[$i][1]--$SaveIniPar[$i][2]]  $SaveIniPar[$i][3] \n$SaveIniPar[$i][4]\n";    
    if ($parmarker eq false)  {
        s/\\mpar //g;
    }
###############print TMP "==================$_\n\n";
   $parone = $SaveIniPar[$i][0];            ##      Parameters of the current parline
   $partwo = $SaveIniPar[$i][1];
   $parthree = $SaveIniPar[$i][2];
   $parfour = $SaveIniPar[$i][3];

##@@@print TEMP "parone=$parone    partwo/three=[$partwo--$parthree]    parfour=$parfour\n";

##          The following blocks create lists of breaks for the current line
##          Looking for $artcon breakers
   $k = 0;
   $j = 0;
   while ($artcon[$j] ne "")  {
      $lps = 0;
      while ($lps >= 0)  {   
         $curpos = index($_, $artcon[$j], $lps);
         if ($curpos >= 0)  {   
            $stack[$k][0] = 0;  
            $stack[$k][1] = $j;  
            $stack[$k][2] = $curpos;
            $stack[$k][3] = $i;
            ###print ERR "\n$_\n$stack[$k][0] || $stack[$k][1] || $stack[$k][2] || $stack[$k][3]\n\n";
            $k += 1;
            $lps = $curpos + 5;
         }  else  {
            $lps = -1;
         }
      }
      $j += 1;
   }

##          Looking for $parstr breakers
   $j = 0; 
   while ($parstr[$j] ne "")  {
      $lps = 0;
      while ($lps >= 0)  {   
         $curpos = index($_, $parstr[$j], $lps);
         if ($curpos >= 0)  {     
            $stack[$k][0] = 1;  
            $stack[$k][1] = $j;  
            $stack[$k][2] = $curpos;
            $stack[$k][3] = $i;
            $k += 1;
            $lps = $curpos + 5;
         }  else  {
            $lps = -1;
         }
      }
      $j += 1;
   }   

##          Looking for $parend breakers
   $j = 0;   
   while ($parend[$j] ne "")  {
      $lps = 0;
      while ($lps >= 0)  {   
         $curpos = index($_, $parend[$j], $lps);
         if ($curpos >= 0)  {     
            $stack[$k][0] = 2;  
            $stack[$k][1] = $j;  
            $stack[$k][2] = $curpos;
            $stack[$k][3] = $i;
            $k += 1;
            $lps = $curpos + 5;
         }  else  {
            $lps = -1;
         }
      }
      $j += 1;
   }      
######        Non-orderred list of breaks is created
##            Test output for non-ordered parlines 
   if ($k > 0)  {
      ##///////////////////////////////////print ERR "\n\n\n$k checks for Parline $i\n";
      for ($l = 0; $l < $k; $l++)  {
         ##////////////////////////////////print ERR "TypeINI = $stack[$l][0]  Number = $stack[$l][1]    Position = $stack[$l][2]\n";
      }
   }
##          Ordering breaks in accending mode      
   if ($k > 1)  {  
      for ($ii =  0; $ii < $k; $ii++)  {
         $stock[$ii] = $stack[$ii][2];
      }                
##          Sorting numerically
      @ordlist = sort { $a <=> $b } @stock;
      for ($ii=0; $ii<$k; $ii++)  {
         for ($jj=0; $jj<$k; $jj++)  {
            if ($ordlist[$ii] == $stack[$jj][2])  {
               for ($s=0; $s<4; $s++)  {
                  $stuck[$ii][$s] = $stack[$jj][$s];
               }
            }
         }
      }      
      for ($ii=0; $ii<$k; $ii++)  {
         $stock[$ii] = 1000000;
      }
   }  else  {
      for ($s=0; $s<4; $s++)  {
         $stuck[0][$s] = $stack[0][$s];
      }
   }                         
####                The list of breaks is orderred      ##########################################
##                  Test printing of orderred list 
   if ($k > 0)  {
      ##print TMP "$_\n";
      ##print TMP "$k breaks for ordered Parline $i\n";
      for ($l = 0; $l < $k; $l++)  {
          ##print TMP "TypeORD =  $stuck[$l][0]  Number = $stuck[$l][1]    Position = $stuck[$l][2]\n";
      }
   }  
####            Merging preamble lines
   if (($i == 0) && ($SaveIniPar[$i][3] =~ /\"indent\"/))  {
      ##///////////////////////////////print ERR "First line of input TeX file should start with preamble text\n";
      $errcount += 1;
   } 
   if ($SaveIniPar[$i][3] =~ /\"preamble\"/)  {
      $partail = $SaveIniPar[$i][4];
      $partail =~ s/\<\/p\>//g;
      $SavePar[0][4] .= "$partail";
      $labpre = true;
   }  else {  
      if ($labpre eq true)  { 
         $SavePar[0][2] = $SaveIniPar[$i-1][2];
         $labpre = false;
      }
####                        ##  Processing non-preamble lines       ################################      
      if ($k > 0)  {        ##  Lines with breaks <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
         $lencurstring = length($_);
         $sposit = 0;                       ##      Start position of current fragment
         if (($k == 1) && ($stuck[0][2] == 0))  {        ##      One break starts from position=0
            $parcnt += 1;
            $SavePar[$parcnt][0] = $parcnt;
            $SavePar[$parcnt][1] = $partwo;
            $SavePar[$parcnt][2] = $parthree;     
            $SavePar[$parcnt][3] = $parfour; 
            $SavePar[$parcnt][4] = $_;   
            if ($stuck[$k-1][0] == 0)  {           ##      artcon branch  (type 0)
               $subst = $parart[$stuck[0][1]];   
               $SavePar[$parcnt][3] =~ s/indent/$subst/;
            }  else  {                           ##      types 1 and 2
               $subst = $partype[$stuck[0][1]];               
               $SavePar[$parcnt][3] =~ s/indent/$subst/;               
            } 
         }  elsif (($k == 1) && ($stuck[$0][2] > 0))  {        ##      One break starts from arbitrary position          
            
            $stpos = $stuck[0][2];        
            $fipart =  substr($_, $sposit, $stpos-$sposit);
            $tailpart = substr($_, $stpos);
            $parcnt += 1;                   ##      Saving first part
            $SavePar[$parcnt][0] = $parcnt;
            $SavePar[$parcnt][1] = $partwo;
            $SavePar[$parcnt][2] = $parthree;     
            $SavePar[$parcnt][3] = $parfour; 
            $SavePar[$parcnt][4] = $fipart;               
##          Maybe it is necessary to set assigning par numbers to reference items in the configuration file 
##          !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
            if (($SavePar[$parcnt][4] =~ /^(\\noindent)/)  ||  ($SavePar[$parcnt][4] =~ /^(\\reference)/))  {  ##  \noindent text paragraph
               $SavePar[$parcnt][4] =~ s/\\noindent//;               
               $SavePar[$parcnt][3] =~ s/indent/noindent/;
            }              
            $parcnt += 1;                   ##      Saving tail part
            $SavePar[$parcnt][0] = $parcnt;
            $SavePar[$parcnt][1] = $partwo;
            $SavePar[$parcnt][2] = $parthree;     
            $SavePar[$parcnt][3] = $parfour; 
            $SavePar[$parcnt][4] = $tailpart;                     
            if ($stuck[$k-1][0] == 0)  {           ##      artcon branch  (type 0)
               $subst = $parart[$stuck[0][1]];   
               $SavePar[$parcnt][3] =~ s/indent/$subst/;
            }  else  {                           ##      types 1 and 2
               $subst = $partype[$stuck[0][1]];               
               $SavePar[$parcnt][3] =~ s/indent/$subst/;               
            } 
         }  elsif (($k > 1) && ($stuck[0][2] == 0))  {     ##    Many breaks, the first one starts from position=0           
            $sposit = 0;
            for ($l = 0; $l < $k; $l++)  {            
               if ($l < $k-1)  {
                  $stpos = $stuck[$l+1][2];         ##      Break position of current fragment
                  $fipart =  substr($_, $sposit, $stpos-$sposit);
                  $sposit = $stpos;
               }  else  {
                  $fipart =  substr($_, $sposit); 
               }             
               $parcnt += 1;
               $SavePar[$parcnt][0] = $parcnt;
               $SavePar[$parcnt][1] = $partwo;
               $SavePar[$parcnt][2] = $parthree;     
               $SavePar[$parcnt][3] = $parfour; 
               $SavePar[$parcnt][4] = $fipart;   
               if ($stuck[$l][0] == 0)  {           ##      artcon branch  (type 0)
                  $subst = $parart[$stuck[$l][1]];   
                  $SavePar[$parcnt][3] =~ s/indent/$subst/;
               }  else  {                           ##      types 1 and 2
                  $subst = $partype[$stuck[$l][1]];               
                  $SavePar[$parcnt][3] =~ s/indent/$subst/;               
               } 
            }
         }  elsif (($k > 1) && ($stuck[0][2] > 0))  {     ##    Many breaks, the first one starts from arbitrary position    

            $sposit = 0;
            for ($l = 0; $l < $k; $l++)  {     ##  k breaks produce k+1 fragments in this case
               $stpos = $stuck[$l][2];         ##      Break position of current fragment
               $fipart =  substr($_, $sposit, $stpos-$sposit);
               $sposit = $stpos;
               $parcnt += 1;
               $SavePar[$parcnt][0] = $parcnt;
               $SavePar[$parcnt][1] = $partwo;
               $SavePar[$parcnt][2] = $parthree;     
               $SavePar[$parcnt][4] = $fipart;   
               $SavePar[$parcnt][3] = $parfour; 
               if ($l > 0)  {
                  if ($stuck[$l-1][0] == 0)  {           ##      artcon branch  (type 0)
                     $subst = $parart[$stuck[$l-1][1]];   
                     $SavePar[$parcnt][3] =~ s/indent/$subst/;
                  }  else  {                           ##      types 1 and 2
                     $subst = $partype[$stuck[$l-1][1]];               
                     $SavePar[$parcnt][3] =~ s/indent/$subst/;               
                  } 
               }
            }
##                                  Composing last fragment            
            $stpos = $stuck[$k-1][2];         ##      Break position of last fragment
            $tailpart = substr($_, $stpos); 
            $parcnt += 1;
            $SavePar[$parcnt][0] = $parcnt;
            $SavePar[$parcnt][1] = $partwo;
            $SavePar[$parcnt][2] = $parthree;     
            $SavePar[$parcnt][4] = $tailpart;   
            $SavePar[$parcnt][3] = $parfour; 
            if ($stuck[$k-1][0] == 0)  {           ##      artcon branch  (type 0)
               $subst = $parart[$stuck[$k-1][1]];   
               $SavePar[$parcnt][3] =~ s/indent/$subst/;
            }  else  {                           ##      types 1 and 2
               $subst = $partype[$stuck[$k-1][1]];               
               $SavePar[$parcnt][3] =~ s/indent/$subst/;               
            } 
         }
      }  else  {   
##          Copying non-broken strings
         $parcnt += 1;
         $SavePar[$parcnt][0] = $parcnt;
         $SavePar[$parcnt][1] = $partwo;
         $SavePar[$parcnt][2] = $parthree;     
         $SavePar[$parcnt][4] = $_;   
         if (/^(\\noindent)/)  {
            s/\\noindent//;
            s/^( +)//;
            $SavePar[$parcnt][3] = "<p id=\"none\" type=\"indent\">"; 
         }
      }
   }      
}
###++++++++++++++++++++++++###print TMP "\n\nPARCNT = $parcnt\n\n";
 
########print ERR "\n\nS P L I T T E D    P A R A G R A P H S  \n\n";  
for ($iw = 0; $iw <= $parcnt; $iw++)  {
    ########print ERR "[$SavePar[$iw][0]]     $SavePar[$iw][1]--$SavePar[$iw][2]  [$SavePar[$iw][3]]     $SavePar[$iw][4]\n";
}

$totpara = $parcnt;
##      This step  breaks special paragraphs and their text tails  
$parcnt = 0;              ##  Counter of splitted paragraphs  
$SaveFinPar[$parcnt][0] = $SavePar[0][0];
$SaveFinPar[$parcnt][1] = $SavePar[0][1];
$SaveFinPar[$parcnt][2] = $SavePar[0][2];
$SaveFinPar[$parcnt][3] = $SavePar[0][3];
$SaveFinPar[$parcnt][4] = $SavePar[0][4]; 

for ($i = 1; $i <= $totpara; $i++)  {  
   $_ = $SavePar[$i][4];  
   if ((/^(\\begin\{)/)  ||  (/^(\\end\{)/))  {
      $brpos = index($_, "\}");      
      $fipart = substr($_, 0, $brpos+1);
      $tailpart = substr($_, $brpos+1);
      $tailpart =~ s/^( +)//;
      $parcnt += 1;             ##      Saving macro part             
      $SaveFinPar[$parcnt][0] = $parcnt;
      $SaveFinPar[$parcnt][1] = $SavePar[$i][1];
      $SaveFinPar[$parcnt][2] = $SavePar[$i][2];
      $SaveFinPar[$parcnt][3] = $SavePar[$i][3];
      $SaveFinPar[$parcnt][4] = $fipart;
      if (length($tailpart) > 0)  {
         $parcnt += 1;          ##      Saving tail part           
         $SaveFinPar[$parcnt][0] = $parcnt;
         $SaveFinPar[$parcnt][1] = $SavePar[$i][1];
         $SaveFinPar[$parcnt][2] = $SavePar[$i][2];
         $SaveFinPar[$parcnt][3] = $SavePar[$i][3];
         $SaveFinPar[$parcnt][4] = $tailpart;                       
         if (/^(\\end\{)/)  {         
            if ($tailpart =~ /^(\\mpar\\)/)  {
               $SaveFinPar[$parcnt][3] = "<p id=\"none\" type=\"indent\">";
            }  else  {
               $SaveFinPar[$parcnt][3] = "<p id=\"none\" type=\"noindent\">";  
            }
         }                               
      }                                    
   }  else  {           
      $artfound = false;
      for ($v = 1; $v < 11; $v++)  {       ##      ARTCON branch
         if (/^($artpat[$v])/)  {
            $vv = $v;
            $nn = $parlen[$vv];
            &FindMatchBracket($_, 0, $nn);      
            if ($cpb eq false)  {
                print ERR "Error in ARTCON branch, CPB eq false\n";
                $errcount += 1;
                goto OUTER;
            }
            $compart = substr($_, 0, $nepar+1);
            $tailpart = substr($_, $nepar+1);
            $tailpart =~ s/^( +)//;
            $parcnt += 1;             ##      Saving macro part             
            $SaveFinPar[$parcnt][0] = $parcnt;
            $SaveFinPar[$parcnt][1] = $SavePar[$i][1];
            $SaveFinPar[$parcnt][2] = $SavePar[$i][2];
            $SaveFinPar[$parcnt][3] = $SavePar[$i][3];
##            $SaveFinPar[$parcnt][3] = $parart[$v];
            $SaveFinPar[$parcnt][4] = $compart;
            if (length($tailpart) > 0)  {
               $parcnt += 1;          ##      Saving tail part           
               $SaveFinPar[$parcnt][0] = $parcnt;
               $SaveFinPar[$parcnt][1] = $SavePar[$i][1];
               $SaveFinPar[$parcnt][2] = $SavePar[$i][2];
               $SaveFinPar[$parcnt][3] = "<p id=\"none\" type=$parart[$v]>";
               $SaveFinPar[$parcnt][4] = $tailpart;   
            }
            $artfound = true;
         }  
      }
      for ($v = 11; $v < 14; $v++)  {       ##      ARTCON branch -> continued for acknowledgment
         if (/^($artpat[$v])/)  {
            $vv = $v;
            $nn = $parlen[$vv];
            &FindMatchBracket($_, 0, $nn);  
            if ($cpb eq false)  {
                print ERR "Error in ARTCON branch, CPB eq false. (for acknow)\n";
                $errcount += 1;
                goto OUTER;
            }
            $compart = substr($_, 0, $nepar+1);
            $tailpart = substr($_, $nepar+1);
            $tailpart =~ s/^( +)//;
            $parcnt += 1;             ##      Saving macro part             
            $SaveFinPar[$parcnt][0] = $parcnt;
            $SaveFinPar[$parcnt][1] = $SavePar[$i][1];
            $SaveFinPar[$parcnt][2] = $SavePar[$i][2];
            $SaveFinPar[$parcnt][3] = $SavePar[$i][3];
            $SaveFinPar[$parcnt][4] = $compart;
            if (length($tailpart) > 0)  {
               $parcnt += 1;          ##      Saving tail part           
               $SaveFinPar[$parcnt][0] = $parcnt;
               $SaveFinPar[$parcnt][1] = $SavePar[$i][1];
               $SaveFinPar[$parcnt][2] = $SavePar[$i][2];
               $SaveFinPar[$parcnt][3] = "<p id=\"none\" type=$parart[$v]>";
               $SaveFinPar[$parcnt][4] = $tailpart;   
            }
            $artfound = true;
            if ($v == 11)  {        ##  Skipping is added to prevent double acknowledgment strings
                $v += 1;
            }
         }  
      }
      if ($artfound eq false)  {
         $parcnt += 1;          ##      Saving text strings    
         $SaveFinPar[$parcnt][0] = $parcnt;
         $SaveFinPar[$parcnt][1] = $SavePar[$i][1];
         $SaveFinPar[$parcnt][2] = $SavePar[$i][2];
         if (/^(\\noindent)/)  {
            $SaveFinPar[$parcnt][3] = "<p id=\"none\" type=\"noindent\">";
         }  else  {
            $SaveFinPar[$parcnt][3] = "<p id=\"none\" type=\"indent\">";  
         }
         $SaveFinPar[$parcnt][4] = $_;  
      }    
   }  
}    

##  N O T E !!   Before composing modified TeX file special signs should be restored !!!!!!!!!!!!!!!!!!!
  
####    The following block produces modified TeX file which saves initial meanings and structure
####

$parlab = false;            ##  Paragraphs' marker: false -- not numberred; true -- numberred

for ($iw = 0; $iw <= $parcnt; $iw++)  {
   $_ = $SaveFinPar[$iw][4];
   $SaveFinPar[$iw][4] = $_;
   $l4 = length($_);
   if ($l4 <= 1)  {                 ##      Hiddens empty strings
      $SaveFinPar[$iw][3] = "<p id=\"none\" type=\"hidden\">";  
   }       

   if (/\\begin\{document\}/)  {
      $parlab = true;
   } elsif (/\\begin\{references\}/)  {
      $parlab = false;
   } elsif (/\\noreferences/)  {
      $parlab = false;
   }  elsif  (/\\end\{document\}/)  {
      $parlab = false;
   }      
}

#################################  print TMP "\n\nF  I  N  A  L          P  A  R  A  G  R  A  P  H  S   parcnt = $parcnt  \n\n"; 
#################################  Removing empty strings and renumbering 
$no = 0;
for ($iw = 0; $iw <= $parcnt; $iw++)  {
    if (length($SaveFinPar[$iw][4]) > 0)  {
############        print TMP "$SaveFinPar[$iw][0]  [$SaveFinPar[$iw][1] -- $SaveFinPar[$iw][2]]  $SaveFinPar[$iw][3]  $SaveFinPar[$iw][4]\n";
############        print TMP "$SaveFinPar[$iw][3]  $SaveFinPar[$iw][4]\n";
        $SaveCleanPar[$no][0] = $no;
        $SaveCleanPar[$no][1] = $SaveFinPar[$iw][1];
        $SaveCleanPar[$no][2] = $SaveFinPar[$iw][2];
        $SaveCleanPar[$no][3] = $SaveFinPar[$iw][3];
        $SaveCleanPar[$no][4] = $SaveFinPar[$iw][4];
        $no += 1;
    }
}
$no -= 1;

####print TMP "\n\nC L E A N E D        P  A  R  A  G  R  A  P  H  S   No = $no   PASS 2:\n\n"; 
###############################################################
####for ($iw = 0; $iw <= $no; $iw++)  {
    ####print TMP "$SaveCleanPar[$iw][0]  [$SaveCleanPar[$iw][1] -- $SaveCleanPar[$iw][2]]  $SaveCleanPar[$iw][3]  $SaveCleanPar[$iw][4]\n";
    ####print TMP "$SaveCleanPar[$iw][4]\n";
####}
###print TMP "\n\nB E F O R E     P A S S   3 \n\n\n";

###############################################################################
##        PASS 3:  Extracting parameters from PREAMBLE block                 ##
###############################################################################
print "done\nPASS  3: Extracting parameters from PREAMBLE block  . . . . . . . ";     

$prestring = $SaveFinPar[0][4];

&SplitPreamble();       ##  Runs preamble splitter

$icode = 0;             ##  What is this?

if ($langcodetype eq "eng")  {
   $absname = "Abstract";
   $figtypename = "Figure";
   $figsname = "Figures";
   $tabtypename = "Table";
   $tabsname = "Tables";
   $acknowname = "Acknowledgment";
   $acknownames = "Acknowledgments";
   $refername = "References";
   $receivname = "Received";
   $acceptname = "accepted";
   $publishname = "published";
   $artmapname = "Article Map";
   $citname = "Citation";
   $contname = "Contents";
} elsif ($langcodetype eq "rus")  {
   $absname = "@mmnr`vh";
   $figtypename = "Phq.";
   $figsname = "Phqsmjh";
   $tabtypename = "R`ak.";
   $tabsname = "R`akhv{";
   $acknowname = "Ak`cnd`pmnqr|";
   $acknownames = "Ak`cnd`pmnqrh";
   $refername = "Khrep`rsp`";
   $receivname = "Onkswemn";
   $acceptname = "ophmrn";
   $publishname = "nosakhjnb`mn";
   $artmapname = "J`pr` dnjslemr`"; 
   $citname = "Qq{kj`";    
   $contname = "Qndepf`mhe";
} else {
   print ERR "Unknown or neither language type is defined.\n";
   $errcount += 1;
}

################print ERR "PAPERID = $paperid    |||   langcodetype = $langcodetype \n";

#######################print TMP "\n\nB E F O R E     P A S S   4 \n\n\n";

###############################################################################
##        PASS 4:  Setting blocked frags and replacements for font markups   ##
###############################################################################
print "done\nPASS  4: Setting block frags and replacements for font markups. . ";

####   Processing para 91  
for ($i = 2; $i < $no; $i++)  {
    ####$i = 91;        ###   Processing of fixed record
    $_ = $SaveCleanPar[$i][4];
##  Removing \par markers
    if (/^\\par /)  {
       s/^\\par / /;
    }
    s/^\\par\\noindent/\\noindent/;

    if (/\\parbox ?\{/)  {
        $nepar = 0;
        ####print ERR "WW1-parbox==== $_\n";
        s/\\parbox +\{/\\parbox\{/;
        s/\} +\{/\}\{/g;
        $ipbstr = index($_, "\\parbox\{", 0);       ##  $ipbstr - position of \parbox
        $ipbcdr = $ipbstr + 7;                      ##  $ipbcdr - position of opening brace for para width
        #######print ERR "WW2-parbox==== $_\n";
        &FindMatchBracket($_, $ipbstr, 1);          ##  $nepar  - position of closing brace for para width
        #######print ERR "ipbstr = $ipbstr     ipbcdr = $ipbcdr      nepar = $nepar\n";
        #######print ERR "WW2       ---- $_\n";
        #######print ERR "ipbstr = $ipbstr     widstr = $widstr\n";
        $partone = substr ($_, 0, $ipbstr);
        $parttwo = substr ($_, $nepar+1);
        $_ = $partone."<parbox>".$parttwo;
        #######print ERR "WW3       ---- $_\n";
        #######print ERR "WW4 $parttwo\n";
        &FindMatchBracket($parttwo, 0, 1);
        #######print ERR "nepar = $nepar    cpb = $cpb\n";
        $partthr = substr ($parttwo, 0, $nepar+1);
        $partfor = substr ($parttwo, $nepar+1);
        $parttwo = $partthr."<\/parbox>".$partfor;
        #######print ERR "WW5 $parttwo\n";
        $_ = $partone."<parbox>".$partthr."<\/parbox>".$partfor;
        s/\\noindent//;
        #######print ERR "WW6 $_\n\n\n";
        ##///////////////////////////////print TMP "\n";
    }

    if ($SaveCleanPar[$i][3] =~ /type=\"indent\"/)  {
        $_ = "<p>".$_."<\/p>";
    }  ###elsif ($SaveCleanPar[$i][3] =~ /type=\"noindent\"/)  {
##        $_ = $_."<p \/>";
##    }
##      Defining blocked fragments (math and verbatin)
#################################    $_ = $SaveCleanPar[$i][4];
##  Correct source string with font emphasize to standard form as defined in config file
    s/\\!//g;                       ##  Removing negative spaces
    s/\\bf/\\bfseries/g;
    s/seriesseries/series/g;
    s/\\bfseries/\\bfseries /g;
    s/\\md/\\mdseries/g;
    s/seriesseries/series/g;
    s/\\mdseries/\\mdseries /g;
    s/\\itc\{/\{\\it /g;            ##  Replacing \itc to \it vs \itshape
    s/\\it/\\itshape/g;
    s/shapeshape/shape/g;
    s/\\itshape/\\itshape /g;
    s/\\sl/\\slshape/g;
    s/shapeshape/shape/g;
    s/\\slshape/\\slshape /g;
    s/\\sc/\\scshape/g;
    s/shapeshape/shape/g;
    s/\\scshape/\\scshape /g;
    s/ +/ /g;
    $modline = $_;
    $SaveCleanPar[$i][4] = $_;
########################################################print ERR "MOD: $modline\n";

   if ($SaveCleanPar[$i][3] ne "\<p id=\"none\" type=\"math\"\>")  {
####        $_ = $SaveCleanPar[$i][4];
      $modline = $_;
      &BlockedFrags($_);        
      $_ = $SaveCleanPar[$i][4];        
########################################################################print ERR "\nBefore  $_\n";
##    Removing \mbox'es
      if (/\\mbox/)  {
      ############################################################################print ERR "====\n=$_\n";
         s/\\mbox +\{/\\mbox\{/g;
         s/\\mbox\{ +/\\mbox\{/g;
      ############################################################################print ERR "-$_\n";
         @mbaks = ();
         $mbnum = 0;
         $mbnext = 0;
         while (/\\mbox/)  {
            $mbpos = index($_, "\\mbox", $mbnext);
            $mblab = 1;            
            if ($mbpos >= 0)  {
               for ($ji = 0; $ji < $numblank; $ji++)  {
                  if ($range[$ji][0] <= $mbpos  &&  $mbpos <= $range[$ji][1])  {
                     $mblab = 0;
                  }
               }
               if ($mblab == 1)  {
                  $mbaks[$mbnum] = $mbpos;             ## Break position for \mbox
                  $mbnum += 1;
               }
            } else  {
               goto MBOX;
            }
            $mbnext = $mbpos + 1;
####            s/\\mbox/\\mmmm/;                ## Temporar substitution               
         }
MBOX:
         if ($mbnum < 0)  {
            print ERR "Wrong \\mbox structure in para $i (lines $SaveCleanPar[$i][1] -- $SaveCleanPar[$i][2])\n";
            $errcount += 1;
         }  elsif  ($mbnum > 0)  {
            #######print ERR "======----------======@mbaks\n";
##       Reversed sustitutions for \mbox'es             
            for ($iz = $mbnum - 1; $iz >= 0; $iz--)  {
               #######print ERR "------------------------------mbaks[$iz] = $mbaks[$iz]\n";
               $mbpos = $mbaks[$iz];
               &FindMatchBracket($_, $mbpos, 1);
               ##33##33##print ERR "$_\nmbpos = $mbpos      nepar = $nepar\n";
##    This fragment analyses if braces contains font tags or not.
##    In the first case (font tags) braces should be saved, in the second one - removed
##    $nepar is the position of right brace
               $firstchar = substr($_, $mbpos+6, 1);
########               print ERR "FIRSTCHAR = $firstchar\n";
               if ($firstchar ne "\\")  {         ##  Non-font command branch
                  $elleft = substr($_, 0, $nepar);
                  $elmiddle = substr($_, $nepar, 1);
                  $elright = substr($_, $nepar + 1);
                  $_ = $elleft.$elright;          ##  Right brace removed
                  $elleft = substr($_, 0, $mbpos);
                  $elright = substr($_, $mbpos+6);                  
                  $_ = $elleft.$elright;          ##  Left tag+brace removed                  
               }  else  {                         ##  Font branch 
                  $elleft = substr($_, 0, $mbpos);
                  $elright = substr($_, $mbpos+5);                  
                  $_ = $elleft.$elright;          ##  Left tag+brace removed with saving braces for font boundaries
               }
            }       
         }
         ##################################print ERR "$_\n\n";
      }
#####################################################################################print ERR "After   $_\n";
      $modline = $_;
      $SaveCleanPar[$i][4] = $_;    

      &BlockedFrags($_);        

################################print ERR "After BlockedFrags===  $_\n";
        
####//////////////////////   FONTS  SUBSTITUTION   //////////////////////////////
        $snum = 0;          ##  Number of font substitution in the current line
        @breaks = ();
        for ($f = 0; $f < @fonts; $f++)  {
            $fmn = 0;
            while ($modline =~ /$fnpat[$f]/)  {     ##    C H E C K   B L O C K E D    F R A G M E N T S
                $fnpos = index($modline, $fonts[$f], $fmn);
                #########################print ERR "FMN = $fmn     FNPOS = $fnpos      NUMBLANK = $numblank\n";
                $fmlab = 1;
                if ($fnpos >= 0)  {
                    for ($ji = 0; $ji < $numblank; $ji++)  {
                        if ($range[$ji][0] <= $fnpos  &&  $fnpos <= $range[$ji][1])  {
                            ###print TMP "fnpos = $fnpos   f = $f     inside block $range[$ji][0] -- $range[$ji][1]     fnpat = $fnpat[$f] :: $fonts[$f]  \n";
                            $fmlab = 0;
                        }
                    }
                    if ($fmlab == 1)  {
            ###print TMP "fnpos = $fnpos   f = $f     fnpat = $fnpat[$f] :: $fonts[$f]  \n";
                        $breaks[$snum] = $fnpos * 1000000 + $f;
                        $snum += 1;
                    }
                } else  {
                    goto FONTS;
                }
                $fmn = $fnpos + 1;
            }
FONTS:
        }
        if ($i == 91)  {            ############################################################################  ##$$##
            ###print TMP "Openings  $snum elements\n";    ##$$##
            for ($qq = 0; $qq < $snum; $qq++)  {   ##$$##
                ###print TMP "$breaks[$qq]\n";     ##$$##
            }                           ##$$##
 ##           @breaks = ();
            $lenbreaks = @breaks;
            ###print TMP "lenbreaks = $lenbreaks\n";
        }                           ############################################################################   ##$$##

        if ($snum >= 2)  {           ##  Needs ordering
            @fnsort = ();
            @fnsort = sort { $a <=> $b } @breaks;
        }  elsif ($snum == 1)  {    ##  Rename
            $fnsort[0] = $breaks[0];
        }

        if ($i == 91)  {            ############################################################################  ##$$##
            ###print TMP "Sorted\n";
            ###print TMP "@breaks \n";
            ###print TMP "@fnsort \n";            
            for ($qq = 0; $qq < $snum; $qq++)  {
                ###print TMP "$fnsort[$qq]\n";
            }
        }                           #############################################################################  ##$$##
        ###print TMP "Opening tags\n";

##      Splitting ordered breaks
        for ($jim = 0; $jim < $snum; $jim++)  {
            $lenran = length($fnsort[$jim]);
            $opfn[$jim][0] = (substr($fnsort[$jim], 0, $lenran - 6)) * 1;
            $opfn[$jim][1] = (substr($fnsort[$jim], $lenran - 6)) * 1;
            if ($i == 91)  {            ############################################################################  ##$$##
                ###print TMP "$fnsort[$jim] <> $opfn[$jim][0] <> $opfn[$jim][1]\n";   ####################################################################  ##$$##
            }                           #############################################################################  ##$$##
        }

##      Composing list of closing braces
        @clofn = ();
        for ($jim = 0; $jim < $snum; $jim++)  {
            &FindMatchBracket($modline, $opfn[$jim][0], 1);
            $clofn[$jim] = $nepar * 1000000 + $opfn[$jim][1];
            ####print TMP "++++ jim = $jim      opfn[$jim][0] = $opfn[$jim][0]   nepar = $nepar\n"
        }
        if ($snum >= 2)  {           ##  Needs ordering
            @ordcl = sort { $a <=> $b } @clofn;
        }  elsif ($snum == 1)  {    ##  Rename
            $ordcl[0] = $clofn[0];
        }
        ###print TMP "Closing tags\n";
##      Splitting ordered closings
        for ($jim = 0; $jim < $snum; $jim++)  {
            $lenran = length($ordcl[$jim]);
            $clfn[$jim][0] = (substr($ordcl[$jim], 0, $lenran - 6)) * 1;
            $clfn[$jim][1] = (substr($ordcl[$jim], $lenran - 6)) * 1;
            if ($i == 91)  {            ############################################################################  ##$$##
                ###print TMP "$ordcl[$jim] <> $clfn[$jim][0] <> $clfn[$jim][1]\n";
            }                           #############################################################################  ##$$##
        }
##      Merging opening and closing arays for future ordering
        @merge = 0;
        $nmer = 0;       ##  Accumulated number
        for ($jim = 0; $jim < $snum; $jim++)  {
            $merge[$nmer] = ($opfn[$jim][0] * 1000000 + $opfn[$jim][1]) * 10 + 0;
            $nmer += 1;
        }
        for ($jim = 0; $jim < $snum; $jim++)  {
            $merge[$nmer] = ($clfn[$jim][0] * 1000000 + $clfn[$jim][1]) * 10 + 1;
            $nmer += 1;
        }
        @mersort = sort { $a <=> $b } @merge;
        $mervol = @mersort;
   
        ##if ($i == 91)  {            ############################################################################    ##$$##
            ###print TMP "Merged and ordered\n";
            ##for ($qq = 0; $qq < $nmer; $qq++)  {
                ###print TMP "$mersort[$qq]\n";
            ##}
        ##}                           #############################################################################   ##$$##
###################################before last##    print ERR "Reversed mersort\n";
        ##if ($i == 91)  {            ############################################################################   ##$$##
            ##print ERR "Reversed mersort  nmer = $nmer  \n";
        ##}                           #############################################################################   ##$$##
        for ($kik = $nmer - 1; $kik >= 0; $kik--) {
            $leng = length($mersort[$kik]);
            $tag  = (substr($mersort[$kik], 0, $leng - 7)) * 1;
            $fnam = (substr($mersort[$kik], $leng - 7, 6)) * 1;
            $ocmark = (substr($mersort[$kik], $leng - 1)) * 1;
            ##if ($i == 91)  {            ############################################################################  ##$$##
                ##print ERR "Reversed mersort  kik = $kik    mersort[$kik] = $mersort[$kik]   tag = $tag       fnam = $fnam      ocmark = $ocmark \n";
            ##}                           #############################################################################  ##$$##
######################################before last##        print ERR "$mersort[$kik]   tag = $tag       fnam = $fnam      ocmark = $ocmark \n";
            $elone = substr($modline, 0, $tag);
            if ($ocmark == 0)  {                    ##  Opening tag
                $opdiv = $fonts[$f];
                $lendiv = length($opdiv);
##before last##            print ERR "lendiv for opening = $lendiv  vs   $opdiv\n";
                $eltwo = substr($modline, $tag + $fnlen[$fnam]);  ##$lendiv);
                $modline = $elone.$fnopen[$fnam].$eltwo;
            }  elsif ($ocmark == 1)  {                    ##  Closing tag
                $lendiv = 1;
                $eltwo = substr($modline, $tag + $lendiv);
                $modline = $elone.$fnclose[$fnam].$eltwo;
            }  else  {
                print ERR "Something wrong occurred while entering font tags\n";
                $errcount += 1;
            }
            ##if ($i == 91)  {            ############################################################################  ##$$##
                                #########################print ERR "MODIFIED  STRING\n";
                                #########################print ERR "   Modified String---  $modline\n";
            ##}                           #############################################################################  ##$$##
        }

        $_ = $modline;
        $SaveCleanPar[$i][4] = $modline;
#########################################################print TMP "====$_\n";
        &BlockedFrags($_);        
###########################print ERR "Before PASS 4a    ===  $_\n";

###############################################################################
##        PASS 4a:  Replacing diacritical symbols with UTF-8 codes           ##
###############################################################################

##  At this step all diacritical in-text symbols are replaced with UTF-8 symbols
##  While scanning string all inline math fragments are skipped to save them unchanged
##  before being processed with TtM or MathJax
##  Here we have to add sibstitutions for diacritical symbols !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
##print ERR "Numblank-1 = $numblank ====================================================\n";
##  Substitution for some diacritical and special characters

######################################print ERR "Inside 4a diacrit1===  $_\n\n";   
        if (/\\\'/ || /\\\`/ || /\\\"/ || /\\\~/ || /\\\^/ || /\\\=/ || /\\\./ || /\\u/ || /\\H/ || /\\d/ || /\\b/ || /\\r/ || /\\c/ || /\\t/ || /\\v/)  {
            &DiacrChar($_);
        }
##############################print ERR "Inside 4a diacrit2===  $_\n\n";        
        
##print ERR "Numblank-2 = $numblank ====================================================\n";
        #================================================##print ERR "\n$_\nProcessed string is above ==========================================================\n\n";
##      Replacing \verb with <tt>...</tt>  tags
        if (/\\verb/)  {
###print ERR "\n$_\n";
            $spoint = 0;
            while (/\\verb/)  {
                $curf = index($_, "\\verb", $spoint);       ##  Start point for the current \verb tag
                $fiel = substr($_, 0, $curf);               ##  First element
                $closer = substr($_, $curf+5, 1);           ##  Closing tag value
                $curs = index($_, $closer, $curf+6);        ##  Position of closing tag
                $lenmid = $curs - $curf - 6;                ##  Length of middle element
                $midel = substr($_, $curf+6, $lenmid);      ##  Middle element
                $tail = substr($_, $curs+1);                ##  Tail element
                $modiflin = $fiel."<span class=\"verb\">".$midel."<\/span>".$tail;
##\/\/  print ERR "curf = $curf ||  fiel = $fiel  ||  closer = $closer  ||  curs = $curs    ||  lenmid = $lenmid  ||  midel = $midel   ||   tail = $tail \n";
##\/\/  print ERR "$modiflin\n";
###print ERR "$modiflin\n";
                $_ = $modiflin;
            }
            $spoint = $curs + 1;
            ###print ERR "$_\n";
        }
        $SaveCleanPar[$i][4] = $_;
#####    print TMP "()()()()$SaveCleanPar[$i][0]   [$SaveCleanPar[$i][1] --  $SaveCleanPar[$i][2]]   $SaveCleanPar[$i][3]     $SaveCleanPar[$i][4]\n";
#####    print TMP "()()()()$SaveCleanPar[$i][4]\n";
########################################print ERR "Before BlockedFrag===  $_\n\n";
        &BlockedFrags($_);        

############################print ERR "Before PASS 4b    ===  $_\n";

###############################################################################
##        PASS 4b:  Substitution in-text symbols                             ##
###############################################################################
    
##    Here we unblock in-text control symbols, namely  [dollar], [degree], [percent], and [permil]  
##    The substitution is different for text and math mode
##    It is assumed that this list will be expanded in the next version
      $comsymb[0][0] = "\[dollar\]";
      $comsymb[0][1] = 8;
      $comsymb[0][2] = "\&\#x24\;";            ## Text mode substitution
      $comsymb[0][3] = "\\\$";                 ## Math mode substitution
      $comsymb[1][0] = "\[degree\]";  
      $comsymb[1][1] = 8; 
      $comsymb[1][2] = "\&\#xB0\;";            ## Text mode substitution
      $comsymb[1][3] = "\\mbox\{\&\#xB0\;\}";  ## Math mode substitution
      $comsymb[2][0] = "\[percent\]";  
      $comsymb[2][1] = 9;
      $comsymb[2][2] = "\%";                   ## Text mode substitution
      $comsymb[2][3] = "\\\%";                 ## Math mode substitution
      $comsymb[3][0] = "\[underscore\]";  
      $comsymb[3][1] = 12;
      $comsymb[3][2] = "\_";                   ## Text mode substitution
      $comsymb[3][3] = "\_";                   ## Math mode substitution
      $comsymb[4][0] = "\[permil\]";  
      $comsymb[4][1] = 8;
      $comsymb[4][2] = "\&\#x2030\;";          ## Text mode substitution
      $comsymb[4][3] = "\&\#x2030\;";          ## Math mode substitution   ????????????????????????????????
      $comsnum = 0;
      @comsarr =(); 
##    Scanning
      for ($coms = 0; $coms < @comsymb; $coms++)  {
         if (/$comsymb[$coms][0]/)  {
            $start = 0;
            while (/$comsymb[$coms][0]/)  {
               $sypos = index($_, $comsymb[$coms][0], $start);
               if ($sypos < 0)  {
                  goto SYMB;
               }
###      print ERR "\n$_\n";
###      print ERR "Line $i    comsymb[$coms][0] = $comsymb[$coms][0]  on position $sypos\n";
               $comsarr[$comsnum] = $sypos * 1000 + $coms;
               $comsnum += 1; 
               $start = $sypos + $comsymb[$coms][1];
            }
SYMB:
         }
      }
##             Accumulated and orderred breaks
      @ordcomsarr = sort { $a <=> $b } @comsarr;
      for ($ab = $comsnum-1; $ab >= 0; $ab--)  {
         $accpos = int($ordcomsarr[$ab] / 1000);
         $acctype = $ordcomsarr[$ab] - $accpos * 1000;
         #######print ERR "accpos = $accpos       acctype = $acctype       $comsymb[$acctype][0]      ";
         $substype = 2;       ## 2 - substitution in text mode;   3 - substitution in math mode
##    Checking for text/math substitution
         for ($ji = 0; $ji < $numblank; $ji++)  {        
            if ($range[$ji][0] <= $accpos  &&  $accpos <= $range[$ji][1])  { 
               $substype = 3; 
            }
         }            
         #########print ERR "substype = $comsymb[$acctype][$substype]\n";
         $fracmidlen = 
         $fracone = substr($_, 0, $accpos);
         $fracmid = substr($_, $accpos, $comsymb[$acctype][1]);
         $fracsec = substr($_, $accpos+$comsymb[$acctype][1]);
         
         ##print ERR "$fracone <> $fracmid <> $fracsec\n";
         $modifline = $fracone.$comsymb[$acctype][$substype].$fracsec;
         ##print ERR "++++$modifline\n";         
         $_ = $modifline;
         ##print ERR "$_\n";           
      }
    }  else  {
##        print TMP "Math string  $i\n";
    }
    ###########################################################print TMP "$_\n\n";
    ###########################################################print TMP "$_\n";
    s/<tt>/<span class=\"fontt\">/g;
    s/<\/tt>/<\/span>/g;
    $SaveCleanPar[$i][4] = $_;
}  

###===========================================================================================
####print TMP "\n\nA F T E R       F O N T     S U B S T I T U T I O N \n\n";

for ($iw = 0; $iw <= $no; $iw++)  {
    print INT "$SaveCleanPar[$iw][0] ||| $SaveCleanPar[$iw][1] ||| $SaveCleanPar[$iw][2] ||| $SaveCleanPar[$iw][3] ||| $SaveCleanPar[$iw][4]\n";
    #######print INT "$SaveCleanPar[$iw][4]\n";
}
close (INT);
###===========================================================================================

################################################    print TST "\n\n                 BEFORE   PASS 5           \n\n";

###############################################################################
##        PASS 5:  Extracting contents, metadada, and references             ##
###############################################################################
print "done\nPASS  5: Extracting contents, metadada, and references. . . . . . ";
open (ITEMS, ">items.tmp")  ||  die "Cannot open  items.tmp  file.";

$i5 = 0;                     ##  Counter of cleaned records
@cleaned = ();

$conlin = 0;            ##  Contents line counter
@contents = ();         ##  Contents array
$authnum = 0;           ##  Number of authors
$affinum = 0;           ##  Number of affiliations
$keysnum = 0;           ##  Number of keywords
$sectnum = 1;           ##  Number of sections
$iref = 0;              ##  Number of references
@refs = ();             ##  Array for accumulating references
@divs = ();             ##  Array for accumulating divs
@fodivs = ();           ##  Array for accumulating footnotes
$reflabel = 0;          ##  References list is closed
$crcl = 0;              ##  CR citation list counter
$htmref = 0;            ##  HTML citation list counter
$nebref = 0;            ##  NEB citation list counter 

$citblocklab = 0;       ##  0 -> closed;  1 -> opened
        $authlinedir = "";
        $authlinerev = "";
        $affilline = "";

########print TMP "\n\n===========================////===============================\n\n";

open (INT, "<interim.tmp")  || die "Cannot open TEMP.TEX file.";
while (<INT>)  {
########print TMP "$_";
    chop();
    @SaveCur = split(/ \|\|\| /, $_);
    $_ = $SaveCur[4];
########print TMP "$_\n";
    if  ($SaveCur[3] =~ /type=\"title\"/)  {         ##  Extracting article title
        $articletitle = $SaveCur[4];
        $articletitle =~ s/\\title\{//;
        $articletitle =~ s/\}$//;
#####print ERR "\n\ntitle = $articletitle\n\n";
        $artitcr = $articletitle;
        $artitcr =~ s/<it>//g;
        $artitcr =~ s/<\/it>//g;
        $artitcr =~ s/``/"/g;
        $artitcr =~ s/''/"/g;       ##    $artitcr  - title for -cr.xml and for meta tags
        $artitht = $articletitle;
        $artitht =~ s/<it>/<i>/g;  
        $artitht =~ s/<\/it>/<\/i>/g; 
        $artitht =~ s/``/"/g;
        $artitht =~ s/''/"/g;       ##    $artitht  - title for titles in html texts     
        if (length($articletitle) > 0)  {
            $contents[0][$conlin] = "title";
            $contents[1][$conlin] = $artitht;
            $contents[2][$conlin] = "titlink";
            $contents[3][$conlin] = 1;          ##       Level of content item, will be used while composing TOC  and MAP
            $conlin += 1;
        }
        $_ = "<h1><a accesskey=\"titlink\" id=\"titlink\">  <\/a>".$artitht."<\/h1>";                 ##  Sending title to HTML
        
        $SaveCur[4] = $_;
        for ($kk = 0; $kk <  @SaveCur; $kk++)  {
            $SaveInterim[$i5][$kk] = $SaveCur[$kk];
        }        
        $SaveInterim[$i5][3] = "<p id=\"none\" type=\"title\">";        
        $i5 += 1;        

    }  elsif ($SaveCur[3] =~ /type=\"author\"/)  {    ##  Extracting author name
        $authorname = $SaveCur[4];
        $authorname =~ s/\\author\{//;
        $authorname =~ s/\}$//;
        ############################print ERR "author = $authorname\n";
        if (length($authorname) > 0)  {
            $authors[$authnum] = $authorname;
            $authnum += 1;
        }
        $_ = "removed";
    }  elsif ($SaveCur[3] =~ /type=\"affil\"/)  {    ##  Extracting affiliation name
        $affilname = $SaveCur[4];
        $affilname =~ s/\\affil\{//;
        $affilname =~ s/\}$//;
#####   print ERR "\naffil = $affilname\n";
        if (length($affilname) > 0)  {
            @elaff = split(/\}\{/, $affilname);
            
#####            print ERR "ELAFF = $elaff[0] || $elaff[1] || $elaff[2] || $elaff[3] || $elaff[4]  \n";
            
            $neborgname = $elaff[1];
            
#####            print ERR "\n++++neborgname = $neborgname\n";
            
            $nebadrname = $elaff[2];
            if ($elaff[3] ne "")  {
                $nebadrname .= ", ".$elaff[3].", ".$elaff[4];
            }  else  {
                $nebadrname .= ", ".$elaff[4];
            }
            ####$affinum += 1;
            
#####            print ERR "\n++++nebadrname = $nebadrname\n";            
           
            $affilhtm = $elaff[1].", ".$elaff[2];
                if ($elaff[3] ne "")  {
                    $affilhtm .= ", ".$elaff[3].", ".$elaff[4];
                }  else  {
                    $affilhtm .= ", ".$elaff[4];
                }
            $affils[$affinum] = $affilhtm;      ##  Merged address for HTML file
            $neborg[$affinum] = $neborgname;    ##  Organisation for NEB
            $nebadr[$affinum] = $nebadrname;    ##  Address for NEB        
            $affinum += 1;            
        }
        $_ = "removed";
        ##$SaveCleanPar[$i][3] = "";
        ##$SaveCleanPar[$i][4] = $_;  
        ##$cleaned[i5] = $i;
        ##$i5 += 1;
    }  elsif (/\\keywd\{/)  {
##      Extracting keywords.  It is possible that an array of keywords may contain blank strings.
##      That is why we use the 'while' operator
        while(/\\keywd\{/)  {
            $kwpos = index($_,"\\keywd\{", 0) + 6;       
            &FindMatchBracket($_, $kwpos, 1);
            $lenkey = $nepar - $kwpos - 1;
            $kwval = substr($_, $kwpos+1, $lenkey);
            $keywordval[$keysnum] = $kwval;
            $keysnum += 1;
            s/keywd/dwyek/;
        }
                   
    }  elsif ($SaveCur[3] =~ /type=\"abstr\"/)  {   ##  Extracting abstract
        $abstract = $SaveCur[4];
        if ($abstract =~ /\\abstract/)  {
            $abstract =~ s/\\abstract\{//;
        }
        $abstract =~ s/\}$//;
        ###############   print TST "abstract = $abstract\n";
        if (length($abstract) > 0)  {
            $contents[0][$conlin] = "abstr";
            $contents[1][$conlin] = $absname;
            $contents[2][$conlin] = "abslink";
            $contents[3][$conlin] = 3;          ##       Level of content item, will be used while composing TOC and MAP                        
            $conlin += 1;
        }
##  Composing author(s) and affiliation(s) strings
        for ($ad = 0; $ad < $authnum; $ad++)  {
            #################################################print ERR "$authors[$ad]\n";
            @elaut = split(/\}\{/, $authors[$ad]);
            if ($ad == 0)  {
                $authlinedir .= $elaut[2]." ".$elaut[1];
                $authlinerev .= $elaut[1]." ".$elaut[2];
                $fauthlinedir = $authlinedir;
                $fauthlinerev = $authlinerev;
                if ($elaut[3] ne "")  {
                    $authlinedir .= ", ".$elaut[3];
                    $authlinerev .= ", ".$elaut[3];
                }
                if ($affinum > 1)  {
                    $authlinedir .= "<sup>".$elaut[4]."<\/sup>";
                    $authlinerev .= "<sup>".$elaut[4]."<\/sup>";
                    if ($elaut[5] ne "")  {
                        $authlinedir .= "<sup>\,".$elaut[5]."<\/sup>";
                        $authlinerev .= "<sup>\,".$elaut[5]."<\/sup>";
                    }
                }
            }  else  {
                $authlinedir .= ", ".$elaut[2]." ".$elaut[1];
                $authlinerev .= ", ".$elaut[2]." ".$elaut[1];
                if ($elaut[3] ne "")  {
                    $authlinedir .= ", ".$elaut[3];
                    $authlinerev .= ", ".$elaut[3];
                }
                if ($affinum > 1)  {
                    $authlinedir .= "<sup>".$elaut[4]."<\/sup>";
                    $authlinerev .= "<sup>".$elaut[4]."<\/sup>";
                    if ($elaut[5] ne "")  {
                        $authlinedir .= "<sup>\,".$elaut[5]."<\/sup>";
                        $authlinerev .= "<sup>\,".$elaut[5]."<\/sup>";
                    }
                }
            }
        }
##      Removing superscripts from author lines
        $authcitdir = $authlinedir;
        $authcitrev = $authlinerev;
        $authcitdir =~ s/<sup>\d+<\/sup>//g;
        $authcitrev =~ s/<sup>\d+<\/sup>//g;
        $authcitdir =~ s/<sup>,\d<\/sup>//g;
        $authcitrev =~ s/<sup>,\d<\/sup>//g;
        $authcitdir =~ s/ +/ /g;
        $authcitrev =~ s/ +/ /g;
        
###        print "\n\ndir = $authcitdir\nrev = $authcitrev\n\n";
        
##      Removing superscripts from first author line
        $fauthcitdir = $fauthlinedir;
        $fauthcitrev = $fauthlinerev;
        $fauthcitdir =~ s/<sup>\d<\/sup>//g;
        $fauthcitrev =~ s/<sup>\d<\/sup>//g;
        $fauthcitdir =~ s/<sup>,\d<\/sup>//g;
        $fauthcitrev =~ s/<sup>,\d<\/sup>//g;
        $fauthcitdir =~ s/ +/ /g;
        $fauthcitrev =~ s/ +/ /g;

##  The next cleaned authors' line (\$authcitdir) will be used to convert back UTF-8 to TeX notation
##  and then will be used for composing EBPPK  title page        
##  print  "\n\ndir = $authcitdir\n\n";

        if ($affinum == 1)  {
            $affilline = "<p class=\"aff\">".$affils[0]."<\/p>";
        }  elsif ($affinum > 1)  {
            for ($adf = 1; $adf <= $affinum; $adf++)  {
                if ($adf == 1)  {
                    $affilline = "<p class=\"aff\"><sup>".$adf."<\/sup>".$affils[$adf - 1]."<\/p>";
                }  else  {
                    $affilline .= "<p class=\"aff\"><sup>".$adf."<\/sup>".$affils[$adf - 1]."<\/p>";
                }
            }
        }  else  {
            print ERR "There is no affiliations in this article\n";
            $errcount += 1;
        }
        ####print TST "$authlinedir\n$authlinerev\n";
        for ($af = 0; $af < $affinum; $af++)  {
            ####print TST "$affils[$af]\n";
            @elaff = split(/\}\{/, $affils[$af]);
        }

#####=============================##########=============================#####        print ERR "<p><b><i>$authlinedir<\/i><\/b><\/p>\n";

        $SaveInterim[$i5][3] = "<p id=\"none\" type=\"author\">";
        $SaveInterim[$i5][4] = "<p class=\"auth\"><b><i>".$authlinedir."<\/i><\/b><\/p>";
            ###print TMP  "$SaveInterim[$i5][4]\n";
        $i5 += 1;
        $SaveInterim[$i5][3] = "<p id=\"none\" type=\"affil\">";
        $SaveInterim[$i5][4] = "$affilline\n\n";
            ###print TMP  "++++++++++++++++++++++++==================$SaveInterim[$i5][4]\n";
        $i5 += 1;
        $SaveInterim[$i5][3] = "<p id=\"none\" type=\"abstr\">";
        $SaveInterim[$i5][4] = "<a accesskey=\"abslink\" id=\"abslink\">  <\/a><h3>".$absname."<\/h3>"; 
            ###print TMP  "$SaveInterim[$i5][4]\n";
        $i5 += 1;
        $SaveInterim[$i5][3] = "<p id=\"none\" type=\"abstr\">";
        $SaveInterim[$i5][4] = "<p class=\"abs\">".$abstract." <\/p>";
            ###print TMP  "$SaveInterim[$i5][4]\n";
        $i5 += 1;

####//////////////////////////////////////////////////////////////////////////////////////////////////////////print ERR "====$_\n";

    }  elsif ($SaveCur[3] =~ /type=\"sect\"/)  {    ##  Extracting section title
        $secttitle = $SaveCur[4];
        $secttitle =~ s/\\section\{//;
        $secttitle =~ s/\}$//;
        ###############################print ERR "sect = $secttitle\n";
        if (length($secttitle) > 0)  {
            $contents[0][$conlin] = "sect";
            $contents[1][$conlin] = $secttitle;
            $contents[2][$conlin] = "sect".$sectnum;
            $contents[3][$conlin] = 3;          ##       Level of content item, will be used while composing TOC and MAP      
            $_ = "<h3><a accesskey=\"".$contents[2][$conlin]."\" id=\"".$contents[2][$conlin]."\">  <\/a>".$secttitle."<\/h3>";                 ##  Sending section title to HTML

            $SaveCur[4] = $_;
            for ($kk = 0; $kk <  @SaveCur; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;                    

###print ERR "$_\n";
            $sectnum += 1;
            $conlin += 1;
        }
    }  elsif ($SaveCur[3] =~ /type=\"ssect\"/)  {   ##  Extracting subsection title
        $ssecttitle = $SaveCur[4];
        $ssecttitle =~ s/\\subsection\{//;
        $ssecttitle =~ s/\}$//;
        ##############################print ERR "ssect = $ssecttitle\n";
        if (length($ssecttitle) > 0)  {
            $contents[0][$conlin] = "ssect";
            $contents[1][$conlin] = $ssecttitle;
            $contents[2][$conlin] = "sect".$sectnum;
            $contents[3][$conlin] = 4;          ##       Level of content item, will be used while composing TOC and MAP      
            $_ = "<h4><a accesskey=\"".$contents[2][$conlin]."\" id=\"".$contents[2][$conlin]."\">  <\/a>".$ssecttitle."<\/h4>";                 ##  Sending subsection title to HTML

            $SaveCur[4] = $_;
            for ($kk = 0; $kk <  @SaveCur; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;                       

###print ERR "$_\n";
            $sectnum += 1;
            $conlin += 1;
        }
    }  elsif ($SaveCur[3] =~ /type=\"sssect\"/)  {   ##  Extracting subsubsection title
        $sssecttitle = $SaveCur[4];
        $sssecttitle =~ s/\\subsubsection\{//;
        $sssecttitle =~ s/\}$//;        
        ##########################print ERR "sssect = $sssecttitle\n";
        if (length($sssecttitle) > 0)  {
            $contents[0][$conlin] = "sssect";
            $contents[1][$conlin] = $sssecttitle;
            $contents[2][$conlin] = "sect".$sectnum;
            $contents[3][$conlin] = 5;          ##       Level of content item, will be used while composing TOC and MAP      
            $_ = "<h5><a accesskey=\"".$contents[2][$conlin]."\" id=\"".$contents[2][$conlin]."\">  <\/a>".$sssecttitle."<\/h5>";                 ##  Sending subsubsection title to HTML
            $SaveCur[4] = $_;
            for ($kk = 0; $kk <  @SaveCur; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;                        
            $sectnum += 1;
            $conlin += 1;
        }
    }  elsif ($SaveCur[3] =~ /type=\"flsect\"/)  {   ##  Extracting float section title
        $flsecttitle = $SaveCur[4];
        $flsecttitle =~ s/\\floatsection\{//;
        $flsecttitle =~ s/\}$//;
        #################print ERR "flsect = $flsecttitle\n";
        if (length($flsecttitle) > 0)  {
            $contents[0][$conlin] = "flsect";
            $contents[1][$conlin] = $flsecttitle;
            $contents[2][$conlin] = "flsection";
            $contents[3][$conlin] = 3;          ##       Level of content item, will be used while composing TOC and MAP      
            $_ = "<h3><a accesskey=\"".$contents[2][$conlin]."\" id=\"".$contents[2][$conlin]."\">  <\/a>".$flsecttitle."<\/h3>";                 ##  Sending subsection title to HTML
            $SaveCur[4] = $_;
            for ($kk = 0; $kk <  @SaveCur; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;                        

###print ERR "$_\n";
            $conlin += 1;
        }
    }  elsif ($SaveCur[3] =~ /type=\"acknow\"/)  {   ##  Extracting acknowledgment(s) title
        $acknowledge = $SaveCur[4];
        if ($acknowledge =~ /\\acknowledgments/)  {
            $acknowledge =~ s/\\acknowledgments\{//;
            $acknowhead = $acknownames;   ###  "Acknowledgments";
        } elsif  ($acknowledge =~ /\\acknowledgment/)  {
            $acknowledge =~ s/\\acknowledgment\{//;
            $acknowhead = $acknowname;    ###  "Acknowledgment";
        }
        $acknowledge =~ s/\}$//;
        ########################print ERR "acknow = $acknowledge\n";
        if (length($acknowledge) > 0)  {
            $contents[0][$conlin] = "acknow";
            $contents[1][$conlin] = $acknowhead;
            $contents[2][$conlin] = "acknow";
            $contents[3][$conlin] = 3;          ##       Level of content item, will be used while composing TOC and MAP      
            $_ = "<h4><a accesskey=\"acknow\" id=\"acknow\">  <\/a>".$acknowhead."<\/h4>  ".$acknowledge;

            $SaveCur[4] = $_;
            for ($kk = 0; $kk <  @SaveCur; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;                    

###print ERR "$_\n";
            $conlin += 1;
        }        
    }  elsif ($SaveCur[3] =~ /type=\"append\"/)  {   ##  Extracting appendix title
        $appendix = $SaveCur[4];
        $appendix =~ s/\\appendix\{//;
        $appendix =~ s/\}$//;
        ###############################print ERR "append = $appendix\n";
        if (length($appendix) > 0)  {
            $contents[0][$conlin] = "append";
            $contents[1][$conlin] = "";  ###"<\!-- Start of appendicies -->";
            $contents[2][$conlin] = "append";
            $contents[3][$conlin] = 3;          ##       Level of content item, will be used while composing TOC and MAP      
            $_ = "<h3><a accesskey=\"append\" id=\"append\">  <\/a> Appendix<\/h3>";

            $SaveCur[4] = $_;
            for ($kk = 0; $kk <  @SaveCur; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;                    
            
###print ERR "$_\n";
            $conlin += 1;
        }
    }  elsif ($SaveCur[3] =~ /type=\"refer\"/)  {   ##  Extracting references list
        ######################print ERR "refer = References   reflabel = $reflabel\n";
        if ($reflabel == 0)  {
            $contents[0][$conlin] = "refer";
            $contents[1][$conlin] = $refername;       ### "References";
            $contents[2][$conlin] = "openref";
            $contents[3][$conlin] = 3;          ##       Level of content item, will be used while composing TOC and MAP      
            $_ = "<h3><a accesskey=\"openref\" id=\"openref\">  <\/a>$refername<\/h3>";

            $SaveCur[4] = $_;
            for ($kk = 0; $kk <  @SaveCur; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;                    

###print ERR "$_\n";
            $conlin += 1;
            $reflabel = 1;       ##          References list is open
        }  elsif  ($reflabel == 1)  {
            $contents[0][$conlin] = "refer";
            $contents[1][$conlin] = " ";   ###<!-- End of References-->";
            $conlin += 1;
            $reflabel = 0;       ##          References list is closed
            $_ = "";
        }
    }  else  {

#####################  R E F E R E N C E S  #################################
#################   Processing Reference List   #############################

        if ($reflabel == 1)  {
            s/--/\&\#x2013\;/g;
            if ($citblocklab == 0)  {
                $citlist[$crcl] = "<citation_list>";
                $crcl += 1;
                $citblocklab = 1;
            }
           
#####################################################           print ERR "\n=============================================\n$_\n";
           
            if (/\\reference/)  {
                $inreftype = "";
                $inrefmerged = "";              ##  Unstructured citation
                @inrefauthneb = ();             ##  Author array in reference for NEB
                @inrefauthhtml = ();            ##  Author array in reference for HTML
                $numofauth = 0;                 ##  Number of authors
                $inrefgroup = "";
                $inrefyear = "";
                $inreftitle = "";
                $inrefbook = "";
                $inrefedit = "";
                $inrefjour = "";
                $inrefthesis = "";
                $inrefvol = "";
                $inrefnumb = "";
                $inrefpages = "";
                $inrefpubl = "";
                $inreflocat = "";
                $inrefaccess = "";
                $inrefdate = "";
                $inrefdoi = "";
                $jourbook = "";
                $doireplacement = "";
                s/\\reference +\{/\\reference\{/g;
                $compos = index($_, "\\reference\{", 0);
                $stser = $compos + 10;
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $reftar = substr($_, $stser + 1, $lref);
                $refs[$iref][0] = $reftar;                ##    Adding target element to references array
            ########################################################################################################################$iref += 1;
                s/\\reference\{/<a accesskey=\"/;
                s/\}/\" id=\"$reftar\">  <\/a>/;
                $citlist[$crcl] = "   <citation key=\"".$regtitle[$journumb][5]."\/".$paperid."-".$reftar."\">";
                ####print ERR "$citlist[$crcl]\n";
                $crcl += 1;
            }

            if (/\\reftype/)  {                             ##      REFTYPE
                s/\\reftype +\{/\\reftype\{/g;
                $compos = index($_, "\\reftype\{", 0);
                $stser = $compos + 8;
                $strtypepos = $stser + 1;
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $inreftype = substr($_, $stser+1, $lref);                
                $inreftype *= 1; 
####            print ERR "inreftype = $inreftype\n";
                if ($inreftype >= 1 && $inreftype <= 7)  {          ##   <= 6)
                }  else  {
                    print ERR "\\reftype is out of range in the reference \n$_ + $reftar\n";
                    $errcount += 1;
                }
            }

            if (/\\refmerged/)  {                             ##   REFMERGED
                s/\\refmerged +\{/\\refmerged\{/g;
                $compos = index($_, "\\refmerged\{", 0);
                $stser = $compos + 10;
                $endmergedpos = $compos - 1;
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $inrefmerged = substr($_, $stser + 1, $lref);
###        print "\ninrefmerged = $inrefmerged\n";
            }

            if (/\\refdoi/)  {                                ##      REFDOI
                s/\\refdoi +\{/\\refdoi\{/g;
                $compos = index($_, "\\refdoi\{", 0);
                $stser = $compos + 7;
                $endnbdoipos = $compos - 1;
#rem#                print ERR "\nNBDOI:   $_\ncompos = $compos\nendnbdoipos = $endnbdoipos\n";     #########
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $inrefdoi = substr($_, $stser + 1, $lref);
#rem#          print "\ninrefdoi = $inrefdoi\n";     ################################
            }
            if ($inreftype == 2 && $inrefdoi eq "")  {        
                print ERR "There is no DOI number for \\reftype = 2\n$_\n";
                $errcount += 1;
            }

            if (/\\refauthf/)  {                            ##      FIRST AUTHOR
                s/\\refauthf +\{/\\refauthf\{/g;
                s/\\refauth +\{/\\refauth\{/g;
                $compos = index($_, "\\refauthf\{", 0);
                $stser = $compos + 9;
                $strauthfpos = $stser + 1;
                ###$nebrefline = "";
                ###$htmlrefline = "";
            ####print ERR "\nstser = $stser       strauthfpos = $strauthfpos\n";
                &FindMatchBracket($_, $stser, 3);
                $lref = $nepar - $stser - 1;
                $crauthf = substr($_, $stser+1, $lref);
                @elauthf = split(/\}\{/, $crauthf);
            ####print ERR "elauthf = $elauthf[0]  ||  $elauthf[1]  ||  $elauthf[2]\n";
                s/\\refauthf\{/<span class="ref">/;
                s/\}//;
                if ($elauthf[2] eq "")  {
                    $inrefauthneb[$numofauth] = $elauthf[0]."\, ".$elauthf[1];
                    $inrefauthhtml[$numofauth] = $inrefauthneb[$numofauth];
                } else { 
                    $inrefauthneb[$numofauth] = $elauthf[0]."\, ".$elauthf[1]." ".$elauthf[2];
                    $inrefauthhtml[$numofauth] = $inrefauthneb[$numofauth];
                }                
                $numofauth += 1;           
            }

            if (/\\refauth/)  {                             ##      MORE AUTHORS
                while(/\\refauth/)  {       
                    $compos = index($_, "\\refauth\{", 0);
                    $stser = $compos + 8;
                    $strauthpos = $stser + 1;
                    ###$nebrefline = "";
                    ###$htmlrefline = "";
                ####print ERR "\nstser = $stser       strauthpos = $strauthpos\n";
                    &FindMatchBracket($_, $stser, 3);
                    $lref = $nepar - $stser - 1;
                    $crauth = substr($_, $stser+1, $lref);
                    @elauth = split(/\}\{/, $crauth);
                ####print ERR "elauth = $elauth[0]  ||  $elauth[1]  ||  $elauth[2]\n";
                    s/\\refauth\{/\\htuafer\{/;
#######                    s/\}//;
                    if ($elauth[2] eq "")  {
                        $inrefauthneb[$numofauth] = $elauth[0]."\, ".$elauth[1];
                        $inrefauthhtml[$numofauth] = $elauth[1]." ".$elauth[0];
                    } else { 
                        $inrefauthneb[$numofauth] = $elauth[0]."\. ".$elauth[1]." ".$elauth[2];
                        $inrefauthhtml[$numofauth] = $elauth[1]." ".$elauth[0]." ".$elauth[2];
                    }                
                    $numofauth += 1;  
                } 
            }
##      Merging authors for NEB and HTML
            $auneb = "";
            $auhtml = "";
########            print ERR "\nAuthors = $numofauth\n";
            for ($aa = 0; $aa < $numofauth; $aa++)  {
                if ($aa == 0)  {
                    $auneb = $inrefauthneb[$aa]; 
                    $auhtml = $inrefauthhtml[$aa];
                }  else  {
                    $auneb = $auneb."\, ".$inrefauthneb[$aa]; 
                    $auhtml = $auhtml."\, ".$inrefauthhtml[$aa];   
                }
            }                

            if (/\\refgroup/)  {                                ##      REFGROUP
                s/\\refgroup +\{/\\refgroup\{/g;
                $compos = index($_, "\\refgroup\{", 0);
                $stser = $compos + 9;
                $strgroupos = $stser + 1;
                ###$nebrefline = "";
                ###$htmlrefline = "";
            ####print ERR "\nstser = $stser       strgroupos = $strgroupos\n";
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $crgroup = substr($_, $stser+1, $lref);

########                print ERR "crgroup = $crgroup\n";
                if ($crgroup eq "")  {
                    $crgroup = "et al.";
                }
                $auneb = $auneb."\, ".$crgroup; 
                $auhtml = $auhtml."\, ".$crgroup; 
            } 

            if (/\\refyear/)  {                                     ##      REFYEAR
                s/\\refyear +\{/\\refyear\{/g;
                $compos = index($_, "\\refyear\{", 0);
                $stser = $compos + 8;
                $endyearpos = $compos - 1;
#####################            print ERR "$_\ncompos = $compos\nendyearpos = $endyearpos\n";
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $cryear = substr($_, $stser + 1, $lref);
######                print ERR "cryear = $cryear\n"; 
                
                $auneb = $auneb." (".$cryear.")\,"; 
                $auhtml = $auhtml." (".$cryear.")"; 
            }

            if ($inreftype != 3)  {                                 ##      REFTITLE
                if (/\\reftitle/)  {
                    s/\\reftitle +\{/\\reftitle\{/g;
                    $compos = index($_, "\\reftitle\{", 0);
                    $stser = $compos + 9;
                    $endtitlepos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendtitlepos = $endtitlepos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inreftitle = substr($_, $stser + 1, $lref);
########                    print ERR "inreftitle = $inreftitle\n"; 
                    if ($inreftitle eq "")  {
                        ##print ERR "\\reftitle is empty in the current reference\n$_ + $reftar\n";
                        ##$errcount += 1; 
                    }                        
                }  else  {
                    ##print ERR "There is no \\reftitle in the current reference\n$_ + $reftar\n";
                    ##$errcount += 1;
                }
            }

            if ($inreftype == 3 || $inreftype == 4)  {                ##      REFBOOK
                if (/\\refbook/)  {
                    s/\\refbook +\{/\\refbook\{/g;
                    $compos = index($_, "\\refbook\{", 0);
                    $stser = $compos + 8;
                    $endbookpos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendbookpos = $endbookpos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefbook = substr($_, $stser + 1, $lref);
########                    print ERR "inrefbook = $inrefbook\n"; 
                    if ($inrefbook eq "")  {
                        print ERR "\\refbook is empty in the current reference\n$_ + $reftar\n";
                        $errcount += 1; 
                    }                        
                }  else  {
                    print ERR "There is no \\refbook in the current reference\n$_ + $reftar\n";
                    $errcount += 1;
                }
            }

            if (/\\refedit/)  {                                       ##      REFEDIT
                s/\\refedit +\{/\\refedit\{/g;
                $compos = index($_, "\\refedit\{", 0);
                $stser = $compos + 8;
                $endeditpos = $compos - 1;
    ##############            print ERR "$_\ncompos = $compos\nendeditpos = $endeditpos\n";
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $inrefedit = substr($_, $stser + 1, $lref);
########                print ERR "inrefedit = $inrefedit\n"; 
            }  

            if ($inreftype == 1 || $inreftype == 2)  {                ##      REFJOUR
                if (/\\refjour/)  {
                    s/\\refjour +\{/\\refjour\{/g;
                    $compos = index($_, "\\refjour\{", 0);
                    $stser = $compos + 8;
                    $endjourpos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendjourpos = $endjourpos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefjour = substr($_, $stser + 1, $lref);
########                    print ERR "inrefjour = $inrefjour\n"; 
                    if ($inrefjour eq "")  {
                        print ERR "\\refjour is empty in the current reference\n$_ + $reftar\n";
                        $errcount += 1; 
                    }                        
                }  else  {
                    print ERR "There is no \\refjour in the current reference\n$_ + $reftar\n";
                    $errcount += 1;
                }
            }

            if ($inreftype == 5)  {                                   ##      REFTHESIS
                if (/\\refthesis/)  {
                    s/\\refthesis +\{/\\refthesis\{/g;
                    $compos = index($_, "\\refthesis\{", 0);
                    $stser = $compos + 10;
                    $endthesispos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendthesispos = $endthesispos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefthesis = substr($_, $stser + 1, $lref);
########                    print ERR "inrefthesis = $inrefthesis\n"; 
                    if ($inrefthesis eq "")  {
                        print ERR "\\refthesis is empty in the current reference\n$_ + $reftar\n";
                        $errcount += 1; 
                    }                        
                }  else  {
                    print ERR "There is no \\refthesis in the current reference\n$_ + $reftar\n";
                    $errcount += 1;
                }
            }

            if ($inreftype == 1 || $inreftype == 2)  {                ##      REFVOL
                if (/\\refvol/)  {
                    s/\\refvol +\{/\\refvol\{/g;
                    $compos = index($_, "\\refvol\{", 0);
                    $stser = $compos + 7;
                    $endvolpos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendvolpos = $endvolpos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefvol = substr($_, $stser + 1, $lref);
########                    print ERR "inrefvol = $inrefvol\n"; 
                }
                if (/\\refnumb/)  {                                  ##      REFNUMB
                    s/\\refnumb +\{/\\refnumb\{/g;
                    $inrefnumb = "";
                    $compos = index($_, "\\refnumb\{", 0);
                    $stser = $compos + 8;
                    $endnumbpos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendnumbpos = $endnumbpos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefnumb = substr($_, $stser + 1, $lref);
########                    print ERR "inrefnumb = $inrefnumb\n"; 
                }
            }            

            if ($inreftype <= 4)  {                                  ##      REFPAGES
                if (/\\refpages/)  {
                    s/\\refpages +\{/\\refpages\{/g;
                    $compos = index($_, "\\refpages\{", 0);
                    $stser = $compos + 9;
                    $endpagespos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendpagespos = $endpagespos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefpages = substr($_, $stser + 1, $lref);
########                    print ERR "inrefpages = $inrefpages\n"; 
                }
            }            

            if ($inreftype >= 3)  {                                   ##      REFPUBL
                if (/\\refpubl/)  {
                    s/\\refpubl +\{/\\refpubl\{/g;
                    $compos = index($_, "\\refpubl\{", 0);
                    $stser = $compos + 8;
                    $endpublpos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendpublpos = $endpublpos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefpubl = substr($_, $stser + 1, $lref);
########                    print ERR "inrefpubl = $inrefpubl\n"; 
                    if (($inrefpubl eq "") && ($inrefdoi eq ""))  {
                        print ERR "\\refpubl is empty in the current reference\n$_ + $reftar\n";
                        $errcount += 1; 
                    }                        
                }##  else  {
                 ##   if ($inrefdoi eq "")  {
                 ##       print ERR "There is no \\refpubl in the current reference\n\\refdoi = $inrefdoi\n$_ + $reftar\n";
                 ##       $errcount += 1;
                 ##   }
                ##}

                if (/\\reflocat/)  {                               ##      REFLOCAT
                    s/\\reflocat +\{/\\reflocat\{/g;
                    $compos = index($_, "\\reflocat\{", 0);
                    $stser = $compos + 9;
                    $endlocatpos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nendlocatpos = $endlocatpos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inreflocat = substr($_, $stser + 1, $lref);
########                   print ERR "inreflocat = $inreflocat\n"; 
                    if (($inreflocat eq "") && ($inrefdoi eq ""))  {
                        print ERR "\\reflocat is empty in the current reference\n$_ + $reftar\n";
                        $errcount += 1; 
                    }                        
                }##  else  {
                 ##   if ($inrefdoi eq "")  {
                 ##       print ERR "There is no \\reflocat in the current reference\n\\refdoi = $inrefdoi\n$_ + $reftar\n";
                 ##       $errcount += 1;     
                 ##   }        
                ##}
            }            

            if ($inreftype == 6)  {                                   ##      REFACCESS
                if (/\\refaccess/)  {
                    s/\\refaccess +\{/\\refaccess\{/g;
                    $compos = index($_, "\\refaccess\{", 0);
                    $stser = $compos + 10;
                    $endaccesspos = $compos - 1;
                ######print ERR "ACCESS:  $_\n$_\ncompos = $compos\nendaccesspos = $endaccesspos\n";
                    &FindMatchBracket($_, $stser, 2);
                    $lref = $nepar - $stser - 1;
                    $inrefaccess = substr($_, $stser + 1, $lref);
#########                    print ERR "inrefaccess = $inrefaccess\n"; 
                    if ($inrefaccess eq "")  {
                        print ERR "\\refaccess is empty in the current reference\n$_\n";
                        $errcount += 1; 
                    }                        
                }##  else  {
                 ##   print ERR "There is no \\refaccess in the current reference\n$_\n";
                 ##   $errcount += 1;
                ##}
            }            

            if ($inreftype == 6)  {                                   ##      REFDATE
                if (/\\refdate/)  {
                    s/\\refdate +\{/\\refdate\{/g;
                    $compos = index($_, "\\refdate\{", 0);
                    $stser = $compos + 8;
                    $enddatepos = $compos - 1;
    #####################            print ERR "$_\ncompos = $compos\nenddatepos = $enddatepos\n";
                    &FindMatchBracket($_, $stser, 1);
                    $lref = $nepar - $stser - 1;
                    $inrefdate = substr($_, $stser + 1, $lref);
########                    print ERR "inrefdate = $inrefdate\n"; 
                }
            }            

            if (/\\endreference/)  {                                       ##      ENDREFERENCE
                s/\\endreference +\{/\\endreference\{/g;
                $compos = index($_, "\\endreference\{", 0);
                $stser = $compos + 13;
                $endreferencepos = $compos - 1;
#####################            print ERR "$_\ncompos = $compos\nendreferencepos = $endreferencepos\n";
                &FindMatchBracket($_, $stser, 1);
                $lref = $nepar - $stser - 1;
                $inrefcomment = substr($_, $stser + 1, $lref);
########                print ERR "inrefcomment = $inrefcomment\n"; 

###         Start composing reference lists for XML and References:          
##-----------------------------------------------------------------   XML for CrossRef
                if ($inreftype == 7) {
                    $citlist[$crcl] = "      <unstructured_citation>$inrefmerged<\/unstructured_citation>";
########print "\n    START of accumulating\n $citlist[$crcl]\n";
                    $crcl += 1;
                }  else {
                    $citlist[$crcl] = "      <author>$elauthf[0]<\/author>";
                    $crcl += 1;
                }
                if (($inreftype != 3) && ($inreftype != 7)){
                    $citlist[$crcl] = "      <article_title>$inreftitle<\/article_title>";
                    $crcl += 1;
                }
                if ($inreftype == 3 || $inreftype == 4) {
                    $citlist[$crcl] = "      <volume_title>$inrefbook<\/volume_title>";
                    $crcl += 1;
                }
                if ($inreftype < 3) {
                    $citlist[$crcl] = "      <journal_title>$inrefjour<\/journal_title>";
                    $crcl += 1;
                    if ($inrefvol ne "")  {
                        $citlist[$crcl] = "      <volume>$inrefvol<\/volume>";
                        $crcl += 1;
                    }  
                    if ($inrefnumb ne "")  {
                        $citlist[$crcl] = "      <issue>$inrefnumb<\/issue>";
                        $crcl += 1;
                    }                     
                }
                if ($inreftype <= 4 && $inrefpages ne "")  {
                    if ($inrefpages =~ /\&\#x2013\;/)  {        ##      Remowing &ndash; and remaining string
                        @pafrg = split(/\&\#x2013\;/, $inrefpages);
                        $citlist[$crcl] = "      <first_page>$pafrg[0]<\/first_page>";
                    }  else  {
                        $citlist[$crcl] = "      <first_page>$inrefpages<\/first_page>";
                    }
                    $crcl += 1; 
                }                   
                if ($inreftype ne 7)  {
                    $citlist[$crcl] = "      <cYear>$cryear<\/cYear>";
                    $crcl += 1;
                }                
                if ($inrefdoi ne "")  {
                    $citlist[$crcl] = "      <doi>$inrefdoi</doi>";

#rem#  print "\nCITLIST $citlist[$crcl]\n";

                    $crcl += 1;
                }
                $citlist[$crcl] = "   <\/citation>";
                $crcl += 1;
###==================================================================================
##-----------------------------------------------------------------   HTML References
###==================================================================================
                $accumline = "<a accesskey=\"$reftar\" id=\"$reftar\">  <\/a> <span class=\"ref\">$auhtml <\/span>";  ## ($cryear)"; 
                $accumerge = "<a accesskey=\"$reftar\" id=\"$reftar\">  <\/a> <span class=\"ref\">$auhtml <\/span>";  ## ($cryear)"; 
                
                if ($inreftype == 7)  {
                    $accumerge .= " ".$inrefmerged;
                    if ($inrefdoi ne "")  {
                        $accumerge .= ", https:\/\/doi.org\/<a href=https:\/\/doi.org\/".$inrefdoi." target=\"blank\">".$inrefdoi."<\/a>";
                        $_ = $accumerge;
                    }
                } else {
                
                
                    if ($inreftype != 3)  {
                        $accumline .= ", ".$inreftitle;
                    }
                    if ($inreftype == 3 || $inreftype == 4)  { 
                        $accumline .= ", <i>".$inrefbook."<\/i>";
                    }
                    if ($inrefedit ne "")  {
                        $accumline .= ", edited by ".$inrefedit;
                    }
                    if ($inreftype == 1 || $inreftype == 2)  {
                        $accumline .= ", <i>".$inrefjour."<\/i>";
                    }
                    if ($inreftype == 5)  {
                        $accumline .= ", ".$inrefthesis;
                    }
                    if ($inreftype < 3  &&  $inrefvol ne "")  {
                        $accumline .= ", <i>".$inrefvol."<\/i>";
                    }
                    if ($inreftype < 3  &&  $inrefnumb ne "")  {
                        $accumline .= ", no. ".$inrefnumb;
                    }
                    if ($inreftype < 5  && $inreftype != 3 &&  $inrefpages ne "")  {
                        $accumline .= ", p. ".$inrefpages;
                    }
                    if ($inreftype == 3 &&  $inrefpages ne "")  {
                        $accumline .= ", ".$inrefpages." pp.";
                    }
                    if ($inreftype >= 3 && $inrefpubl ne "")  {
                        $accumline .= ", ".$inrefpubl;
                    }
                    if ($inreftype >= 3 && $inreflocat ne "")  {
                        $accumline .= ", ".$inreflocat;
                    }
                    if ($inreftype == 6 && $inrefaccess ne "")  {
                        $inrefaccess =~ s/ +//g;
                    
##################        print ERR "\ninrefaccess = $inrefaccess\n";
                    
                        @afrags = split(/\}\{/, $inrefaccess);
                        $afrags[0] =~ s/&#x81;/\_/g;
                ##      More substitutions needed
                        $accmod = "<a href=\"".$afrags[0]."\" target=\"blank\">".$afrags[1]."<\/a>";
                    
###        print ERR "inrefaccess = $inrefaccess  \n  accmod = $accmod =  \n";
                    
                        $accumline .= ", ".$accmod;
                    }
                    if ($inreftype == 6 && $inrefdate ne "")  {
                        $accumline .= ", ".$inrefdate;
                    }
                    if ($inrefdoi ne "")  {
                
####        print "\nINREFDOI = $inrefdoi\n\n";
                        if ($inrefdoi =~ /\%3C/  ||  $inrefdoi =~ /\%3E/)  {
                            ###print ERR "\n\nThe following DOI contains  >  or <  symbols\nInitial inrefdoi =  $inrefdoi\n\n";
                            @inrefdoifrags = split(/\%3C/, $inrefdoi);
                            ###print ERR "\n====@inrefdoifrags\n\n";
                            $finrefdoi = join("\%3C", @inrefdoifrags);
                            ###print ERR "finrefdoi = $finrefdoi\n"; 
                            @inrefdoifrags = split(/\%3E/, $finrefdoi);
                            ###print ERR "\n====@inrefdoifrags\n\n";
                            $inrefdoi = join("\%3E", @inrefdoifrags);
###           print ERR "\nModified sinrefdoi = $sinrefdoi\n======================================\n";                     
                        }
                        $doireplacement = "<a href=\"https\:\/\/doi\.org\/".$inrefdoi."\" target=\"blank\">".$inrefdoi."<\/a>";
####  print "\ndoireplacement = $doireplacement\n"; 
                        $accumline .= ",  https\:\/\/doi.org\/".$doireplacement; 
                    }   
                    if ($inrefcomment ne "")  {
                        $accumline .= " \(".$inrefcomment."\)\.";
                    }  else  {
                ##      Checking if last character is the dot
                        $lenaccumline = length($accumline);
                        $lastchar = substr($accumline, $lenaccumline - 1, 1);
                ####    print ERR "\nlenaccumline = $lenaccumline     lastchar = $lastchar \n";
                        if ($lastchar ne "\.")  {
                            $accumline .= "\.";
                        }
                    }
                
                }
                
 ##################################                 print  "\nACCUMLINE = $accumline\n";
                

                if ($inreftype == 7)  {
                    $_ = $accumerge;
                } else {
                    $_ = $accumline;
                }

                  ##Test==## print ITEMS "$_\n";
###=====================================================================================================
##-------------------------------------------------------------------- HTML References for popup windows   
###=====================================================================================================
    ##      Filling in refs array
                $jourbook = "";
   
                if ($inrefjour eq "" && $inrefbook eq "" && $SaveCleanPar[$i][3] eq "indent")  {
                    print ERR "Both journal and book titles are absent!!\n";
                    $errcount += 1;
                }
                if ($inrefjour ne "")  {
                    $jourbook .= "<i>".$inrefjour."<\/i>";
                }
                if ($inrefbook ne "" && $inreftype == 3)  {
                    $inreftitle = $inrefbook;
                }
                if ($inrefbook ne "" && $inreftype == 4)  {
                    $jourbook .= "<i>".$inrefbook."<\/i>";
                }
                if ($inrefvol ne "")  {
                    $jourbook .= ", <i>".$inrefvol."<\/i>";
                }
                if ($inrefnumb ne "")  {
                    $jourbook .= ", ".$inrefnumb;
                }
                if ($inreftype == 3 && $inrefpages ne "")  {
                    $jourbook .= $inrefpages." pp.";
                }
                if ($inreftype != 3 && $inrefpages ne "")  {
                    $jourbook .= " p. ".$inrefpages;
                }
                $refs[$iref][3] = $jourbook;
                $refs[$iref][4] = $doireplacement;
##########################                print ERR "\njourbook = $jourbook\n";
                if ($refs[$iref][0] ne "")  {
                    $curreffile = $reflistdir."/".$refs[$iref][0]."\.html";
                    ###print ERR "\n   curreffile = $curreffile\n\n";
                    open (REF, ">$curreffile")  ||  die "Cannot open  $curreffile  file.";
                    print REF "<body bgcolor=\"\#eeeeee\"><a href=\"javascript\: window.parent.showlayer(\'div$refs[$iref][0]\')\"><img src=\"cross.gif\" style=\"float\:right\; width\:17px\; height\:15px\"   alt=\"Close\" title=\"Close\"  \/><\/a>\n";
                              ########################### <body bgcolor="#eeeeee"><a href="javascript: window.parent.showlayer('divagaf84')">                 <img src="cross.gif" style="float:right; width:17px; height:15px"  alt="Close" title="Close" /> <!-- width="17" height="15"  /--></a>
                    if ($inreftype == 3) { 
                        print REF "<font face=\"Verdana\" size=\"-1\"><b>$inrefbook<\/b>,<br \/>$auhtml  ($cryear),\n";
                    }  else  {
                        print REF "<font face=\"Verdana\" size=\"-1\"><b>$inreftitle<\/b>,<br \/>$auhtml  ($cryear),\n";                
                    }
                    if ($jourbook ne "")  {
                        print REF "<br \/>$jourbook";
                    }
                    if ($doireplacement ne "")  {
                        print REF ", <br \/>$doireplacement.<\/font><\/body>\n";
                    }  else  {
                        print REF "<\/font><\/body>\n";
                    }
                    close (REF);
##       Saving DIV fragments in @divs array
                    $divs[$iref] = "<div id=\"div".$reftar."\" style=\"padding\:0\; position\:absolute\; top\:400px\; left\:145px\; display\:none\; background-color\:\#eeeeee\; opacity\:0.9\;\"><iframe id=\"".$reftar."\" frameborder=\"1\" scrolling=\"yes\" src=\"".$reflistdir."\/".$reftar."\.html\" width=\"450\" height=\"75\"><\/iframe><\/div>";
                }




##---------------------------------------------------------------------    XML for NEB (eLIBRARU.RU)             

               #####@nebreference = ();
               $accumneb = "";
               $nebref = 0; 
               $accumneb = $auneb; 
                ##$accumline = "<a accesskey=\"$reftar\" id=\"$reftar\">  <\/a> <span class=\"ref\">$auhtml <\/span> ($cryear)"; 


                
                if ($inreftype != 3)  {
                    $accumneb .= "  ".$inreftitle;
                }  
                if ($inreftype == 3)  {
                    $accumneb .= "  ".$inrefbook;
                }                  
                if ($inreftype == 4)  { 
                    $accumneb .= " \/\/ ".$inrefbook;
                }
                if ($inrefedit ne "")  {
                    $accumneb .= ", edited by ".$inrefedit;
                }
                if ($inreftype == 1 || $inreftype == 2)  {
                    $accumneb .= ", \/\/ ".$inrefjour;
                }
                if ($inreftype >= 3 && $inreflocat ne "")  {
                    $accumneb .= " - ".$inreflocat;
                }
                if ($inreftype >= 3 && $inrefpubl ne "")  {
                    $accumneb .= ": ".$inrefpubl."\.";
                }  elsif ($inreftype >= 3 && $inrefpubl eq "")  { 
                    $accumneb .= ",  ";
                }
                $accumneb .= ", ".$cryear."\.";
                if ($inreftype < 3  &&  $inrefvol ne "")  {
                    $accumneb .= " - v. ".$inrefvol;
                }
                if ($inreftype < 3  &&  $inrefnumb ne "")  {
                    $accumneb .= " - no. ".$inrefnumb;
                }
                if ($inreftype < 5  && $inreftype != 3 &&  $inrefpages ne "")  {
                    $accumneb .= " - p. ".$pafrg[0]."\.";
                }
                if ($inreftype == 3 &&  $inrefpages ne "")  {
                    $accumneb .= " - ".$inrefpages." pp.";
                }

                if ($inreftype == 7 && $inrefdoi ne "")  {
                    $accumneb = $inrefmerged.", doi: ".$inrefdoi;
                }  
                if ($inreftype ne 7 && $inrefdoi ne "")  {
                    $accumneb .= ", doi: ".$inrefdoi;
                }                





#                if ($inreftype == 7 && $inrefdoi ne "")  {
#                    $accumneb = $inrefmerged.", doi: ".$inrefdoi;
#                }  elsif ($inreftype == 7 && $inrefdoi eq "")  {
#                    $accumneb = $inrefmerged;
#                }                
###############print ERR "accumneb = $accumneb\n";                 

$nebreference[$iref] = $accumneb;                
                $iref += 1;

##  N B !!  At the moment defined by CrossRef the set of citation's elements does not contain elements for publisher, 
##  N B !!  location, and access address.  So we can not give correct references to published data sets if they haven't
##  N B !!  assigned DOIs.  

            }
        }  elsif ($reflabel == 0)  {
            if ($citblocklab == 1)  {
                $citlist[$crcl] = "<\/citation_list>";
                ####print ERR "<\/citation_list>\n";
                $crcl += 1;
                $citblocklab = 0;
            }
        }
#######################  End Reflist Processing  ###############################
        $SaveCur[4] = $_;
    
        if (length($SaveCur[4]) > 0 && $SaveCur[4] ne "\n" && $SaveCur[4] ne "\r")  {
            for ($kk = 0; $kk < 5; $kk++)  {
                $SaveInterim[$i5][$kk] = $SaveCur[$kk];
            }
            $SaveInterim[$i5][3] = $SaveCur[3];            
            $i5 += 1;  
        }
    }
}

###         Control printing accumulated NEB references
###############################################################for ($iii = 0; $iii < $iref; $iii++)  {
###############################################################    print ERR "$nebreference[$iii]\n";
###############################################################}

##      Composing keyword string for HTML version.  Keywords are separated by semicolons
$keywords = "";
for ($jk = 0; $jk < $keysnum; $jk++)  {
    if ($jk == 0)  {
        $keywords = $keywordval[$jk];
    }  else  {
        $keywords = $keywords."\; ".$keywordval[$jk];            
    }
}
#############print ERR "KEYS = $keywords\n\n";

##IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

###print TST "\n\n I N T E R I M    T E S T     O U T P U T      Lines = $i5 \n\n";

##      Cleaning SaveCleanPar
$i = 0;
for ($xxx = 0; $xxx < $i5; $xxx++)  {
    print TST "$SaveInterim[$xxx][3] ||| $SaveInterim[$xxx][4]\n";
###    $SaveCleanPar[$i][3] = $SaveInterim[$xxx][3];
###    $SaveCleanPar[$i][4] = $SaveInterim[$xxx][4];
    $i += 1;        
}
$itot = $i;
close (TST);

open (TST, "<$tstfile")  || die "Cannot open $tstfile file.";

while (<TST>)  {
    chop();
    $thisline = length($_);
    if ($thisline > 0)  {
        print TMP "$_\n";       ##  This print shoud not be removed,  it saves strings for renumbering
    }
}

close (TST);
close (TMP);

$icur = 0;
open (TMP, "<temp.tex")  || die "Cannot open TEMP.TEX file.";
while (<TMP>)  {
    chop();
    @thfo = split(/ \|\|\| /, $_);
    $SaveCleanPar[$icur][3] = $thfo[0];
    $SaveCleanPar[$icur][4] = $thfo[1];
    $icur += 1;
}
$itot = $icur;

open (TST, ">$tstfile")  || die "Cannot open $tstfile file for writing.";

##++++##----##print TST "\n\n    R E S T O R I N G   SaveCleanPar   B E F O R E    P A S S  6      Lines = $itot \n\n";

for ($i = 0; $i <= $itot; $i++)  {
    ####print TST "$i  <<>>  $SaveCleanPar[$i][3] <<>> $SaveCleanPar[$i][4]\n"; 
    print TST "$SaveCleanPar[$i][4]\n"; 
}
close (TST);

###############################################################################
##        PASS 6:  Formatting TeX file for EBOOK (miniPDF) version           ##
###############################################################################
print "done\nPASS  6: Formatting TeX file for EBOOK (miniPDF) version  . . . . ";

##  Formatting EBOOK preamble from temporal.tex
##  Composing title of EBOOK version

$rcab = substr($infile, 4, 2);
$ebfile = $infile;
if (($rcab eq "ES") || ($rcab eq "NZ")) {
    $ebfile =~ s/000/\_EB/;
} elsif ($rcab eq "BS") {
    $ebfile =~ s/BS/BS\_EB/; 
} else {
    print ERR "Regcode of journal is not defined in config file\n";    
    $errcount +=1; 
} 
##print "\n$ebfile\n"; 

open (INEB, "<temporal.tex") ||  die "Cannot open $temporal.tex file";
open (EBFIN, ">$ebfile")  ||  die "Cannot open $ebfile file";

print EBFIN <<EOM;
\\documentclass\[epub,pdf\]\{ebook\}
\\usepackage\[cm\]\{sfmath\}
\\usepackage\{amsmath\}
\\usepackage\{color\}
\\usepackage\[pdftoolbar=false, pdfpagemode=UseNone, linkbordercolor={0 0 0}\]\{hyperref\}
EOM

$openbody = 0;
@elaueb = ();
$fauthors = "";
$aunumb = 0;        ##  Number of authors
$afnumb = 0;        ##  Number of affiliations
while (<INEB>)  {
    chop();
    if (/^(\\journalid)/)  {
        s/\\journalid\{//;
        @eleb = split(/\}\{/, $_);
        $eleb[@eleb - 1] = "20".$eleb[@eleb - 1];
        $eleb[@eleb - 1] =~ s/\}//;        
    }
    if (/^(\\paperid)/)  {
        s/\\paperid\{//;
        s/\}//;        
        $ebident = "\\ident\{".$eleb[0]."\}\{".$eleb[1]."\}\{".$eleb[2]."\}\{".$eleb[3]."\}\{".$_."\}";
        print EBFIN "\n$ebident\n";

        print EBFIN <<EOM;
\\cpright\{\}\{$eleb[3]\}
\\pagestyle\{empty\}
\\definecolor\{brown\}\{RGB\}\{157,23,4\}\n
\\begin\{document\}\n
\\vspace*\{2\\baselineskip\}
EOM
    }    
    if (/^(\\title)/)  {
        s/\\title\{//;
        s/\}//;
        print EBFIN "\n\\title\{".$_."\}\n\n";
    }
    if (/^(\\author\{)/)  {
        s/\\author\{//;
        @elau = split(/\}\{/, $_);
        $_ = $elau[2]." ".$elau[1];
        if ($elau[3] ne "") {
            $_ .= ", ".$elau[3];
        }
        if (($elau[4] ne "") && ($elau[5] ne ""))  {
            $_ .= "\$^\{$elau[4]\,$elau[5]\}\$";
        } elsif (($elau[4] ne "") && ($elau[5] eq ""))  { 
            $_ .= "\$^\{$elau[4]\}\$";
        }
        $elaueb[$aunumb] = $_;          ##  Accumulated authors
        $aunumb += 1;
    }
    if (/^(\\affil\{)/)  {
        s/\}\{/, /g;
        s/, ,/, /;
        s/, /\}\{/; 
        $elafeb[$afnumb] = "$_\n"; 
        for ($iaf = 0; $iaf < 4; $iaf++) {
            $elafeb[$afnumb][$iaf] = $elaf[$iaf];
        }
        $afnumb += 1;
    }
    if (/^(\\abstract\{)/)  {       ## Analysis of author/affil types 
        $authorstring = join("\, ", @elaueb);  
        if (($aunumb == 1) || ($afnumb == 1))  {
            $authorstring =~ s/\$\^\(.\)\$//g;
            $authorstring =~ s/\$\^\(.\,.\)\$//g;
        }
        print EBFIN "\\author\{$authorstring\}\n\n";
        for ($iif = 0; $iif < $afnumb; $iif++)  {
            if (($aunumb == 1) || ($afnumb == 1))  {
                $elafeb[$iif] =~ s/\\affil\{.\}/\\affil\{\}/;
                $elafeb[$iif] =~ s/\\affil\{..\}/\\affil\{\}/;
            }    
            print EBFIN "$elafeb[$iif]";
        }
    }
}

###############print EBFIN   "\n=============================Before middle part\n";
@parfigeb = ();
$figext = 0;  
##      Copying the middle part to array ==================================

open (IN, "<$infile") || die "Cannot open $infile file.";
##open (EBFIN, ">>$ebfile")  ||  die "Cannot open $ebfile file";

$figextmp = $names[0]."-figmod.tex";
#################################################print "$figextmp\n";
###open (FIGTMP, ">$figextmp")  ||  die "Cannot open $figextmp file";

open (COBO, ">$figextmp")  ||  die "Cannot open $figextmp file";

$ijk = 0;
###print "===============$abstract\n";
###  Here we break abstract body longer than 900 characters
$strpoint = 900;
while ($strpoint)  {
    $posbr = substr($abstract,$strpoint,1);
    if ($posbr ne " ")  {
        $strpoint -= 1;
    } else {
        ##  empty char
        $breakpoint = $strpoint;
        goto BREAK;        
    }
}
BREAK:

###print "breakpoint = $breakpoint\n";

$firstabspart = substr($abstract,0,$breakpoint);
$secondabspart = substr($abstract,$breakpoint); 
###print ERR "----firstabspart = $firstabspart\n";
###print ERR "----secondabspart = $secondabspart\n";

###$abstractmod = $firstabspart." \\linebreak\\newpage\}\\noindent\\centerline\{\\parbox\{100mm\}\{ ".$secondabspart."\}";

$abstract = "";
$abstract = $firstabspart." \\linebreak\\newpage\}\\noindent\\centerline\{\\parbox\{100mm\}\{ ".$secondabspart."\}\}";

###$abstract = $abstractmod;


###print "....abstract = $abstract\n";
###print ERR "....abstract = $abstract\n";

$firststring = "\\abstract\{".$abstract;
print COBO "$ijk -> $firststring\n";
$ijk += 1;  
while (<IN>)  {
    chop();
    if (/^(\\section\{)/)  {         
        $openbody = 1;
    } elsif (/\\begin\{references\}/)  {
        $openbody = 0;
    }
    if ($openbody == 1)  {
        $contbody[$ijk] = $_;
        print COBO "$ijk -> $_\n";
        $ijk += 1;                         ##  Counting of inpit strings        
    }
}
print COBO "\nTotal strings in array = $ijk\n";

##################################print ERR ">>>>>>>>>before>>>>>>>>>>>>>>>\n>>>>>>>>>>>>>>>>>>>>>>>>\n";
for ($iii = 0; $iii < $ijk; $iii++)  {
 ################====================############################===========================   print ERR "$contbody[$iii]\n";
}
########################################print ERR ">>>>>>>>>>>>>>>>>>>>>>>>\n>>>>>>>>>>>>>>>>>>>>>>>>\n";

##    Editing middle part  =============================

$fignumb = 0;
for ($mik = 0; $mik < $ijk; $mik++)  {
    if  ($contbody[$mik] =~ /\\setimage\{/)  {
        $fignumb += 1;
        $icor = $mik;
        @frg = split(/\}\{/, $contbody[$mik]);
        $frg[4] =~ s/\}//;
        $curimg = $frg[4]."\.png";
##print "\nCurimg = $curimg\n";  
        &ImageParams($curimg);
##print "\nSizes = $sizes[0]    $sizes[1]\n";
        if ($ratio <= 1)  {     ##      Portrait orientation
            $contbody[$icor] = "\\setimage\{\}\{\}\{115mm\}\{\}\{".$frg[4]."\}";
            $contbody[$icor-1] = "\\figurewidth\{90mm\}";
            $contbody[$icor-2] = "\\begin\{figure\}                      \% Fig ".$fignumb;
            if ($contbody[$icor+1] =~ /caption\{/)  {
                @parts = split(/caption\{/, $contbody[$icor+1]);
                $contbody[$icor+1] = "\\fcaplabel\{".$parts[1];
            }
        }  elsif ($ratio > 1)  {       ##     Landscape orientation
            $contbody[$icor] = "\\setimage\{\}\{\}\{158mm\}\{\}\{".$frg[4]."\}";
            $contbody[$icor-1] = "\\figurewidth\{140mm\}";
            $contbody[$icor-2] = "\\begin\{sidewaysfigure\}                      \% Fig ".$fignumb;
            if ($contbody[$icor+1] =~ /caption\{/)  {
                @parts = split(/caption\{/, $contbody[$icor+1]);
                $contbody[$icor+1] = "\\fcaplabel\{".$parts[1];
            }
        }           
    }
    if ($contbody[$mik] =~ /\\end\{figure/)  {
        if ($ratio <= 1)  {     ##      Portrait orientation
            $contbody[$mik] = "\\end\{figure\}\n";
        }  elsif ($ratio > 1)  {       ##     Landscape orientation
            $contbody[$mik] = "\\end\{sidewaysfigure\}\n";
        }
    }            
}

##>>>>>>>>>>>>>>>>>>>>>>> Control printing of  middle part  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##print ERR ">>>>>>>>>>after>>>>>>>>>>>>>>\n>>>>>>>>>>>>>>>>>>>>>>>>\n";

print EBFIN "\n\\abstract\{$abstract\n\n";   ##   Adding one-string abstract

for ($iii = 0; $iii < $ijk; $iii++)  {
    print EBFIN "$contbody[$iii]\n";
}
##print ERR ">>>>>>>>>>>>>>>>>>>>>>>>\n>>>>>>>>>>>>>>>>>>>>>>>>\n";
##print ERR "\n\nTotal records in contbody  = $ijk \n\n\n"; 

print EBFIN "\\begin\{references\}\n";

close (FIGTMP);

##    E X T R A C T I N G   R E F E R E N C E   I T E M S   A N D   ################################
##    C O M P O S I N G   T E X  F I L E  F O R   E B O O K         ################################
@refebook = ();
###$refebnum = 0;

open (TST, "<$tstfile")  || die "Cannot open $tstfile file for reading.";
open (REFER, ">$refforebook")  ||  die "Cannot open $refforebook file.";

$refcount = 0;

while (<TST>)  {
    chop();    
    if (/id=\"openref\"\>  \<\/a\>References\<\/h3\>/)  { 
        $ebookref = true;
        ###print "ebookref = $ebookref\n";
    } elsif (/\\end\{references\}/ || /\\noreferences/)  {
        $ebookref = false;
        ###print "ebookref = $ebookref\n";
    }
    
    if (/\<span class=\"ref\"\>/)  { 
        ###print REF "refcount = $refcount \n";
        @prts = split(/\" id=\"/, $_); 
        $_ = "\\reference\{".@prts[1];
        s/\"\>  \<\/a\> \<span class=\"ref\"\>/\} /g;
        s/ \<\/span\> \(/ \(/g;
        s/, \<i\>/, \{\\itshape /g;
        s/\<\/i\>/\}/g;
        s/\&\#x2013\;/--/g;
        if (/doi\.org/) {       ##  DOI link exists
            @prtstwo = split(/https\:\/\/doi\.org\//, $_);
            @dois = split(/\" target=\"blank\"\>/, $prtstwo[2]);
            $tail = "\\href\{https\:\/\/doi\.org\/".$dois[0]."\}\{\\textcolor{brown}{\\space\\bfseries Cross\\-ref\}\}";
            ##print REF "TAIL = $tail\n";
            $_ = $prtstwo[0].$tail;
            #################################print REF "$_\n";
            $refebook[$refcount] = $_;
        } else {
            ##$_ = $prtstwo[0];            
            #################################print REF "$_\n"; 
            $refebook[$refcount] = $_;
        }        
        $refcount += 1;
    }    
}

##      Saving modified references in jobname-ref.tex file 
#####print REFER "\n This file is generated by elxfinal.pl script for including it into mini-PDF version of article\n\n";

for ($ire = 0; $ire < $refcount; $ire++)  {
    $_ = $refebook[$ire];
######print "\nSTR  $refebook[$ire]";
    print ERR "\n";
    print ERR "$_\n";
    $refemod = $_;
    $shift = 0;
##  Removing </span>
    $refemod =~ s/<\/span>//g;
##  Extracting UTF-8 chars.  
    while($shift >= 0)  {
        $utfstr = index($refemod,"\&\#x", $shift);   ##  Start point uf UTF-8
        $shift = $utfstr + 3;
        if ($utfstr > 0) {
            $utfend = index($refemod,"\;", $shift);  ##  End point of UTF-8             
            $lenutf = $utfend - $utfstr + 1;
            $strutf = substr($refemod, $utfstr, $lenutf);
            &revertUTF($strutf);    ##  Converts UTF to TeX format
            $refemod =~ s/$strutf/$texfrag/g;  ##  Substitution $texfrag over @strutf
##########print "\nEND  $refemod\n";
        } else {
            goto UTFSTR;
        }                  
    }
UTFSTR:
    print REFER "$refemod\n\n";
    print EBFIN "$refemod\n\n";
}
#########################print REF "\n\nrefcount = $refcount\n\n";

print EBFIN "\\end\{references\}\n";
print EBFIN "\\end\{document\}\n";

close (REFER);
close (EBFIN);

##============================== articletitle =======================================================
##  Replacing UTF to TeX for articletitle in EBOOK
    $_ = $articletitle;
    $refemod = $_;
    $shift = 0;
##  Extracting UTF-8 chars.
###print "\n\n$refemod\n";
    while($shift >= 0)  {
        $utfstr = index($refemod,"\&\#x", $shift);   ##  Start point uf UTF-8
        $shift = $utfstr + 3;
        if ($utfstr > 0) {
            $utfend = index($refemod,"\;", $shift);  ##  End point of UTF-8
            $lenutf = $utfend - $utfstr + 1;
            $strutf = substr($refemod, $utfstr, $lenutf);
            &revertUTF($strutf);    ##  Converts UTF to TeX format
            $refemod =~ s/$strutf/$texfrag/g;  ##  Substitution $texfrag over @strutf
        } else { 
            goto UTFTIT;
        }
    }
UTFTIT:
        $articletitle = $refemod;
###print "\n$refemod\n\n";

##============================== authcitdir =======================================================
##  Replacing UTF to TeX for authcitdir in EBOOK
    $_ = $authcitdir;
    $refemod = $_;
    $shift = 0;
##  Extracting UTF-8 chars.
###print "\n\n$refemod\n";
    while($shift >= 0)  {
        $utfstr = index($refemod,"\&\#x", $shift);   ##  Start point uf UTF-8
        $shift = $utfstr + 3;
        if ($utfstr > 0) {
            $utfend = index($refemod,"\;", $shift);  ##  End point of UTF-8
            $lenutf = $utfend - $utfstr + 1;
            $strutf = substr($refemod, $utfstr, $lenutf);
            &revertUTF($strutf);    ##  Converts UTF to TeX format
            $refemod =~ s/$strutf/$texfrag/g;  ##  Substitution $texfrag over @strutf
        } else {
            goto UTFCIT;
        }                  
    }
UTFCIT:
        $authcitdir = $refemod;
###print "\n$refemod\n\n";

##=====================================================================================
###############################################################################
##        PASS 7:  Composing metadada XML files for CrossRef and eLibrary    ##
###############################################################################
print "done\nPASS  7: Composing metadada XML files for CrossRef and eLibrary . ";

open (XML, ">$xmlnamcr")  ||  die "Cannot open $xmlnamcr file/\n";
open (NEB, ">$xmlnamneb")  ||  die "Cannot open $xmlnamneb file/\n";

print XML <<EOM;
<?xml version="1.0" encoding="UTF-8"?>
<doi_batch version="4.3.0" xmlns="http://www.crossref.org/schema/4.3.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.crossref.org/schema/4.3.0 http://www.crossref.org/schema/deposit/crossref4.3.0.xsd">
   <head>
      <doi_batch_id>$citatnumb</doi_batch_id>
      <timestamp>$timestamp</timestamp>
      <depositor>
         <name>$crdepositorname</name>
         <email_address>$crdepositoremail</email_address>
      </depositor>
      <registrant>$regtitle[$journumb][6]</registrant>
   </head>
   <body>
      <journal>
         <journal_metadata language="en">
            <full_title>$regtitle[$journumb][1]</full_title>
            <abbrev_title>$regtitle[$journumb][2]</abbrev_title>
            <issn media_type="electronic">$regtitle[$journumb][4]</issn>
         </journal_metadata>
         <journal_issue>
            <publication_date media_type="online">
               <year>20$jouryear</year>
            </publication_date>
            <journal_volume>
               <volume>$jourvol</volume>
            </journal_volume>
            <issue>$journum</issue>
         </journal_issue>
         <journal_article publication_type="full_text">
            <titles>
               <title>$artitcr</title>
            </titles>
            <contributors>
EOM

print NEB <<EOM;
<?xml version='1.0' standalone='no' ?>
<journal xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="JournalArticulus.xsd">
<!-- Start of article metadata -->
         <article>
            <pages>1-$lastpage</pages>
            <artType>$papertype</artType>
            <authors>
EOM

for ($nau = 0; $nau < $authnum; $nau++)  {
    $naut = $nau + 1;
    if ($naut < 10)  {
       $nauto = "00".$naut;
    }  elsif ($naut < 100)  {
       $nauto = "0".$naut;
    }  elsif ($naut < 1000)  {
       $nauto = $naut;
    }
##    Output NEB author
    if ($nau == 0)  {
        print XML "               <person_name sequence=\"first\" contributor_role=\"author\">\n";
    } else {
        print XML "               <person_name sequence=\"additional\" contributor_role=\"author\">\n";
    }
    @elaut = split(/\}\{/, $authors[$nau]);
    $orgname = $affils[$elaut[4]-1];
    $neborgfrag = $neborg[$elaut[4]-1];    
    $nebadrfrag = $nebadr[$elaut[4]-1];    
    print XML <<EOM;
                  <given_name>$elaut[2]</given_name>
                  <surname>$elaut[1]</surname>
               </person_name>
EOM
    print NEB <<EOM;
               <author num=\"$nauto\">
                  <individInfo lang=\"ENG\">  
                     <surname>$elaut[1]</surname>
                     <initials>$elaut[2]</initials>
                     <orgName>$neborgfrag</orgName>
                     <address>$nebadrfrag</address>
                  </individInfo>
               </author>
EOM
}
##             Closing author block and adding title and abstract
   print NEB <<EOM;
               </authors>
            <artTitles>
               <artTitle lang="ENG">$artitcr</artTitle>
            </artTitles>
            <abstracts>
               <abstract lang="ENG">$abstract</abstract>
            </abstracts>
            <text lang="ENG">
                $joinedtextline
            </text>
            <keywords>
               <kwdGroup lang="ANY">
EOM
##          Adding keywords to NEB     
    for ($kj = 0; $kj < $keysnum; $kj++)  {
        print NEB "                  <keyword>$keywordval[$kj]</keyword>\n";
    }
    print NEB <<EOM;
               </kwdGroup>
            </keywords>
            <references>
EOM

for ($iii = 0; $iii < $iref; $iii++)  {
    print NEB "               <reference>$nebreference[$iii]<\/reference>\n";
}
###################print NEB closing fragment\n";

$verecfile = $names[0]."\.pdf";
$furllink = "https\:\/\/doi\.org\/10\.2205\/".$names[0];

print NEB <<EOM;
            <\/references>
            <files>
               <file>$verecfile<\/file>
               <furl>$furllink<\/furl>
            </files>
         </article>
<!-- End of article metadata -->
EOM

print XML <<EOM;
            </contributors>
            <publication_date media_type="online">
               <month>$imon</month>
               <day>$dpublished</day>
               <year>$ypublished</year>
            </publication_date>
            <pages>
               <first_page>1</first_page>
               <last_page>$lastpage</last_page>
            </pages>
            <publisher_item>
               <identifier id_type="pii">$regcode[$journumb]-$jourvol-$paperid</identifier>
            </publisher_item>
            <doi_data>
               <doi>$regtitle[$journumb][5]/$paperid</doi>
                  <timestamp>$timestamp</timestamp>
                  <resource>$regtitle[$journumb][10]$respage</resource> <!-- DOI's prime URL -->
               <collection property="list-based" multi-resolution="lock" />
            </doi_data>
EOM
##      Saving citation list

print XML "Before ===========================================================\n";

for ($xm = 0; $xm < $crcl; $xm++)  {
    print XML "            $citlist[$xm]\n";
}

print XML "After ============================================================\n";

print XML <<EOM;
            </citation_list>
         </journal_article>
      </journal>
   </body>
</doi_batch>
EOM
close (XML);
###############################   End of XML composing  #################################

##++++++##------##print TST "\n\n    A F T E R   P A S S  7      Crossref        \n\n";
##++++++##------##for ($i = 0; $i < $itot; $i++)  {
##++++++##------##    print TST "$i  <<>>  $SaveCleanPar[$i][3] <<>> $SaveCleanPar[$i][4]\n"; 
##++++++##------##}   

###############################################################################
##        PASS 8:  Setting internal and external hyperlinks                  ##
###############################################################################
print "done\nPASS  8: Setting internal and external hyperlinks . . . . . . . . ";

$addlabs = "addlabs.tmp";
$opmathlab = 0;
open (ADD, ">$addlabs")  ||  die  "Cannot open $addlabs  file.";

#####################################print TST "\n\n   I N S I D E   P A S S   7     S T A R T\n\n";

###print ERR "\nITOT  =  $itot\n\n";  

@fignailabs = ();       ##  Labels for figure's first occurrence
@tabnailabs = ();       ##  Labels for table's first occurrence

for ($i = 2; $i < $itot; $i++)  {
    $_ = $SaveCleanPar[$i][4];

####print ERR "-=-$_\n";

##                      R E F L I N K                                           R E F L I N K
##      Looking for \reflink command and replacing it with the internal hyperlink to corresponding item in the References list
    $rlstr = 0;
    while (/\\reflink\{.+\}\{.+\}/)  {                                        ###       REFLINK    REFLINK     REFLINK 
        $rlpos = index($_, "\\reflink\{", $rlstr);
        if ($rlpos < 0)  {
            goto RLOUT;
        }

        $strlin = rindex($_, "<it>", $rlpos);

######        print ERR "\n$_\n"; 
######        print ERR "SEARCH BACK: rlpos = $rlpos     strlin = $strlin\n";        
         
        $rlstr = $rlpos + 8;
        &FindMatchBracket($_, $rlstr, 2);
        $rllen = $nepar - $rlstr - 1;
        $rlparts = substr($_, $rlstr + 1, $rllen);
        $rlsubst = "\\reflink\{".$rlparts."\}";
        @rlelems = split(/\}\{/, $rlparts);
        $rlnewsubst = "<a href=\"\#".$rlelems[0]."\" onClick=\"javascript\:showlayer(\'div".$rlelems[0]."\');return false;\">".$rlelems[1]."<\/a>";
#################        print ERR "rlnewsubst = $rlnewsubst\n";
        $loldsub = length($rlsubst);
        $lnewsub = length($rlnewsubst);
        $rlfistr = substr($_, 0, $rlpos);
        $rlsestr = substr($_, $rlpos + $loldsub);
        $_ = $rlfistr.$rlnewsubst.$rlsestr;
######        print ERR "AFTER  BACK: rlpos = $rlpos     strlin = $strlin\n";             
        if ($strlin >= 0)  {
            $prelin = substr($_, 0, $strlin);
            $lenlin = $rlpos - $strlin;
            $midlin = substr($_, $strlin, $lenlin);
            $aftlin = substr($_, $rlpos);
#######            print ERR "$prelin ||| $midlin ||| $aftlin\n";
            ##$midlin =~ s/<it>/<reflink>/;
            ##$midlin =~ s/<\/it>/<\/reflink>/;
            $midlin =~ s/<it>/<span class="int">/;
            $midlin =~ s/<\/it>/<\/span>/;
                        
            $_ = $prelin.$midlin.$aftlin;

        }
        
        ###print ERR  "====rlparts = $rlparts      rlsubst = $rlsubst       rlnewsubst = $rlnewsubst \n";
        ########################print ERR "$_\n";
        $rlstr += 1;
    }
RLOUT:

##                  F I G R E F S  - List of figure numbers with no links to figures files
##      Looking for \figrefs command and replacing it with the text like  (Figures NN--MM)

    $frsstr = 0;
    while (/\\figrefs\{.+\}/)  {        

        #####/////////////////////////////print ERR "FIGREFS STRING = $_\n";

        $frspos = index($_, "\\figrefs\{", $frsstr);
        if ($frspos < 0)  {
            goto FRSOUT;
        }  else  {
            #####/////////////////////////////print ERR "\n$_\nfrspos = $frspos";
        }
        $frsstr = $frspos + 8;
        &FindMatchBracket($_, $frsstr, 1);
        $frlen = $nepar - $frsstr - 1;
        $frspart = substr($_, $frsstr + 1, $frlen);
        
        #####print ERR "VALUE = $frspart|||\n";
        
        $frsoldsubst = "\\figrefs\{".$frspart."\}";
        #########//////////////////////////////////////print ERR " frsoldsubst = $frsoldsubst\n"; 
        ################################print ERR  "ww = $ww =            hh = $hh\n";
        $frsnewsubst = $figsname." ".$frspart." "; 
        $lsoldsub = length($frsoldsubst);
        $lsnewsub = length($frsnewsubst);
        $frsfistr = substr($_, 0, $frspos);
        $frssestr = substr($_, $frspos + $lsoldsub);
        $_ = $frsfistr.$frsnewsubst.$frssestr;
        ######print ERR "FFF=$frsfistr |||| SSS=$frssestr\n$_\n";
        $frsstr += 1;
    }
FRSOUT:

##                  F I G R E F                                       F I G R E F 
##      Looking for \figref command and replacing it with the hyperlink to corresponding Figure's file
    $frstr = 0;
    @frontfigthumb = ();
    $frontfignum = 0;
    while (/\\figref\{.+\}/)  {                                            ###     FIGREF     FIGREF     FIGREF      
######                print ERR "FFFF-  \n$_\n";
        $frpos = index($_, "\\figref\{", $frstr);
        if ($frpos < 0)  {
            goto FROUT;
        }  else  {
######                print ERR "\n$_\nfrpos = $frpos\n";
        }
        $frstr = $frpos + 7;
        &FindMatchBracket($_, $frstr, 1);
        $frlen = $nepar - $frstr - 1;
        $frpart = substr($_, $frstr + 1, $frlen);
        $froldsubst = "\\figref\{".$frpart."\}";
#####print ERR " froldsubst = $froldsubst\n"; 
        $fralp = $frpart;
        if ($fralp < 10)  {            ##  Number of Figures limited to 99 per article
            $fralp = "0".$fralp;
        } 
        $lelab = length($fignailabs[$frpart]);   
#####print ERR "i = $i\nfrpart = $frpart\n||$fignailabs[$frpart]||\nlelab = $lelab\n\n";
        if ($lelab == 0 && $SaveCleanPar[$i][3] ne "tabular")  {
            $fignailabs[$frpart] = "1";
            $frontfigthumb[$frontfignum] = "figparsplaceholder[".$fralp."] ";        ##  Placeholder for thumbnails 
            $frontfignum += 1;           
        }      
        $ww = $figparams[$frpart][5] + 600;
        $hh = $figparams[$frpart][6] + 600;
        
        ################################print ERR "ww = $ww =            hh = $hh\n";
        
        $frnewsubst = "<a href=\"".$paperid."-fig".$fralp."\.html\" title=\"Call Figure\&\#xA0\;".$frpart." into new window\" onClick=\"OpenWinAlt(\'".$paperid."-fig".$fralp."\.html\', \'win".$fralp."\', ".$ww.", ".$hh.")\; return false\;\">$figtypename\&\#xA0\;".$frpart."<\/a>"; 
##################################print ERR "frnewsubst = $frnewsubst\n"; 
        $loldsub = length($froldsubst);
        $lnewsub = length($frnewsubst);
        $frfistr = substr($_, 0, $frpos);
        $frsestr = substr($_, $frpos + $loldsub);

        $_ = $frfistr.$frnewsubst.$frsestr;
        
######                print ERR "FFF=$frfistr |||| SSS=$frsestr\n$_\n";
        
        $frstr += 1;
    }
FROUT:
##                  T A B R E F S  - List of table numbers with no links to tables files
##      Looking for \tabrefs command and replacing it with the text like  (Tables NN--MM)

    $trsstr = 0;
    while (/\\tabrefs\{.+\}/)  {        
        print ERR "TABREFS STRING = $_\n";
        $trspos = index($_, "\\tabrefs\{", $trsstr);
        if ($trspos < 0)  {
            goto TRSOUT;
        }  else  {
            print ERR "\n$_\ntrspos = $trspos";
        }
        $trsstr = $trspos + 8;
        &FindMatchBracket($_, $trsstr, 1);
        $trlen = $nepar - $trsstr - 1;
        $trspart = substr($_, $trsstr + 1, $trlen);
        print ERR "VALUE = $trspart|||\n";
        $trsoldsubst = "\\tabrefs\{".$trspart."\}";
        print ERR " trsoldsubst = $trsoldsubst\n"; 
        ################################print ERR "ww = $ww =            hh = $hh\n";
        $trsnewsubst = $tabsname." ".$trspart." "; 
        $lsoldsub = length($trsoldsubst);
        $lsnewsub = length($trsnewsubst);
        $trsfistr = substr($_, 0, $trspos);
        $trssestr = substr($_, $trspos + $lsoldsub);
        $_ = $trsfistr.$trsnewsubst.$trssestr;
        print ERR "FFF=$trsfistr |||| SSS=$trssestr\n$_\n";
       $trsstr += 1;
    }
TRSOUT:

##                  T A B R E F                                       T A B R E F 
##      Looking for \tabref command and replacing it with the hyperlink to corresponding Table's file
    $trstr = 0;
    @fronttabthumb = ();
    $fronttabnum = 0;
    while (/\\tabref\{.+\}/)  {                                     ####            TABREF     TABREF     TABREF     
        ################################print ERR "FFFF-  \n$_\n";
        $trpos = index($_, "\\tabref\{", $trstr);
        if ($trpos < 0)  {
            goto TROUT;
        }
        #######################print ERR "trpos = $trpos\n";
        $trstr = $trpos + 7;
        &FindMatchBracket($_, $trstr, 1);
        $trlen = $nepar - $trstr - 1;
        $trpart = substr($_, $trstr + 1, $trlen);
        $troldsubst = "\\tabref\{".$trpart."\}";
        $tralp = $trpart;
        if ($tralp < 10)  {            ##  Number of Tables limited to 99 per article
            $tralp = "0".$tralp;
        }

        $letab = length($tabnailabs[$trpart]);
        ##################print ERR "i = $i\ntrpart = $trpart\n||$tabnailabs[$trpart]||\nletab = $letab\n\n";
        if ($letab == 0 && $SaveCleanPar[$i][3] ne "tabular")  {
            $tabnailabs[$trpart] = "1";
            $fronttabthumb[$fronttabnum] = "tabparsplaceholder[".$tralp."] ";       ##  Placeholder for thumbnails 
            $fronttabnum += 1;           
        }      

        ###$ww = $tabparams[$trpart-1][12];
        ###$hh = $tabparams[$trpart-1][13];
        $ww = 600;
        $hh = 600;

########################print ERR "\nWW = $ww    HH= $hh\n";

##$ww = 600;
##$hh = 400;
###$ww = $tabparams[$trpart-1][12];
###$hh = $tabparams[$trpart][13];

########################print ERR "\nWW = $ww    HH= $hh\n";

        $trnewsubst = "<a href=\"".$paperid."-tab".$tralp."\.html\" title=\"Call Table\&\#xA0\;".$trpart." into new window\" onClick=\"OpenWinAlt(\'".$paperid."-tab".$tralp."\.html\', \'win".$tralp."\', ".$ww.", ".$hh.")\; return false\;\">Table\&\#xA0\;".$trpart."<\/a>"; 

        $loldsub = length($troldsubst);
        $lnewsub = length($trnewsubst);
        $trfistr = substr($_, 0, $trpos);
        $trsestr = substr($_, $trpos + $loldsub);
        $_ = $trfistr.$trnewsubst.$trsestr;
        ####print ERR "SSSS-  \n$_\n";
        $trstr += 1;
    }
TROUT:

if ($frontfignum > 0 || $fronttabnum > 0 )    {
##    print ERR "frontfignum = $frontfignum   fronttabnum = $fronttabnum\n";

##  Adding preceeding thumbnails
#    $forwardedthumbs = "<p> ";
    $forwardedthumbs = "";
    if ($frontfignum > 0 )  {
        for ($iff = 0; $iff < $frontfignum; $iff++)  {
            $forwardedthumbs .= $frontfigthumb[$iff]." ";
        }
    }
    if ($fronttabnum > 0 )  {
        for ($ift = 0; $ift < $fronttabnum; $ift++)  {
            $forwardedthumbs .= $fronttabthumb[$ift]." ";
        }
    }
    if (/^<p>/)  {
        $_ =~ s/^<p>/$forwardedthumbs/; 
    } else  {
        $_ =~ s/^/$forwardedthumbs/;     
    }
    $SaveCleanPar[$i][4] = $_; 
}   

##                  U R L                      U R L                            U R L
##      Looking for \url command and replacing it with the hyperlink to corresponding spot/site
    $urstr = 0;
    while (/\\url\{.+\}/)  {
        ####print ERR "FFFF-  \n$_\n";
        $urpos = index($_, "\\url\{", $urstr);
        if ($urpos < 0)  {
            goto UROUT;
        }
        #################print ERR "urpos = $urpos\n";
        $urstr = $urpos + 4;
        &FindMatchBracket($_, $urstr, 1);
        $urlen = $nepar - $urstr - 1;
        $urpart = substr($_, $urstr + 1, $urlen);
        $uroldsubst = "\\url\{".$urpart."\}";
        $urnewsubst = "<a href=\"".$urpart."\"  target=\"blank\">".$urpart."<\/a>";
        $loldsub = length($uroldsubst);
        $lnewsub = length($urnewsubst);
        $urfistr = substr($_, 0, $urpos);
        $ursestr = substr($_, $urpos + $loldsub);
        $_ = $urfistr.$urnewsubst.$ursestr;
        ###print ERR "SSSS-  \n$_\n";
        $urstr += 1;
    }
UROUT:

##                      H R E F                       H R E F                       H R E F
##      Looking for \href command and replacing it with the hyperlink to corresponding site
    $hrstr = 0;
    while (/\\href\{.+\}/)  {
        ####print ERR "FFFF-  \n$_\n";
        $hrpos = index($_, "\\href\{", $hrstr);
        if ($hrpos < 0)  {
            goto HROUT;
        }
        ####print ERR "hrpos = $hrpos\n";
        $hrstr = $hrpos + 5;
        &FindMatchBracket($_, $hrstr, 2);
        $hrlen = $nepar - $hrstr - 1;
        $hrparts = substr($_, $hrstr + 1, $hrlen);
        $hroldsubst = "\\href\{".$hrparts."\}";
        @hrelems = split(/\}\{/, $hrparts);
        $hrnewsubst = "<a href=\"".$hrelems[0]."\" target=\"blank\">".$hrelems[1]."<\/a>";
        $loldsub = length($hroldsubst);
        $lnewsub = length($hrnewsubst);
        $hrfistr = substr($_, 0, $hrpos);
        $hrsestr = substr($_, $hrpos + $loldsub);
        $_ = $hrfistr.$hrnewsubst.$hrsestr;
        ####print ERR "SSSS-  \n$_\n";
        $hrstr += 1;
    }
HROUT:

##              H Y P E R L I N K                                  H Y P E R L I N K
##      Looking for \hyperlink command and replacing it with the hyperlink to corresponding target
    $hlstr = 0;
    while (/\\hyperlink\{.+\}/)  {
        ########print ERR "LLLL - $_\n";
        $hlpos = index($_, "\\hyperlink\{", $hlstr);
        if ($hlpos < 0)  {
            goto HLOUT;
        }
        ###print ERR "hlpos = $hlpos\n";
        $hlstr = $hlpos + 10;
        &FindMatchBracket($_, $hlstr, 2);
        $hllen = $nepar - $hlstr - 1;
        $hlparts = substr($_, $hlstr + 1, $hllen);
        $hloldsubst = "\\hyperlink\{".$hlparts."\}";
        @hlelems = split(/\}\{/, $hlparts);
        $hlnewsubst = "<a href=\"\#".$hlelems[0]."\">".$hlelems[1]."<\/a>";
        $loldsub = length($hloldsubst);
        $lnewsub = length($hlnewsubst);
        ###print ERR "---$hloldsubst \n===$hlnewsubst\n";
        $hlfistr = substr($_, 0, $hlpos);
        $hlsestr = substr($_, $hlpos + $loldsub);
        $_ = $hlfistr.$hlnewsubst.$hlsestr;
        ########print ERR "SSSS - $_\n";
        $hlstr += 1;
    }
HLOUT:

##              E Q R E F                      E Q R E F                           E Q R E F 
##      Looking for \eqref command and replacing it with the hyperlink to corresponding equation
    $eqstr = 0;
    while (/\\eqref\{.+\}/)  {
        ############print ERR "FFFF-  \n$_\n";
        $eqpos = index($_, "\\eqref\{", $eqstr);
        if ($eqpos < 0)  {
            goto EQOUT;
        }
        #####################print ERR "eqpos = $eqpos\n";
        $eqstr = $eqpos + 6;
        &FindMatchBracket($_, $eqstr, 1);
        $eqlen = $nepar - $eqstr - 1;
        $eqpart = substr($_, $eqstr + 1, $eqlen);
        $eqoldsubst = "\\eqref\{".$eqpart."\}";
        $eqalp = $eqpart;
        if ($eqalp < 10)  {            ##  Number of equations limited to 999 per article
            $eqalp = "00".$eqalp;
        } elsif ($eqalp < 100)  {
            $eqalp = "0".$eqalp;
        }
        $eqnewsubst = "(<a href=\"\#eqn".$eqalp."\">".$eqpart."<\/a>)";
        ###print ERR "eqpart = $eqpart     eqoldsubst = $eqoldsubst      eqalp = $eqalp         eqnewsubst = $eqnewsubst\n";
        $loldsub = length($eqoldsubst);
        $lnewsub = length($eqnewsubst);
        $eqfistr = substr($_, 0, $eqpos);
        $eqsestr = substr($_, $eqpos + $loldsub);
        $_ = $eqfistr.$eqnewsubst.$eqsestr;
        ############print ERR "SSSS-  \n$_\n";
        $eqstr += 1;
    }
EQOUT:

##              H Y P E R T A R G E T                     H Y P E R T A R G E T       
##    Replacing \hypertarget in math and text paragraphs
   if ($_ =~ /\\hypertarget\{.+\}/)   {
      if ($SaveCleanPar[$i][3] =~ /type=\"math\"/)  {   
##       \hypertarget  inside math  paragraph  will be processed at the end of this step 
      }  else  {
##    Replacing \hypertarget occurred outside of math paragraph with <a accesskey="label">placeholder</a> expression.
         $htstr = 0;
         while (/\\hypertarget\{.+\}/)  {
            ###print ERR "TTTT - $_\n";
            $htpos = index($_, "\\hypertarget\{", $htstr);
            if ($htpos < 0)  {
               goto HTOUT;
            }
     ###print ERR "htpos = $htpos\n";
         $htstr = $htpos + 12;
            &FindMatchBracket($_, $htstr, 2);
            $htlen = $nepar - $htstr - 1;
            $htparts = substr($_, $htstr + 1, $htlen);
            $htoldsubst = "\\hypertarget\{".$htparts."\}";
            @htelems = split(/\}\{/, $htparts);
            $htnewsubst = "<a accesskey=\"".$htelems[0]."\">".$htelems[1]."<\/a>";
            $loldsub = length($htoldsubst);
            $lnewsub = length($htnewsubst);
        ###print ERR "---oldsubst = $htoldsubst \n===newsubst = $htnewsubst\n";
            $htfistr = substr($_, 0, $htpos);
            $htsestr = substr($_, $htpos + $loldsub);
            $_ = $htfistr.$htnewsubst.$htsestr;
            ###print ERR "SSSS - $_\n";
            $htstr += 1;
         }
HTOUT:
      }      
   } 

##      Extracting TeX formatting commands
##      Inserting extra lines with hypertargets

##              H Y P E R R E F                    H Y P E R R E F       
##    Looking for \hyperref command and replacing it with the hyperref to corresponding target
   if ($_ =~ /\\hyperref\{.+\}/)   {
        $hrstr = 0;
        while (/\\hyperref\{.+\}/)  {
####        print ERR "LLLL - $_\n";
            $hrpos = index($_, "\\hyperref\{", $hrstr);
            if ($hrpos < 0)  {
                goto HROUT;
            }
####            print ERR "hrpos = $hrpos\n";
            $hrstr = $hrpos + 9;
            &FindMatchBracket($_, $hrstr, 4);
            $hrlen = $nepar - $hrstr - 1;
            $hrparts = substr($_, $hrstr + 1, $hrlen);
            $hroldsubst = "\\hyperref\{".$hrparts."\}";
            @hrelems = split(/\}\{/, $hrparts);
            $hrnewsubst = "<a href=\"\#".$hrelems[2]."\">".$hrelems[3]."<\/a>";
            $roldsub = length($hroldsubst);
            $rnewsub = length($hrnewsubst);
####        print ERR "---$hloldsubst \n===$hlnewsubst\n";
            $hrfistr = substr($_, 0, $hrpos);
            $hrsestr = substr($_, $hrpos + $roldsub);
            $_ = $hrfistr.$hrnewsubst.$hrsestr;
####        print ERR "SSSS - $_\n";
            $hlstr += 1;
        }
   }
HROUT:

##              H Y P E R D E F                    H Y P E R D E F       
##    Looking for \hyperdef command and replacing it with the hyperdef to corresponding target
   if ($_ =~ /\\hyperdef\{.+\}/)   {
        $hdstr = 0;
        while (/\\hyperdef\{.+\}/)  {
####   print ERR "LLLL - $_\n";
            $hdpos = index($_, "\\hyperdef\{", $hrdtr);
            if ($hdpos < 0)  {
                goto HDOUT;
            }
####            print ERR "hdpos = $hdpos\n";
            $hdstr = $hdpos + 9;
            &FindMatchBracket($_, $hdstr, 3);
            $hdlen = $nepar - $hdstr - 1;
            $hdparts = substr($_, $hdstr + 1, $hdlen);
            $hdoldsubst = "\\hyperdef\{".$hdparts."\}";
            @hdelems = split(/\}\{/, $hdparts);
            $hdnewsubst = "<a accesskey=\"".$hdelems[1]."\" id=\"".$hdelems[1]."\">".$hdelems[2]."<\/a>";
            $doldsub = length($hdoldsubst);
            $dnewsub = length($hdnewsubst);
####        print ERR "---$hdoldsubst \n===$hdnewsubst\n";
            $hdfistr = substr($_, 0, $hdpos);
            $hdsestr = substr($_, $hdpos + $doldsub);
            $_ = $hdfistr.$hdnewsubst.$hdsestr;
####        print ERR "SSSS - $_\n";
            $hdstr += 1;
        }
   }
HDOUT:

##      Removing minipage environment around \hyperdef
    
    $SaveCleanPar[$i][4] = $_;

##Test==## print ITEMS "\\==$_\n";
   
   ##################################################print ERR "===========$_\n";
   ##################################################
   
   if ($SaveCleanPar[$i][3] =~ /type=\"math\"/)  {   ##    Processing math strings

##    The following fragment replaces \label{.}  in equations with  \tag*{(.)} which is ----------------  added 7.01.15
##    necessary to produce MathML-compatible numberred equations  
      if (/^\\label\{/)  { 
         $poslabop = index($_, "\\label\{", 0) + 7;   
         $poslabcl = index($_, "\}", $poslabop + 1);
         $labvalue = substr($_, $poslabop, $poslabcl - $poslabop);
         $labeltail = substr($_, $poslabcl+1);
         $newlabstring = "\\tag*\{\(".$labvalue."\)\}";
         $_ = $newlabstring.$labeltail;
         $SaveCleanPar[$i][4] = $_;
      }
##------------------------------------------------------------------------------------------------------   
      if (/^\\begin\{equation\}/ && $opmathlab == 0)  {         ##    Opens equation
         $opmathlab = 1;
      }  elsif ((/^\\tag\*\{/ || /^\\hypertarget\{/) && $opmathlab == 1)  { 
##      print ERR "$_\n";
             
##       Extracting target value, now we are processing only \tag-type target  or \hypertarget

         if (/^\\tag\*\{/)  {
            $postagop = index($_, "\\tag\*\{", 0) + 6;   
            $postagcl = index($_, "\}", $postagop + 1);
            $tagvalue = substr($_, $postagop, $postagcl - $postagop);
            $tagvalue =~ s/\(//;
            $tagvalue =~ s/\)//;
            $tagnum = $tagvalue * 1;
            if ($tagnum < 10)  {
               $tagvalue = "eqn00".$tagvalue;
            } elsif ($tagnum < 100)  {
               $tagvalue = "eqn0".$tagvalue;
            }
         } elsif  (/^\\hypertarget\{/)  {
            s/\\hypertarget\{//;                     
            $posdbr = index($_, "\}\{"); 
            if ($posdbr < 0)  {
               print ERR "Problem with hypertarget in equation [para $SaveCleanPar[$i][i] -- $SaveCleanPar[$i][i]]\n";
               $errcount += 1;
               goto TARGET; 
            }          
            $tagvalue = substr($_, 0, $posdbr);            
            s/\}\{//;
            s/\)\}\}/\)\}/;
            s/^$tagvalue//;
         }
         print ADD "$SaveCleanPar[$i][0] [[[]]] $SaveCleanPar[$i][1] [[[]]] $SaveCleanPar[$i][2] [[[]]] <p id=\"none\" type=\"indent\"> [[[]]] <a accesskey=\"$tagvalue\" id=\"$tagvalue\">  <\/a>\n";
         print ADD "$SaveCleanPar[$i][0] [[[]]] $SaveCleanPar[$i][1] [[[]]] $SaveCleanPar[$i][2] [[[]]] $SaveCleanPar[$i][3] [[[]]] \\begin\{equation\}\n";       
         print ADD "$SaveCleanPar[$i][0] [[[]]] $SaveCleanPar[$i][1] [[[]]] $SaveCleanPar[$i][2] [[[]]] $SaveCleanPar[$i][3] [[[]]] $_\n";
      }  else  {
         $opmathlab = 0;
         print ADD "$SaveCleanPar[$i][0] [[[]]] $SaveCleanPar[$i][1] [[[]]] $SaveCleanPar[$i][2] [[[]]] $SaveCleanPar[$i][3] [[[]]] $_\n";
      }         
   }  else  {
      print ADD "$SaveCleanPar[$i][0] [[[]]] $SaveCleanPar[$i][1] [[[]]] $SaveCleanPar[$i][2] [[[]]] $SaveCleanPar[$i][3] [[[]]] $_\n";
   }    
}
TARGET:
close (ADD);

##    Checkout of correctness targets substitution

open (ADD, "<$addlabs")  ||  die  "Cannot open $addlabs  file.";
$i = 0;        ##    Inserting multiline records into $SaveCleanPar array structure
while (<ADD>)  {
   chop();
   @elems = split(/ \[\[\[\]\]\] /, $_);
   $numel = @elems;
   if ($numel == 5)  {
      $SaveCleanPar[$i][0] = $elems[0]; 
      $SaveCleanPar[$i][1] = $elems[1]; 
      $SaveCleanPar[$i][2] = $elems[2]; 
      $SaveCleanPar[$i][3] = $elems[3]; 
      $SaveCleanPar[$i][4] = $elems[4]; 
   }  elsif ($numel == 1)  {
      $SaveCleanPar[$i][0] = "empty"; 
      $SaveCleanPar[$i][1] = "empty"; 
      $SaveCleanPar[$i][2] = "empty"; 
      $SaveCleanPar[$i][3] = "empty"; 
      $SaveCleanPar[$i][4] = $elems[0]; 
   } 
   $i += 1;
}
$no = $i;         ##  Modified number of strings

#++#####   Test printout of modified massif
#++print ERR  "Strings = $no\n\n";   
#++for ($j = 2; $j < $no; $j++)  {
#++   print ERR "$SaveCleanPar[$j][4]\n";
#++}
close (ADD);
################################unlink($addlabs);

##++++++##------##print TST "\n\n    A F T E R   P A S S  7      Hyperlinks        \n\n";
##++++++##------##for ($i = 0; $i < $no; $i++)  {
##++++++##------##    print TST "$i  <<>>  $SaveCleanPar[$i][3] <<>> $SaveCleanPar[$i][4]\n"; 
##++++++##------##}   

###open (ITEMS, ">items.tmp")  ||  die "Cannot open  items.tmp  file.";

###############################################################################
##        PASS 9:  Extracting floats, footnotes and in-text tabulars         ##
###############################################################################
print "done\nPASS  9: Extracting floats, footnotes and in-text tabulars. . . . ";

##  In this fragment we compose image containing files.
##  The following steps should be passed:
##  1. Extract figure-containing subparagraphs from splitted to semantical
##     initial TeX file and put them  into separate temporary files fitmpNN.html
##  2. Check if temporary files contain no more than three strings with the 
##     second one containing basic parameters of figure file, i.e. \caption width,
##     \setimage params, and caption text.  All these parameters are extracted for
##     being used in the next step.
##  3. Basic recommendation for preparation graphix files requests that along with
##     version of images necessary for translation TeX file to PDF, versions of
##     these files reduced to the screen resolution (maybe with the factor of 3,
##     or less for electronic books) should appear in the current directory, as
##     well as corresponding thumbnail images.
##  4. The following rule of naming these images is as follows:
##     <paperid>-fNN.png   -  for the basic (PDF) version
##     <paperid>-oNN.png   -  for the HTML version,  jpg or gif also acceptable
##     <paperid>-thNN.png  -  thumbnail images for HTML version,  jpg or gif also acceptable
##  5. In case when -o- or -th- images are absent they are generated by the script
##     using ImageMagick program.

$inifloat = 0;          ##  0 - means that current(previous) string was not marked as float

@intabaccum = ();
$intabcount = 0;            ## in-text \tabular counter
$tabulxy = 0;               ## shows if in-text tabular is open

####################################################################################################################$savehold = "";
##++++++##------##    print TST "\n\n                 BEFORE   PASS 9           \n\n";

for ($i = 0; $i < $no; $i++)  {
    $_ = $SaveCleanPar[$i][4];
    s/\\fitclose//g;
    s/\\fitopen\{.+\}//g;
    
    s/\\begin\{minipage\}\{20pc\}//g;       ##      Removing minipage environment
    s/\\end\{minipage\}//g;    
    
    s/---/\&\#x2014\;/g;
    s/--/\&\#x2013\;/g;

    s/\`\`/\"/g;
    s/\'\'/\"/g;
    s/<it>/<i>/g;
    s/<\/it>/<\/i>/g;
    
##      Substitutions Unicode for Russian fragments

    if (/\\selectlanguage\{russian\}/)  {
        $lanpos = index($_, "\\selectlanguage\{russian\}", 0) + 24;
        if ($lanpos >= 0)  {
            &FindMatchBracket($_, $lanpos, 1);
            $lenlang = $nepar - $lanpos - 1; 
            print ERR "\n============ lanpos = $lanpos     lenlang = $lenlang\n";
            $llll = substr($_, 0, $lanpos - 24);
            $rrrr = substr($_, $nepar+1);
            $mmmm = substr($_, $lanpos+1, $lenlang);
            @arrchars = split(//, $mmmm);
            $numarr = @arrchars;
            for ($cr = 0; $cr < $numarr; $cr++)  {
                for ($cl = 0; $cl < $icyr; $cl++)  {
                    if ($arrchars[$cr] eq $ruslist[0][$cl])  {
                        $arrchars[$cr] = $ruslist[1][$cl];
                    }
                }
            }
            $mmmm = join("", @arrchars); 
            $modline = $llll.$mmmm.$rrrr;
            $_ = $modline; 
            print ERR "$modline\n\n";
        }
    } 
    ##++++##____##print TST "$SaveCleanPar[$i][3]    ===    $_\n";

###     F I G U R E S  

    if ($SaveCleanPar[$i][3] =~ /type=\"figure\"/  && $_ =~ /\\begin\{figure/)  {   ##  start figure
        $inifloat = 1;
        $figcount += 1;
        if ($figcount < 10) {
            $fnumstr = "fitmp0".$figcount;
        }  else {
            $fnumstr = "fitmp".$figcount;
        }
        $curfloatname = $fnumstr."\.html";
###########################        print ERR "CURRENT FLOAT = $curfloatname\n";
        open (FLOAT, ">$curfloatname")  ||  die  "Cannot open $curfloatname file.";
        print FLOAT "$_\n";
        $_ = "";
    }  elsif ($SaveCleanPar[$i][3] =~ /type=\"figure\"/  && $inifloat == 1)  {   ##  continued figure
        print FLOAT "$_\n";
        if  ($_ =~ /\\end\{figure/)  {   ##  end figure
            $_ = "";
            $inifloat = 0;
            close(FLOAT);
        } else {
            $_ = "";
        }
    }  
###print ERR "\n\n F I G U R E S  =  $figcount\n";

###     T A B L E S  
    if ($SaveCleanPar[$i][3] =~ /type=\"table\"/  && $_ =~ /\\begin\{table/)  {   ##  start table
        $savehold = "";
        $inifloat = 1;
        $tabcount += 1;
        if ($tabcount < 10) {
            $tnumstr = "tab0".$tabcount;
        }  else {
            $tnumstr = "tab".$tabcount;
        }
        $curfloatname = $tnumstr."\.tex";
        open (FLOAT, ">$curfloatname")  ||  die  "Cannot open $curfloatname file.";
        s/\[linebreak\]/ \\\\ /g;
        print FLOAT "$_\n";
        #==#print ITEMS "\n\n\nF0->$_\n";
        $_ = "";
    }  elsif  ($SaveCleanPar[$i][3] =~ /type=\"table\"/  && $_ =~ /\\end\{table/)  {   ##  end table
        s/\[linebreak\]/ \\\\ /g;
        print FLOAT "$_\n";
        #==#print ITEMS "F1->$_\n";
        $_ = "";
        $savehold = "";
        $inifloat = 0;
        
######        print ERR "\nInside table: inifloat = $inifloat\n\n"; 
        
        close(FLOAT);
        
##      Printout for verification===============================================================        
        open (FLO, "<$curfloatname")  ||  die  "Cannot open $curfloatname file.";
        #==#print ITEMS "\ncurfloatname = $curfloatname\n\n";
        while (<FLO>)  {
            #==#print ITEMS "===$_";
        }
##  The next branch replaces \tabularx with \tabular  and removes extra \tabularx's parameter
    }  elsif (($SaveCleanPar[$i][3] =~ /type=\"table\"/  ||  $SaveCleanPar[$i][3] =~ /type=\"tabularx/) && $inifloat == 1)  {   ##  continued table
        if (/\\begin\{tabularx\}/  ||  /\\end\{tabularx\}/)  {
            s/\\begin\{tabularx\}/\\begin\{tabular\}/;
            s/\\end\{tabularx\}/\\end\{tabular\}/;
            s/\[linebreak\]/ \\\\ /g;
            print FLOAT "$_\n";
        #==#print ITEMS "F2->$_\n";
            $_ = "";
        }  else  {
            $ccb = index($_, "\}", 0);
            if (/^\{/  &&  $ccb > 3  &&  $ccb < 8)  {
                $correctedstring = substr($_, $ccb+1);
                $_ = $correctedstring;
                #==#print ITEMS "CCB = $ccb ======$correctedstring\n";
            }  
            s/\[linebreak\]/ \\\\ /g;
            if (/caption\{/)  {
               $caposini = index($_, "caption\{", 0) + 7;
               &FindMatchBracket($_, $caposini, 1); 
               ##########################print ERR "$_\n$caposini  $nepar\n"; 
               $tcaplen = $nepar - $caposini - 1;
               $curcaptab = substr($_, $caposini+1, $tcaplen);
               ##########################print ERR "$curcaptab\n\n"; 
               $tabparams[$tabcount-1][8] = $curcaptab;           
            }
            
            #==#print ITEMS "\nAFTER CAPTION  $_\n\n";
            
            print FLOAT "$_\n";
        #==#print ITEMS "F3->$_\n";
            $_ = "";
        }
    }  elsif (($SaveCleanPar[$i][3] =~ /type=\"table\"/  ||  $SaveCleanPar[$i][3] =~ /type=\"tabular/) && $inifloat == 1)  {   ##  continued table
        if ($SaveCleanPar[$i][4] =~ /caption\{/)  {
#############            print ERR "CCCC====  $_\n";
        }
        s/\[linebreak\]/ \\\\ /g;
        print FLOAT "$_\n";
        #==#print ITEMS "F4->$_\n";
        $_ = "";
###        $_ = $savehold;
    }  
###print ERR       "\n\n T A B L E S  =  $tabcount\n";

###     IN-TEXT  T A B U L A R S 
 
    if ($SaveCleanPar[$i][3] =~ /type=\"tabular/  && $_ =~ /\\begin\{tabular/  &&  $inifloat == 0)  {   ##  start in-text tabular
        $htmltabul = "";
        $tabulxy = 1;        
        $_ = "<table  class=\"gridtable\">";
        $SaveCleanPar[$i][4] = $_;
        $intabaccum[$intabcount][0] = $_;
    } elsif ($inifloat == 0 && $tabulxy == 1 && /\\end\{tabular/) {  ##      save end tabular
        $tabulxy = 0;
        $_ = "<\/table>";
        $SaveCleanPar[$i][4] = $_;
    } elsif ($inifloat == 0 && $tabulxy == 1) {     ##      save tabular string
        $intabaccum[$intabcount][1] = $_;
        &ConvIntextTabul($intabaccum[$intabcount][1]);
        $_ = $htmltabul;
        $SaveCleanPar[$i][4] = $_;
    }

##       Extracting footnotes                          F O O T N O T E S   ====================================
## Note!  Each of the reference files can be called from more than one spot, while 
## every footnote file has one link to it in opposite to multiple links to reference files. 

   if (/\\footnote/)  {
      s/\\footnote +\{/\\footnote\{/g;
      $footstr = 0;
      while (/\\footnote/)  {
         $footpos = index($_, "\\footnote", $footstr);
         if ($footpos < 0)  {
            goto FOOT;
         }
         $footins = $footpos + 9;
         &FindMatchBracket($_, $footins, 1);
         $foleft = substr($_, 0, $footpos);
         $foright = substr($_, $nepar+1);
         $footlen = $nepar - $footpos;
         $fomiddle = substr($_, $footpos, $footlen);
         $fosource = $fomiddle;
         $fosource =~ s/\\footnote\{//;
         ########print ERR "FOSOURCE = $fosource\n";
         $footlist[$footcount] = $fosource;
         $footcount += 1;
         $numfrag = "";
         if ($footcount < 10)  {
            $numfrag = "0".$footcount;
         }  else  {
            $numfrag = "".$footcount; 
         }
##       Creating footnote file and writing current footnote to it.
         $footfile = $reflistdir."\/foot".$numfrag."\.html";
         $footdivcur = "divfoot".$numfrag;
         $footifrcur = "foot".$numfrag;
         open (FOOT, ">$footfile")  ||  die "Cannot open   $footfile  file.";
         print FOOT "<body bgcolor=\"\#eeeeee\"><a href=\"javascript\: window.parent.showlayer(\'$footdivcur\')\"><img src=\"cross.gif\" style=\"float\:right\; width\:17px\; height\:15px\"   alt=\"Close\" title=\"Close\" width=\"17\" height=\"15\"  \/><\/a><font face=\"Verdana\" size=\"-1\">".$fosource."<\/font><\/body>\n";
         close (FOOT);
##       Creating DIV element for the current footnote         
         
         $fodivs[$footcount-1] = "<div id=\"".$footdivcur."\" style=\"padding\:0\;position\:absolute\;top\:400px\;left\:145px\;display\:none\;background-color\:\#eeeeee\;opacity\:0.9\;\">";
         $fodivs[$footcount-1] .= "<iframe id=\"".$footifrcur."\" frameborder=\"1\" scrolling=\"yes\" src=\"".$footfile."\" width=\"450\" height=\"75\"><\/iframe><\/div>";         
                 
         $newmiddle = "<a href=\"".$reflistdir."\/foot".$numfrag."\" title=\"Click on for more info\" alt=\"Click on for more info\"  onClick=\"javascript\:showlayer(\'divfoot".$numfrag."\');return false;\"><sup><b><font color=\"\#A52A00\">\[$footcount\]<\/font><\/b><\/sup><\/a> ";
         $modline = $foleft.$newmiddle.$foright; 

         $_ = $modline;        
         $footstr += 10;
      }
FOOT:
   }
####        Writing strings after extracting floats, etc.

    $SaveCleanPar[$i][4] = $_;
    
    ####print ERR "Line = $i:    $_\n";
    
}
##      Composing citation line
$doilink = $regtitle[$journumb][5]."\/".$paperid;
$citation = "<b>$citname:<\/b> ".$authcitrev." (20".$jouryear."), ".$articletitle.", <i>".$regtitle[$journumb][2].", ".$jourvol."<\/i>, ".$citatnumb.", doi\:<a href=\"http\:\/\/dx.doi.org\/".$doilink."\">".$doilink."<\/a>";
$citationnourl = "$citname: ".$authcitrev." (20".$jouryear."), ".$articletitle.", ".$regtitle[$journumb][2].", ".$jourvol.", ".$citatnumb.", doi\:".$doilink."\.";

###///////////////////////////////////////////////////////////////////print ERR "\n\n$citation\n\n";

##  HTML headers  and FOOTERS for files
@header = (
"<\!DOCTYPE html>",
"<html>",
"<head>",
"<title>$currentfig<\/title>",
"    <script type=\"text/x-mathjax-config\">",
"    MathJax.Hub.Config({tex2jax: {inlineMath: [['\$','\$'], ['\\\\(','\\\\)']]\}\})\;",
"</script>",
"<script type=\"text/javascript\"",
"     src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full\">",
"<\/script>",
"<link rel=\"stylesheet\" type=\"text/css\" href=\"css/elx-online.css\" \/>",
"<meta name=\"title\" content=\"$artitcr\" \/>",
"<meta name=\"authors\" content=\"$authcitrev\" \/>",
"<meta name=\"first-author\" content=\"$fauthcitrev\" \/>",
"<meta name=\"journal\" content=\"$regtitle[$journumb][1]\" \/>",
"<meta name=\"doi\" content=\"$doiindex\" \/>",
"<meta name=\"paper-number\" content=\"$paperid\" \/>",
"<meta name=\"paper-type\" content=\"Article\" \/>",
"<meta name=\"publisher\" content=\"$regtitle[$journumb][6]\" \/>",
"<meta name=\"citation\" content=\"$citationnourl\" />",
"<meta name=\"copyright\" content=\"Copyright $cpryear by the  $regtitle[$journumb][3]\" \/>",
"<meta name=\"published-online\" content=\"$published\" \/>",
"<meta name=\"html-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/index.html\" \/>",
"<meta name=\"abstract-url\" content=\"$regtitle[$regcode][11]abstract\/$jourvol\/$paperid-abs.html\" \/>",
"<meta name=\"pdf-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/$paperid.pdf\" \/>",
"<meta name=\"gcmd-terms\" content=\"$gcmdterms\" \/>",
"<meta name=\"agu-terms\" content=\"$aguterms\" \/>",
"<meta name=\"keywords\" content=\"$keywords\" \/>",
"<\/head>",
"<body>");

@footer = (
"<hr class=\"short\" \/>",
"<p>",
"<a href=\"http\:\/\/elpub\.wdcb\.ru\/journals\/rjes\"><img class=\"logo\" src=\"images\/rjesCitationLogo.jpg\" alt=\"RJES\"\/><\/a>      \&\#x2003\;\&\#x2003\;\&\#x2003\;\&\#x2003\;\&\#x2003;   <a href=\"http:\/\/www.mathjax.org\/\"> <img title=\"Powered by MathJax\" src=\"images\/mathjax-badge.jpg\"  alt=\"Powered by MathJax\" \/><\/a>",
"<\/p>",
"<p class=\"citat\">\&\#x2003\;<br \/>$citation.<br \/>\&\#x2003\;<\/p>",
"<p id=\"copyright\"><a href=\"http:\/\/elpub.wdcb.ru\/journals\/rjes\/copyright.html\">Copyright  $cpryear  by the  $regtitle[$journumb][3].<\/a><\/p>",
"<hr \/><span class=\"texweb\">Generated from LaTeX source by <a href=\"http\:\/\/eos\.wdcb\.ru\/tools\/2.0\/elxfinal_2.0.zip\">ELXfinal, $vernumb<\/a> software package.<\/span>",
"<\/td><\/tr><\/table>");

##      Creating $headerline   and   $footerline
$headerline = $header[0];
$footerlinefig = $footer[0];
$footerlinetab = $footer[0];

for ($hd = 1; $hd < @header; $hd++)  {
    $headerline .= "\n".$header[$hd];
}
for ($ft = 1; $ft < @footer; $ft++)  {
    $footerlinefig .= "\n".$footer[$ft];
}
$footerlinefig .= "<\/body><\/html>\n";
for ($ft = 1; $ft < @footer-1; $ft++)  {
    $footerlinetab .= "\n".$footer[$ft];
}
$footerlinetab .= "<\/body><\/html>\n";
$footerlinefig =~ s/\~/\&\#xA0\;/g;
$footerlinefig =~ s/---/--/g;
$footerlinefig =~ s/--/\&\#x2013\;/g;
$footerlinetab =~ s/\~/\&\#xA0\;/g;
$footerlinetab =~ s/---/--/g;
$footerlinetab =~ s/--/\&\#x2013\;/g;


#########         Preparing data to figure files         #########

##  $figparams[][] - two-dimensional array for accumulating initial and generated parameters

for ($ifg = 0; $ifg < $figcount; $ifg++)  {
    $fcount = $ifg + 1;
    if ($fcount < 10) {
        $fnumstr = "fitmp0".$fcount;
    }  else {
        $fnumstr = "fitmp".$fcount;
    }
    $curfigname = $fnumstr."\.html";
    $figparams[$ifg][0] = $curfigname;           ##  Name of figure file
    $figfinal = $curfigname;
    $figfinal =~ s/fitmp/-fig/;
    $figfinal = $paperid.$figfinal;
    $figparams[$ifg][1] = $figfinal;             ##  Final name of figure file

    open (FIG, "<$curfigname")  ||  die "Cannot open $curfigname file.";
    $fstrings = 0;
    while (<FIG>)  {
        ###print ERR "++++++++++++++++++++$_";
        chop();
        $curfigure[$fstrings] = $_;
        $fstrings += 1;
    }
    close(FIG);
    if ($fstrings != 3)  {
        print ERR "Extra strings in $curfigname = $fstrings\n";
        $errcount += 1;
    }

    #######################print ERR "\n$curfigure[1]\n";

    $scanstr = 0;
    $wdpos = index($curfigure[1], "\\figurewidth", $scanstr);        ##      Looking for figurewidth
    ###################print ERR "wdpos = $wdpos\n";
    if ($wdpos < 0)  {
    }  else  {
        $wdpos += 12;
        &FindMatchBracket($curfigure[1], $wdpos, 1);
        $lenca = $nepar - $wdpos - 1;
        $fcapwid = substr($curfigure[1], $wdpos + 1, $lenca);        ##      Caption width parameter
        #####################print ERR "capwid = |$fcapwid|\n";
        $scanstr = $nepar;
        $figparams[$ifg][2] = $fcapwid;                             ##  Caption width
    }
    $wdpos = index($curfigure[1], "\\setimage", $scanstr);           ##      Looking for setimage
    ########################print ERR "wdpos = $wdpos\n";
    if ($wdpos < 0)  {
    }  else  {
        $wdpos += 9;
        &FindMatchBracket($curfigure[1], $wdpos, 5);
        $lenca = $nepar - $wdpos - 1;
        $setimline = substr($curfigure[1], $wdpos + 1, $lenca);            ##      Setimage string
        ###########################print ERR "setimline = $setimline\n";
        $scanstr = $nepar;
        @parimg = split(/\}\{/, $setimline);      ##  1 - h-shift, 2 - v-shift, 3 - width, 4 - height, 5 - image name
        $lensim = @parimg;
        if ($lensim != 5)  {
            print ERR "Wrong structure of the \setimage  command in the figure $curfigname\n";
            $errcount += 1;
        }
        ###print ERR "lensim = $lensim\n";
        ####################################################print ERR ">>$parimg[0]<<>>$parimg[1]<<>>$parimg[2]<<>>$parimg[3]<<>>$parimg[4]<<\n";
        $figparams[$ifg][3] = $parimg[0];                             ##  Image h-shift
        $figparams[$ifg][4] = $parimg[1];                             ##  Image v-shift
        $figparams[$ifg][5] = $parimg[2];                             ##  Image width
        $figparams[$ifg][6] = $parimg[3];                             ##  Image height
        $figparams[$ifg][7] = $parimg[4];                             ##  Image file name
    }
    $wdpos = index($curfigure[1], "caption\{", $scanstr);              ##  Looking for caption
    #####################print ERR "wdpos = $wdpos\n";
    if ($wdpos < 0)  {
    }  else  {
        $wdpos += 7;
        &FindMatchBracket($curfigure[1], $wdpos, 1);
        $lenca = $nepar - $wdpos - 1;
        $fcaption = substr($curfigure[1], $wdpos + 1, $lenca);         ##  Caption string
        ############################print ERR "capwid = |$fcaption|\n";
        $scanstr = $nepar;
        $figparams[$ifg][8] = $fcaption;                              ##  Figure caption
    }
    $imgname = $parimg[4]."\.png";
    if (-e $imgname)  {                 ##  Checking existence of basic image
        &ImageParams($imgname);
        $figparams[$ifg][9] = $sizes[0];                              ##  Basic image width
        $figparams[$ifg][10] = $sizes[1];                              ##  Basic image height
    }  else  {
        print ERR "There is no image for figure $fcount\n";
        $errcount += 1;
        goto OUTER;
    }
    #########################################################################################################print ERR "width = $sizes[0]     height = $sizes[1]\n";
    $ratio = $sizes[0] / $sizes[1];
    #########################################################################################################print ERR "thumb = $thumb    ratio = $ratio\n";
    $thumb = $imgname;
    $thumb =~ s/-f/-th/;
    $dispim = $imgname;
    $dispim =~ s/-f/-o/;
    $figparams[$ifg][11] = $dispim;
    if (-e $dispim)  {                  ##  Checking existence of screen image
        &ImageParams($dispim);
        $figparams[$ifg][12] = $sizes[0];                              ##  Screen image width
        $figparams[$ifg][13] = $sizes[1];                              ##  Screen image height
    }  else  {                          ##  Creating screen image
        if ($ratio > 1)  {              ##  Portrait
            $scwd = 800;
            $scht = $scwd / $ratio;
            if ($scht >600)  {
                $scht = 600;
                $scwd = $scht * $ratio;
            }
        }  else  {                      ##  Landscape
            $scht = 600;
            $scwd = $scht * $ratio;
            if ($scwd > 800)  {
                $scwd = 800;
                $scht = $scwd / $ratio;
            }
        }
        $ratone = int(($scwd / $sizes[0]) * 100);
        $comline = $imagick."convert ".$imgname." -resize ".$ratone."\% ".$dispim;
        system $comline;
        &ImageParams($dispim);
        $figparams[$ifg][12] = $sizes[0];                              ##  Screen image width
        $figparams[$ifg][13] = $sizes[1];                              ##  Screen image height
    }
    $figparams[$ifg][14] = $thumb;
    if (-e $thumb)  {                   ##  Checking existence of thumbnail image
        &ImageParams($thumb);
        $figparams[$ifg][15] = $sizes[0];                              ##  Thumb image width
        $figparams[$ifg][16] = $sizes[1];                              ##  Thumb image height
    }  else  {                          ##  Creating thumbnail image
        if ($ratio > 1)  {              ##  Portrait
            $thwd = 100;
            $thht = $thwd / $ratio;
        }  else  {                      ##  Landscape
            $thht = 100;
            $thwd = $thht * $ratio;
        }
        $rattwo = int(($thwd / $sizes[0]) * 100);
        $comline = $imagick."convert ".$imgname." -resize ".$rattwo."\% ".$thumb;
        system $comline;
        &ImageParams($thumb);
        $figparams[$ifg][15] = $sizes[0];                              ##  Thumb image width
        $figparams[$ifg][16] = $sizes[1];                              ##  Thumb image height
    }

##  FIGPARAMS  content

    for ($ijk = 0; $ijk <= 16; $ijk++)  {
        ###############################################################################################print ERR "$ijk     $figparams[$ifg][$ijk]\n";
    }

##  Writing figure file
    $currentfig = $figparams[$ifg][1];
    $figtitle = $currentfig;
    $figtitle =~ s/\.html//;
    $headerlinemod = $headerline;
    $headerlinemod =~ s/<title><\/title>/<title>$figtitle<\/title>/;   
    open (FIG, ">$currentfig")  ||  die  "Cannot open  $currentfig  file.";
    print FIG "$headerlinemod\n";
    $fcaption =~ s/~/\&\#xA0\;/g;
    $fcaption =~ s/---/\&\#x2014\;/g;
    $fcaption =~ s/--/\&\#x2013\;/g;
##      Temporary substitutions --> will be replaced later with CSS///////////////////////////////////////////////////////////
    $fcaption =~ s/<it>/<i>/g;
    $fcaption =~ s/<\/it>/<\/i>/g;
    $fcaption =~ s/<bf>/<b>/g;
    $fcaption =~ s/<\/bf>/<\/b>/g;

     ###################################   F I G U R E     C O N T E N T S   ###################################

##    Correction to hyperlink in captions    

    $linsuffix = "<a href=\"\#";
    $linkfull = "<a href=\"".$paperid."\.html\#";
    $fcaption =~ s/$linsuffix/$linkfull/g;
   
    print FIG <<EOM;
<table><tr><td>
<p class=\"ident\">$identline<\/p><hr class=\"short\" \/>
<img src=\"images\/$figparams[$ifg][11]\" \/>       
<p>
<b>$figtypename $fcount.<\/b>   $fcaption
<\/p>
EOM
    print FIG "$footerlinefig\n";
    close (FIG);
    unlink($curfigname);
}           ##              End of writing figure files

#################################################################
##         Preparing data to table files          ###############

unlink("errors.tmp");       ##      Cleaning file for ta2ht.pl errors

##  $tabparams[][] - two-dimensional array for accumulating initial and generated parameters

for ($itg = 0; $itg < $tabcount; $itg++)  {
    $tcount = $itg + 1;

##print "\n  Table branch\n";

    if (tcount < 10) {
        $tnumstr = "tab0".$tcount;
    }  else {
        $tnumstr = "tab".$tcount;
    }
    $curtabname = $tnumstr."\.tex";
    $tabparams[$itg][0] = $curtabname;           ##  Name of table file
    $tabfinal = $curtabname;
    $tabfinal =~ s/tab/-tab/;
    $tabfinal = $paperid.$tabfinal;
    $tabfinal =~ s/\.tex/\.html/;
    $tabparams[$itg][1] = $tabfinal;             ##  Final name of table file

    ########print ERR "FROM ta2ht.pl <--\n";  
    
    &formHtmlTable($curtabname, $tabfinal, $tcount);   ##       Converts TeX table to HTML table
      
##################++++++++++++++++++++++++++    unlink($curtabname);  

####################################print ERR "TABLE  $itg  CAPTION = $tabparams[$itg][8]\n";

    $interim = "ini-".$tnumstr."\.tmp";

##      Replacing ident line and adding tail fragment

    open (INI, "<$tabfinal")  ||  die  "Cannot open  $tabfinal file.";
    open (TAB, ">$interim")   ||  die  "Cannot open  $interim file.";
    $startheadlab = 0;
##  Ajusting headerline
    $tabtitle = $tabfinal;
    $tabtitle =~ s/\.html//; 
    $headerlinemod = $headerline;
    $headerlinemod =~ s/<title><\/title>/<title>$tabtitle<\/title>/;   
    print TAB "$headerlinemod\n";

    #==#print ITEMS "\n\nReading table initial set\n\n";

    while (<INI>)  {
       
    #==#print ITEMS $_;
        
        chop();
        s/<CENTER>PUT HERE RUNNING HEAD<\/CENTER><HR>/<p class=\"ident\">$identline<\/p><hr class=\"short\" \/>/;
        s/~/\&\#xA0\;/g;
        s/--/\&\#x2013\;/g;
        ##s/\\deg ?/\&\#xB0\;/g;
        ##  Only for non-math fragments     s/\\\%/\$\\\%\$/g;
        ##     Removing extra align inserted by  ta2ht.pl  programme   NOTE!!!   REWRITE TA2HT.PL!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        s/<td align=\"left\">/<td>/g;
        s/<td align=\"center\">/<td>/g;        
        s/<td align=\"right\">/<td>/g; 
        s/\\hfill//g;             
        
        if (/^<body>/) {
            $startheadlab = 1;
        }   elsif ($startheadlab == 1)  {

            if (/\(VERBLINE/)  {   ##      Replacing verbatim data
                &verbReplace($_);
                $_ = $modifstring;
            }

##      Temporary substitutions --> will be replaced later with CSS///////////////////////////////////////////////////////////
            s/<it>/<i>/g;
            s/<\/it>/<\/i>/g;
            s/<bf>/<b>/g;
            s/<\/bf>/<\/b>/g;
            
##      Setting full hypertink into table data             
            if (/<a href=\"\#/)  {
               $linsuffix = "<a href=\"\#";
               $linkfull = "<a href=\"".$paperid."\.html\#";
               s/$linsuffix/$linkfull/g; 
            }          
            if (/colspan/)  {        ###        Removing extra braces in table footnotes    
            ##    s/\{//g;
            ##    s/\}//g;
                s/\\footnotesize//;             ##      Check and correct this removing
                s/\\baselineskip=//;            
            }
            print TAB "$_\n";
        }
    }
    print TAB "$footerlinetab\n";
    close (INI);
    close (TAB);
    unlink ($tabfinal);
    rename ($interim, $tabfinal);
}   ##              End of writing table files

##++++++##------##print TST "\n\nB E F O R E     P A S S   9   H T M L  \n\n\n";

###############################################################################
##        PASS 10:  Converting to HTML format                                 ##
###############################################################################
print "done\nPASS 10: Converting to HTML format. . . . . . . . . . . . . . . . ";

$ssslab = 0;
$sssnext = 0;
##      Here we define a type of dynamic TOC list (with or without bullets)
$idyt = 0;
$dyntoc[$idyt] = "<div id=\"button\" style=\"position:fixed\;top:10px\;right:50px\;\">\n";
$idyt += 1;
$dyntoc[$idyt] = "<form name=\"Form\">\n";
$idyt += 1;
$dyntoc[$idyt] = "<input id=\"togbut\" type=\"button\"  value=\"Show\/Hide TOC\"  onclick=\"javascript:showlayer(\'toc\')\;return false\;\" \/>\n";
$idyt += 1;
$dyntoc[$idyt] = "<\/form><\/div>\n";
$idyt += 1;

$dyntoc[$idyt] = "<div id=\"dyn_toc\" style=\"position:fixed\;top:40px\;right:5px\;width:200px\;\">";
$idyt += 1;
$dyntoc[$idyt] = "<div id=\"toc\" style=\"visibility:visible\">";
$idyt += 1;
$dyntoc[$idyt] = "<div id=\"nav\" style=\"font-size:12px\;font-family:Arial,Helvetica,sans-serif\;background-color:\#eeeeee\;opacity:0.85\;padding:5px\;border:2px solid gray\;\">";
$idyt += 1;

$bullet = 1;
for ($cl = 0; $cl < $conlin-1; $cl++)  {
    if ($contents[1][$cl] =~ /^\d/)  {
        $bullet = 0;
        goto BULLET;
    }
}
BULLET:
#########################print ERR "\nbullet = $bullet\n";
for ($cl = 1; $cl < $conlin-1; $cl++)  {
    $tostr = "";
    if ($bullet == 0)  {
        ###$tostr .= "\&\#x2003\;";
        if ($contents[0][$cl] eq "ssect") {
            $tostr .= "\&\#x2003\;";
        }
        if ($contents[0][$cl] eq "sssect") {
            $tostr .= "\&\#x2003\;\&\#x2003\;";
       }
    }  else  {
        if ($contents[0][$cl] eq "ssect") {        
            $tostr .= "\&\#x2003\;\&\#x25CB\;\&\#x2003\;";
        }  elsif ($contents[0][$cl] eq "sssect") {
            $tostr .= "\&\#x2003\;\&\#x2003\;\&\#xD7\;\&\#x2003\;";  
        }  else {
            $tostr .= "\&\#x25CF\;\&\#x2003\;";  
        }
    }      
    $tocline = $contents[1][$cl];
    $tlinlen = length($tocline);
    if ($tlinlen > 40)  {
        $pobl = index($tocline, " ", 35);
        $subline = substr($tocline, 0, $pobl);
        $subline .= "...";
    }  else  {
        $subline = $tocline;
    }  
    $dyntoc[$idyt] = $tostr."<a href=\"".$paperid.".html\#".$contents[2][$cl]."\">".$subline."<\/a><br \/>";
    $idyt += 1;
}

$dyntoc[$idyt] = " <br \/>";
$idyt += 1;
if ($figcnt > 0)  {
    if ($bullet == 0)  {
        $dyntoc[$idyt] = "<a href=\"".$paperid."-figures.html\" target=\"_new\"><span class=\"ref\">$figsname<\/span><\/a><br \/>";
    }  else  {
        $dyntoc[$idyt] = "\&\#x25CF\;\&\#x2003\;<a href=\"".$paperid."-figures.html\" target=\"_new\"><span class=\"ref\">$figsname<\/span><\/a><br \/>";     
    }
}    
$idyt += 1;
if ($tabcnt > 0)  {
    if ($bullet == 0)  {
        $dyntoc[$idyt] = "<a href=\"".$paperid."-tables.html\" target=\"_new\"><span class=\"ref\">$tabsname<\/span><\/a><br \/>";
    }  else  {
        $dyntoc[$idyt] = "\&\#x25CF\;\&\#x2003\;<a href=\"".$paperid."-tables.html\" target=\"_new\"><span class=\"ref\">$tabsname<\/span><\/a><br \/>";    
    }
}     
$idyt += 1; 
if ($bullet == 0)  {
    $dyntoc[$idyt] = "<a href=\"".$paperid."-map.html\" target=\"_new\"><span class=\"ref\">$artmapname<\/span><\/a><br \/>";
}  else  {
    $dyntoc[$idyt] = "\&\#x25CF\;\&\#x2003\;<a href=\"".$paperid."-map.html\" target=\"_new\"><span class=\"ref\">$artmapname<\/span><\/a><br \/>";    
} 
$idyt += 1;  
$dyntoc[$idyt] = "<\/div><\/div><\/div>";  
$idyt += 1;  
 
for ($menu = 0; $menu < $idyt; $menu++)  {
    ##################################################print ERR "$dyntoc[$menu] \n";
} 
###================================================= Dynamic TOC composed ====================================

###      A C C U M U L A T I N G     H T M L   R O O T   F I L E 

open (HTML, ">$fulldoc")  ||  die  "Cannot open $fulldoc file.";

print HTML <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>$paperid</title>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config(\{tex2jax: \{inlineMath: \[\[\'\$\',\'\$\'\], \[\'\\\\(\',\'\\\\)\'\]\]\}\});
</script>
<script type="text/javascript"
     src="http\:\/\/cdn.mathjax.org\/mathjax\/latest\/MathJax.js\?config=TeX-AMS-MML_HTMLorMML-full">
</script>
<script type="text/javascript">
function OpenWinAlt(item1,item2,ww,hh) {
	winfea ="toolbar=no,scrollbars=yes,location=no,directories=no,status=no,menubar=no,resizable=yes,width="+ww+",height="+hh;
   	msgWindow=window.open(item1,item2,winfea);
}
</script>

<script language="JavaScript" type="text/javascript">
<!-- Hide from old browsers
var winWidth;
window.onload = init;
function init() {
   winWidth = document.body.clientWidth;
   if (window.Event) {
      document.captureEvents(Event.MOUSEMOVE);
   }
   document.onmousemove = getCursorXY;
}
var xpos;
var ypos;
var field;
function getCursorXY(e) {
	xpos = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	ypos = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}

var namfil;
function showlayer(layer){
   var myLayer = document.getElementById(layer).style.display;
   var winWidth = document.body.clientWidth;
   if(myLayer=="none"){
      if (winWidth <= 450)  {
         xpos = 0;
      }  else if (winWidth >= 450 && winWidth < xpos + 450)  {
         xpos = winWidth - 456;
      }
      document.getElementById(layer).style.top=ypos;
      document.getElementById(layer).style.left=xpos;
      document.getElementById(layer).style.display="block";
   } else {
      document.getElementById(layer).style.display="none";
   }
}
//End of hiding -->
</script>

<link rel=\"stylesheet\" type=\"text\/css\" href=\"css/elx-online.css\" \/>

<meta name=\"title\" content=\"$artitcr\" \/>
<meta name=\"authors\" content=\"$authcitrev\" \/>
<meta name=\"first-author\" content=\"$fauthcitrev\" \/>
<meta name=\"journal\" content=\"$regtitle[$journumb][1]\" \/>
<meta name=\"doi\" content=\"$doiindex\" \/>
<meta name=\"paper-number\" content=\"$paperid\" \/>
<meta name=\"paper-type\" content=\"Article\" \/>
<meta name=\"publisher\" content=\"$regtitle[$journumb][6]\" \/>
<meta name=\"citation\" content=\"$citationnourl\" />
<meta name=\"copyright\" content=\"Copyright $cpryear by the  $regtitle[$journumb][3]\" \/>
<meta name=\"published-online\" content=\"$published\" \/>
<meta name=\"html-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/index.html\" \/>
<meta name=\"abstract-url\" content=\"$regtitle[$regcode][11]abstract\/$jourvol\/$paperid-abs.html\" \/>
<meta name=\"pdf-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/$paperid.pdf\" \/>
<meta name=\"gcmd-terms\" content=\"$gcmdterms\" \/>
<meta name=\"agu-terms\" content=\"$aguterms\" \/>
<meta name=\"keywords\" content=\"$keywords\" \/>
</head>
<body>

<!-- Start of dynamics menu -->

EOM

for ($menu = 0; $menu < $idyt; $menu++)  {
    print HTML "$dyntoc[$menu] \n";
} 
print HTML "\n<!-- End of dynamics menu -->\n\n";
print HTML "<p class=\"ident\">$identline<\/p><hr \/>\n";

######============================######print ERR "$citation \n";

$openssstit = 0;
$subsub = 0;
$subnext = 0;
$laboldel = 0;          ##      Marker for list with continuation ...
$listopen = 0;
$mergedlist = "";
for ($i = 0; $i < $no; $i++)  {             ##------------------->>  Start STEP 9  HTMLSTEP 9  STEP 9  STEP 9  STEP 9  STEP 9  STEP 9  
    $_ = $SaveCleanPar[$i][4];
    
    print ITEMS "===$_\n"; 
    
##  Restoring VERBATIMs and VERBs
    if (/\[VERBDISP/)  {
        @elmes = split(/\[VERBDISP-/, $_);
        @numes = split(/\]/, $elmes[1]);
        $curnumdisp = $numes[0];
        ###print "\nNUM =  $curnumdisp\n";
        $insverdis = $verbdisp[$curnumdisp];
        $insverdis =~ s/</\&\#x3C\;/g;      ##  <
        $insverdis =~ s/>/\&\#x3E\;/g;      ##  >
        $insverdis =~ s/\\begin\{verbatim\}\|=\|/<p><span class=\"verb\">/;
        $insverdis =~ s/\|=\|\\end\{verbatim\}/<\/span><br \/><\/p>/;
        $insverdis =~ s/\|=\|/<\/span><br \/><span  class=\"verb\">/g;
        ###print ERR "\n\nINSVERDIS = $insverdis\n\n";
        $_ = $insverdis;
    }
    if (/\(VERBLINE/)  {        ##  Restoring inline verbatims
        &verbReplace($_);
        $_ = $modifstring;
    }
########print ITEMS "\n$_\n";

    if (/\\begin\{itemize\}/ || /\\begin\{enumerate\}/)  {
        $listopen += 1;
        $mergedlist .= $_;
        ########print ITEMS "$_\n$mergedlist\n";
        $_ = "";
    } elsif (/\[item\]/)  {
        $mergedlist .= $_;
        ########print ITEMS "$_\n$mergedlist\n";
        $_ = "";

    } elsif (/\\end\{itemize\}/ || /\\end\{enumerate\}/)  {
        $listopen -= 1;
        $mergedlist .= $_;
        ########print ITEMS "$_\n$mergedlist\n";
        if ($listopen == 0)  {
            $_ = "";
        } else  {
            $_ = "";
        }
    } 
    if ($listopen <= 0 && $mergedlist ne "")  {
        ####$_ = "";
        ########print ITEMS ">>$_\n>>MERGEDLIST =  $mergedlist\n\n";
        ####$_ = $mergedlist;
        $meraccum = $mergedlist; 
########    print ITEMS "$meraccum\n";
        $meraccum =~ s/\\begin\{itemize\}/\[itemizeopen\]/g;
        $meraccum =~ s/\\begin\{enumerate\}/\[enumerateopen\]/g;        
        $meraccum =~ s/\\end\{itemize\}/\[itemizeclose\]/g;
        $meraccum =~ s/\\end\{enumerate\}/\[enumerateclose\]/g;    
        $meraccum =~ s/\[item\]/\[enditem\]\[item\]/g;        
        $meraccum =~ s/\[enumerateclose\]/\[enumerateclose\]\[enditem\]/g;
        $meraccum =~ s/\[itemizeclose\]/\[itemizeclose\]\[enditem\]/g;
##    Removing double tags
        $meraccum =~ s/\[itemizeopen\]\[enditem\]\[item\]/\[itemizeopen\]\[item\]/g;
        $meraccum =~ s/\[enumerateopen\]\[enditem\]\[item\]/\[enumerateopen\]\[item\]/g;
        $meraccum =~ s/\[itemizeclose\]\[enditem\]/\[enditem\]\[itemizeclose\]\[enditem\]/g;
        $meraccum =~ s/\[enumerateclose\]\[enditem\]/\[enditem\]\[enumerateclose\]\[enditem\]/g;
        $meraccum =~ s/\[enditem\]\[enditem\]/\[enditem\]/g;
###########################
########   print ITEMS "---$meraccum\n";        
        $meraccum =~ s/\[item\]/\<li\>/g;
        $meraccum =~ s/\[enditem\]/\<\/li\>/g;        
        $meraccum =~ s/\[itemizeopen\]/\<ul\>/g;        
        $meraccum =~ s/\[itemizeclose\]/\<\/ul\>/g;        
        $meraccum =~ s/\[enumerateopen\]/\<ol\>/g;        
        $meraccum =~ s/\[enumerateclose\]/\<\/ol\>/g;                
        $meraccum =~ s/\<\/li\>$//;  
##          Removing extra paragraph tags
        $meraccum =~ s/\<p\>//g;
        $meraccum =~ s/\<\/p\>//g;
        $meraccum =~ s/ +/ /g;        
############################
########   print ITEMS "===$meraccum\n";
        $_ = $meraccum;          ##    Replacing current record with the correct list string
#############print ITEMS "====----====$_\n";
        $mergedlist = "";
    }       

    if ($SaveCleanPar[$i][3]=~/type=\"abstr\"/ && /^(<p class=\"abs\">)/)  { 
        $parmarcount += 1;
        if ($parmarker eq true) {
            $paba = "<span class=\"parnumb\">\[$parmarcount\]<\/span> ";
        }  else  {
            $paba = "";
        }
        s/<p class=\"abs\">/<p class=\"abs\">$paba/;
    }
    if (/\\mpar/)  {
        $parmarcount += 1;
        s/\\mpar/<span class=\"parnumb\">\[$parmarcount\]<\/span> /;
    }
    $SaveCleanPar[$i][4] = $_;              
#####print TST "$_\n";
    @lstfin = ();
    if ($SaveCleanPar[$i][3]=~/type=\"math\"/  && /\&/)  {
 ###     s/\&/\&amp\;/g;
    } 
    if ($SaveCleanPar[$i][3]=~/type=\"math\"/  && /\[linebreak\]/)  { 
       s/\[linebreak\]/ \\\\ /g;
    }
###    print TST "$_\n";            ##   Before processing lists=========================================
    s/\~/\&\#xA0\;/g;
    s/---/\&\#x2014\;/g;
    s/--/\&\#x2013\;/g;
####################################################################    s/\\noindent ?//;
    s/\[linebreak\]/ \\\\ /g;
    ####s/\[dollar\]/\$\\\$\$/g;
    s/\[ampersand\]/\&amp\;/g;
    s/\[permil\]/\&\#x2030\;/g;
    if ($SaveCleanPar[$i][3]=~/type=\"math\"/  && /\[percent\]/)  {
        s/\[percent\]/\\\% /g;    
    }     
##      Removing TeX style formatting commands
    s/\\def\\topfraction\{.+\}//;
    s/\\def\\dbltopfraction\{.+\}//;
    s/\\def\\bottomfraction\{.+\}//;
    s/\\def\\textfraction\{.+\}//;
    s/\\appendix//;
    s/\`\`/\"/g;
    s/\'\'/\"/g;
    s/\\AA/\&\#xC5\;/g;
    s/\\aa/\&\#xE5\;/g;
    s/\\AE/\&\#xC6\;/g;
    s/\\ae/\&\#xE6\;/g;
    s/<it>/<i>/g;
    s/<\/it>/<\/i>/g;
 
###  LISTBREAK  ========================================###=====================================================================###=======================================================

##      Temporary substitutions --> will be replaced later with CSS///////////////////////////////////////////////////////////

    s/<it>/<i>/g;
    s/<\/it>/<\/i>/g;
    s/<bf>/<b>/g;
    s/<\/bf>/<\/b>/g;
    s/\\latex/LaTeX/g;
    s/<li> ?\\noindent ?<\/li>//g;
    s/\\noindent//g;                ##       Check later to prevent extra paragraph
    
###    s/\\\\//g;
###   print TST "$_\n";
###      Removing <parbox> and </parbox>  in tabular environments
        if (/<tr><td colspan=.+><parbox>/)  {
            s/\<parbox\>//g;
            s/\<\/parbox\>//g;
        }

##    Adding thumbnails to html file

    $phmark = 0;

#####################################################################################

    if (/figparsplaceholder/  || /tabparsplaceholder/)  {
        $modplholder = $_;
#####print ERR "MPLHOL-0 = $modplholder\n";   #########################################<<<<---######################################
        $phmark = 1;
        $phstr = 0;
        while ($modplholder =~ /figparsplaceholder/)  {
            $fphpos = index($modplholder, "figparsplaceholder", $phstr);
#####print ERR "fphpos = $fphpos\n";
            if ($phstr < 0)  {
                goto HOLDFIG;
            }  else  {
                $hdleft = substr($modplholder, 0, $fphpos);
                $hdmiddle = substr($modplholder, $fphpos, 22);
                $hdright = substr($modplholder, $fphpos+22);
                $fiexnum = substr($modplholder, $fphpos+18, 4);
            #######print ERR "fiexnum-1 = $fiexnum\n";
                $fiexalp = $fiexnum;
                $fiexalp =~ s/\[//;
                $fiexalp =~ s/\]//;
            ######print ERR "fiexnum-2 = $fiexalp\n";
                $fiexnum =~ s/\]//;
                $fiexnum =~ s/\[0//;
                $fiexnum =~ s/\[//;
                $fiexnum *= 1;
                $curthumb = $figparams[$fiexnum-1][7]."\.png";
                $curthumb =~ s/-f/-th/;
            ######print ERR "fiexnum-3 = $fiexnum        curthumb = $curthumb\n";
                $subsmiddle = "<a href=\"".$paperid."-fig".$fiexalp."\.html\" title=\"Call Figure\&\#xA0\;".$fiexnum." into new window\"  onClick=\"OpenWinAlt(\'".$paperid."-fig".$fiexalp."\.html\', \'win".$fiexalp."\', ".$ww.", ".$hh.")\; return false\;\"><table class=\"icon\"><tr><td><img src=\"images\/$curthumb\" alt=\"Fig $fiexnum\" \/><\/td><\/tr><tr><td><b>$figtypename  $fiexnum<\/b><\/td><\/tr><\/table><\/a>";

                $modplholder = $hdleft.$subsmiddle.$hdright;
######print ERR "MPLHOL-1 = $modplholder\n";
            }
            $phstr += 17;
        }
HOLDFIG;
         $_ = $modplholder;

        $phtab = 0;
        while (/tabparsplaceholder/)  {
            $tphpos = index($_, "tabparsplaceholder", $phtab);
            if ($phtab < 0)  {
                goto HOLDTAB;
            }  else  {
                $hdleft = substr($_, 0, $tphpos);
                $hdmiddle = substr($_, $tphpos, 22);
                $hdright = substr($_, $tphpos+22);
                $fiexnum = substr($_, $tphpos+18, 4);
                $fiexalp = $fiexnum;
                $fiexalp =~ s/\[//;
                $fiexalp =~ s/\]//;
                $fiexnum =~ s/\]//;
                $fiexnum =~ s/\[0//;
                $fiexnum =~ s/\[//;
                $fiexnum *= 1;
                $curthtab = $tabparams[$fiexnum-1][14];
                $subsmiddle = "<a href=\"".$paperid."-tab".$fiexalp."\.html\" title=\"Call Table\&\#xA0\;".$fiexnum." into new window\" onClick=\"OpenWinAlt(\'".$paperid."-tab".$fiexalp."\.html\', \'win".$fiexalp."\', ".$ww.", ".$hh.")\; return false\;\"> <table class=\"icon\"><tr><td><img src=\"images\/$curthtab\" alt=\"Table $fiexnum\" \/><\/td><\/tr><tr><td><b>Table  $fiexnum<\/b><\/td><\/tr><\/table><\/a>";
                $_ = $hdleft.$subsmiddle.$hdright;
            }
            $phtab += 17;
        }
HOLDTAB;
    }

##  Marking-up quotes  ==========================================================================

    if(/<parbox>\{/)  {
        ########print ERR "PARBOX $_\n";
        ##  Removing TeX font commands
        s/<parbox>\{//;
        @elpars = split(/ /, $_);
        ########print ERR "ELPARS-1 = @elpars\n";
        ########print ERR "elpars = $elpars[0] || $elpars[1] || $elpars[2] || $elpars[3]\n";
        $elpars[1] = "";
        ########print ERR "ELPARS-2 = @elpars\n";
        $corparline = join(" ", @elpars);
        $_ = "<p class=\"quote\">".$corparline;
        ###s/<parbox>\{/<p class="quote">/;
        ########print ERR "CORBOX $_\n";
        s/^ +//;
    }
    if(/\}<\/parbox>/)  {
        s/\}<\/parbox>/<\/p>/;
        ########print ERR "CORBOX $_\n";
    }
##  =============================================================================================    
  
    $SaveCleanPar[$i][4] = $_;
    
    ####print ERR "$_\n";   ##############################################################################################################################################
    
####print ITEMS "==(())==$_\n";
########################print ERR "----$SaveCleanPar[$i][3]--------$_\n";

##    Checking if paragraph's opening and closing tags are exist

    s/^ +//;
    if (length{$_} > 0)  {
        if ($SaveCleanPar[$i][3] =~ /type=\"hidden\"/  ||
            $SaveCleanPar[$i][3] =~ /type=\"figure\"/  ||
            $SaveCleanPar[$i][3] =~ /type=\"table\"/)  {
        }  elsif ($SaveCleanPar[$i][3] =~ /type=\"math\"/  ||
            $SaveCleanPar[$i][3] =~ /type=\"items\"/  ||
            $SaveCleanPar[$i][3] =~ /type=\"sect\"/  ||  
            $SaveCleanPar[$i][3] =~ /type=\"ssect\"/)  { 
##      Removing extra and double backslash 
            s/\\TeX/TeX/g;
            s/\\LaTeX/LaTeX/g;
            s/\\latex/LaTeX2<sub>e<\/sub>/g;
            s/\\elxfinal/<b><i>ELXfinal<\/i><\/b>/g;
            s/\\TeX nician/TeXnician/g;
            s/\\\\//g;            
            if (/\&/)  {    ##      Replacing & with &amp;
                @setofchars = split(//, $_);
                $chnum = @setofchars;
                for ($ca = 0; $ca < $chnum; $ca++)  {
                    if ($setofchars[$ca] eq "\&" && $setofchars[$ca+1] ne "\#" && $setofchars[$ca+2] ne "x")  { ##  Current char does not open UTF
                        $setofchars[$ca] =~ s/\&/\&amp\;/;
                    }
                }
                $modline = join("", @setofchars);
                $modline =~ s/\&amp\;lt\;/\&lt\;/g;
                $modline =~ s/\&amp\;gt\;/\&gt\;/g;                
                $_ = $modline;
            }
           
            print HTML "$_\n"; 
            
print ITEMS "HTML-1=$_\n";
                      
        }  elsif ($SaveCleanPar[$i][3] =~ /type=\"sssect\"/)  {         ##      for replacing  \subsubsection{}
            $SaveCleanPar[$i][4] = $_;
            $parmarcount += 1;
            if ($parmarker eq true) {
                $pabb = "<span class=\"parnumb\">\[$parmarcount\]<\/span> ";
            }  else  {
                $pabb = "";
            }
            s/<\/h5>/<\/span>/;
            s/<h5>/<p>$pabb <span class="ssstit">/;
            $subsub = $i;
            $ssslab = 1;
            $subnext = 1;

            if (/^<p>/ && /<span class=\"ssstit\"><a accesskey=\"sect/)  {      ##  This string starts subsubsection fragment
                ###print ERR "SSSSSSSS-1 = $openssstit\n";
                $openssstit = 1;
                ###print ERR "SSSSSSSS-2 = $openssstit\n";
            }
            print HTML "$_\n";

####print ERR ":::$_\n";            
####print ITEMS "HTML-2=$_\n";
                      
        }  else  {     ##    Controlled strings (paragraphs)
            if (/<p>/ || /<p class/ || /<h1>/ || /<h2>/ || /<h3>/ || /<h4>/ || /^(<table)/ || /^(<tr><td)/ || /^(<\/table>)/ || /<ul>/ || /<ol>/)  {

            } elsif (($phmark == 1) && ($openssstit == 0))  {        ##    Seting  <p>  after placeholders

                ##############################################print ERR "---$_\n";

                if (/<\/b><\/td><\/tr><\/table><\/a>/)  {
                    $parpos = 0;
                    while ($parpos >= 0)  {
                        $ipar = index($_, "<\/b><\/td><\/tr><\/table><\/a>", $parpos);
                        if ($ipar > 0)  {
                            $parpos = $ipar + 26;
                        }  else  {
                            goto PARA;
                        }
                    }
                }  else  {
                    print ERR "No placeholder strings occured for phmark label in record $i \n $_\n";
                    $errcount += 1;
                }
PARA:
                $leftplhold = substr($_, 0, $parpos);
                $rightplhold = substr($_, $parpos+1);
                $_ = $leftplhold." <p> ".$rightplhold;
##############################################print ERR "\n++++$_\n\n";
            }  else  {
                ####print ERR "+++$_\n";
                if ($subsub > 0) {
                    $subsub = 0;
                    ####################$_ = "<p> ".$_;
                } else  {       ####  Removed  29/01/16
                    $_ = "<p> ".$_;
                }
            }
            if (/<\/p>/ || /<\/h1>/ || /<\/h2>/ || /<\/h3>/ || /<\/h4>/ || /^(<table)/ || /^(<tr><td)/ || /^(<\/table>)/ || /<\/ul>/ || /<\/ol>/ || $_ eq "")  {
            } else  {
                $_ .= "<\/p>";
            }
##################################################################################print ERR "\n>>>>$_\n\n";
##          Removing extra and double backslash 
            s/\\TeX/TeX/g;
            s/\\LaTeX/LaTeX/g;
            s/\\latex/LaTeX2<sub>e<\/sub>/g;
            s/\\elxfinal/<b><i>ELXfinal<\/i><\/b>/g;
            s/\\TeX nician/TeXnician/g;
            s/\\\\//g;

            if (/\&/)  {        ##  Replacing & with &amp;
                @setofchars = split(//, $_);
                $chnum = @setofchars;
                for ($ca = 0; $ca < $chnum; $ca++)  {
                    if ($setofchars[$ca] eq "\&" && $setofchars[$ca+1] ne "\#" && $setofchars[$ca+2] ne "x")  { ##  Current char does not open UTF
                        $setofchars[$ca] =~ s/\&/\&amp\;/;
                    }
                }
                $modline = join("", @setofchars);
                $modline =~ s/\&amp\;lt\;/\&lt\;/g;
                $modline =~ s/\&amp\;gt\;/\&gt\;/g;       
                $_ = $modline;
            }

            ####print ERR "...$_\n";   ######################################################################################################################

            print HTML "$_\n";
        
            print ITEMS "$_\n\n";
        }
    }

    ##      Extracting modified abstract            A B S T R A C T  
    if ($SaveCleanPar[$i][3] =~ /type=\"abstr\"/ && /<p class=\"abs\">/)  {
        $modabstract = $_;
###    print ITEMS "\n\nABS = $modabstract\n\n";
    }
}

print HTML <<EOM;
<hr />
<p class="dates">$receivname $received;  $acceptname  $accepted;  $publishname  $published.<\/p>
<hr class=\"short\" \/>
<a href=\"http\:\/\/elpub\.wdcb\.ru\/journals\/rjes\"><img class=\"logo\" src=\"images\/rjesCitationLogo.jpg\" alt=\"RJES\"\/><\/a>      \&\#x2003\;\&\#x2003\;\&\#x2003\;\&\#x2003\;\&\#x2003;   <a href=\"http:\/\/www.mathjax.org\/\"> <img title=\"Powered by MathJax\" src=\"images\/mathjax-badge.jpg\"  alt=\"Powered by MathJax\" \/><\/a> <br \/>
<p class="citat">\&\#x2003\;<br \/>
$citation.<br \/>\&\#x2003\;<\/p>
<p id=\"copyright\"><a href=\"http:\/\/elpub.wdcb.ru\/journals\/rjes\/copyright.html\">Copyright  $cpryear  by the  $regtitle[$journumb][3].<\/a><\/p>
<hr \/><span class=\"texweb\">Generated from LaTeX source by <a href=\"http\:\/\/eos\.wdcb\.ru\/tools\/2.0\/elxfinal_2.0.zip\">ELXfinal, $vernumb<\/a> software package.<\/span>
EOM

print HTML "<p><!-- Fragment for DIVs --><\/p>\n";

for ($zz = 0; $zz < $iref; $zz++)  {         ##    DIVs for references
   print HTML "$divs[$zz]\n";
}
for ($yy = 0; $yy < $footcount; $yy++)  {         ##    DIVs for footnotes
   print HTML "$fodivs[$yy]\n";
}

########print ERR "\n===========  C O N T E N T S   -->  \$contents\[0\]\[\$cl\]  array   ==============\n\n";      #####################################

for ($cl = 0; $cl < $conlin; $cl++)  {                                                                      #####################################
########    print ERR "$contents[0][$cl]  ||  $contents[1][$cl]  ||  $contents[2][$cl]  ||  $contents[3][$cl]\n";   #####################################
}                                                                                                           #####################################

#######  print ERR "TOTAL:  authors = $authnum    affiliations = $affinum \n";

for ($au = 0; $au < $authnum; $au++)  {
    @autitem = split(/\}\{/, $authors[$au]);
    $aulen = @autitem;
##==##    print ERR "$authors[$au]   [$aulen]    @autitem\n";
}
for ($af = 0; $af < $affinum; $af++)  {
    @affitem = split(/\}\{/, $affils[$af]);
    $aflen = @affitem;
##==##    print ERR "$affils[$af]   [$aflen]    @affitem\n";
}

##==##print ERR "\n===========  C O N T E N T S     E N D  -->  \$contents\[0\]\[\$cl\]  array   ==============\n\n";

################+++++++++++++++ Opening browser +++++++++++++++++++++++++++++++++++++++++++++##
   ####$comline = $browser_path." ".$fulldoc."\n";     ##    Loads $fulldoc into default browser ##
   ####print ERR "COMLINE + $comline\n";                                                     ##
   ####system $comline;                                                                          ##
###############################################################################################


###############################################################################
##        PASS 11:  Creating ancillary files (toc, map, figs, tabs)          ##
###############################################################################
print "done\nPASS 11: Creating ancillary files (toc, map, figs, tabs). . . . . ";


##############################  A B S T R A C T   ##############################
##    The following substitutions should be centralized on step 5  

$abstract =~ s/\~/\&\#xA0\;/g;
$abstract =~ s/---/\&\#x2014\;/g;
$abstract =~ s/--/\&\#x2013\;/g;
$abstract =~ s/<it>/<i>/g;
$abstract =~ s/<\/it>/<\/i>/g;

open (ABS, ">$absalone")  ||  die "Cannot open $absalone  file.";

print ABS <<EOM;
$headerline
<p class=\"ident\">$identline<\/p><hr class=\"short\" \/>
<h1>$contents[1][0]<\/h1> 
<p class=\"auth\"><b><i>$authcitdir<\/i><\/b><\/p>
<h3>$absname<\/h3>
$modabstract
<p class="dates">$receivname $received;  $acceptname  $accepted;  $publishname  $published.<\/p>
$footerlinetab
EOM
print HTML <<EOM;
</body>
</html>
EOM
close (HTML);
close (ABS);

print ERR "\n\n$abstract\n\n";

######################  C O R R E C T I O N   B L O C K  #############################

open (HTML, "<$fulldoc")  ||  die  "Cannot open $fulldoc file.";
$htmlines = 0;
@prehtml = ();
while (<HTML>)  {
   chop();
   $prehtml[$htmlines] = $_;
   $htmlines += 1;
}
close (HTML);

unlink ($fulldoc);

$martit = 0;
$extratitlab = 0;

open (HTML, ">$fulldoc")  ||  die  "Cannot open $fulldoc file.";

for ($ist = 0; $ist < $htmlines; $ist++)  {

   $_ = $prehtml[$ist];
   s/ +/ /g;
   

   if (/^<p>/ && /span class=\"ssstit\"><a accesskey=\"sect/ && /<\/span>$/)  {        ## subsubsection  stands alone

      $savebuf = $_;
      $martit = $ist;
      $nextit = $martit+1;
############      print ERR "S A V E = savebuf = $savebuf\nmartit = $martit\nnextit = $nextit\n";
   }
   if (/^<p>/ && (/Call Figure/ || /Call Table/) && /<\/b><\/td><\/tr><\/table><\/a>/)  {     ## Figure/Table in paragraph
      s/<p>//;
      s/<\/b><\/td><\/tr><\/table><\/a>/<\/b><\/td><\/tr><\/table><\/a> <p>/;
###############      print ERR ">>>>>$_\n";  ########################################
      print HTML "$_\n";
   }  elsif ((/Call Figure/ || /Call Table/) && /<\/b><\/td><\/tr><\/table><\/a>/)  {     ## Figure/Table in titled paragraph
##############      print ERR ">>>>>$_\n";  ########################################
      @frags = split(/<\/b><\/td><\/tr><\/table><\/a>/, $_);
      $lenfra = @frags;
#############      print ERR "\nNUMBER = $lenfra\n\n";   ###############################################################
      $leftfrag = "";
      for ($lf = 0; $lf < $lenfra; $lf++)  {
         if ($lf < $lenfra - 1)  { 
            $leftfrag .= $frags[$lf]."<\/b><\/td><\/tr><\/table><\/a>";
         } elsif ($lf == $lenfra - 1)  {
            $leftfrag .= $savebuf." ".$frags[$lf];
         }
      }
###      print ERR "--->>---$leftfrag\n";  ##################################################################
      print HTML "$leftfrag\n";
   }  else {
      if ((/span class=\"ssstit\"><a accesskey=\"sect/ && /<\/span>/)  && ($prehtml[$ist+1] =~ /<\/b><\/td><\/tr><\/table><\/a>/))  {
      }  else  {
######         print ERR "$_\n";
         print HTML "$_\n";
      }
   }
} 

##############################  F I G U R E S   ##############################
#####print ERR   "FIGCOUNT = $figcount\nTABCOUNT = $tabcount \n";

if ($figcount > 0)  {      ##    Creating  figures.html  file
   open (FIG, ">$figsfile")  ||  die "Cannot open $figsfile file.";
   print FIG <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>$paperid - $figsname</title>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config(\{tex2jax: \{inlineMath: \[\[\'\$\',\'\$\'\], \[\'\\\\(\',\'\\\\)\'\]\]\}\});
</script>
<script type="text/javascript"
     src="http\:\/\/cdn.mathjax.org\/mathjax\/latest\/MathJax.js\?config=TeX-AMS-MML_HTMLorMML-full">
</script>
<script type="text/javascript">
function OpenWinAlt(item1,item2,ww,hh) {
	winfea ="toolbar=no,scrollbars=yes,location=no,directories=no,status=no,menubar=no,resizable=yes,width="+ww+",height="+hh;
   	msgWindow=window.open(item1,item2,winfea);
}
</script>
<link rel=\"stylesheet\" type=\"text\/css\" href=\"css\/elx-online.css\" \/>
<meta name=\"title\" content=\"$artitcr\" \/>
<meta name=\"authors\" content=\"$authcitrev\" \/>
<meta name=\"first-author\" content=\"$fauthcitrev\" \/>
<meta name=\"journal\" content=\"$regtitle[$journumb][1]\" \/>
<meta name=\"doi\" content=\"$doiindex\" \/>
<meta name=\"paper-number\" content=\"$paperid\" \/>
<meta name=\"paper-type\" content=\"Article\" \/>
<meta name=\"publisher\" content=\"$regtitle[$journumb][6]\" \/>
<meta name=\"citation\" content=\"$citationnourl\" />
<meta name=\"copyright\" content=\"Copyright $cpryear by the  $regtitle[$journumb][3]\" \/>
<meta name=\"published-online\" content=\"$published\" \/>
<meta name=\"html-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/index.html\" \/>
<meta name=\"abstract-url\" content=\"$regtitle[$regcode][11]abstract\/$jourvol\/$paperid-abs.html\" \/>
<meta name=\"pdf-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/$paperid.pdf\" \/>
<meta name=\"gcmd-terms\" content=\"$gcmdterms\" \/>
<meta name=\"agu-terms\" content=\"$aguterms\" \/>
<meta name=\"keywords\" content=\"$keywords\" \/>
</head>
<body>
<p class=\"ident\">$identline<\/p><hr class=\"short\" \/>
<h3>$figsname\&\#x2003\;\&\#x2003\;\&\#x2003\;\&\#x2003\;<span class=\"link\">[Click on image to zoom]<\/span><\/h3>
<table class=\"list\"><tr>
EOM

$fitagroup = $figstabs[$figcount];
    for ($ifig = 0; $ifig < $figcount; $ifig++)  {
        $figi = $ifig + 1;
        if ($figi < 10)  {
            $figa = "0".$figi;
        }  else  {
            $figa = $figi;
        }
        $ww = $figparams[$ifig][12] + 50;
        $hh = $figparams[$ifig][13] + 50;
        print FIG <<EOM;   
<td>
<a href=\"$paperid-fig$figa.html\"  onClick=\"OpenWinAlt(\'$paperid-fig$figa.html\', \'winfig$figa\', $ww, $hh)\; return false\;\"><img src=\"images\/$paperidsm-th$figa.png\" title=\"Click on image to zoom\" width=\"$figparams[$ifig][15]\" height=\"$figparams[$ifig][16]\"  \/><\/a>
<br \/>$figtypename  $figi
<\/td>
EOM
        $endrow = $figi - int($figi / $fitagroup) * $fitagroup;
        if ($endrow == 0)  {
            print FIG "<\/tr><tr>\n";
            print FIG "<td colspan= \"$fitagroup\"><hr \/><\/td><\/tr><tr>\n";
        }
    }
    print FIG <<EOM;
<\/tr><\/table>
$footerlinetab
EOM

########print ERR "footerlinetab = $footerlinetab\n";

close (FIG);
}

##############################  T A B L E S   ##############################

if ($tabcount > 0)  {      ##    Creating  tables.html  file
   open (TAB, ">$tabsfile")  ||  die "Cannot open $tabsfile file.";
   print TAB <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>$paperid - $tabsname</title>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config(\{tex2jax: \{inlineMath: \[\[\'\$\',\'\$\'\], \[\'\\\\(\',\'\\\\)\'\]\]\}\});
</script>
<script type="text/javascript"
     src="http\:\/\/cdn.mathjax.org\/mathjax\/latest\/MathJax.js\?config=TeX-AMS-MML_HTMLorMML-full">
</script>
<script type="text/javascript">
function OpenWinAlt(item1,item2,ww,hh) {
	winfea ="toolbar=no,scrollbars=yes,location=no,directories=no,status=no,menubar=no,resizable=yes,width="+ww+",height="+hh;
   	msgWindow=window.open(item1,item2,winfea);
}
</script>
<link rel=\"stylesheet\" type=\"text\/css\" href=\"css\/elx-online.css\" \/>
<meta name=\"title\" content=\"$articletitle\" \/>
<meta name=\"authors\" content=\"$authcitrev\" \/>
<meta name=\"first-author\" content=\"$fauthcitrev\" \/>
<meta name=\"journal\" content=\"$regtitle[$journumb][1]\" \/>
<meta name=\"doi\" content=\"$doiindex\" \/>
<meta name=\"paper-number\" content=\"$paperid\" \/>
<meta name=\"paper-type\" content=\"Article\" \/>
<meta name=\"publisher\" content=\"$regtitle[$journumb][6]\" \/>
<meta name=\"citation\" content=\"$citationnourl\" />
<meta name=\"copyright\" content=\"Copyright $cpryear by the  $regtitle[$journumb][3]\" \/>
<meta name=\"published-online\" content=\"$published\" \/>
<meta name=\"html-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/index.html\" \/>
<meta name=\"abstract-url\" content=\"$regtitle[$regcode][11]abstract\/$jourvol\/$paperid-abs.html\" \/>
<meta name=\"pdf-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/$paperid.pdf\" \/>
<meta name=\"gcmd-terms\" content=\"$gcmdterms\" \/>
<meta name=\"agu-terms\" content=\"$aguterms\" \/>
<meta name=\"keywords\" content=\"$keywords\" \/>
</head>
<body>
<p class=\"ident\">$identline<\/p><hr class=\"short\" \/>
<h3>$tabsname\&\#x2003\;\&\#x2003\;\&\#x2003\;\&\#x2003\;<span class=\"link\">[Click on image to zoom]<\/span><\/h3>
<table class=\"list\"><tr>
EOM

$fitagroup = $figstabs[$tabcount];
   for ($itab = 0; $itab < $tabcount; $itab++)  {
      $tabi = $itab + 1;
      if ($tabi < 10)  {
         $taba = "0".$tabi;
      }  else  {
         $taba = $tabi;
      }
      $ww = $tabparams[$itab][12] + 50;
      $hh = $tabparams[$itab][13] + 50;
      print TAB <<EOM;   
<td>
<a href=\"$paperid-tab$taba.html\"  onClick=\"OpenWinAlt(\'$paperid-tab$taba.html\', \'wintab$taba\', $ww, $hh)\; return false\;\"><img src=\"images\/$tabparams[$itab][14]\" title=\"Click on image to zoom\" width=\"$tabparams[$itab][15]\" height=\"$tabparams[$itab][16]\"  \/><\/a>
<br \/>Table  $tabi
<\/td>
EOM
        $endrow = $tabi - int($tabi / $fitagroup) * $fitagroup;
        if ($endrow == 0)  {
            print TAB "<\/tr><tr>\n";
            print TAB "<td colspan= \"$fitagroup\"><hr \/><\/td><\/tr><tr>\n";
        }
    }
   print TAB <<EOM;
<\/tr><\/table>
$footerlinetab
EOM
close (FIG);
}

##############################  C O N T E N T S   ##############################

open (CON, ">$connam")  ||  die "Cannot open $connam  file.";
print CON <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>$paperid</title>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config(\{tex2jax: \{inlineMath: \[\[\'\$\',\'\$\'\], \[\'\\\\(\',\'\\\\)\'\]\]\}\});
</script>
<script type="text/javascript"
     src="http\:\/\/cdn.mathjax.org\/mathjax\/latest\/MathJax.js\?config=TeX-AMS-MML_HTMLorMML-full">
</script>
<link rel=\"stylesheet\" type=\"text\/css\" href=\"css\/elx-online.css\" \/>
<meta name=\"title\" content=\"$artitcr\" \/>
<meta name=\"authors\" content=\"$authcitrev\" \/>
<meta name=\"first-author\" content=\"$fauthcitrev\" \/>
<meta name=\"journal\" content=\"$regtitle[$journumb][1]\" \/>
<meta name=\"doi\" content=\"$doiindex\" \/>
<meta name=\"paper-number\" content=\"$paperid\" \/>
<meta name=\"paper-type\" content=\"Article\" \/>
<meta name=\"publisher\" content=\"$regtitle[$journumb][6]\" \/>
<meta name=\"citation\" content=\"$citationnourl\" />
<meta name=\"copyright\" content=\"Copyright $cpryear by the  $regtitle[$journumb][3]\" \/>
<meta name=\"published-online\" content=\"$published\" \/>
<meta name=\"html-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/index.html\" \/>
<meta name=\"abstract-url\" content=\"$regtitle[$regcode][11]abstract\/$jourvol\/$paperid-abs.html\" \/>
<meta name=\"pdf-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/$paperid.pdf\" \/>
<meta name=\"gcmd-terms\" content=\"$gcmdterms\" \/>
<meta name=\"agu-terms\" content=\"$aguterms\" \/>
<meta name=\"keywords\" content=\"$keywords\" \/>
</head>
<body>
<p class=\"ident\">$identline<\/p><hr class=\"short\" \/>
<h3>$contname<\/h3>
EOM

#######################  A R T I C L E     M A P     ##########################

open (MAP, ">$mapnam")  ||  die "Cannot open $mapnam  file.";
print MAP <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>$paperid</title>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config(\{tex2jax: \{inlineMath: \[\[\'\$\',\'\$\'\], \[\'\\\\(\',\'\\\\)\'\]\]\}\});
</script>
<script type="text/javascript"
     src="http\:\/\/cdn.mathjax.org\/mathjax\/latest\/MathJax.js\?config=TeX-AMS-MML_HTMLorMML-full">
</script>
<link rel=\"stylesheet\" type=\"text\/css\" href=\"css\/elx-online.css\" \/>
<meta name=\"title\" content=\"$articletitle\" \/>
<meta name=\"authors\" content=\"$authcitrev\" \/>
<meta name=\"first-author\" content=\"$fauthcitrev\" \/>
<meta name=\"journal\" content=\"$regtitle[$journumb][1]\" \/>
<meta name=\"doi\" content=\"$doiindex\" \/>
<meta name=\"paper-number\" content=\"$paperid\" \/>
<meta name=\"paper-type\" content=\"Article\" \/>
<meta name=\"publisher\" content=\"$regtitle[$journumb][6]\" \/>
<meta name=\"citation\" content=\"$citationnourl\" />
<meta name=\"copyright\" content=\"Copyright $cpryear by the  $regtitle[$journumb][3]\" \/>
<meta name=\"published-online\" content=\"$published\" \/>
<meta name=\"html-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/index.html\" \/>
<meta name=\"abstract-url\" content=\"$regtitle[$regcode][11]abstract\/$jourvol\/$paperid-abs.html\" \/>
<meta name=\"pdf-url\" content=\"$regtitle[$regcode][11]$jourvol\/$paperid\/$paperid.pdf\" \/>
<meta name=\"gcmd-terms\" content=\"$gcmdterms\" \/>
<meta name=\"agu-terms\" content=\"$aguterms\" \/>
<meta name=\"keywords\" content=\"$keywords\" \/>
</head>
<body>
<p class=\"ident\">$identline<\/p><hr class=\"short\" \/>
<h3>$artmapname<\/h3>
EOM

$switchlab = $contents[3][0];
for ($nc = 0; $nc < $conlin-1; $nc++)  {

    if ($contents[3][$nc] == 5)  {      ##      This blocks content items of level 5 (subsubsections)
    }  else  {
########print ERR "M A P:   contents[3][$nc] =  $contents[3][$nc]   ===   switchlab = $switchlab<br \/>\n"; 
        $contents[1][$nc] =~ s/\~/\&\#xA0\;/g;
        $contents[1][$nc] =~ s/--/\&\#x2013\;/g;
        $contents[1][$nc] =~ s/---/\&\#x2014\;/g;
        if ($nc == 0)  {        ##       Title string
            print CON "<a href=\"$fulldoc\#$contents[2][$nc]\"><h1>$contents[1][$nc]<\/h1><\/a>\n";
            print MAP "<a href=\"$fulldoc\#$contents[2][$nc]\"><h1>$contents[1][$nc]<\/h1><\/a>\n";
        }  else  {
            if ($contents[3][$nc] > $switchlab)  {
                if (($contents[3][$nc] - $switchlab) > 1  &&  $nc > 1)  {
                    print CON "<ul><ul><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";
                    print MAP "<ul><ul><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";          
                } else {
                    print CON "<ul><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";
                    print MAP "<ul><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n"; 
                }
                $switchlab = $contents[3][$nc];
            } elsif ($contents[3][$nc] < $switchlab)  { 
                if (($switchlab - $contents[3][$nc]) > 1)  {
                    print CON "<\/li><\/ul><\/li><\/ul><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";
                    print MAP "<\/li><\/ul><\/li><\/ul><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n"; 
                } else {
                    print CON "<\/li><\/ul><\/li><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";
                    print MAP "<\/li><\/ul><\/li><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";
                } 
                $switchlab = $contents[3][$nc];
            }  else {
                print CON "<\/li><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";
                print MAP "<\/li><li><a href=\"$fulldoc\#$contents[2][$nc]\">$contents[1][$nc]<\/a>\n";       
            }
        }
    }
}
print CON "<\/li><\/ul>\n";
print MAP "<\/li><\/ul>\n";

if ($figcount > 0)  {
   print CON "<a href=\"$paperid-figures.html\" target=\"_new\"><h5>$figsname<\/h5><\/a>\n";
   print MAP "<a href=\"$paperid-figures.html\" target=\"_new\"><h5>$figsname<\/h5><\/a>\n<ul>\n";
   for ($fff = 0; $fff < $figcount; $fff++)  {
      $numcur = $fff + 1;
      $figparams[$fff][8] =~ s/\~/\&\#xA0\;/g;
      $figparams[$fff][8] =~ s/~--~/--/g;
      $figparams[$fff][8] =~ s/--/\&\#x2013\;/g;
      $figparams[$fff][8] =~ s/``/"/g;
      $figparams[$fff][8] =~ s/''/"/g;
##    The subroutine &CutCaption replaces full figure/table caption with the shortened ones.  
##    It selects break point outside of  <a href    >  </a> fragments 
      &CutCaption($figparams[$fff][8]);                              
      print MAP "<li><a href=\"$figparams[$fff][1]\"><b>$figtypename $numcur.<\/b><\/a>  $captshort<\/li>\n";  
   }
   print MAP "<\/ul>\n";
}
if ($tabcount > 0)  {
   print CON "<a href=\"$paperid-tables.html\" target=\"_new\"><h5>$tabsname<\/h5><\/a>\n";
   print MAP "<a href=\"$paperid-tables.html\" target=\"_new\"><h5>$tabsname<\/h5><\/a>\n<ul>\n";
   for ($fff = 0; $fff < $tabcount; $fff++)  {
      $numcur = $fff + 1;
      $tabparams[$fff][8] =~ s/\~/\&\#xA0\;/g;
      $tabparams[$fff][8] =~ s/~--~/--/g;
      $tabparams[$fff][8] =~ s/--/\&\#x2013\;/g;
      $tabparams[$fff][8] =~ s/``/"/g;
      $tabparams[$fff][8] =~ s/''/"/g;
      &CutCaption($tabparams[$fff][8]);    
      print MAP "<li><a href=\"$tabparams[$fff][1]\"><b>Table $numcur.<\/b><\/a>  $captshort<\/li>\n";  
   }
   print MAP "<\/ul>\n";
}
print MAP <<EOM;
$footerlinetab
EOM

print CON <<EOM;
$footerlinetab
EOM

OUTER:

#######################    R E S P O N S E     P A G E       ##########################

$qumenu = "css/quickmenu.txt";
$ebooksuf = $doisuf;
$ebooksuf =~ s/000/\_EB/;

open (ABS, "<$absalone")  ||  die "Cannot open $absalone  file.";
open (RES, ">$respage")  ||  die "Cannot open $respage  file.";
open (QM, "<$qumenu")  ||  die "Cannot open $qumenu  file.";
open (ABOD, ">$absbodyname")  || die "Cannot open $absbodyname  file.";

print ABOD <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
     src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full">
</script>
</head><body>
$modabstract
</body></html>
EOM
close (ABOD);

while (<ABS>) {
    chop();
    print RES "$_\n";
    if (/<meta name=\"keywords\"/)  {
        goto ABSHDR;
    }
}
ABSHDR:

while(<QM>)  {
    chop();
    print RES "$_\n";
}

print RES <<EOM;
<p class="ident">$identline</p><hr class="short" />
<h1>$contents[1][0]</h1>
<p class="auth"><b><i>$authcitdir</i></b></p>


<!-- QuickMenu Structure [Menu 0] -->
<ul id="qm0" class="qmmc">
    <li><a class="qm-startopen qmparent" href="javascript:void(0)" style="width:60px;"><font color="#006600" face="Verdana" size="3"><b>Abstract</b></font></a>
    <ul>
        <li><span class="qmcbox" >
<table style="border-width: 0px; width: 100%;" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="width: 98%; vertical-align: top;">
<div style="border-style: dotted; border-width: 1px; padding: 2px 0px 2px 5px; background-color: rgb(245, 245, 245); margin-bottom: 3px;">
    <iframe id="frame1" frameborder="0" scrolling="yes" src="$absbodyname" width="600" height="420">
    </iframe>
</div>
</td>
</tr>
</tbody>
</table>
    </span></li>
    </ul></li>

	<li><a class="qmparent" href="javascript:void(0)" style="width:60px;"><font color="#006600" face="Verdana" size="3"><b>Cited by</b></font></a>
	<ul>
	<li><span class="qmcbox" >
<table style="border-width: 0px; width: 100%;" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="width: 98%; vertical-align: top;">
<div style="border-style: dotted; border-width: 1px; padding: 2px 0px 2px 5px; background-color: rgb(245, 245, 245); margin-bottom: 3px; cursor: move;">
    <div style="padding: 0pt; height: 90%; position: relative; left: 0px;">
    <iframe id="frame1" frameborder="0" scrolling="yes" src="citzero.html" width="600" height="420">
    </iframe>
    </div>
</div>
</td>
</tr>
</tbody>
</table>
    </span></li>
	</ul></li>
<li class="qmclear">&nbsp;</li></ul>
<!-- Create Menu Settings: (Menu ID, Is Vertical, Show Timer, Hide Timer, On Click (options: 'all' * 'all-always-open' * 'main' * 'lev2'), Right to Left, Horizontal Subs, Flush Left, Flush Top) -->
<script type="text/javascript">qm_create(0,false,0,0,'all-always-open',false,false,true,false);</script>
<!--[END-QM0]-->

<div id="footer" style="padding:5;position:relative;left:5px;top:450px;">
<p class="dates">$receivname $received;  $acceptname  $accepted;  $publishname  $published.<\/p>
<hr class="short" />

<p><font size=-1><b>Keywords:</b> $keywords</font></p>

<p class="citat">&#x2003;<br /><b><font color="#006600">&nbsp;&nbsp;Free Download:</font>&nbsp;&nbsp;&nbsp;&nbsp;
<font color="#A52A00" face="Verdana" size=-2>Full Paper: &nbsp;&nbsp;<a href="http://elpub.wdcb.ru/journals/rjes/v$jourvol/$doisuf/$doisuf.pdf" TARGET="globaut">[PDF]</a>&nbsp;&nbsp;
<a href="http://elpub.wdcb.ru/journals/rjes/v$jourvol/$doisuf/$doisuf.html" TARGET="globaut">[HTML]</a>&nbsp;&nbsp;
Formatted for e-Book:&nbsp;&nbsp;<a href="http://elpub.wdcb.ru/journals/rjes/v$jourvol/$doisuf/$ebooksuf.pdf" TARGET="globaut">[PDF]</a>&nbsp;&nbsp;
<a href="http://elpub.wdcb.ru/journals/rjes/v$jourvol/$doisuf/$doisuf.epub" TARGET="globaut">[EPUB]</a></font></b><br />&#x2003;
</p>
<p class="citat">\&\#x2003\;<br \/>
$citation.<br \/>\&\#x2003\;<\/p>
<p id=\"copyright\"><a href=\"http:\/\/elpub.wdcb.ru\/journals\/rjes\/copyright.html\">Copyright  $cpryear  by the  $regtitle[$journumb][3].<\/a><\/p>
<hr \/><span class=\"texweb\">Generated from LaTeX source by <a href=\"http\:\/\/eos\.wdcb\.ru\/tools\/2.0\/elxfinal_2.0.zip\">ELXfinal, $vernumb<\/a> software package.<\/span>
EOM

##      Copying screen and thumbnail files to 'images' directory
foreach $ffff (<*.png>)  {
    if ($ffff =~ /-o/ || $ffff =~ /-th/ || $ffff =~ /-tth/ || $ffff =~ /-to/)  {
        $comline = "move ".$ffff." ".$imagedir."\\".$ffff." > ".$null;
        system $comline;
    }
}

##      Copying logos and cover/title image files to 'images' directory

$coverimage = $regcodeprefix[$journumb]."cover\.png";
$titleimage = $regcodeprefix[$journumb]."title\.png";

###print ERR "coverimage = $coverimage     titleimage = $titleimage\n";

foreach $eeee (<basic\/*>)  {
   $hhhh = $eeee;
    
               ###print ERR "hhhh = $hhhh\n";
    
   $hhhh =~ s/basic\///;
               ###print ERR "hhhh = $hhhh\n";
   if ($hhhh =~ /.txt/)  {
   } elsif ($hhhh eq $titleimage)  {      ##    Calls to format title page
      if ($journumb == 4)  {
         ###print ERR  "Calling for &setTitlePageRus\n";
         &setTitlePageRus($hhhh);
      } elsif ($journumb == 1)  {
         ###print ERR  "Calling for &setTitlePageEng\n";
         &setTitlePageEng($hhhh);
      }  else  {
         print ERR "No title graphic template for journal code $jourcode in the basic directory.\n"; 
         $errcount += 1;
      }
      $comline = "move ".$tttt." ".$imagedir."\\".$tttt." > ".$null;
      system $comline;  
   } elsif ($hhhh eq $coverimage)  {      ##    Calls to format cover page          
      if ($journumb == 4)  {      
         ###print ERR  "Calling for &setCoverPageRus\n";
         &setCoverPageRus($hhhh);
      } elsif ($journumb == 1)  {
         ###print ERR  "Calling for &setCoverPageEng\n";
         &setCoverPageEng($hhhh);
      }  else  {
         print ERR "No cover graphic template for journal code $jourcode in the basic directory.\n"; 
         $errcount += 1;
      }
      $comline = "move ".$cccc." ".$imagedir."\\".$cccc." > ".$null;
      system $comline;     
   }  else  {
      $comline = "copy basic\\".$hhhh." ".$imagedir."\\".$hhhh." > ".$null;
      system $comline;
   }
}   
################################## C O N T R O L   E R R O R S  ########################################
if ($errcount > 0)  {
   print "done\nProgram was abnormally closed!  errcount = $errcount  See error log file.\n";
   goto STOP;
} else  {
   if ($ebook eq "-x" || $ebook eq "-z")  {

###############################################################################
##        PASS 12:  Setting file structure for EPUB3                         ##
###############################################################################
print "done\nPASS 12: Setting file structure for EPUB3 . . . . . . . . . . . . ";

##   Define absolute path to the current directory - CURDIR

      $comline = "dir > ".$null;
      system $comline;
      open (NULL, "<$null")  ||  die "Cannot open $null file";
      while (<NULL>)  {
         chop();
         s/^ +//;
         if (/Directory of/)  {
            @alim = split(/ +/, $_);
            $curdir = $alim[2];
            goto ALIM;
         }
      }
ALIM:

#########################################   N O T E !  ############################################
##  The name of EPUB directory which should accumulate minimal set of files necessary for composing
##  epub3 version of article looks like:
##  Name    -->  $paperid   -->    default value
##  Content -->  META-INF   -->    containing  'container.xml'
##               OPS        -->    containing all data files (xhtml, package.opf, TOC, etc)
##               OPS/css    -->    css files
##               OPS/images -->    images
##               "mimetype" file  containing one record with mimetype value, i.e.  "application/epub+zip"
      $epubdir = $curdir."\\".$paperid;
      $metadir = $epubdir."\\META-INF";
      $opsdir = $epubdir."\\OPS";
      $cssdir = $epubdir."\\OPS\\css";
      $imagedir = $epubdir."\\OPS\\images";
#==================================================================================================

##    Opening subdirectories.    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
##    NOTE!   Maybe better solution will be preliminary closing $epubdir  and creating new one
##    if there is nothing that should be saved from previous translation

      if (-e $epubdir) {
      }  else  {
         mkdir($epubdir, 0777)  || die  "Cannot open $epubdir ";
      }
      if (-e $metadir) {
      }  else  {
         mkdir($metadir, 0777)  || die  "Cannot open $metadir ";
      }
      if (-e $opsdir) {
      }  else  {
         mkdir($opsdir, 0777)  || die  "Cannot open $OPSdir ";
      }
      if (-e $cssdir) {
      }  else  {
         mkdir($cssdir, 0777)  || die  "Cannot open $CSSdir ";
      }
      if (-e $imagedir) {
      }  else  {
         mkdir($imagedir, 0777)  || die  "Cannot open $IMAGEdir ";         
      }
      
##       Creating title page in OPS directory
      open(TTT, ">titpage.xhtml")  ||  die  "Cannot open OPS directory\n";
      print TTT <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head><title>Title Page</title>
<link rel="stylesheet" type="text/css" href="css/elx-online.css" />
</head>
<body>
<img src="images/title$uniquenumb.jpg"  style="width:500px" />
</body>
</html>    
EOM
      close(TTT);
      $comline = "copy titpage.xhtml ".$names[0]."\\OPS\\titpage.xhtml > ".$null;         ##  Copy to OPS
      system $comline;
      $comline2 = "del titpage.xhtml > ".$null;                                           ##  Delete
      system $comline2;

##    Creating editorial note in OPS directory
      $edinot = "ednote$uniquenumb.xhtml";
      open (EEE, ">$edinot")  ||  die "Cannot open $edinot file.\n";
      print EEE <<EOM;
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head>
<title>
</title>
<link rel="stylesheet" type="text/css" href="css/elx-online.css" />
</head>
<body>
<h3>Editorial Note</h3>
<p class="abs">This book is the <span class="ref">EPUB3</span> 
version of the scientific article (<span 
class="link">doi:$regtitle[1][5]/$names[0]</span>) published in the 
<span class="ref">$regtitle[$journumb][1]</span> 
(<span 
class="link">$regtitle[$journumb][11]</span>). The 
mentioned article's <span class="ref">PDF version of 
record</span> was compiled from LaT<sub><span 
style="font-size:10pt;">E</span></sub>X source file.  The same 
source file was then converted to <span 
class="ref">EPUB3</span> using <span class="ref">ELXfinal</span> software 
package.</p> 
<p class="abs">The result of conversion  was successfully tested using <span class="ref">iBooks2</span> application of <span class="ref">iPad2</span> tablet and <span class="ref">iPhone</span>, <span class="ref">Gyan ePub Reader</span> 
(<span class="link">http://www.handster.com/gyan_epub_reader.html</span>) and <span class="ref">Readium</span>(<span class="link">http://readium.org/</span>), recommended by <span class="ref">IDPF</span>(<span class="link">http://idpf.org/</span>) as a basic software for EPUB Reading Systems,
as well as on two emulators of EPUB Reading Systems, namely <span class="ref">AZARDI </span>(<span class="link">http://www.infogridpacific.com/igp/AZARDI/</span>) and <span class="ref">EPUBReader: Add-on for 
Firefox</span> (<span class="link">https://addons.mozilla.org/en-US/firefox/addon/epubreader/</span>).  
</p>
<p class="abs">
Any comments and criticism will be highly appreciated.
</p>
<p class="abs"><span class="ref">Vitaly Nechitailenko</span><br />
<span class="link">vitaly\@wdcb.ru,  vnechita\@gmail.com</span></p>
<hr />
</body>
</html>
EOM
      close(EEE);
      $comline = "copy ".$edinot."  ".$names[0]."\\OPS\\".$edinot." > ".$null;         ##  Copy to OPS
      system $comline;
      $comline2 = "del ".$edinot." > ".$null;                                           ##  Delete
      system $comline2;

##    Copying standard files to new directories

      $imagedirini = $curdir."\\images";
##   print ERR "IMAGEdirini = $imagedirini   IMAGEdir = $imagedir\n";
      $cssdirini = $curdir."\\css";
##   print ERR "CSSdirini = $cssdirini   CSSdir = $cssdir\n";

      $mani =0;
      @tmpmani = ();

      opendir (IMG, $imagedirini)  || die "Cannot open $imagedirini directory";
      while ($name = readdir(IMG))  {
         $copylab = 0;
         if ($name =~ /\.png/ && ($name =~ /-o/ || $name =~ /-th/ || $name =~ /-to/ || $name =~ /-tth/))  {
###             print ERR "$name\n";
            $copylab = 1;
         }  elsif  ($name =~ /\.png/ || $name =~ /^\.+/)  {
         }  else  {
###             print ERR "$name\n";
            $copylab = 1;
         }
         if ($copylab == 1)  {
            $comline = "copy ".$imagedirini."\\".$name." ".$imagedir."\\".$name." > ".$null;
            system $comline;
            $tmpmani[$mani] = $name;
            $mani += 1;
         }
      }
      closedir (IMG);

      opendir (CSS, $cssdirini)  || die "Cannot open $cssdirini directory";
      while ($name = readdir(CSS))  {
         if  ($name =~ /^\.+/)  {
         }  else  {
            if ($name =~ /\.css/)  {
               $comline = "copy ".$cssdirini."\\".$name." ".$cssdir."\\".$name." > ".$null;
##                  print ERR "$comline\n";
               system $comline;
            }
         }
      }
   
      $metafile = $metadir."\\container.xml";
      $mimefile = $epubdir."\\mimetype";
      open (META, ">$metafile")  ||  die "Cannot open $metafile file";
      open (MIME, ">$mimefile")  ||  die "Cannot open $mimefile file";
      print META <<EOM;
<?xml version="1.0" encoding="UTF-8" ?>
<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">
   <rootfiles>
      <rootfile full-path=\"OPS\/package.opf\" media-type=\"application\/oebps-package+xml\"\/>
   <\/rootfiles>
<\/container>
EOM
      print MIME "application\/epub+zip";
      close (META);
      close (MIME);
################################ E X I T ##################################################################################exit;


###############################################################################
##        PASS 13:  Generation of the set of XHTML files                     ##
###############################################################################
print "done\nPASS 13: Generation of the set of XHTML files . . . . . . . . . . ";

## Writing batch file for converting .html files to .xhtml
      for ($ff = 0; $ff < $figcount; $ff++)  {
         ###print ERR "ff = $ff            figparams[$ff][1] = $figparams[$ff][1]\n";
      }
      for ($tt = 0; $tt < $tabcount; $tt++)  {
         ###print ERR "tt = $tt            tabparams[$tt][1] = $tabparams[$tt][1]\n";
      }
   
      $substmml = "substmml.bat";
      open (BAT, ">$substmml")  ||  die  "Cannot open $substmml file.";
      print BAT "perl elxtomml.pl $paperid-abs\.html $opsdir $langcodetype\n";
      print BAT "perl elxtomml.pl $paperid\.html $opsdir $langcodetype\n";
      for ($ff = 0; $ff < $figcount; $ff++)  {
         print BAT "perl elxtomml.pl $figparams[$ff][1]  $opsdir $langcodetype\n";
      }
      for ($tt = 0; $tt < $tabcount; $tt++)  {
         print BAT "perl elxtomml.pl $tabparams[$tt][1]  $opsdir $langcodetype\n";
      }
      if ($figcount >= 1)  {
         print BAT "perl elxtomml.pl $paperid-figures\.html $opsdir $langcodetype\n";
      }
      if ($tabcount >= 1)  {
         print BAT "perl elxtomml.pl $paperid-tables\.html $opsdir $langcodetype\n";
      }
      print BAT "perl elxtomml.pl $paperid-map\.html $opsdir $langcodetype\n";
      print BAT "perl elxtomml.pl $paperid-toc\.html $opsdir $langcodetype\n";

##    Batch convertion of .html files to .xhtml with replacing TeX math expressions with
##    MathML ones using MathJax CDN-resided software


##################################################################################
      unlink("mathmarks.tmp");   ##    Removes old list
##################################################################################
###goto STOP;  ###
      system $substmml;             ##    Start batch file for converting  html to xhtml
##################################################################################
##    Composing  PACKAGE.OPF  file
##       Number for title pages name  --> $uninum
###############################      print ERR "=================================================Paperid = $paperid\n";
      
      if (length($paperid) == 9)  {
         $uninum = substr($paperid, 6);
      } elsif (length($paperid) == 12)  {
         $uninum = substr($paperid, 9);
      }  else  {
         print ERR "The structure of paperid is not correct? it should be 9 or 12 characters\n";
         $errcount += 1;
      }
      $marklist = "mathmarks.tmp";
      $spin =0;
      @tmpspin = ();
      open (MRK, "<$marklist")  ||  die "Cannot open $marklist file";   ##    Creates new list
      $mrk = 0;
      while (<MRK>)  {
         chop();
         @frac = split(/ \|\|\| /, $_);
         $matmar[0][$mrk] = $frac[0];
         $matmar[1][$mrk] = $frac[1];
         $mrk += 1;
      }
   
      $opffile = $opsdir."\/package.opf";
      open (OPF, ">$opffile")  ||  die "Cannot open $opffile file";
   
      print OPF <<EOM;
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" xml:lang="en" unique-identifier="pub-id">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:title id="title">$artitcr</dc:title>
    <dc:creator id="creator">$authcitdir</dc:creator>
    <dc:language>en</dc:language>
    <dc:identifier id="pub-id">doi:10.2205/$paperid-epub</dc:identifier>
    <dc:source>doi:10.2205/$paperid</dc:source>
    <meta property="dcterms:modified">$dctime</meta>
    <dc:date>$dcyear</dc:date>
    <dc:publisher>Geophysical Center RAS</dc:publisher>
    <dc:rights>B)$dcyear $regtitle[1][3]. All rights reserved</dc:rights>
    <dc:description>This is a series of EPUB3 versions of scientfic articles published in the Russian Journal of Earth Sciences.</dc:description>
    <dc:subject>RJES Ebook Companion</dc:subject>
</metadata>
<manifest>
    <item id="toc" properties="nav" href="TOC$uninum.xhtml" media-type="application/xhtml+xml" />
    <item id="css-001" href="css/elx-online.css" media-type="text/css" />
    <item id="cover-image" properties="cover-image" href="images/cover$uninum.jpg" media-type="image/jpeg" />
    <item id="tit01" href="titpage.xhtml" media-type="application/xhtml+xml" />
    <item id="tit02" href="ednote$uninum.xhtml" media-type="application/xhtml+xml" />
EOM

    $tmpspin[$spin] = "    <itemref idref=\"tit01\" linear=\"yes\" \/>";
    $spin += 1;
    $tmpspin[$spin] = "    <itemref idref=\"tit02\" linear=\"yes\" \/>";
    $spin += 1;
    
##      Marker yes/no for spine fragment
    $noyes = "yes";
   
    for ($ll = 0; $ll < $mrk; $ll++)  {
        if ($ll < 10)  {
            $sufm = "elx0".$ll;
        }  else  {
            $sufm = "elx".$ll;
        }
        $filnam = $matmar[0][$ll];
        $filnam =~ s/\.html/\.xhtml/;
        if ($matmar[1][$ll] eq "math")  {      ##    Add math property
            $linmat = "    <item id=\"".$sufm."\" properties=\"mathml\" href=\"".$filnam."\" media-type=\"application\/xhtml+xml\" \/>";
            print OPF "$linmat\n";
        }  elsif ($matmar[1][$ll] eq "nomath")  {      ##    No math property
            $linmat = "    <item id=\"".$sufm."\" href=\"".$filnam."\" media-type=\"application\/xhtml+xml\" \/>";
            print OPF "$linmat\n";
        }  else  {
            print ERR "Wrong structure of $marklist file\n";
            $errcount += 1;
        }
        if ($filnam =~ /-map.xhtml/)  {
            $noyes = "yes";
            $tmpspin[$spin] = "    <itemref idref=\"$sufm\" linear=\"$noyes\" \/>";
            $spin += 1;
        } elsif ($filnam =~ /-figures/)  {
            $noyes = "yes";
            $tmpspin[$spin] = "    <itemref idref=\"$sufm\" linear=\"$noyes\" \/>";
            $spin += 1;
        } elsif ($filnam =~ /-fig/)  {
            $noyes = "no";
            $tmpspin[$spin] = "    <itemref idref=\"$sufm\" linear=\"$noyes\" \/>";
            $spin += 1;
        } elsif ($filnam =~ /-tables/)  {
            $noyes = "yes";
            $tmpspin[$spin] = "    <itemref idref=\"$sufm\" linear=\"$noyes\" \/>";
            $spin += 1;
        } elsif ($filnam =~ /-tab/)  {
            $noyes = "no";
            $tmpspin[$spin] = "    <itemref idref=\"$sufm\" linear=\"$noyes\" \/>";
            $spin += 1;
        } elsif ($filnam =~ /-toc/)  {
            $noyes = "no";
            $tmpspin[$spin] = "    <itemref idref=\"$sufm\" linear=\"$noyes\" \/>";
            $spin += 1;
        }  else {
            $noyes = "yes";
            $tmpspin[$spin] = "    <itemref idref=\"$sufm\" linear=\"$noyes\" \/>";
            $spin += 1;
        }
    }
##       Adding images to manifest

    for ($il = 0; $il < $mani; $il++)  {
        $jl = $il + $ll;
        if ($jl < 10)  {
            $sufm = "elx0".$jl;
        }  else  {
            $sufm = "elx".$jl;
        }
        @elim = split(/\./, $tmpmani[$il]);
        $elim[1] =~ s/jpg/jpeg/;
        $linmat = "    <item id=\"".$sufm."\" href=\"images\/".$tmpmani[$il]."\" media-type=\"image\/".$elim[1]."\" \/>";
        if ($linmat =~ /images\/cover/)  {     ##  To prevent double including cover image to package.opf file
        } else {
            print OPF "$linmat\n";
        }
    }
    print OPF <<EOM;
</manifest>
<spine page-progression-direction="ltr">
EOM

    for ($im = 0; $im < $spin; $im++)  {
        print OPF "$tmpspin[$im]\n";
    }
    print OPF <<EOM;
</spine>
</package>
EOM
    close (OPF);

####################################################################################

###     Composing TOCNNN.xhtml  file
###        $uninum = substr($paperid, 9);
##print "UNINUM = $uninum\n";
##print "OPSDIR = $opsdir\n";
      $tocxfile = $opsdir."\/TOC".$uninum."\.xhtml";
##print "TOCXFILE = $tocxfile\n";
      open (TOC, ">$tocxfile") ||  die "Cannot open $tocxfile file";

      print TOC <<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>
    <meta http-equiv="default-style" content="text/html; charset=utf-8"/>
    <title>$contname</title>
    <link rel="stylesheet" href="css/elx-online.css" type="text/css"/>
    </head>
    <body>
<nav epub:type="toc">
<h2>$contname</h2>
EOM

      $prevlab = "";
      $secnum = 1;
      for ($cl = 1; $cl < $conlin-1; $cl++)  {
         #####################################################################print ERR "$contents[0][$cl] ||| $contents[1][$cl]\n";
         if (($contents[0][$cl] eq "abstr")  && ($prevlab eq "")) {
            print TOC "<ol><li><a href=\"".$paperid."\.xhtml\#abslink\">".$contents[1][$cl]."<\/a>\n"; 
            $prevlab = "abstr";  
         } elsif (($contents[0][$cl] eq "sect")  && ($prevlab eq "sect" || $prevlab eq "abstr")) {
            $isect = "sect".$secnum;
            $secnum += 1;
            print TOC "<\/li><li><a href=\"".$paperid."\.xhtml\#".$isect."\">".$contents[1][$cl]."<\/a>\n";      
            $prevlab = "sect";
      } elsif (($contents[0][$cl] eq "ssect")  && ($prevlab eq "sect" || $prevlab eq "abstr")) {
         $isect = "sect".$secnum;
         $secnum += 1;
         print TOC "<ol><li><a href=\"".$paperid."\.xhtml\#".$isect."\">".$contents[1][$cl]."<\/a>\n";
         $prevlab = "ssect";      
      } elsif (($contents[0][$cl] eq "ssect")  && ($prevlab eq "ssect")) {
         $isect = "sect".$secnum;
         $secnum += 1;
         print TOC "<\/li><li><a href=\"".$paperid."\.xhtml\#".$isect."\">".$contents[1][$cl]."<\/a>\n";      
         $prevlab = "ssect";
      } elsif (($contents[0][$cl] eq "sssect")  && ($prevlab eq "ssect")) {
         $isect = "sect".$secnum;
         $secnum += 1;
         print TOC "<ol><li><a href=\"".$paperid."\.xhtml\#".$isect."\">".$contents[1][$cl]."<\/a>\n";
         $prevlab = "sssect";      
      } elsif (($contents[0][$cl] eq "sssect")  && ($prevlab eq "sssect")) {
         $isect = "sect".$secnum;
         $secnum += 1;
         print TOC "<\/li><li><a href=\"".$paperid."\.xhtml\#".$isect."\">".$contents[1][$cl]."<\/a>\n";      
         $prevlab = "sssect";
      } elsif (($contents[0][$cl] eq "ssect")  && ($prevlab eq "sssect")) {
         $isect = "sect".$secnum;
         $secnum += 1;
         print TOC "<\/li><\/ol>\n";      
         $prevlab = "ssect";
      } elsif (($contents[0][$cl] eq "sect")  && ($prevlab eq "ssect")) {
         $isect = "sect".$secnum;
         $secnum += 1;
         print TOC "<\/li><\/ol>\n";      
         $prevlab = "sect";
         print TOC "<\/li><li><a href=\"".$paperid."\.xhtml\#".$isect."\">".$contents[1][$cl]."<\/a>\n";      
      } elsif (($contents[0][$cl] eq "sect")  && ($prevlab eq "sssect")) {
         $isect = "sect".$secnum;
         $secnum += 1;
         print TOC "<\/li><\/ol>\n<\/li><\/ol>\n";      
         $prevlab = "sect";
         print TOC "<\/li><li><a href=\"".$paperid."\.xhtml\#".$isect."\">".$contents[1][$cl]."<\/a>\n"; 
      } elsif (($contents[0][$cl] eq "acknow")  && ($prevlab eq "sect")) {     
         print TOC "<\/li><li><a href=\"".$paperid."\.xhtml\#acknow\">".$contents[1][$cl]."<\/a>\n"; 
      } elsif (($contents[0][$cl] eq "openref")  && ($prevlab eq "sect")) {     
         print TOC "<\/li><li><a href=\"".$paperid."\.xhtml\#openref\">".$contents[1][$cl]."<\/a>\n<p \/>\n"; 
      }
   }
   if ($figcount > 0)  {
      print TOC "<\/li><li><a href=\"".$paperid."-figures.xhtml\"><span class=\"ref\">$figsname<\/span><\/a>";
   }
   if ($tabcount > 0)  {
      print TOC "<\/li><li><a href=\"".$paperid."-tables.xhtml\"><span class=\"ref\">$tabsname<\/span><\/a>";
   }

   print TOC "<\/li><li><a href=\"".$paperid."-map.xhtml\"><span class=\"ref\">$artmapname<\/span><\/a>";

   print TOC <<EOM;
</li></ol>
</nav>
</body>
</html>
EOM
close (TOC);

      if ($langcodetype eq "rus")   {          ##  This requires recoding to UTF-8 (package.opf, titpage.xhtml, ednote, TOCNNN
         $fileconv[0] = "package.opf";
         $fileconv[1] = "titpage.xhtml";
         $fileconv[2] = "ednote".$uninum."\.xhtml";
         $fileconv[3] = "TOC".$uninum."\.xhtml";
         for ($iu = 0; $iu < 4; $iu++)  {
            $modname = $opsdir."\/".$fileconv[$iu];
            $identtemp = $fileconv[$iu];
            $identout = $opsdir."\/".$fileconv[$iu];
            ####print ERR "\nIU = $iu   MODNAME = $modname    IDENTTEMP = $identtemp   IDENTOUT = $identout\n\n";
            $comiconv = $iconv_path." -f cp1251 -t utf-8 ".$modname." > ".$identtemp;
            ####print ERR "\ncomiconv = $comiconv\n\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);
         }
      }

##      Zipping the set of OPS files to EPUB format

   if ($ebook eq "-z")  {
        
      print "\nInitiate compressing EPUB\n";
      $epubname = $names[0]."\.epub";
      $metaname = $names[0]."\.META-INF";
      $opsname  = $names[0]."\.OPS";
      $mimename = $names[0]."\.mimetype"; 
            
      $comlinefin = $wwzip."  -yp ".$epubname." ".$metaname." ".$opsname." ".$mimename;
            
      print "comlinefin = $comlinefin\n"; 
            
      system $comlinefin;      
     
      }
   }
}
###########################################################################
STOP:

   print "done\n";
###########################################################################
###########################################################################
##      SUBROUTINE   FindMatchBracket                                    ##
##      This subroutine finds position of last closing curly bracket     ##
##      for arbitrary preceedings pairs                                  ##
###########################################################################
sub FindMatchBracket {
    $cpb = true;
    $tmpstr = $_[0];
    $stpo = $_[1];
    $prlen = $_[2];

##if ($tmpstr =~ /Onqjnk|js rhohwmne/)  {  
##    print ERR "\n\nTMPinFMB = Onqjnk|js rhohwmne\n$tmpstr\nSTRO = $stpo    PRLEN = $prlen \n";
##}
##if ($tmpstr =~ /Qsyeqrbser meqjnk|jn/)  {  
##    print ERR "\n\nTMPinFMB = Qsyeqrbser meqjnk|jn\n$tmpstr\nSTRO = $stpo    PRLEN = $prlen \n";
##}
    $paircnt = 0;
    $newopcnt = 0;
    $pairlab = true;
    while ($paircnt < $prlen)  {
        $inop = index($tmpstr, "\{", $stpo);
        if ($inop < 0)  {
            $inop = 1000000;
        }
        $incl = index($tmpstr, "\}", $stpo);
        if ($incl < 0)  {
            $cpb = false;
        }  else  {
            if ($inop < $incl)  {
               $curbrack = true;       ##  TRUE - opening bracket
               $stpo = $inop + 1;
            }  else  {
               $curbrack = false;      ##  FALSE - closing bracket
               $stpo = $incl + 1;
            }
        }
        if ($curbrack eq true)  {
            $newopcnt += 1;
        }  else  {
            if ($newopcnt > 0)  {
                $newopcnt -= 1;
                if ($newopcnt == 0)  {
                    $paircnt += 1;
                }
            }  else  {
                $cpb = false;
            }
        }
        if ($cpb eq false)  {
            print ERR "FindMatchBracket: Missed or extra closed curly bracket in paragraph $i  ==>\n$tmpstr\n\n";
            $errcount += 1;
            return false;
        }
    }
    $nepar = $incl;
}
########################################################################

########################################################################
##                       Subroutine SplitPreamble                     ##
########################################################################
sub SplitPreamble {

    $prestring =~ s/\\noindent//g;
    $prestring =~ s/\} +\\/\}\\/g;

            ####print ERR "\nPRESTRING INSIDE SplitPreamble\n";
            ####print ERR "$prestring\n";

    @parts = split(/\\usepackage\[/, $prestring);
    @ports = split(/\]/, $parts[1]);
    @items = split(/\,/, $ports[0]);
    $hrnums = @items;
    if ($hrnums > 0)  {
        ###print ERR "hrnums = $hrnums  |||  @items\n";
    }
##      $langcodetype   is used to set UTF-8 encoding for XHTML files if document is in Russian    
    $lamon = 0;
    $langcodetype = "eng";
    for ($lcod = 0; $lcod < $hrnums; $lcod++)  {
        if ($items[$lcod] eq "rus")  {
            $langcodetype = $items[$lcod]; 
            $lamon = 1;            
        }
    }   
####print ERR "langcodetype = $langcodetype   < >    lamon = $lamon\n";
    @parts = split(/\\journalid\{/, $prestring);
    @items = split(/\}\{/, $parts[1]);
    $jourcode = $items[0];                          ##  Journal code
    for ($j = 0; $j < @regcode; $j++)  {
        if ($jourcode eq $regcode[$j])  {
            $journumb = $j;
        }
    }
###    print ERR "\n\njournumb = $journumb     jourcode = $jourcode     regcodeprefix = $regcodeprefix[$journumb]\n\n";
    $jourvol  = $items[1];                          ##  Volume
    $journum  = $items[2];                          ##  Number (Issue)
    $jouryear = substr($items[3], 0, 2);            ##  Year (two last digits)
    ###print ERR "jourcode = $jourcode    jourvol = $jourvol    journum = $journum     jouryear = $jouryear\n";
    ###print ERR "$regtitle[$journumb][1] <> Vol $jourvol <> Issue $journum <>  Year 20$jouryear\n";
    @parts = split(/\\cpright\{/, $prestring);
    @items = split(/\}\{/, $parts[1]);
    $cprowner = $items[0];                          ##  Copyright owner
    $cpryear = substr($items[1], 0, 4);             ##  Copyright year
    ####print ERR "$cprowner     $cpryear\n";
    @parts = split(/\\paperid\{/, $prestring);
    @frogs = split(/\}/, $parts[1]);
    $paperid = $frogs[0];
##    $paperid = substr($parts[1], 0, 12);            ##  Article identifier (DOI suffix)
    $paperidsm = $paperid;
    $paperidsm =~ tr/A-Z/a-z/;
###print ERR "paperid = $paperid      paperidsm = $paperidsm  \n";
    @parts = split(/\\papertype\{/, $prestring);
    $papertype = substr($parts[1], 0, 3);            ##  Article type (value for NEB)
###print ERR "papertype = $papertype \n";

    @parts = split(/\\citnumber\{/, $prestring);
    @items = split(/\}\{/, $parts[1]);
    $speciss = $items[0];                           ##  Mark of special (thematic) issue, =0 if defined
    @smfrag = split(/\}\\/, $items[1]);
    $numiss = $smfrag[0];                           ##  Article number inside issue
    if ($numiss < 10)  {
        $numiss = "00".$numiss;
    } else {
        $numiss = "0".$numiss;
    }
    $citatnumb = $regcode[$journumb].$journum.$numiss;

    #####print ERR "speciss = $speciss     numiss = $numiss     citatnumb = $citatnumb\n";

    @parts = split(/\\lefthead\{/, $prestring);
    @items = split(/\}\{/, $parts[1]);
    @smfrag = split(/\}\\/, $items[0]);
    $lefthead = $smfrag[0];                         ##  Left part of running head
    @parts = split(/\\righthead\{/, $prestring);
    @items = split(/\}\{/, $parts[1]);
    @smfrag = split(/\}\\/, $items[0]);
    $righthead = $smfrag[0];                        ##  Right part of running head

    #print ERR "$lefthead <> $righthead\n";

    @parts = split(/\\received\{/, $prestring);
    @smfrag = split(/\}\\/, $parts[1]);
    @items = split(/\}\{/, $smfrag[0]);
    $dreceived = $items[0];                         ##  Article's received day
    $mreceived = $items[1];                         ##  Article's received month
    $yreceived = $items[2];                         ##  Article's received year
    $received = $dreceived." ".$mreceived." ".$yreceived;
    @parts = split(/\\revised\{/, $prestring);
    @smfrag = split(/\}\\/, $parts[1]);
    @items = split(/\}\{/, $smfrag[0]);
    $drevised = $items[0];                          ##  Article's revised day
    $mrevised = $items[1];                          ##  Article's revised month
    $yrevised = $items[2];                          ##  Article's revised year
    $revised = $drevised." ".$mrevised." ".$yrevised;
    $lenrevi = length($revised);
    if ($lenrevi < 4)  {
      $revised = "";
    }
    @parts = split(/\\accepted\{/, $prestring);
    @smfrag = split(/\}\\/, $parts[1]);
    @items = split(/\}\{/, $smfrag[0]);
    $daccepted = $items[0];                          ##  Article's accepted day
    $maccepted = $items[1];                          ##  Article's accepted month
    $yaccepted = $items[2];                          ##  Article's accepted year
    $accepted = $daccepted." ".$maccepted." ".$yaccepted;
    @parts = split(/\\published\{/, $prestring);
    @smfrag = split(/\}\\/, $parts[1]);
    @items = split(/\}\{/, $smfrag[0]);
    $dpublished = $items[0];                         ##  Article's published day
    $mpublished = $items[1];                         ##  Article's published month
    $ypublished = $items[2];                         ##  Article's published year
    $published = $dpublished." ".$mpublished." ".$ypublished;

##  Converting  $mpublished  to digital form
    ###$imon = -1;
    for ($mmm = 0; $mmm <= 11; $mmm++)  {
        if ($longmon[$lamon][$mmm] eq $mpublished)  {
            $imon = $mmm + 1;
            goto NOMI;
        }
    }
NOMI:
    if ($imon < 1 || $imon > 12)  {
        print ERR "Wrong digital form of publication month.\n";
        $errcount += 1;
    }
####    print ERR "received/revised/accepted/published = $received <> $revised <> $accepted <> $published\n";

    @parts = split(/\\gcmdterms\{/, $prestring);
    @smfrag = split(/\}\\/, $parts[1]);
    $gcmdterms = $smfrag[0];                        ##  GCMD keywords
    @parts = split(/\\aguterms\{/, $prestring);
    @smfrag = split(/\}\\/, $parts[1]);
    $aguterms = $smfrag[0];                         ##  AGU keywords
    @parts = split(/\\keywords\{/, $prestring);
    @smfrag = split(/\}\\/, $parts[1]);
    $keywords = $smfrag[0];                         ##  Arbitrary keywords (author's choice)

    #print ERR "$gcmdterms\n";
    #print ERR "$aguterms\n";
    #print ERR "$keywords\n";

##  Extracting authoraddress data (more than one items is possible)
    $nadr = 0;
    $ipos = 0;
    $aadr = "";
    while ($aadr ne -1)  {
##      Special substitution for \underline in author e-mail addresses
      $prestring =~ s/\{\}/\_/g;
      $prestring =~ s/\\underline//g;
        $aadr = index($prestring, "\\authaddr\{", $ipos);
        $adrfrag = substr($prestring, $aadr);
        $cladr = index($adrfrag, "\}");
        $str = 10;
        $leng = $cladr - $str;
        $authadr[$nadr] = substr($adrfrag, $str, $leng);    ##  Author's address block
        $ipos = $aadr + 1;
        $nadr += 1;
    }
    $nadr -= 1;                                             ##  Number of author's address blocks
    #print ERR "NADR = $nadr\n";

    for ($i = 0; $i < $nadr; $i++)  {
        #print ERR "$authadr[$i]\n";
    }
    $identline = $regtitle[$journumb][0].",  VOL. ".$jourvol.", ".$citatnumb.", doi:".$regtitle[$journumb][5]."\/".$paperid.", 20".$jouryear;
    $doiindex = $regtitle[$journumb][5]."\/".$paperid;
###################    print ERR "IDENT = $identline\n";
}

###############################################################################
##      SUBROUTINE   DiacrChar                                               ##
##      This subroutine converts TeX macro for diacritical chars to UTF-8    ##
###############################################################################

sub DiacrChar  {
####print ERR "Inside DiacrChar\n";

    $_ = $_[0];

    if (/\\\\ ?/)  {        ##  Skip this case
######============================######        print ERR "Skipping   CASE===============Para = $i  $SaveCleanPar[$i][1]--$SaveCleanPar[$i][2]\n";
    }  elsif (/\\ /)  {
        s/\\ / /g;
######============================######        print ERR "Replacing  CASE===============Para = $i  $SaveCleanPar[$i][1]--$SaveCleanPar[$i][2]\n";
    }
    $postart = 0;
    $maxlen = length($_);
    @elems = split(//, $_);
#####print ERR  "STRING = $_\nELEMS = $elems[0] -- $elems[$maxlen - 1]\nelems= @elems\n";        ########################################################################################
##  Blocked frags
    if ($numblank > 0)  {
###        print ERR "    Number frags = $numblank\n";
    }
    for ($ji = 0; $ji < $numblank; $ji++)  {
        ##@@print ERR "    $range[$ji][0] - $range[$ji][1]\n";
    }
##  Reverse scanning of the current string
    $c = $maxlen;
    while ($c >= 0)  {
        $curchar = substr($_, $c, 1);
        if ($curchar eq "\\")  {
            $icurpos = $c;
###        print ERR "Cursor position = $icurpos\n";
##      Checks if $icurpos is outside of blocked frags
            $curmark = 1;       ##  Replacement permitted
###            print ERR "NUMBLANK = $numblank   $numbl\n";
            for ($ji = 0; $ji < $numblank; $ji++)  {
####            print ERR "$range[$ji][0] <> $icurpos  <<<>>>  $icurpos <> $range[$ji][1]\n";
                if ($range[$ji][0] <= $icurpos  &&  $icurpos <= $range[$ji][1])  {
                    ##$curmark = "false";
                    $curmark = 0;           ##  Replacement forbidden
                    $postart = $range[$ji][1];
                    ###print ERR "If blocked curmark = $curmark   postart = $postart\n";
                }
            }
            if ($curmark == 1)  {
##      Define position of nearest right-side backslash
                $nextbs = index($_, $icurpos + 1);
                $secchar  = substr($_, $icurpos+1, 1);
                $thirchar = substr($_, $icurpos+2, 1);
                $fifchar  = substr($_, $icurpos+4, 1);
                if ($secchar =~ /[a-zA-Z]/ && $thirchar =~ /[a-zA-Z]/)   {
                    ##@@##@@##@@##@@##@@##@@print ERR "Not accent backslash!!\n";
                ####}  elsif  ($secchar eq " ")   {
                }  else  {
                    $fipart = substr($_, 0, $icurpos);
                    if ($thirchar eq "\{" || $thirchar eq " ")  {
                        if ($fifchar eq "\\")  {
                            $lenmid = 4;
                        }  else  {
                            $lenmid = 5;
                        }
                    }  else  {
                        $lenmid = 3;            ###???????????????????????????????????????????????????????????????????????????    33333333333333333
                    }
                    $bodymid = substr($_, $icurpos, $lenmid);
                    $separt  = substr($_, $icurpos+$lenmid);
#####TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT        print ERR "Selected fragment for replacement = <$bodymid>  lenmid = $lenmid\n";

##      Find matching substitution in utf-8 table
                    $su = 0;
                    $bodysub = "";
                    while ($symb01[$su][0] ne "")  {
##print ERR "Before comparison:  bodymid = $bodymid    substitution = $symb01[$su][0]\n";
                        if ($bodymid eq $symb01[$su][0])  {
                            $bodysub = $symb01[$su][1];
                            ####print ERR "HAVE FOUND:  bodymid = $bodymid    substitution = $symb01[$su][0]\n";
                            last;
                        }  else  {
                            $su += 1;
                        }
                    }
                    if ($bodysub eq "")  {
                        &AddSymbol($_, $bodymid);           ##  Call for manual substitution
                    }
                    $_ = $fipart.$bodysub.$separt;          ##  Substituted !!
                    ### $_ = $fipart.$bodymid.$separt;
##      Replaced fragment can make the current string shorter or longer. Its length should be corrected.
                    $maxlen = length($_);
                }
            }  else  {
                goto AAAA;
##                $postart = $icurpos + 1;
            }
        }
AAAA:
        $c -= 1;
    }

####################################   }
####        print ERR "\n$_\nProcesssed string is above ==========================================================\n\n";
}

###############################################################################
##      SUBROUTINE   AddSymbol                                               ##
##      Supports possibility to add UTF-8 substitution for TeX diacritical   ##
##      characters not included into the predefined set.                     ##
###############################################################################

sub AddSymbol  {
    $_ = $_[0];
    $bodymid = $_[1];
##########################################    print ERR "AddSymbol  --> $dialogue\n";
    if ($dialogue eq true)  {
        print ERR "There is no substitution  for [$bodymid] in the predefined symbols list.\n";
        print ERR "Enter utf-8 code in the format  \"xNN[NN]\" or \"s\" to skip current substitution \n";
        print ERR "or \"A\" to block all requests for substitution/\n"

##      W A R N I N G ! !  This subroutine does not support  "verbose" option in TeX file preamble

##        open (<STDIN>);
##        $abc = <STDIN>;


#        while($_ = <STDIN>) {
##            chop();
##            if ($abc eq "s")  {
##                print "OK!\n";
##            }  else  {
##                print "No input!\n";
##            }
#        }
    }  else  {
        $bodysub = "\&\#x81\;";
        return;
    }
}

###############################################################################
##      SUBROUTINE   VerbDelimit                                             ##
##      Defines the value of $verblet delimiter symbols for \verb command    ##
###############################################################################

sub VerbDelimit {
    $verstr = $_[0];
    $verblet = "";
    for ($iv = 0; $iv < @verbdiv; $iv ++)  {
        $verbcheck = "\\".$verbdiv[$iv];
        if ($verstr =~ /$verbcheck/)  {
        }  else  {
            $verblet = $verbdiv[$iv];
            last;
        }
    }
}

###############################################################################
##      SUBROUTINE   ImageParams                                             ##
##      Defines sizes of figure image                                        ##
###############################################################################

sub ImageParams {
    $imgname = $_[0];
    $comline = $imagick."identify ".$imgname." > c:\\temp\\imgpar.tmp";
    system $comline;
    open (IMG, "<$imgpar")  ||  die  "Cannot open  $imgpar file.";
    $parimg = <IMG>;
    close (IMG);
    @frags = split(/ +/, $parimg);
    @sizes = split(/x/, $frags[2]);
    return;
}

###############################################################################

###############################################################################
##      SUBROUTINE   BlockedFrags                                            ##
##      Defines list of blocked fragments for preventing \verb and           ##
##      math  from breaking by font tags and diacritical signs               ##
###############################################################################

sub BlockedFrags {
    $imgname = $_[0];
##      The fragment below sets BLOCK MARKS FOR \VERB substrings to
##      prevent substitution of UTF-8 chars
        $lencurline = length($_);
        $bln = 0;
        if (/\\verb/)  {
            $stpos = 0;
            while ($stpos < $lencurline)  {
                $blo[$bln] = index($_, "\\verb", $stpos);
                if ($blo[$bln] > 0)  {
                    $blmpos = $blo[$bln] + 5;
                    $blm = substr($_, $blmpos, 1);
                    $blc[$bln] = index($_, $blm, $blmpos+1);
                    ##print ERR "Current opening [$blm] position $blo[$bln] on line $i\n";
                    ##print ERR "Current closing [$blm] position $blc[$bln] on line $i\n";
                    $stpos = $blc[$bln];
                    $bln += 1;
                }  else  {
                    last;
                }
            }
            ####print ERR "Blocked verbatim frags  BLN = $bln\n";
            for ($jj = 0; $jj < $bln; $jj++)  {
                ####print ERR "$blo[$jj] <> $blc[$jj]\n";
            }
        }
##      The fragment below sets BLOCK MARKS FOR INLINE MATH substrings to
##      prevent substitution of UTF-8 chars
        $swdol = 0;
        $don = 0;
        if (/\$/)  {
            $stpos = 0;
            while (/\$/) {
              $dolpos = index($_, "\$", $stpos);
                $presym = substr($_, $dolpos-1, 1);
                if ($dolpos < 0)  {
                    last;
                }
                if ($presym ne "\\")  {
##      Check if the current $dolpos is out of blocked substrings
                    $dolab = "true";
                    for ($jj = 0; $jj < $bln; $jj++)  {
                        if ($dolpos >= $blo[$jj] && $dolpos <= $blc[$jj])  {    ##  $dolpos is inside blocked substring
                            $dolab = "false";
                        }
                    }
                    if ($dolab eq "true")  {
                        if ($swdol == 0)  {
                            $doo[$don] = $dolpos;
                            $swdol = 1;
                        }  else  {
                            $doc[$don] = $dolpos;
                            $swdol = 0;
                            $don += 1;
                        }
                    }
                }
                $stpos = $dolpos + 1;
            }
##      Checking consistancy of inline math tags
            ##print ERR "Blocked inline math frags  DON = $don \n";
            for ($k = 0; $k < $don; $k++)  {
                ##print ERR "$doo[$k] <> $doc[$k] \n";
            }
            if ($swdol == 1)  {
                print ERR "Wrong inline math structure in para $i (lines  $SaveCleanPar[$i][1] -- $SaveCleanPar[$i][2]) \n";
                $errcount += 1;
                goto OUTER;
            }
        }
##      Merging blocked frags
        @jnt = ();
        if ($bln > 0 || $don > 0)  {
            $im = 0;
            for ($jj = 0; $jj < $bln; $jj++)  {
                $jnt[$im] = $blo[$jj] * 1000000 + $blc[$jj];
                $im += 1;
            }
            for ($k = 0; $k < $don; $k++)  {
                $jnt[$im] = $doo[$k] * 1000000 + $doc[$k];
                $im += 1;
            }
            $imax = $bln + $don;
            if ($imax != $im)  {
            }  else  {
                for ($jj = 0; $jj < $imax; $jj++)  {
                }
##          Ordering (sorting) blocked frags
                @rightlist = sort { $a <=> $b } @jnt;
            }
        }
        $numbl = @rightlist;
        if ($numbl > 0)  {
        }
        for ($iii = 0; $iii < $numbl; $iii++)   {
            $lenran = length($rightlist[$iii]);
            $range[$iii][0] = (substr($rightlist[$iii], 0, $lenran - 6)) * 1;
            $range[$iii][1] = (substr($rightlist[$iii], $lenran - 6)) * 1;

##before last##
###            if ($i == 91)  {
###                print ERR "$range[$iii][0] <> $range[$iii][1]\n";
###            }
        }
        $numblank = $numbl;
##before last##        print ERR "Numblank before cleaning = $numblank\n";
        $numbl = 0;
        @rightlist = ();        ##      Emptying list
##before last##        print ERR "Numblank after cleaning = $numblank\n";

##  Now we have the list of blocked fragments !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
###############################################################################

###############################################################################
##      SUBROUTINE   CutCaption                                              ##
##      Reduces figure/table captions                                        ##
###############################################################################

sub CutCaption {
    $captshort = $_[0];
####    print ERR "$captshort \n\n";
    $lenini = length($captshort);
    if ($lenini <= 65)  {
        return;
    }  elsif ($captshort =~ /<a href=/  && $captshort =~ /<\/a>/)  {    ##  Caption contains one or more hyperlinks
        $posblop = index($captshort, "<a href=");
        if ($posblop > 60) {
            $posblank = index($captshort, " ", 55);
        }  else  {
            $posblcl = index($captshort, "<\/a>");
            if ($posblcl <= $posblop)  {
                print ERR "Caption \"$captshort\"  contains wrong structure of <a href=...> <\/a> tags.\n";
                $errcount += 1;
            }  else  {
                $postwop = index($captshort, "<a href=", $posblcl);
                if ($postwop < 0)   {
                    goto ENDSC;
                }  else  {
                    $pointone = $posblcl + 4;
                    $pointtwo = $postwop;
                    $lentwo = $postwop - $pointone;
                    $vistr = $posblop + $lentwo + 10;
####                print ERR  "posblop = $posblop   posblcl = $posblcl    postwop = $postwop    pointone = $pointone   pointtwo = $pointtwo    $lentwo = $lentwo   vistr = $vistr\n";
                }
                if ($vistr > 60)  {
                    $addiv = $posblcl - $posblop - 6;
                    $posblank = index($captshort, " ", 55+$addiv);
                }
            }
ENDSC:
            $addiv = $posblcl - $posblop - 6;
            $posblank = index($captshort, " ", 55+$addiv);
        }
        $captshort = substr($captshort, 0, $posblank);
        $captshort .= "...";
    }  elsif ($captshort =~ /<a href=/  || $captshort =~ /<\/a>/)  {    ##  Wrong hyperlink structure
        print ERR "Caption \"$captshort\"  has wrong structure\n";
        $errcount += 1;
    }  else  {                                                          ##  Long caption
        $posbreak = index($captshort, " ", 60);
        $captshort = substr($captshort, 0, $posbreak);
        $captshort .= "...";
    }
}

###############################################################################

###############################################################################
##      SUBROUTINE   setTitlePageEng                                         ##
##      Adds detalization parameter to the title page                        ##
###############################################################################
sub setTitlePageEng {
    $titleini = $_[0];
    $titleini =~ s/\.png//;    
    print ERR "titleini = $titleini\n";
    ##      merging initials with last name
    $mergedauthors = $authcitdir;
    print ERR "mergedauthors = $mergedauthors\n";    
    $mergedauthors =~ s/\. /\.\~/g;
    $gentittex = "title".$listdirnam."\.tex";
    $inpdf = $gentittex;
    $inpdf =~ s/tex/pdf/;
    $injpg = $gentittex;
    $injpg =~ s/tex/jpg/;
    open (TIT, ">$gentittex")  ||  die "Cannot open $gencovtex file.\n";
    print TIT <<EOM;
\\documentclass[epub,pdf]{ebook}
\\usepackage{color}
\\usepackage[pdftoolbar=false, pdfpagemode=UseNone, linkbordercolor={0 0 0}]{hyperref}
\\definecolor{khaki}{RGB}{247,247,31}
\\definecolor{shadow}{RGB}{5,5,5}
\\definecolor{brown}{RGB}{157,23,4}
\\begin{document}
\\begin{figure}
\\setimage{}{-300mm}{100mm}{}{basic\/$titleini}
\\setlength{\\unitlength}{1pc}
\\begin{picture}(10,10)
\\put(11,39.3){\\makebox(15,2){\\bfseries{\\small\\sf \\textcolor{khaki}{ISSN 1681-1208}}}}
\\put(5.5,32.3){\\makebox(15,2)[r]{\\bfseries{\\small\\sf \\textcolor{khaki}{EPUB Companion to Published Articles}}}}
\\put(5.5,31){\\makebox(15,2)[r]{\\bfseries{\\small\\sf \\textcolor{khaki}{doi:10.2205\/$names[0]}}}}
\\put(0.08,22.92){\\makebox(25,5){\\textcolor{shadow}{\\parbox{70mm}{\\small  $articletitle \\vspace*{1.5\\baselineskip} \\\\  \\centerline{\\parbox{70mm}{\\itshape by $authcitdir}}}}}}
\\put(0,23){\\makebox(25,5){\\textcolor{white}{\\parbox{70mm}{\\small $articletitle \\vspace*{1.5\\baselineskip} \\\\  \\centerline{\\parbox{70mm}{\\itshape by $authcitdir}}}}}}
\\put(8,11){\\makebox(10,2)[c]{\\bfseries{\\small\\sf \\textcolor{khaki}{Moscow  2019}}}}
\\end{picture}
\\end{figure}
\\end{document} 
EOM
close(TIT);
##      Start pdflatex to produce title image
    $comline1 = "pdflatex ".$gentittex." > ".$null;
    system $comline1;
##      Using ImageMagick to convert  PDF to JPG
    $comline2 = $imagick."convert -density 300 ".$inpdf." ".$injpg;
    system $comline2;
##      Trimming extra space around the image
    $comline3 = $imagick."mogrify -trim ".$injpg;
    system $comline3;
    $tttt = $injpg;    
    return;
}
###############################################################################

###############################################################################
##      SUBROUTINE   setTitlePageRus                                         ##
##      Adds detalization parameter to the title page                        ##
###############################################################################
sub setTitlePageRus {
    $titleini = $_[0];
    $titleini =~ s/\.png//;    
    ###print ERR "titleini = $titleini\n";
    
    ##      merging initials with last name
    $mergedauthors = $authcitdir;
    $mergedauthors =~ s/\. /\.\~/g;

##    $gentittex = "title".$listdirnam."\.tex";
##    $inpdf = $gentittex;
##    $inpdf =~ s/tex/pdf/;
##    $injpg = $gentittex;
##    $injpg =~ s/tex/jpg/;
    $gentittex = "title".$listdirnam."\.tex";
    $inpdf = $gentittex;
    $inpdf =~ s/tex/pdf/;
    $injpg = $gentittex;
    $injpg =~ s/tex/jpg/;
    print ERR "inpdf = $inpdf\n";
    if (-e $inpdf)  {
    }  else  {
        open (TIT, ">$gentittex")  ||  die "Cannot open $gencovtex file.\n";
        print TIT <<EOM;
\\documentclass[epub,pdf]{ebook}
\\usepackage{color}
\\usepackage[pdftoolbar=false, pdfpagemode=UseNone, linkbordercolor={0 0 0}]{hyperref}
\\definecolor{khaki}{RGB}{247,247,31}
\\definecolor{shadow}{RGB}{5,5,5}
\\definecolor{brown}{RGB}{157,23,4}
\\begin{document}
\\begin{figure}
\\setimage{}{-300mm}{100mm}{}{basic\/$titleini}
\\setlength{\\unitlength}{1pc}
\\begin{picture}(10,10)
\\put(11,39.3){\\makebox(15,2){\\bfseries{\\small\\sf \\textcolor{khaki}{ISSN 1681-1208}}}}
\\put(5.5,32.3){\\makebox(15,2)[r]{\\bfseries{\\small\\sf \\textcolor{khaki}{EPUB Companion to Published Articles}}}}
\\put(5.5,31){\\makebox(15,2)[r]{\\bfseries{\\small\\sf \\textcolor{khaki}{doi:10.2205\/$names[0]}}}}
\\put(0.08,22.92){\\makebox(25,5){\\textcolor{shadow}{\\parbox{70mm}{\\small  $articletitle \\vspace*{1.5\\baselineskip} \\\\  \\centerline{\\parbox{70mm}{\\itshape by $mergedauthors}}}}}}
\\put(0,23){\\makebox(25,5){\\textcolor{white}{\\parbox{70mm}{\\small $articletitle \\vspace*{1.5\\baselineskip} \\\\  \\centerline{\\parbox{70mm}{\\itshape by $mergedauthors}}}}}}
\\put(8,11){\\makebox(10,2)[c]{\\bfseries{\\small\\sf \\textcolor{khaki}{Moscow  2019}}}}
\\end{picture}
\\end{figure}
\\end{document}
EOM
close(TIT);

##      Start pdflatex to produce title image
        $comline1 = "pdflatex ".$gentittex." > ".$null;
        system $comline1;    
    }        
    
##      Using ImageMagick to convert  PDF to JPG
    $comline2 = $imagick."convert -density 300 ".$inpdf." ".$injpg;
    
    print ERR "comline2 = $comline2\n";
    
    system $comline2;
##      Trimming extra space around the image
    $comline3 = $imagick."mogrify -trim ".$injpg;
    
    print ERR "comline3 = $comline3\n";

    system $comline3;
    $tttt = $injpg;    
    return;
}
###############################################################################

###############################################################################
##      SUBROUTINE   setCoverPageEng                                         ##
##      Adds detalization parameter to the cover page                        ##
###############################################################################
sub setCoverPageEng {
    $coverini = $_[0];
    $coverini =~ s/\.png//;    
    ###print ERR "coverini = $coverini\n";
   
    $gencovtex = "cover".$listdirnam."\.tex";
    $inpdf = $gencovtex;
    $inpdf =~ s/tex/pdf/;
    $injpg = $gencovtex;
    $injpg =~ s/tex/jpg/;
    open (COV, ">$gencovtex")  ||  die "Cannot open $gencovtex file.\n";
print COV <<EOM;
\\documentclass[epub,pdf]{ebook}
\\usepackage{color}
\\usepackage[pdftoolbar=false, pdfpagemode=UseNone, linkbordercolor={0 0 0}]{hyperref}
\\definecolor{khaki}{RGB}{247,247,31}
\\newcommand{\\fontcovnumb}{\\fontsize{22}{28}\\selectfont}
\\begin{document}
\\thispagestyle{empty}
\\begin{figure}
\\setimage{}{-300mm}{100mm}{}{basic\/$coverini}
\\setlength{\\unitlength}{1pc}
\\begin{picture}(10,10)
\\put(11,39.3){\\makebox(15,2){\\bfseries{\\small\\sf \\textcolor{khaki}{ISSN 1681-1208}}}}
\\put(2.5,30){\\makebox(20,2){\\bfseries{\\small\\sf \\textcolor{khaki}{EPUB Companion to Published Articles}}}}
\\put(2.6,25){\\makebox(20,2){\\bfseries{\\large{\\bfseries\\scshape \\textcolor{red}{A R T I C L E}}}}}
\\put(2.6,22){\\makebox(20,2){\\bfseries{\\fontcovnumb{\\bfseries \\textcolor{red}{$names[0]}}}}}
\\put(8,11){\\makebox(10,2){\\bfseries{\\small\\sf \\textcolor{khaki}{Moscow  2019}}}}
\\end{picture}
\\end{figure}
\\end{document} 
EOM
close(COV);

##      Start pdflatex to produce cover image
    $comline1 = "pdflatex ".$gencovtex." > ".$null;
    system $comline1;
##      Using ImageMagick to convert  PDF to JPG
    $comline2 = $imagick."convert -density 300 ".$inpdf." ".$injpg;
    system $comline2;
##      Trimming extra space around the image
    $comline3 = $imagick."mogrify -trim ".$injpg;
    system $comline3;
    $cccc = $injpg;    
    return;
}
##############################################################################

###############################################################################
##      SUBROUTINE   setCoverPageRus                                         ##
##      Adds detalization parameter to the cover page                        ##
###############################################################################
sub setCoverPageRus {
    $coverini = $_[0];
    $coverini =~ s/\.png//;    
    ###print ERR "coverini = $coverini\n";
   
    $gencovtex = "cover".$listdirnam."\.tex";
    $inpdf = $gencovtex;
    $inpdf =~ s/tex/pdf/;
    $injpg = $gencovtex;
    $injpg =~ s/tex/jpg/;
    open (COV, ">$gencovtex")  ||  die "Cannot open $gencovtex file.\n";
print COV <<EOM;
\\documentclass[epub,pdf]{ebook}
\\usepackage{color}
\\usepackage[pdftoolbar=false, pdfpagemode=UseNone, linkbordercolor={0 0 0}]{hyperref}
\\definecolor{khaki}{RGB}{247,247,31}
\\newcommand{\\fontcovnumb}{\\fontsize{22}{28}\\selectfont}
\\begin{document}
\\thispagestyle{empty}
\\begin{figure}
\\setimage{}{-300mm}{100mm}{}{basic\/$coverini}
\\setlength{\\unitlength}{1pc}
\\begin{picture}(10,10)
\\put(2.5,30){\\makebox(20,2){\\bfseries{\\small\\sf \\textcolor{khaki}{EPUB Companion to Published Articles}}}}
\\put(2.6,25){\\makebox(20,2){\\bfseries{\\large{\\bfseries\\scshape \\textcolor{red}{A R T I C L E}}}}}
\\put(2.6,22){\\makebox(20,2){\\bfseries{\\fontcovnumb{\\bfseries \\textcolor{red}{$names[0]}}}}}
\\put(8,11){\\makebox(10,2){\\bfseries{\\small\\sf \\textcolor{khaki}{Moscow  2019}}}}
\\end{picture}
\\end{figure}
\\end{document} 
EOM
close(COV);

##      Start pdflatex to produce cover image
    $comline1 = "pdflatex ".$gencovtex." > ".$null;
    system $comline1;
##      Using ImageMagick to convert  PDF to JPG
    $comline2 = $imagick."convert -density 300 ".$inpdf." ".$injpg;
    system $comline2;
##      Trimming extra space around the image
    $comline3 = $imagick."mogrify -trim ".$injpg;
    system $comline3;
    $cccc = $injpg;    
    return;
}
##############################################################################

##############################################################################
##          SUBROUTINE  formHtmlTable  to convert TeX tables into HTML      ## 
##  This script supports only \table/\table* environment, no \longtable or  ##
##  \supertabular                                                           ## 
##############################################################################
sub formHtmlTable {

    $intextab = $_[0];
    $outtabfile = $intextab;
    @namestab = split(/\./,$outtabfile);
##  $outtabfile = $namestab[0]."tot.html"; 
    $outtab = $_[1];
    $tabtitle = $outtab;
    $tabtitle =~ s/\.html//;
    $tcount = $_[2];
##    $curtabcaption = $_[3];
##  $outtab = $names[0].".html"; 
####$errfile  = $names[0].".err";
##       Removing extra spaces and splitting fields         


##$intextab = "tab01.tex";
##$outtab = "2015ES000546-tab01.html";

#######################################print ERR "ACCEPTED BY formHtmlTable  intextab = $intextab    outtab = $outtab    tcount = $tcount\n";

    open (INTAB, "<$intextab") ||  die "Cannot open $intextab file.";
    ####print ITEMS "\n\n========================================================\n Accepted by formHtmlTable \n=======================================\n";
##  Scanning input file and extract tables with merging broken lines
    $itab = 0;				##	Number of lines
    $lintab[0] = 0;		    ##	Current line (table)
    $lintab[1] = "";
    $labins = false;
    $in = 0;				##	Counter of input strings
    $err = 0;				##	Error counter
    $inf = 0;				##	Warning counter
    $merline = "";          ##  Table merged as one line
    while (<INTAB>)  {
####        print ITEMS $_; 
        chop();
        if (/\\multicolumn/  &&  /parbox/)  {
            s/\<parbox\>\{//g;
            s/\}\<\/parbox\>//g;
        }
        $merline .= $_." ";
##==    print ERR "III merline = $merline\n";
    }
##$tables = $itab;
#####print OUT "<p \/>Tables $tables\n";
#####print ITEMS "\n\n======================== End ================================\n";
    close (INTAB);
    $merline =~ s/ figparsplaceholder\[..\]  //g;
    $merline =~ s/ tabparsplaceholder\[..\]  //g;
###    print ERR "SSS merline = $merline\n";
    $lintab[1] = $merline;
####close (CON);

##	N O T E!  In this version it is assumed that LaTeXed table version already cleaned
##  from extra spaces \vspace and some other formatting commands
##	Main cycle of scanning table
#####print OUT "\n\n\n";

##for ($itab = 0; $itab < $tables; $itab++)  {
	$_ = $lintab[1];
	s/\\\\\[/\\\\ \[/g;
	s/--/-/g;
	s/ +/ /g;
##		Extracting captions
	$curtabcaption = "";
	if (/\\.*caption\{/)  {
        $capos = index($_, "caption\{");
        ###print ERR "$_\n";
        ###print ERR "capos = $capos\n";
		$firstpart = substr($_, 0, $capos);
		$secondpart = substr($_, $capos+8);
        ###print ERR "$firstpart\n$secondpart\n";
		&CheckPairBrackets($secondpart);
		if ($cpb eq false)  {
            print ERR "ERROR: Not matching curly  brackets occured while extracting \\caption. \n";
            $errcount += 1;
        }  else  {
			$tcaption = $body;
############print ERR "CAPTION-INS = $tcaption\n";
		}
	}  else  {
		$inf += 1;
		###print ERR "WARNING: There is no caption in Table $itab\n";
	}
	$lintab[2] = $tcaption;
##	print ERR "\n0-$lintab[0]\n";
##	print ERR "1-$lintab[1]\n";
##	print ERR "2-$lintab[2]\n";
##	print ERR "3-$lintab[3]\n\n";
################################################################################################################

##		Extracting tablefootnote
##	N O T E!  It is assumed that table has only one \tablefootnote  !!!!!!!!!!!!!!!!!!!!!!!!!
	$footnote = "";
	if (/\\tablefootnote\{.+\}\{.?\}\{/)  {
		$tapos = index($_, "\\tablefootnote\{");
		$firstpart = substr($_, 0, $tapos);
		$secondpart = substr($_, $tapos+15);
		@frags = split(/\}\{/, $secondpart);
		&CheckPairBrackets($frags[2]);
		if ($cpb eq false)  {
			print ERR "ERROR: Not matching curly  brackets occured while extracting \\tablefootnote. \n";
            $errcount += 1;
		}  else  {
			$footnote = $body;
		}
	}
	$lintab[3] = $footnote;
	#####print OUT "$lintab[3]\n";

	###print ERR "0-$lintab[0]\n";
	###print ERR "1-$lintab[1]\n";
	###print ERR "2-$lintab[2]\n";
	###print ERR "3-$lintab[3]\n";
##		Analysis of \begin{tabular}
	$tab = index($_, "\\begin\{tabular\}");
	$tail = substr($_, $tab+17);
###print ERR "COLUMNS IN = $tail\n";
	&CheckPairBrackets($tail);	
	if ($cpb eq false)  {
		print ERR "ERROR: Not matching curly  brackets occured while extracting \\tabular. \n";
        $errcount += 1;
	}  else  {
		$tabset = $body;
	}
##	print ERR "TABSET-1 = $tabset\n";
	$tabset =~ s/\\hspace//g;
	$tabset =~ s/[\d]//g;
	$tabset =~ s/\{pt\}//g;
	$tabset =~ s/\{pc\}//g;
	$tabset =~ s/\@\{\}//g;
	$tabset =~ s/ //g;
	$tabset =~ s/\|//g;
##	print ERR "TABSET-2 = $tabset\n";
	@cell = split(//, $tabset);
	$lentab = @cell;
	$demo = join("<>", @cell);
###print ERR "\nCELLS = $lentab  STR = $demo\n";
###print ERR "TAIL  = $tail\n\n";
##	Removing \end{tabular}\end{table}
	$etpos = index($tail, "\\end\{tabular\}");
	$middle = substr($tail, 0, $etpos);
###print ITEMS "\nMIDDLE-1 = $middle\n\n";
	$tail = "";
##------------------------==============--------------===============
	$middle =~ s/\\hline//g;
	$middle =~ s/(\d)+pt//g;
	$middle =~ s/(\d)+pc//g;
	$middle =~ s/\[\+\]//g;
	$middle =~ s/\[\-\]//g;
	$middle =~ s/\[\]//g;
	$middle =~ s/\\cline\{.{1,2}\-.{1,2}\}//g;
	$middle =~ s/ +/ /g;
	$middle =~ s/^( ?\\\\)//;
	$middle =~ s/(\\\\ +)$//;
###print ITEMS "MIDDLE-2 = $middle\n\n\n";
##	Splitting \tabular to strings
	@strings = split(/\\\\/, $middle);
	$numstr = @strings;
	$empty = 0;
	$noem = 0;
	for ($itt = 0; $itt < $numstr; $itt++)  {
		$strings[$itt] =~ s/^( +)//;
		if ($strings[$itt] eq "")  {
			$empty += 1;
		}  else  {
			$restr[$noem] = $strings[$itt];
			$noem += 1;			##	Number of non-empty strings
		}
####        print ERR "==--==$strings[$itt]\n";         ##      Print table strings
	}
####    print ERR "empty = $empty        noem = $noem\n";

##	Output test for compressed set of strings
	for ($ito = 0; $ito < $noem; $ito++)  {
####        print ERR "LINE=$ito  <> $restr[$ito]\n";
	}
##print ERR "NUMSTR = $numstr   EMPTY = $empty  NONEMPTY = $noem\n";
#	Estimate table width                       ##################  TABLE  WIDTH  ?????  ####################
	$strlen = 0;
	for ($ito = 0; $ito < $numstr; $ito++)  {
		$strcur = length($strings[$ito]);
###        print ERR "$strcur <> $strings[$ito]\n";
		if ($strcur > $strlen)  {
			$strlen = $strcur;
		}
###        print ERR "$strlen\n";
	}
##	$strlen parameter is fixed for future use
###    print ERR "WIDTH = $strlen\n";
##	Opening current table file
	$tabsuf = $lintab[0] + 1;
    $ittt = $tabsuf;
	if ($tabsuf < 10)  {
		$tabsuf = "0".$tabsuf;
	}
	####$tabnam = $names[0]."-tab".$tabsuf."\.shtml";

#############    print ERR "\n====\nTABTITLE = $tabtitle       outtab = $outtab\n\n";

	open (FLOAT, ">$outtab")  || die "Cannot open $outtab file.";
	print FLOAT <<EOM;
<!DOCTYPE html>
<html>
<head>
<title>$tabtitle</title>
    <script type="text/x-mathjax-config">
    MathJax.Hub.Config({tex2jax: {inlineMath: [['\$','\$'], ['\\\\(','\\\\)']]\}\});
</script>
<script type="text/javascript"
     src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full">
</script>
</head>
<body>
<CENTER>PUT HERE RUNNING HEAD</CENTER><HR>
<b>Table $tcount.</b>  $tcaption
<table border=\"1\">
EOM
##	Splitting all strings into cells
##  Before splitting string into cells we need  to prevent diacritical symbols
	for ($ito = 0; $ito < $noem; $ito++)  {
        $restr[$ito] =~ s/\&\#x/\[dcr\]/g;
##        if ($ito == $noem-1)  {
##            print ERR "\n$restr[$ito]\n\n";
##        }
		@td = split(/\&/, $restr[$ito]);
		$ncel = @td;
        ##print ERR "ncel = $ncel  |||  @td\n";
		$tabrow = "<tr>";
##	Check cells!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		for ($j = 0; $j < $ncel; $j++)  {
##        Restore diacritical symbols
          $td[$j] =~ s/\[dcr\]/\&\#x/g;             ##  Restoring diacritical symbols
		  #############################################################################print ERR "CELL-to-CELL  td[$j] = $td[$j]\n";
		}
		for ($j = 0; $j < $ncel; $j++)  {
			if ($td[$j] =~ /\\multicolumn/)  {		## 	\multicolumn branch
				$labfoot = false;
				$poscol = index($td[$j], "\\multicolumn") + 13;
				$tdcol = substr($td[$j], $poscol);
				$pospos = index($tdcol, "\}\{");
				$tdpos = substr($tdcol, $pospos + 2);
				$tdcol = substr($tdcol, 0, $pospos);
                $frone = "<td colspan=\"".$tdcol."\" ";
				$poscont = index($tdpos, "\}\{");
				$tdcont = substr($tdpos, $poscont + 2);
				$tdpos = substr($tdpos, 0, $poscont);
				$body = "";
				$tail = "";
				&CheckPairBrackets($tdcont);
				if ($cpb eq false)  {
					$err += 1;
           				print ERR "ERROR: 1-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
				}  else  {
					$tdcont = $body;
				}
			
				if (($tail ne "") && ($tail ne " ")) {
					$err += 1;
           				print ERR "ERROR: 2-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
				}

				$tail = "";
######				print OUT "NCEL=$ncel [] MultCol  $td[$j] <<>> $tdcol <> $tdpos <> $tdcont \n";
			}  elsif ($td[$j] =~ /\\tablefootnote/)   {	##	\tablefootnote branch
				$labfoot = true;
				$poscol = index($td[$j], "\\tablefootnote") + 15;
				$tdcol = substr($td[$j], $poscol);
				$pospos = index($tdcol, "\}\{");
				$tdpos = substr($tdcol, $pospos + 2);
				$tdcol = substr($tdcol, 0, $pospos);
                $frone = "<td colspan=\"".$tdcol."\" ";
				$poscont = index($tdpos, "\}\{");
				$tdcont = substr($tdpos, $poscont + 2);
				$tdpos = substr($tdpos, 0, $poscont);
				$body = "";
				$tail = "";
				&CheckPairBrackets($tdcont);
				if ($cpb eq false)  {
					$err += 1;
           				print ERR "ERROR: 1-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
				}  else  {
					$tdcont = $body;
				}
				if (($tail ne "") && ($tail ne " ")) {
					$err += 1;
           				print ERR "ERROR: 2-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
				}
				$tail = "";
				$tdcont = "<sup>".$tdpos."</sup>".$tdcont;

			} elsif($td[$j] =~ /\\vtcell\[/)  {             ##  VTCELL      \vtcell[l]{First column}
                                                            ##  <td class="versubtit">First&nbsp;column</td>
                $td[$j] =~ s/\\vtcell\[.\]\{//;
                $td[$j] =~ s/\}//;
                $td[$j] =~ s/&nbsp;/\&\#xA0\;/g;
                $td[$j] =~ s/\~/\&\#xA0\;/g;
				$tdcont = $td[$j];                
                $frone = "<td class=\"versubtit\"";
			} elsif($td[$j] =~ /\\begin\{turnbox\}/)  {     ##  TURNBOX     \begin{turnbox}{40}{First column}\end{turnbox}
                $td[$j] =~ s/\\begin\{turnbox\}\{//;        ##  <td style="border-width: 0px; height: 100px; width: 20px; 
                $td[$j] =~ s/\}\\end\{turnbox\}//;          ##  transform: rotate(-40deg); -webkit-transform: rotate(-40deg); 
                @elams = split(/\}\{/, $td[$j]);            ##  -moz-transform: rotate(-40deg); -o-transform: rotate(-40deg); -ms-transform: rotate(-40deg);">  
                $grad = $elams[0] * -1;
                $teval = $elams[1];                              
                $teval =~ s/\&nbsp\;/\&\#xA0\;/g;
                $teval =~ s/\~/\&\#xA0\;/g;
				$tdcont = $teval;                
                $frone = "<td style=\"border-width\: 0px\; height\: 100px\; width\: 20px\; transform\: rotate(".$grad."deg)\; -webkit-transform\: rotate(".$grad."deg)\; -moz-transform\: rotate(".$grad."deg)\; -o-transform\: rotate(".$grad."deg)\; -ms-transform\: rotate(".$grad."deg)\;\"";
            }  else  {
				$labfoot = false;
				$tdcol = "1";
                $frone = "<td ";
				$tdpos = $cell[$j];
				$tdcont = $td[$j];
			}
            $frtwo = ">";           ##  Blocking 'align' parameter  for xhtml version
			$tabrow = $tabrow.$frone.$frtwo.$tdcont."<\/td>";
 		}								
		$tabrow = $tabrow."<\/tr>";	
        $tabrow =~ s/~/\&\#xA0\;/g;
		print FLOAT "$tabrow\n";
    }
	print FLOAT <<EOM;
</table>
EOM
close (FLOAT);
unlink (FLOAT);
}

###########################################################################
##      SUBROUTINE   CheckPairBrackets                                   ##
##      This subroutine checks if number of curly brackets is even       ##
###########################################################################
sub CheckPairBrackets {
  	$cpb = false;
   	$tail = $_[0];
   	$tmpstr = $tail;
	$poslab = -1;
	$loglab = -1;
	$start = 0;
	while ($loglab < 0)  {
		$indop = index($tmpstr, "\{", $start);
		$indcl = index($tmpstr, "\}", $start);
		if ($indop >= 0 && $indcl >= 0)  {		##	Both positive
			if ($indop > $indcl)  {
				$start = $indcl + 1;
				$loglab += 1;
				$poslab = $indcl;
				$cpb = true;
			} else {
				$start = $indop + 1;
				$loglab -= 1;
				$poslab = $indop;
				$cpb = true;
			}
		}  elsif ($indop >= 0 && $indcl < 0)  {		##	Open positive
			$cpb = false;
	##		last;
		}  elsif ($indop < 0 && $indcl >= 0)  {		##	Close positive
			$start = $indcl + 1;
			$loglab += 1;
			$poslab = $indcl;
			$cpb = true;
		}  else  {
			$cpb = false;
	##		last;
		}
	}
	if ($poslab >= 0)  {
		$body = substr($tmpstr, 0, $poslab);
		$tail = substr($tmpstr, $poslab + 1);
	}
    if ($cpb eq false)  {
        $tail = $tmpstr;
        $body = "";
    }
    if ($tmpstr =~ /^}/)  {
        $body = "";
        $cpb = true;
        $tail = substr($tmpstr, 1);
    }
}

########################################################################

###########################################################################
##      SUBROUTINE   ConvIntextTabul                                     ##
##      This subroutine converts inb-text tabulars to HTML               ##
###########################################################################
sub ConvIntextTabul {
 
    $midtabul = $_[0];
	$midtabul =~ s/\\hline//g;
	$midtabul =~ s/(\d)pt//g;
	$midtabul =~ s/(\d)pc//g;
	$midtabul =~ s/\[\+\]//g;
	$midtabul =~ s/\[\-\]//g;
	$midtabul =~ s/\[\]//g;
	$midtabul =~ s/\\cline\{.{1,2}\-.{1,2}\}//g;
	$midtabul =~ s/ +/ /g;
	$midtabul =~ s/^( ?\\\\)//;
	$midtabul =~ s/(\\\\ +)$//;
    ###print ERR "\n\nSTART_OF_ConvIntextTabul: MIDTABUL = $midtabul\n\n";
    $htmltabul = "";

##	Splitting \tabular to strings
	@strings = split(/\[linebreak\]/, $midtabul);
	$numstr = @strings;
    $strings[0] = "";
	$empty = 0;
	$noem = 0;
	for ($itt = 0; $itt < $numstr; $itt++)  {
		$strings[$itt] =~ s/^( +)//;
		if ($strings[$itt] eq "")  {
			$empty += 1;
		}  else  {
			$restr[$noem] = $strings[$itt];
			$noem += 1;			##	Number of non-empty strings
		}
        ###print ERR "====$strings[$itt]\n";
	}
    ###print ERR "numstr = $numstr    empty = $empty        noem = $noem\n";
##	Output test for compressed set of strings
	for ($ito = 0; $ito < $noem; $ito++)  {
        ###print ERR "LINE=$ito  <> $restr[$ito]\n";
	}
###print ERR "NUMSTR = $numstr   EMPTY = $empty  NONEMPTY = $noem\n"; 
##	Estimate table width                       ##################  TABLE  WIDTH  ?????  ####################
	$strlen = 0;
	for ($ito = 0; $ito < $numstr; $ito++)  {
		$strcur = length($strings[$ito]);
###        print ERR "$strcur <> $strings[$ito]\n";
		if ($strcur > $strlen)  {
			$strlen = $strcur;
		}
###        print ERR "$strlen\n";
	}
##	Splitting all strings into cells
##  Before splitting string into cells we need  to protect diacritical symbols

	for ($ito = 0; $ito < $noem; $ito++)  {            ##      row-by-row processing
        $restr[$ito] =~ s/\&\#x/\[dcr\]/g;
		@td = split(/\&/, $restr[$ito]);
		$ncel = @td;
        ###print ERR "ncel = $ncel  |||  @td\n";
		$tabrow = "<tr>";
##	    Check cells!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		for ($j = 0; $j < $ncel; $j++)  {
          $td[$j] =~ s/\[dcr\]/\&\#x/g;             ##  Restoring diacritical symbols
		}
		for ($j = 0; $j < $ncel; $j++)  {
			if ($td[$j] =~ /\\multicolumn/)  {		## 	\multicolumn branch
				$labfoot = false;
				$poscol = index($td[$j], "\\multicolumn") + 13;
				$tdcol = substr($td[$j], $poscol);
				$pospos = index($tdcol, "\}\{");
				$tdpos = substr($tdcol, $pospos + 2);
				$tdcol = substr($tdcol, 0, $pospos);
				$poscont = index($tdpos, "\}\{");
				$tdcont = substr($tdpos, $poscont + 2);
				$tdpos = substr($tdpos, 0, $poscont);
				$body = "";
				$tail = "";
				&CheckPairBrackets($tdcont);
				if ($cpb eq false)  {
           			print ERR "ERROR: 1-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
                    $errcount += 1;
				}  else  {
					$tdcont = $body;
				}
				if (($tail ne "") && ($tail ne " ")) {
  				  print ERR "ERROR: 2-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
                    $errcount += 1;
				}
				$tail = "";
		print OUT "NCEL=$ncel [] MultCol  $td[$j] <<>> $tdcol <> $tdpos <> $tdcont \n";
			}  elsif ($td[$j] =~ /\\tablefootnote/)   {	##	\tablefootnote branch
				$labfoot = true;
				$poscol = index($td[$j], "\\tablefootnote") + 15;
				$tdcol = substr($td[$j], $poscol);
				$pospos = index($tdcol, "\}\{");
				$tdpos = substr($tdcol, $pospos + 2);
				$tdcol = substr($tdcol, 0, $pospos);
				$poscont = index($tdpos, "\}\{");
				$tdcont = substr($tdpos, $poscont + 2);
				$tdpos = substr($tdpos, 0, $poscont);
				$body = "";
				$tail = "";
				&CheckPairBrackets($tdcont);
				if ($cpb eq false)  {
           			print ERR "ERROR: 3-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
                    $errcount += 1;
				}  else  {
					$tdcont = $body;
				}
				if (($tail ne "") && ($tail ne " ")) {
           			print ERR "ERROR: 4-Something wrong in Table $itab, string $it0, cell [$td[$j]]. \n";
                    $errcount += 1;
				}
				$tail = "";
				$tdcont = "<sup>".$tdpos."</sup>".$tdcont;
			}  else  {
				$labfoot = false;
				$tdcol = "1";
				$tdpos = $cell[$j];
				$tdcont = $td[$j];
			}
			if ($tdcol eq 1)  {
				$frone = "<td ";
			}  else  {
				$frone = "<td colspan=\"".$tdcol."\" ";
			}
            $frtwo = ">";     ##  Blocking 'align' parameter  for xhtml version
			$tabrow = $tabrow.$frone.$frtwo.$tdcont."<\/td>";
 		}								
		$tabrow = $tabrow."<\/tr>";	
        $tabrow =~ s/~/\&\#xA0\;/g;
    ###print ERR "$tabrow\n";
        $htmltabul .= $tabrow."";   
    }
    $htmltabul =~ s/\{//g;
    $htmltabul =~ s/\}//g;
####    print ERR "\n\nEND_OF_ConvIntextTabul = $htmltabul\n\n";
}

##########################################################################

##########################################################################
##                    Subroutine verbReplace                            ##
##   This subroutine replaces \verb+ markers with initial texts         ##
##########################################################################  
sub verbReplace {
    $modifstring = $_[0];
####    print ITEMS "\nmodifstring-1 = $modifstring\n"; 
    if ($modifstring =~ /\(VERBLINE/)  {
        $sfrom = 0;
        while ($modifstring =~ /\(VERBLINE/)  {
            $posverop = index($modifstring, "\(VERBLINE", $sfrom);
            $posvercl = index($modifstring, "\)", $posverop);
            $lennumb = $posvercl - $posverop - 10;
            $franum = substr($modifstring, $posverop+10, $lennumb);
            $substfrag = $verbline[$franum];
            $substfrag =~ s/</\&\#x3C\;/g;      ##  <
            $substfrag =~ s/>/\&\#x3E\;/g;      ##  >
            $fraleft = substr($modifstring, 0, $posverop);
            $fraright = substr($modifstring, $posvercl+1);
            $modifstring = $fraleft."<span class=\"verb\">".$substfrag."<\/span>".$fraright;
####    print ITEMS "modifstring-2 = $modifstring\n\n"; 
        }
    }
}

##########################################################################
##                    Subroutine revertUTF                              ##
##   This subroutine reverts UTF-8 to TeX format for making miniPDF     ##
##########################################################################  
sub revertUTF {
    $utffrag = $_[0];
####    print ERR "\n SBR utffrag =$utffrag\n";
##  Looking for TeX equivalent in @symb01 array 
    $texfrag = "";  
    for ($is = 0; $is < $s1; $is++)  {
####print ERR "utffrag = $utffrag  <<>>  symb01[$is][1] = $symb01[$is][1]\n";
        if($utffrag eq $symb01[$is][1])  { 
            $texfrag = $symb01[$is][0];
        }
    }
    if ($texfrag eq "")  {      ##  Switch to look in @symb02 array 
        for ($is = 0; $is < $s2; $is++)  {
            if($utffrag eq $symb02[$is][1])  { 
                $texfrag = $symb02[$is][0]." ";
            }
        }
    } 
    return;    
}    
##########################################################################
## Current strings = 8344 with .cfg  -  July 11, 2019    
##########################################################################
