#!/bin/perl
#
# mkgrph.pl
#
# This program creates the datafiles and batchfile needed by xmgr.
# Usage: mkgrph Z gtype batchfile datafile1 datafile2 psfile x_start x_end 
#               y_start y_end rho density htmltable
# ARGV[0]: Z is just the atomic number (01-92), or a compound
# ARGV[1]: gtype, graphtype is a number (0-4).
# ARGV[2]: batchfile is the output batch file for xmgr,
# ARGV[3]: datafile1 is the Chantler data file for xmgr.
# ARGV[4]: datafile2 is the Henke data file for xmgr.
# ARGV[5]: name of postscript file for output.
# ARGV[6]-ARGV[9]: $x_start, $x_end, $y_start, $y_end.
# ARGV[10] rho
# ARGV[11] density
# ARGV[12] htmltable (1= display data as HTML table)
# Then all you have to do to create the graph is
# run 'noxmgr -nxy -batch $batchfile -printfile PSFILE $datafile'
# Output tmp files are PhysRefData/FFast/tmp/
#     ffast_$$_1.dat
#     ffast_$$_2.dat
#     ffast_$$_3.dat
#     ffast_$$.bat
#####################################################################

#  Check number of arguments
if ( $#ARGV != 12 ) {     
    die "mkgrph.pl:  Insufficient number of arguments ($#ARGV)\n";
} 

#WWWrequire ("/home/www/htdocs/PhysRefData/FFast02/bin/AtWts.pl");  
#WWWrequire ("/home/www/htdocs/PhysRefData/FFast02/bin/AtWts.pl");  
require ("parseformula.pl");  
require ("AtWts.pl");  

# Some useful directories
$rootdir="/home/www/htdocs/PhysRefData/FFast02";
#WWW$tabledir="$rootdir/data/table";
#WWW$TMPDIR="/u/www/htdocs/PhysRefData/FFast02/tmp";
$tabledir="table";
$TMPDIR="tmp";
$debug=1;  # print debugging information to the file $TMPDIR/debug
if ($debug) { open (DEBUG, ">$TMPDIR/debug"); }
if ($debug) { print DEBUG "first argment is $ARGV[0]"; }

########### Get the arguments, parse the formula ##############
$Z=$ARGV[0];
if ($Z == 0) {
    if ($debug) { print DEBUG "Working with a formula:$ARGV[0]\n"; }
    $Formula=$Z;
    %Weights=&ParseFormula($Formula);
    @Elements=sort numerically keys(%Weights);
    $NumEl=$#Elements+1;
    for ($i=0; $i < $NumEl; $i++) {
         if (($Elements[$i] > 0) && ($Elements[$i]< 10))  {
             $OZ= "0" . $Elements[$i];
             $Weights{$OZ}=$Weights{$Elements[$i]};
             delete $Weights{$Elements[$i]};
             $Elements[$i] = $OZ;
            
             }
         }

    $OZ=$Elements[0];   #FIX
    $Z=$Elements[0];   #FIX
    $Zdesc="Compound=$Z";
    }
else { $OZ=$Z; }
$gtype=int($ARGV[1]);
$batchfile=$ARGV[2];
$datafile1=$ARGV[3];
$datafile2=$ARGV[4];
$psfile=$ARGV[5];
$x_start=$ARGV[6];
$x_end=$ARGV[7];
$y_start=$ARGV[8];
$y_end=$ARGV[9];
$rho=$ARGV[10];
$density=$ARGV[11];
if ($density > 0) { $densitymsg="Density=$density"; }
$htmltable=$ARGV[12];

if ($debug) {print DEBUG "density is $density\n"; }

#WWW$pid=$psfile;
#WWW$pid=~ s#$TMPDIR/ffast_(\d+).ps#$1#;
#WWW$datafile3="$TMPDIR/ffast_" . $pid . "_3.dat";
$datafile3="$TMPDIR/ffast_3.dat";

##############  set variables so data files can be read in  ##############
# Find the input files (one for Chantler data, one for Henke data)
$inputdfile1="$tabledir/z$OZ.tab";
$inputdfile2="$tabledir/z$OZ" . "_hen.tab";
$factorfile="$rootdir/data/factors/$OZ.fact";
$datafileweb="$datafile1" . "web";

# Open files for CHANTLER data
# DFILE1 is output, IDFILE1 is input (Chantler data)
open (DFILE1, "> $datafile1") || die "Cannot open output data file #1 : $datafile1\n";

####### Set up some variables  need for printing data to browser.
open (DFILEWEB, "> $datafileweb") || die "Cannot open output data file #1 for web data: $datafileweb\n";
if ( $gtype==0)
    { $col2hdr_a="  <i>f</i><sub>1</sub>"; $col2hdr_b=""; $col2hdr_c="<i>e</i> atom<sup>-1</sup>"; }
elsif ( $gtype==1)
    { $col2hdr_a="  <i>f</i><sub>2</sub>"; $col2hdr_b=""; $col2hdr_c="<i>e</i> atom<sup>-1</sup>"; }
elsif (( $gtype==2) && (!$density))    # Mu
    { $col2hdr_a=qq(  [&#181;\/<img src="/Images/rho.gif" ALT="rho">]); $col2hdr_b="photoelectric"; $col2hdr_c="  cm<sup>2</sup>g<sup>-1</sup>";}
elsif (( $gtype==2) && ($density))    # Mu
    { $col2hdr_a=qq(  [&#181;]); $col2hdr_b="photoelectric"; $col2hdr_c="  cm<sup>2</sup>g<sup>-1</sup>";}
elsif (( $gtype==3) && (!$density))
    { $col2hdr_a=qq( [&#181;\/<img src="/Images/rho.gif" ALT="rho">]); $col2hdr_b="  total"; $col2hdr_c="cm<sup>2</sup> g<sup>-1</sup>"; }         
elsif (( $gtype==3) && ($density))
    { $col2hdr_a=" [&#181;]"; $col2hdr_b="  total"; $col2hdr_c="cm<sup>2</sup> g<sup>-1</sup>"; }         

if ($htmltable) {
    $STARTTBL="<TABLE BORDER=\"2\" CELLSPACING=\"0\" CELLPADDING=\"0\">"
;
   
    if ($gtype<=2) {
        $TBLHDR="<TR><TH ALIGN=\"CENTER\"><i>E</i><br>(keV)</TH><TH ALIGN=\"CENTER\">$col2hdr_a<br>$col2hdr_c</TH></TR>";
        }
    else {
        $TBLHDR="<TR><TH ALIGN=\"CENTER\"><i>E</i><br>(keV)</TH><TH ALIGN=\"CENTER\">$col2hdr_a<br>$col2hdr_b<br>$col2hdr_c</TH></TR>";
        }
    $TR="<TR><TD ALIGN=\"RIGHT\">";
    $TD="</TD><TD ALIGN=\"RIGHT\">&nbsp;&nbsp;";
    $ENDTR="</TD></TR>";
    $ENDTBL="</TABLE>";
    }
else {
    if ($gtype<=2) {
        $TBLHDR="      <i>E</i>          $col2hdr_a\n    (keV)         $col2hdr_c\n";
        }
    else {
        $TBLHDR="      <i>E</i>       $col2hdr_a\n             $col2hdr_b\n    (keV)      $col2hdr_c\n";
        }
    $STARTTBL="<PRE>";
    $ENDTBL="</PRE>";
    }   

######################  START SECTION, COMPOUND  ##########################
if ($Formula ne "") { 
    print DFILEWEB "<HR><H3>Data for: $Formula, $x_start-$x_end (keV)<br>$densitymsg</H3>"; 
    # print each component and constituent weight
    for ($i=0; $i < $NumEl; $i++) 
        { print DFILEWEB $Elements[$i], ": ", $Weights{$Elements[$i]}, "<br>"; }

    print DFILEWEB $STARTTBL, $TBLHDR;

    # Some notes on the data structures:
    #
    # At this point, all the elements in the compound have been loaded into the array
    # $Elements[] where $NumEl represents the number of elements in the compound
    # As you can see looking a few lines back the hash array $Weights {} contains
    # constituent weights.  Looping through the elements, the file descriptor DATA
    # will be used to read through each data file.  
    # Each line of a data file will be read from the file descriptor DATA  into the
    # perl variable called "$_" which will then be split by white space and stored in
    # the array $line[].  Data will eventually be stored into a separate hash for each element.
    #
    # Summary of variables/datastructures
    # $NumEl      - number of elements in the compound
    # $Elements[] - array contains Z values for each element in compound
    # $Weights{}  - hash array  e.g. for H2O   $Weights{"01"} has the value 0.111904
    #                                          $Weights{"08"} has the value 0.888096
    # DATA        - file descriptor used for reading data from files
    # _$          - perl variable which holds the line just read 
    # $line[]     - array which splits each data line by white space.  
    #               e.g.  $line[0] - energy
    #                     $line[1] - f1 value
    #                     $line[2] - f2 value, etc.
    #                     $line[3] - mu value, etc.
    #                     $line[5] - Total Attenuation Coefficient value, etc.

    #####   For each element, read data into a hash array  #########
    for ($i=0; $i<$NumEl; $i++) 
    {
    $datafile="$tabledir/z" . $Elements[$i] . ".tab";
    open (DATA, "<$datafile") || die "can not open $datafile";
    
    #if (debug) { print DEBUG "Element $i is $Elements[$i]\n"};

    #read in data file and then create data file for graph
    while (<DATA>) {
     @line=split(/[ ]+/, $_);
     # Determine which values are needed, based on graphtype
       if ( $gtype == 0 ) {
           $dkey=$line[0]; $dvalue=$line[1];
           }
       if (( $gtype == 1 ) && ( $line[2] > 0 ))  {
           $dkey=$line[0]; $dvalue=$line[2];
           }
       if (( $gtype == 2 ) && ( $line[3] > 0 ))  {
           $dkey=$line[0]; $dvalue=$line[3];
           }
       if ( $gtype == 3 ) {
           $dkey=$line[0]; $dvalue=$line[5];
           }
       $allenergies{$dkey}="1";  # for all elements combined, create a list 
                                 # of all energies
       $$i{$dkey}=$dvalue;   # there will be a separate hash array for each element
                             # based on its subscript in the array $Elements
                             # e.g.  For H2O, $Elements[0]=01  (Z=01) and
                             #                $Elements[1]=08  (Z-08)  
                             # Therefore the hash arrays $$i{} correspond to
                             #                $0{} for Z=01 and
                             #                $1{} for Z=08.  A bit tricky notation but it works
                             # for any number of elements specified.  The $dkey is the energy value
                             # and the $dvalue is the data value for the given graph type.  For example
                             # $0{1.069000E-02}=4.546820E-01
                             # $0{1.142761E-02}=3.971700E-01 ,etc and for Oxygen
        }
    
    close (DATA);
    }

    #####  Now that the data structures have been filled with data,   #####
    #####  create a sorted array of all energies and then loop        #####
    #####  through it.  Decide whether it is necessary to interpolate #####

    @Energies=sort numerically keys(%allenergies);

    if ($debug) { print DEBUG "number of energies is ", $#Energies+1, "\n"; }
    
    foreach $k (@Energies) {
       $defined=0;
       for ($j=0; $j<$NumEl; $j++) {
           if ($$j{$k}) { 
               $defined++;
               }
           }
       if ($defined==$NumEl) { # No need to interpolate, just do the calculation
           print DFILE1 $k, "\t";
           print DFILEWEB "$TR $k \t";
           $value=0;
           for ($j=0; $j<$NumEl; $j++) {
               $value+=$$j{$k}*$Weights{$Elements[$j]};
               }
           printf DFILE1 "%.6E\n", $value; 
           printf DFILEWEB "$TD %.6E$ENDTR\n", $value; 
           }
      else {
          print "Need to interpolate at $k\n";
          }
      }
    close (DFILE1);
    print DFILEWEB $ENDTBL;
    close (DFILEWEB);
    }

######################  END SECTION, COMPOUND  ##########################

######################  START SECTION, Z  ##########################
else { print DFILEWEB "<HR><H3>Data for Z=$Z, $x_start-$x_end (keV)<br>$densitymsg</H3>"; 

print DFILEWEB $STARTTBL, $TBLHDR;
### End web data file setup
if (($gtype == 1) || (($gtype == 2) && ($x_end > 2))) {
open (DFILE3, "> $datafile3") || die "Cannot open output data file : $kshelldata\n"; 
}

open (IDFILE1, "< $inputdfile1") || die  "Cannot open input data file: $inputdfile1";

# DETERMINE FACTOR
if ( $gtype == 1) {
   open (FACTOR, "< $factorfile") || die "Cannot open factor file: $factorfile";

    while (<FACTOR>) 
        { $factor=1000/$_; }

    close (FACTOR)
    }

# EXTRACT APPROPRIATE COLUMNS of CHANTLER DATA 
while (<IDFILE1>) {
 chop $_;
 @line=split(/[ ]+/, $_);
 # Print out the different columns according to graphtype
 if ( ( $line[0] <= $x_end ) && ( $line[0] >= $x_start ) ) {
   if ( $gtype == 0 ) {
       print DFILE1 "$line[0] $line[1]\n"; 
       print DFILEWEB "$TR$line[0]$TD   $line[1]$ENDTR\n"; 
       }
   if (( $gtype == 1 ) && ( $line[2] > 0 ))  {
   ## can't plot log-log graph with values <= 0. So ignore such values
       $n=$line[6]*$factor*$line[0];
       if ( $n > 0 ) 
           { print DFILE3 "$line[0] $n\n"; }
       print DFILE1 "$line[0] $line[2]\n"; 
       print DFILEWEB "$TR$line[0]$TD $line[2]$ENDTR\n"; 
       }
   if (( $gtype == 2 ) && ( $line[3] > 0 ))  {
       print DFILE1 "$line[0] ";
       print DFILEWEB "$TR $line[0] ";
print DEFILEWEB "density is .$density.\n";
       if ($density >0 ) {     # CALCULATE DENSITY
            $value=$line[3]*$density;  
            printf DFILE1 "%.4E\n", $value;   
            printf DFILEWEB "$TD %.4E$ENDTR\n", $value;   
            }
       else {
         print DFILE1 "$line[3]\n"; 
         print DFILEWEB "$TD $line[3]$ENDTR\n"; 
         if ( $x_end > 2)  # PREPARE DATA TO GRAPH K-SHELL
             { print DFILE3 "$line[0] $line[4]\n";  }
         }
        }
   if ( $gtype == 3 ) {
         print DFILE1 "$line[0] ";
         print DFILEWEB "$TR $line[0] ";
         if ($density)  {
             $value=$line[5]*$density; 
             printf DFILE1 "%.4E\n", $value;   
             printf DFILEWEB "$TD %.4E$ENDTR\n", $value;   
             }
         else {
             print DFILE1 "$line[2]\n"; 
             print DFILEWEB "$TD $line[2]$ENDTR\n"; 
              }
       }
 }
}
close(DFILE1);
print DFILEWEB $ENDTBL;
close(DFILEWEB);
if (($gtype == 1) || (($gtype == 2) & ($x_end > 2))) 
    { close (DFILE3); }

# DFILE2 is output, IDFILE2 is input (Henke data)
# OPEN FILES FOR HENKE DATA
open (DFILE2, "> $datafile2") || die "Cannot open output data file #2: $datafile2\n";
open (IDFILE2, "< $inputdfile2") || die "Cannot open input data file: $inputdfile2\n";
# If nothing gets put into DFILE2 (i.e. no Henke data in range), xmgr

# will not complain but a legend may not be correct
$henkedatafound = "no";

$i=0;
 
while ($i <= 92) {
        $energy[$i] = .0100000;  # 10.0000 eV
        $i=$i+1;
        }
 
$energy[1] = .0169805;
$energy[2] = .0247000;
$energy[10] = .0217000;
$energy[18] = .0159000;
$energy[36] = .0142000;
$energy[54] = .0123193;


# EXTRACT APPROPRIATE COLUMNS of HENKE DATA 
while (<IDFILE2>)
{
 chop $_;
 @line=split(/[ ]+/, $_);
 # Henke data has units of eV, NOT KeV, so convert it...
     $line[0] = $line[0]/1000;
     # Print out the right numbers according to graphtype
     if ( ( $line[0] <= $x_end ) && ( $line[0] >= $x_start )) {
      $henkedatafound = "yes";
      if ( $gtype == 0 ) {
         if ( $line[1] ne "-9999.00")
             { print DFILE2 "$line[0] $line[1]\n"; }
         }
         if ( $gtype == 1 )  {
             if ($line[0] >= $energy[$Z])   
                { print DFILE2 "$line[0] $line[2]\n"; }
             }
         if ( $gtype == 2 )  {
             if ($line[0] >= $energy[$Z])   
                { print DFILE2 "$line[0] $line[3]\n"; }
             }
         }  
}

}
##########################  END SECTION, Z  ###############################

# WRITE BATCH FILE FOR XMGR
# All of the labels, starts, ends, etc. go in the
# batch file that is fed to xmgr

# The xlabel is always the same
$xlabel="Energy (keV)";


if ($x_end <= ($x_start*100))
    { $nsr = "yes"; }

# The y-axis labels change according to the graph type
# \\8 changes to Greek font, \\1 is normal, \\s is subscript
# \\S is superscript, and \\N ends a super- or subscript
if ($gtype == 0)
    { $ylabel="f\\5\\s1\\N (e/atom)"; }
if ($gtype == 1)
    { $ylabel="f\\5\\s2\\N (e/atom)"; }
if ($gtype == 2)
    { $ylabel="\\8m\\0(cm\\5\\S2\\N/g)"; }
if ($gtype == 3)
    { $ylabel="Attenuation Coefficient\\N (cm\\5\\S2\\N/g)"; }

# Start keeping track of the arguments that xmgr gets
$xmgropt="-nxy -noask -device 2 ";
if ($gtype  == 0) {
   if ($nsr ne "yes")
       { $xmgropt .= "-graphtype logx "; }
   ## else
   ##  non-liner xy axis labels
   }
else  {
   if ($nsr ne "yes")
       { $xmgropt .= "-graphtype logxy "; }
   ##else
   ## non-liner xy axis labels
    }

if (($gtype == 1) || (($gtype == 2) && ($x_end > 2))) {
    $xmgropt .= "-batch $batchfile -printfile $psfile $datafile1 $datafile2 $datafile3";
    }
else {
    $xmgropt .= "-batch $batchfile -printfile $psfile $datafile1 $datafile2 ";
    }


# The title of the graph
if  ($Formula ne "")
  { $title="$Formula, E = $x_start - $x_end keV"; }
else
  { $title="Z = $Z, E = $x_start - $x_end keV"; }

if ($debug) {
    print DEBUG "xmgropts are $xmgropt\n";
    print DEBUG "title is $title\n";
    }

# Start printing to the batchfile
open ( BFILE, ">> $batchfile") || die "Cannot open batch file: $batchfile\n";

#  Note that the xticks and yticks programs generate some information for
#  the batch file so that information is not generated here.

###########################     Code for Narrow sub range   ###############
if ($nsr eq "yes")   {
#------------------------------
print BFILE "TITLE \"$title\"\n";
#------------------------------
print BFILE "WORLD XMIN $x_start\n";
print BFILE "WORLD XMAX $x_end\n";
# Note:  the following command formerly did not have $y_start, $y_end
# defined so WORLD YMIN was written to the batch file (without a value)
# but everything ran ok.  This program now has access to $y_start, $y_end
# but printing them for many cases causes the graph to not be displayed.
# So for now, just do it the old way that works
# print BFILE "WORLD YMIN $y_start\n";
# print BFILE "WORLD YMAX $y_end\n";
print BFILE "WORLD YMIN\n";
print BFILE "WORLD YMAX\n";
#------------------------------
# This makes the colors come out correctly
if ($henkedatafound eq "yes") {
    print BFILE "s0 linestyle 1\n";
    print BFILE "s1 linestyle 2\n";
    print BFILE "s0 color 1\n";
    print BFILE "s1 color 2\n";
    print BFILE "s2 color 4\n";
    print BFILE "s2 linestyle 4\n";
    }
else {   # No Henke data - 2nd line plotted will represent K-shell data
    print BFILE "s0 linestyle 1\n";
    print BFILE "s1 linestyle 4\n";
    print BFILE "s0 color 1\n";
    print BFILE "s1 color 4\n";
    }
#------------------------------
# Set up the tick marks
# Set  up my xticks, yticks programs

#------------------------------
# This makes the box
print BFILE "view xmin 0.2\n";
print BFILE "view xmax 0.94\n";
print BFILE "view ymin 0.35\n";
print BFILE "view ymax 0.65\n";
#------------------------------
print BFILE "XAXIS LABEL \"$xlabel\"\n";
print BFILE "YAXIS LABEL \"$ylabel\"\n";

#------------------------------
if (( $gtype == 0 )  || ( $gtype == 1 )) {
  print BFILE "LEGEND ON\n";
  print BFILE "LEGEND X1 0.2\n";
  print BFILE "LEGEND Y1 0.3\n";
  print BFILE "LEGEND STRING 0 \"Current\"\n";
  print BFILE "LEGEND STRING 1 \"Henke\"\n";
  }
if ( $gtype == 1)  {
  if ($henkedatafound eq "yes") 
      { print BFILE "LEGEND STRING 2 \"f\\5\\s2\\N K-shell\"\n"; }
  else
      # Note: overwrite prior LEGEND STRING 1
      { print BFILE "LEGEND STRING 1 \"f\\5\\s2\\N K-shell\"\n"; }
  }


if (( $gtype == 2)  && ( $x_end > 2)) {
  print BFILE "LEGEND ON\n";
  print BFILE "LEGEND X1 0.2\n";
  print BFILE "LEGEND Y1 0.3\n";
  print BFILE "LEGEND STRING 0 \"Current\"\n";
  if ($henkedatafound eq "yes")  {
      print BFILE "LEGEND STRING 1 \"Henke\"\n";
      print BFILE "LEGEND STRING 2 \"\\8s\\1(coh+inc)\"\n"; 
      }
  else
      { print BFILE "LEGEND STRING 1 \"\\8s\\1(coh+inc)\"\n"; }
   }
if (( $gtype == 2)  && ( $x_start < 2)) {
  print BFILE "LEGEND ON\n";
  print BFILE "LEGEND X1 0.2\n";
  print BFILE "LEGEND Y1 0.3\n";
  print BFILE "LEGEND STRING 0 \"Current\"\n";
  print BFILE "LEGEND STRING 1 \"Henke\"\n";
   }
if (( $y_end < .0001)) {
  print BFILE "YAXIS  TICKLABEL FORMAT EXPONENTIAL\n"; 
  print BFILE "YAXIS TICKLABEL PREC 1\n"; 
  }

}
else  {
###########################     Code for regular range   ###############
#------------------------------
print BFILE "TITLE \"$title\"\n";
#------------------------------
print BFILE "WORLD XMIN $x_start\n";
print BFILE "WORLD XMAX $x_end\n";
### print BFILE "WORLD YMIN $y_start\n";
### print BFILE "WORLD YMAX $y_end\n";
#------------------------------
# This makes the colors come out correctly
if ($henkedatafound eq "yes") {
    print BFILE "s0 linestyle 1\n";
    print BFILE "s1 linestyle 2\n";
    print BFILE "s0 color 1\n";
    print BFILE "s1 color 2\n";
    print BFILE "s2 color 4\n";
    print BFILE "s2 linestyle 4\n";
    }
else {   # No Henke data - 2nd line plotted will represent K-shell data
    print BFILE "s0 linestyle 1\n";
    print BFILE "s1 linestyle 4\n";
    print BFILE "s0 color 1\n";
    print BFILE "s1 color 4\n";
    }
#------------------------------
# Set up the tick marks
print BFILE "XAXIS TICK MAJOR ON\n";
print BFILE "XAXIS TICK MINOR OFF\n";

if ($x_start >= 1) 
  { print BFILE "XAXIS TICKLABEL PREC 0\n"; }
else 
  { print BFILE "XAXIS TICKLABEL PREC 3\n"; }

#Note for most cases, f1 vs E (lower energy) requires prec = 0 or 1
#but in a few cases prec is 3 = 4.  To simplify matters, always use prec=3 
#for f1 vs E graph for all energy ranges.

if (($gtype == 0) && ($x_end < 2.01)) {   # Lower energy range
   print BFILE "YAXIS TICKLABEL PREC 0\n";
   # Special cases:
   if ($Z == 1) 
       { print BFILE "YAXIS TICKLABEL PREC 1\n"; }
   }
if (($gtype == 0) && ($x_end > 2.01)) {   # Upper energy range
   if ($Z == 1)
      { print BFILE "YAXIS TICKLABEL PREC 4\n"; }
   elsif (($Z == 2) || ($Z == 3))
      { print BFILE "YAXIS TICKLABEL PREC 3\n"; }
   elsif (($Z >= 4) && ($Z <= 12)) 
      { print BFILE "YAXIS TICKLABEL PREC 2\n"; }
   elsif (($Z == 13) || ($Z == 14)) 
      { print BFILE "YAXIS TICKLABEL PREC 1\n"; }
   elsif ($Z >= 15)
      { print BFILE "YAXIS TICKLABEL PREC 0\n"; }
   }

if (($gtype == 1) && ($x_end > 2) && ($x_start < 2))  
       { print BFILE "YAXIS  TICKLABEL FORMAT EXPONENTIAL\n";}




if (($gtype == 1) && ($x_end <= 2))  {   # Graph type f2, lower range
   if ($Z == 1)
       { print BFILE "YAXIS TICKLABEL PREC 4\n"; }
   elsif (($Z == 2) || ($Z == 3))
       { print BFILE "YAXIS TICKLABEL PREC 2\n";} 
   else
       { print BFILE "YAXIS TICKLABEL PREC 1\n";} 
   }

if (($gtype == 1) && ($x_start >= 2))  {   # Graph type f2, upper range
# Note: exponential format used since negative exponents won't
# display properly using powers of 10.
   if (($Z >= 23) && ($Z <= 35))
       { print BFILE "YAXIS TICKLABEL PREC 3\n"; }
   elsif (($Z >= 36) && ($Z <= 56))
       { print BFILE "YAXIS TICKLABEL PREC 2\n"; }
   elsif (($Z >= 57) && ($Z <= 92))
       { print BFILE "YAXIS TICKLABEL PREC 1\n"; }
   else
       { print BFILE "YAXIS  TICKLABEL FORMAT EXPONENTIAL\n";}
   }

if ($gtype == 2) {
# Note: the following YAXIS format was changed since negative exponents won't
   print BFILE "YAXIS  TICKLABEL FORMAT EXPONENTIAL\n"; 
   print BFILE "YAXIS TICKLABEL PREC 0\n"; 
   }

if ($gtype == 3) {
   print BFILE "YAXIS  TICKLABEL FORMAT EXPONENTIAL\n"; 
   print BFILE "YAXIS TICKLABEL PREC 0\n"; 
   }

print BFILE "YAXIS TICK MAJOR ON\n";
print BFILE "YAXIS TICK MINOR OFF\n";

#------------------------------
# This makes the box
print BFILE "view xmin 0.2\n";
print BFILE "view xmax 0.94\n";
print BFILE "view ymin 0.35\n";
print BFILE "view ymax 0.65\n";
#------------------------------
print BFILE "XAXIS LABEL \"$xlabel\"\n";
print BFILE "YAXIS LABEL \"$ylabel\"\n";

#------------------------------
if (( $gtype == 0 )  || ( $gtype == 1 )) {
  print BFILE "LEGEND ON\n";
  print BFILE "LEGEND X1 0.2\n";
  print BFILE "LEGEND Y1 0.3\n";
  print BFILE "LEGEND STRING 0 \"Current\"\n";
  print BFILE "LEGEND STRING 1 \"Henke\"\n";
  }
if ( $gtype == 1)  {
  if ($henkedatafound eq "yes")
      { print BFILE "LEGEND STRING 2 \"f\\5\\s2\\N K-shell\"\n"; }
  else
      # Note: overwrite prior LEGEND STRING 1
      { print BFILE "LEGEND STRING 1 \"f\\5\\s2\\N K-shell\"\n"; }
  }
 

if (( $gtype == 2)  && ( $x_end > 2)) {
  print BFILE "LEGEND ON\n";
  print BFILE "LEGEND X1 0.2\n";
  print BFILE "LEGEND Y1 0.3\n";
  print BFILE "LEGEND STRING 0 \"Current\"\n";
  if ($henkedatafound eq "yes")  {
      print BFILE "LEGEND STRING 1 \"Henke\"\n";
      print BFILE "LEGEND STRING 2 \"\\8s\\1(coh+inc)\"\n";
      }
  else
      { print BFILE "LEGEND STRING 1 \"\\8s\\1(coh+inc)\"\n"; }
   }

if (( $gtype == 2)  && ( $x_start < 2)) {
  print BFILE "LEGEND ON\n";
  print BFILE "LEGEND X1 0.2\n";
  print BFILE "LEGEND Y1 0.3\n";
  print BFILE "LEGEND STRING 0 \"Current\"\n";
  print BFILE "LEGEND STRING 1 \"Henke\"\n";
   }

}

#------------------------------
# Tells xmgr to recalculate and print and exit
print BFILE "REDRAW\n";
print BFILE "PRINT TO FILE\n";
print BFILE "HARDCOPY\n";
print BFILE "EXIT\n";

close (BFILE);
#------------------------------

# Output the xmgr arguments
#WWWprint "$xmgropt\n";
