#!/usr/bin/perl
# (c) 2008 Neil Christensen
$version="1.54";
#############################################################################################################
#Version Notes:
#############################################################################################################
#1.54   March  25, 2021 
#       run-time error messages now are displayed on the screen 
#1.53 : January 5, 2021
#       improved copy of the output results 
#       for the consistency with the html interface
#1.52 : February 25, 2020
#       Created new key phrase "SLHA Widths"
#       Turned on by default.  Set to "Off" or "False" to turn them off and use the built-in width calculator.
#1.51 : February 11, 2020
#       Created new key phrase "Reuse Session"
#       False by default.  If set to True, then the session.dat from the previous run will be used if available.
#1.50 : February 3, 2020
#       call of nCompil and ld_n is realized via blind mode of s_calchep  
#1.49 : December 13, 2019
#       Reestablished Off and None as valid PDF values.
#       Added warning about keyword not being recognized
#1.48 : November 19, 2019
#       Added link to library for the compatibility with Quadruple precision 
#1.47 : November 19, 2019
#       Added statement to user when cs is too low so that they can increase the luminosity.
#1.46 : September 10, 2019
#       modified to create separate sub-folder for each job in batch_results folder
#1.45 : February 21, 2019
#       Moved LD_LIBRARY_PATH line after batch-system-specific  instructions. Thanks to Dan Locke.
#       Modified ending when 0 events are requested to results are stored in  .tgz form.
#       Don't try to create plots if they are not requested.
#1.44 : February 20, 2019
#       Commented exit(0) on line 2824 to allow CalcHEP to save results into batch_results in .tgz form 
#       even if user    do not generate events 
#1.43 : January 22, 2019
#       Removed colon in Parallelization line of session.dat.
#1.42 : October 5, 2018
#       Added support for latest MAC OS (high sierra)
#1.41 : March 15, 2018
#       Added support for missing parts of the cuts specification.
#       Added polarization to the html help files.
#1.40 : March 14, 2018
#       Added support for polarization.  
#1.39 : August 20, 2017
#       added support for "cteq6l" PDF name which is set to be equivalent to cteq6l1
#       for backward compatibility with old calchep and batch files
#1.38 : July 5, 2017
#       added batch_results folder where results of batch runs are collected.
#       Events and html folder still exists for backward compatibility
#1.37 : March 22, 2017
#       The limit on number of models to match the mattern was extended from 100 to 1000
#1.36 : March 2, 2017
#       Added total cross-section error after summing but before decays.
#1.35 : Feb 3, 2017
#       Fixed typos with the process library.
#1.34 : October 31, 2016
#       Updated to deal with new PDT: functions  
#1.33 : October 12, 2016
#       Added output in the .txt for the distributions  
#       Fix bug for small nbin distributions (e.g 10, 15 which is confused with 100 and 150  when use "f" in the blind mode)
#1.32 : July 14, 2016
#       Format of the files with distributions was changed to .jpg as well the color code
#       for gnuplot command was changed to be consistent with recent gnuplot version to 
#       avoid related problems
#1.31 : July 6, 2016
#       Fixed typo in showering statement.
#       Updated cteq6l1 from cteq6l.
#       Added support for user to specify pdf scales separately and showering scale.
#1.30 : Added QCD scale support fot Z and S symbols in case of particles change the place
#1.29 : Added QCD scale support fot T symbol in case of particles change the place
#1.28 : More $LHAPDFPATH.
#1.27 : Added $LHAPDFPATH.
#1.26 : If cs=0, set nevents=0.
#1.25 : Updated for change in event generation.
#1.24 : Fixed fix in 1.22.
#       Fixed bug introduced by the change to the numerical menu for
#         generating the SLHA width file.
#1.23 : Case Insensitive choice for internal PDFs is implemented
#1.22 : Bug for the case of "Remove :0:" intermediate particles fixed
#1.21 : Further Fixed bug with aux being written to concurrently by 
#         parallel jobs.
#1.20 : Bug fixed on line 1664 for #ppn choice in the menu
#1.19 : Updated to work with new session.dat ordering.
#1.18 : Fixed a problem using suspect in parallel mode.
#1.17 : Parallelized symbolic calculation.
#1.16 : Parallelized event generation.
#1.15 : More support for parallelization.
#1.14 : Added support for parallelized version of CH.
#1.13 : Fixed bug with aux being written to concurrently by 
#         parallel jobs.
#1.12 : Allow parameter definition to include formula.
#         Also, allow this formula to be a function of
#         scan parameters.
#       Also, allow p1,p2 to be formula in terms of
#         scan parameters.
#1.11 : Added total cs to scan page when there are no decays.
#       Added plot of total cs when scanned in 1-d.
#1.10 : Added remove statement for decays.
#1.9  : Read cs when negative.
#       Added Mathematica plot files.
#1.8  : Fixed html for event library to show .gz files.
#1.7  : Further fixed bug with long composite definitions.  
#1.6  : Fixed bug with Composite definitions that were very long.
#       Added html help notes about Remove statement.
#1.5  : Improved scale parameter to allow M12.
#1.4  : Fixed order of \$cLib/serv.a and \$cLib/dynamic_me.a in
#         numerical compilation.
#       Added switch for virtual W/Z decays.  Default is ON.
#1.3  : Fixed uncertainty output when cs or width=0.
#1.2  : Added new key phrase "Subprocess full events".  When
#         set to True, the full number of events is generated
#         for each subprocess.
#1.1  : Updated for new sbin dir.
#1.0  : Added arXiv number!
#0.146: Added MC uncertainty to html and txt progress pages.
#0.145: Increased max_lumi to 10^9.
#       Removed max_lumi from decays.
#0.144: Added keywords "Alias" and "Scan" but kept
#         "Composite" and "Run" so old batch files
#         are not broken.
#0.143: Improved html and txt output.
#0.142: Fixed formatting of ISR&Beam in session.dat.
#0.141: Finalized fixing of infinitesimarl cs events.
#       Fixed gzip line when .gz file was already present.
#0.140: Zipped the final event files.
#0.139: Fixed problem with event generation when the cs is 
#         infinitesimal.
#0.138: Fixed column alignment for alias table.
#0.137: Decreased default max luminosity to 1e6 and added units
#         to event file header.
#       Added version variable.
#0.136: Added support for max luminosity so event_mixer won't run
#         too long when cs's are tiny.
#0.135: Fixed bug when cs=0 for event generation and distributions.
#0.134: Linked models dir in w (width) directory.
#       Added decay regularization
#       Added BW info to event file header.
#0.133: Added BW menu items.
#0.132: Fixed renumber_Mparts when scale ends in M34 for example.
#0.131: Added renumber_Mparts to fix the scale problem reported
#         by Laura Daniels.
#0.130: Working on SLURM batch file.
#0.129: Captured err=123 (when cs or w = 0).
#0.128: Commented out code to check whether a job was prematurely
#         killed.  It is causing more headaches than it is helping
#         right now.  Perhaps I will come back to it later.
#0.127: Added WORK to symbolic shell script.
#       Added more printing when error.
#0.126: Fixed pbs problem.
#0.125: Fixed the parallelization on a local computer.
#0.124: Replaced subproc_cycle with blind string to have
#         better control.
#       Calculate widths in first pass.
#0.123: Updated to work with new CH where composites are
#         defined in gui.
#       Added alpha Fact Q and alpha Ren Q to event file.
#0.122: Turned off sleep when done for a few key pages.
#0.121: Updated to allow different scales for pdf and
#         renormalization.
#0.120: Fixed sort of distribution parameters to not sort the
#         first term in A,C and P.
#       Fixed distribution summing when using composites.
#       Removed rename_parts from distributions.
#         Now, only use the distribution name directly.
#0.119: Slightly improved show_distr command.
#0.118: Replaced | wc -l with length(split("\n", when determining
#         if a job is still running.  Also, only check after 
#         certain time.
#0.117: Added code designed to print message and quit if some jobs
#         are killed prematurely (for example by the pbs cluster).
#0.116: Removed run_vegas and use my own n_calchep -blind command.
#       Set the minimum values nSess=5 and nCalls=10000.
#0.115: Added missing -e in if statement.
#0.114: Changed redirection operator from &> (which was having
#         trouble on Ubunut 11.10 to 2>&1 1> which appears to work.
#       Set nSess2=0 for event generation.
#0.113: Updated default sub-cubes and precision of #QCD line.
#0.112: Updated to work with new version of CH where the libraries
#         where changed slightly.
#0.111: Updated to work with new version of interactive session
#         where event generation was slightly changed.
#0.110: Rewrote how the number of events in each subprocess is
#         determined.  It now starts with the expectation value
#         for each subprocess, N.  If N<10 then it sets N=10.
#         It then sets N=N+5*sqrt(N) to include the possibility
#         of a fluctuation of 5 Gaussian sigmas in the number 
#         of events in each channel.
#0.109: Removed "PDG" from LHAPDF line.
#       Fixed #Vegas_calls and #Events line of session.dat.
#         Someone had removed the user input from these lines.
#       Fixed bug that looked for CH Error in the wrong file.
#0.108: Commented out various lines linking autoprot.h
#         and EXTLIB which are not used anymore.
#       Fixed Vegas calls line to update with new
#         version of CalcHEP.
#       Removed make_VandP_old since it is no longer
#         needed.
#       Changed the order of writing the md5sums
#         for the model and compiling VandP.  This 
#         should fix the bug Sasha Pukhov found.
#       Changed the requested number of events to 1.2
#         times the nominal number since event_mixer
#         was running out too frequently after 
#         event_mixer was fixed to not go back to the
#         start of the file.
#0.107: Changed lhapdf input to what is inside the 
#         quotes.
#       Set cleanup to False by default.
#       Changed Error to CH Error.
#         Also print error message to stdout.
#0.106: Updated the final number of events to work
#         with new version of CalcHEP.(Pukhov)
#0.105: Replaced link to job.o to job.out.
#       Catch event_mixer error.
#0.104: Removed incorrect \. (Pukhov)
#0.103: Switched gnuplot plots to differential cs.
#0.102: Updated blind command to work with new
#         version of CH. (Pukhov)
#0.101: Remove html/mN if model changes.
#       Compile VandP.so every time in case
#         the user external libs changed.
#0.100: Check funcLocal if funcX.mdl changes.
#       Added WORK:= to VandP makefile.
#       Added -V option to PBS and LSF clusters.
#0.99 : Improved VandP generation.
#       Generate list of processes in Processes/mX.
#         Users session in WORK is not affected now.
#       Regenerates VandP.so if model changed.
#       Regenerates all codes if prtclesX.mdl or 
#         lgrngX.mdl changed.
#       Removed symbolic tmp dir and results/*.a
#         during symbolic job if Cleanup=True.
#       Redirect all output to job.o and cs.o.
#         No longer rely on cluster redirection.
#0.98 : Removed code that removed model directories if 
#         not in models.txt.  Added line to models.txt
#         if present model is not included.
#       Added VandP.so to Processes/mX and linked it to
#         n_calchep codes.  If VandP.so is removed, it
#         will be recreated without recreating n_calchep.
#         This should enable changes to varsX.mdl and
#         extlibX.mdl.  Thanks to Sasha Pukhov for help
#         with this.
#0.97 : If CALCHEP evironment variable is not set, exit.
#       Removed Model Changed from html help files.
#         It is no longer needed so not advertised.        
#       Switched signal of succesful completion of
#         symbolic job to presence of n_calchep.
#       When premature termination occurs, a nonzero
#         integer signal is returned.  See 
#         kill_all_jobs for definition of signals.
#       Thoroughly rewrote the cleanup code.
#         Now, it removes everything that is not 
#         reused.
#0.96 : Changed full path symbolic links to relative
#         links for results directory binaries.
#0.95 : Added kill_all_jobs that is used if the user
#         kills batch script or if a job has
#         an error.
#       Removed allDec! for widths.
#         Now use one of the other processes for 
#         widths.
#0.94 : Write finished file at the end of a job to
#         signal the end of a job.
#       Watch for nonzero return value of CH programs.
#         Write error to file if nonzero.
#0.93 : Added the -f option to the remove command.
#0.92 : Added SLURM commands.  Needs to be tested.
#       Fixed pid for local jobs.
#0.91 : Updated to work with new version of CH according
#         to Sasha Pukhov and Sasha Belyaev's suggestions.
#0.90 : Fixed a problem where n_calchep produced an 
#         infinite number of events when the partial
#         width was zero.
#0.89 : Replaced $line =~ s/q($param)/$dist_param[$k]/g;
#         with $param =~ s/([.+*?])/\\$1/g;
#         $line =~ s/$param/$dist_param[$k]/g;
#	 Other characters can be added to escape if
#         necessary.
#0.88 : Replaced $line =~ s/$param/$dist_param[$k]/g;
#         with $line =~ s/q($param)/$dist_param[$k]/g;
#	 to cause $param to be interpreted literally.
#0.87 : Added Remove to the copy of the batch
#         file included in the lhe file.
#0.86 : Fixed bug where gnuplot instructions 
#         didn't work when a variable in 
#         vars.mdl began with * such as in 
#         the case of *slhaON.
#0.85 : Fixed bug where distributions aren't 
#         plotted when only 1 subprocess is
#         done.
#0.84 : Fixed bug where help dir was not being
#         created when no batch file was present.
#0.83 : Fixed bugs in LSF mode.  
#         Thanks to Riccardo Torre.
#0.82 : Fixed regexp for cs.o.  Thanks to Riccardo
#         Torre for finding the bug.
#0.81 : Added removal of particles.
#       Added warning to help files about checking
#         the prt_1 files.
#0.80 : Fixed a few stupid bugs with 0.78.
#       Added html for LSF.
#0.79 : Added html directory to batch file.
#         Thanks to Riccardo Torre!
#0.78 : Added LSF cluster ability.
#         Thanks to Riccardo Torre!
#0.77 : Fixed bug in kinematics renumbering.
#       Also added kinematics feature for decays
#         in response to Can Kilic's request.
#         He was doing a 1->4 decay.
#0.76 : Added cut inverse option.
#0.75 : Set luminosity to 1E+50 so that it won't run
#         short when very small cross sections are 
#         encountered.
#       Fixed small bug in decay and width session.dat
#         that wrote physical parameters twice.
#0.74 : Fixed some typos in html help files.
#0.73 : Fixed bug in distributions where 
#         it was trying to link to decay
#         distributions.
#       Fixed bug with 3*x in processes.
#0.72 : Fixed link to CalcHEP.
#0.71 : Finished first draft of help files.
#       Added link to CalcHEP.
#       Added empty link to future paper.
#       Added model name to html progress reports.
#       Updated warning messages.
#0.70 : Fixed bug with distribution in the following
#         example: p,p->l,l with dist M(l,l) which
#         gave M(E,E), M(E,e) and M(e,e).  Now it
#         only gives M(E,e). 
#       Added more material to help files.
#0.69 : Moved feature requests to google group page.
#       Rewrote the instructions in README.
#       Edited calchep_batch shell script.
#0.68 : Changed to full path to html/index.html in
#         message printed to shell.
#0.67 : Fixed bug where filename was not being printed
#         in run_details.
#0.66 : Changed cp to mv for final event file since 
#         apparently some people produce event files 
#         which are too big to have two copies on the
#         same disk.
#0.65 : Changed allNew to allDec to include all decays.
#       Changed cat to cp for final event file since
#         run_details is included by event_mixer now.
#0.64 : Changed from model number to model name.
#       Fixed pbs mem bug ", mem"->" -l mem".
#       Fixed N events in html/runs/single.txt.
#       Fixed distribution bug where bin size of
#       2/100 didn't work properly.  Replaced it
#         with 2/100.0.
#       Fixed QCD scale.  It now allows both MZ/2
#         and M34 (for example).
#       If cleanup is set to true, batch_results/tmp is 
#         also cleaned up.
#       Added minor tics to gnuplot distributions.
#0.63 : Updated to use new version of event_mixer.
#       Removed plain format.
#       Changed name from calchep_batch back to run_batch.
#       Added ntuple option.
#       Read url from extlib and add it to lsh header.
#       Added model name to lsh header.
#       Removed # from batch details in lsh header.
#       Added email to PBS instructions.
#0.62 : Added memory specification for pbs job script.
#0.61 : Added output for CH errors.  Set to exit if CH error
#         encountered.
#       Started help files.
#       Set default CH_PATH to working dir (if shell variable
#         CALCHEP is not set.)
#0.60 : Finished update to use s_calchep rather than calchep.
#0.59 : Updated the batch details in event file.
#       Only print pdf info relevant to pdf.
#0.58 : Fixed the cuts and distributions so that if they have more
#         than 2 parameters, duplicate parameters are allowed
#         if there are the same number or more duplicates
#         in the process.  This finishes the fix begun in 
#         v0.52.
#0.57 : Changed to read batch file name as argument without flag.
#       The shell script in user directory needs to be updated.
#       Changed to use calchep environment variable for bin
#         directory location.
#0.56 : Changed the name to calchep_batch.
#0.55 : Added text output when batch file is not found.
#       Added text output specifying where to find progress
#         and Events.
#       Made change so events are generated without recalculating
#         the cross section.
#       Modified the progress reports to split production, decays
#         and widths and emphasize that the cross section is a 
#         production cross section.
#       Added decay partial widths to the progress reports.
#       Updated final cs with final cs from event_mixer.
#0.54 : Changed "Estimating Cross Section" to "Calculating Cross
#         Section".
#       Changed decaySLHA1.txt to decaySLHA.txt.
#0.53 : Allowed allNew! as particle name.
#       Updated to use results/list_prc.txt for subprocess list.
#       Added widths in decaySLHA1.txt to event generation.
#         This is to enable the cross section to be updated with the
#         branching ratios of the decays.
#         This file is linked to batch_results/tmp where event_mixer works.
#         event_mixer needs to be updated now.
#       Updated progress to state "Done!" when 0 events are requested.
#         Just the cross section is being computed or just distributions
#         are being generated.
#0.52 : Fixed bug in cuts where J(u,u) would not be written since the script
#         only wrote nonidentical particles.  It appears that there is also
#         a problem in CH with identical particles here.  (When CH is fixed
#         I need to also fix this for cuts with 3 and 4 parameters.)
#         CH has been fixed.
#0.51 : Added photon pdfs.  Needs to be tested.
#       Added 1*x and 3*x to possible final states.  Needs to be tested.
#0.50 : Fixed bug where run parameters were not being written to the gnuplot
#         instruction file correctly.
#0.49 : Fixed a minor bug where the number of bins for the distribution was
#         not always being chosen correctly.
#0.48 : Passes user defined observable names (Uxxx) without modification.
#       Made more improvements to the distribution functionality.
#       Plots are automatically shown in numerical html.
#0.47 : Fixed bugs in distribution production.
#0.46 : Fixed bug in v0.45 where the {par} were being replaced in the wrong order.
#0.45 : Improved the cuts and distribution values to allow for run parameters
#         that are not part of the model.  This could be useful when calculating
#         the SM and want to place cuts that correspond with those set in
#         the new model calculation.  For example, if the new model has a Z',
#         then it may be convenient to set a cut on M(le,le) that depends on 
#         MZP.  This is straight forward in the new model, but in the SM, it 
#         was not possible.  Now, if run parameter are placed inside curly
#         brackets in the min or max values, they will be replaced with the value.
#         For example, Cut min: {MZP}/10, will be replaced with (1000)/10 if
#         the value of MZP is 1000.  Only the run parameters can be used in this
#         way.  The parameters of the model (including those in the run) can 
#         still be used directly and will not be replaced.  So,
#         Cut min: MZP/10 will remain MZP/10.
#0.44 : Updated script to work with 2.5.o.  Use -n switch to work with 2.5.n.
#       Cut and distribution names are determined on the fly.
#       Duplicates are removed.
#0.43 : Added basic 1 parameter distribution functionality.
#         Much still to be done on this.
#       Stopped the script after calculating the cross section if 0 events were
#         requested.
#       Made the html menu fixed, so that it does not scroll off the screen.
#         User needs to remove html/style.css to have this take effect.
#         This might not work in IE, but it does in Firefox.
#0.42 : Fixed 2.5.o issue where parantheses were ignored in cuts.
#0.41 : Improved specification of process for cuts etc.  Now, :n: means the nth
#         process and : means to apply it to all processes.
#0.40 : Fixed bug where it complained when it couldn't remove events_1.txt.
#         This happened when the cross section or decay rate was too small to produce
#         any events. 
#         (Thanks to Ismail Turan for pointing out the problem.)
#0.39 : Fixed problem with pbs server dropping jobs.  If a jobid of 0 is returned, 
#         the script simply reruns it.
#0.38 : Fixed bug in 0.37 improvement.
#0.37 : Improved the regexp identification of the cs during the cs estimation phase.
#0.36 : Added version number to header of run_batch.
#0.35 : Allowed real walltimes to be specified, thus allowing minutes.  E.g. a walltime of 
#         1.25 means 1hr 15min.
#0.34 : Fixed bug with determination of subprocesses.  Changed =~ to eq when comparing particle
#         strings.
#0.33 : Set the default Beamstrahlung parameters to be the same as in CH (~ILC).
#0.32 : Put the cross section in scientific notation in html and txt progress files.
#0.31 : Added ISR and Beam parameters to event file details.
#0.30 : Added ISR and Beamstrahlung for electron positron colliders.
#0.29 : Added cleanup parameter.  If set to True of Yes, the individual event files will
#         be removed after they are combined.
#       Updated batch details printed in combined events file.
#0.28 : Fixed bug where combine_events would get ahead of itself and think it was combining a
#         run parameter ahead of where it really was.
#0.27 : Fixed cosmetic bug where the number of events produced was incorrectly reported in html.
#         wc -l only gives an estimate.  Now, the final N events is taken from CH output.
#0.26 : Fixed bug where sometimes cuts, etc were not being renumbered correctly.
#0.25 : Fixed a bug with the pbs job_script files not being completed.
#       Fixed bug with numbering of process library directories.  Duplicates were being created.
#         New process numbers are now being created by finding the highest number used and adding one.
#0.24 : Added new nt_maker.  Now automatically splits nt's into 50K increments.
#     	 Improved the event library.
#     	 Commented out link to Batch Request.  (Was this really useful?  If so, I should update it.)
#0.23 : Incremented random number seed for each subprocess and decay.
#         Previously, the random seed was the same for all subprocesses and decays.
#         This caused strong correlations between diferrent decay modes and erroneous results.
#      Uppercased random number seed.
#      Padded beginning of random number seed with 1's instead of 0's.
#      Fixed maxN bug.  It was writing it as an integer.  Now, as a real.
#0.22 : Updated the vegas and generate events parameters in decays.
#         Previously, they were left at the default values.
#       Wrapped the number of events to produce in int().
#       niced event_mixer and nt_maker.
#0.21 : Added nice level specification to batch file.  Defaults to 19.
#       Added nt_maker if present.  (Creates nt on the fly.)
#0.20 : Fixed issue where the .a files were not being linked.
#       Also linked the EXTLIB and extern.h, although I don't know if
#         either was necessary.  (I don't see a difference in the results.)
#0.19 : Fixed issue with alphaPDF defaulting to 0.
############################################################################################################# 
use File::stat;
use Time::localtime;
use Getopt::Std;
%options=();
getopts("nrf:",\%options);

####################################################
#		Catch kill                         #
####################################################
$SIG{'HUP'} = 'Handler';
$SIG{'INT'} = 'Handler';
$SIG{'QUIT'} = 'Handler';
$SIG{'ABRT'} = 'Handler';
$SIG{'ALRM'} = 'Handler';
$SIG{'TERM'} = 'Handler';

####################################################
#		Print version                      #
####################################################
print "\ncalchep_batch version $version\n";

####################################################
#               Global variables                   #
####################################################
$sleep_time=3;
$batch_file_name="";
#$batch_file_name=$options{f} if defined $options{f};
$batch_file_name=$ARGV[0] if defined $ARGV[0];
$working_dir="";
@models = ();
$model_num=0;
$model_name = "";
$model_url  = "";
$gauge = "Feynman";
@mod_dirs = ();
@mod_names = ();
@lib_dirs = ();
$next_lib_dir=0;
@lib_procs = ();
@lib_removes = ();
@processes = ();
@decays = ();
@removes = ();
@removesNumber = ();
@removesD = ();
@removesDNumber = ();
@partons = ();
$n_subs=0;
@subprocesses = ();
@subproc_which_proc = ();
@subproc_dir = ();
@subproc_in_lib = ();
@subremoves=();
$n_decay_subs=0;
@decay_subprocesses = ();
@decay_subproc_which_decay = ();
@decay_subproc_dir = ();
@decay_subproc_in_lib = ();
@decay_subremoves = ();
$widths_dir="";
$widths_in_lib=0;
@all_subprocesses = ();
@all_subproc_dir = ();
@all_subproc_in_lib = ();
$pol1 = 0.0;
$pol2 = 0.0;
$pdf1="";
$pdf2="";
$pdf1_name="\"OFF\"";
$pdf2_name="\"OFF\"";
$bunch_size   = 560;
$bunch_length = 0.4;
$bunch_number = 2E+10;
$photon_particle                 = "e^+";
$photon_Qmax                     = 100;
$photon_incoming_particle_mass   = 0.938;
$photon_incoming_particle_charge = 1;
$photon_Q2max                    = 2;
$photon_proton_ptCut             = 0.1;
$p1=7000;
$p2=7000;
$p1def=7000;
$p2def=7000;
$BWrange=2.7;
$TchannelWidths=0;
$GItchannel=0;
$GIschannel=0;
@param_names=();
@param_values=();
@vars_names=();
@vars_values=();
@run_param = ();
@run_begin = ();
@run_step  = ();
@run_n     = ();
$VVdecay   = "On";
$SLHAwidths= "On";
$alphaPDF  = "On";
$alphaMZ   = 0.1172;
$alphaNF   = 5;
$alphaOrder= 2;
$alphaMbMb = 4.2;
$alphaMtp  = 175;
@alphaScale= ();
@alphaNumber=();
@alphaFact1Scale=();
@alphaFact1Number=();
@alphaFact2Scale=();
@alphaFact2Number=();
@alphaRenScale=();
@alphaRenNumber=();
@alphaShowScale=();
@alphaShowNumber=();
@cut_param = ();
@cut_Number= ();
@cut_invert= ();
@cut_min   = ();
@cut_max   = ();
@kinematics= ();
@kin_Number= ();
@decay_kinematics= ();
@decay_kin_Number= ();
@reg_mom   = ();
@reg_Number= ();
@reg_mass  = ();
@reg_width = ();
@reg_pow   = ();
@decay_reg_mom   = ();
@decay_reg_Number= ();
@decay_reg_mass  = ();
@decay_reg_width = ();
@decay_reg_pow   = ();
@dist_param = ();
@dist_Number= ();
@dist_min   = ();
@dist_max   = ();
@dist_title = ();
@dist_x_title=();
@dist_n_bins= ();
@dist_filenames = ();
@plot_filenames = ();
$n_events  = 0;
$sub_gen_n = 0;
$max_lumi  = 1e+9;
$fileName = "";
$fileFormat = "";
$ntuple    = "False";
$cleanup   = "False";
$reuse_sess = "False";
$par_meth  = "this computer";
$max_cpus  = 1;
$max_ppn   = 1; #processors per node (for threading)
$que       = "";
$walltime  = 0;
$memory    = 0;
$email     = "";
$LSFproject = "";
$nice_level=19;
@pids      = ();
$symb_begin_time = 0;
$symb_end_time = 0;
$cs_begin_time = 0;
$cs_end_time = 0;
@cs = ();
@cs_tot = ();
@final_cs = ();
$events_begin_time = 0;
$events_end_time = 0;
@event_filenames = ();
$nSess1 = 5;
$nCalls1 = 10000;
$nSess2 = 5;
$nCalls2 = 100000;
$subCubes = 10000;
$unWeighted = 1;
$randSearch = 100;
$simpSearch = 50;
$maxN = "2.000000";
$findNewMax = 50;
$randTime = time();

#Get current directory
chomp($working_dir = `pwd`);
$html_dir="$working_dir/html";
$CH_PATH=$ENV{'CALCHEP'};
if($CH_PATH eq ""){
  print "CALCHEP environment variable is not set.\nQuitting.\n";
  exit(6);  
}
#print "$CH_PATH\n";
#print "$ARGV[0]\n";

$LHAPDFPATH=$ENV{'LHAPDFPATH'};



####################################################
#               Read batch file.                   #
####################################################
print_index(-1);
#Check to see if the batch file is present.
#If not,  warn the user.
if (!(-e $batch_file_name)) {
  print_no_batch_file();
  if (!(-d $html_dir)){system("mkdir $html_dir");}
  if (!(-e "$html_dir/style.css")){print_style_file();}
  
  if (!(-e "$html_dir/runs")){system("mkdir $html_dir/runs");}
 
  
  #if (-d "$html_dir/help"){system("rm -r $html_dir/help");}
  if (!(-d "$html_dir/help")){
    system("mkdir $html_dir/help");
    print_help();
  }
  exit(6);
}
#Tell the user we are processing batch.
print("\nProcessing batch:\n");
#Open and process batch_file.
open(BATCH_FILE, "<$batch_file_name");
LINE: while($line = <BATCH_FILE>){
	if ($line =~ /^#/){next LINE;}
	elsif ($line =~ /^\s*$/){next LINE;}
	elsif ($line =~ /html\s*dir[^:]*:([^:]*)/){$html_dir=$1;$html_dir=~s/\s//g;}
#	elsif ($line =~ /Model\s*:\s*(\d+)/){$model_num=$1;$model_num =~ s/\s//g;}
	elsif ($line =~ /Model\s*:\s*([^:]+)/){$model_name=$1;}
	elsif ($line =~ /Model changed\s*:\s*(\w+)/){$model_changed=$1;$model_changed =~ s/\s//g;}
	elsif ($line =~ /[Gg]auge\s*:\s*(\w+)/){$gauge=$1;$gauge =~ s/\s//g;}
	elsif ($line =~ /[Rr]emove\s*[Dd]ec[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@removesDNumber,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@removesD,$tmp)}
	elsif ($line =~ /[Rr]emove\s*[Dd]ec[^:]*:([^:]*)/){push(@removesDNumber,-1);$tmp=$1;$tmp =~ s/\s//g;push(@removesD,join(",",sort(split(",",$tmp))));}
	elsif ($line =~ /[Rr]emove[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@removesNumber,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@removes,$tmp)}
	elsif ($line =~ /[Rr]emove[^:]*:([^:]*)/){push(@removesNumber,-1);$tmp=$1;$tmp =~ s/\s//g;push(@removes,join(",",sort(split(",",$tmp))));}
	elsif ($line =~ /Process\s*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@processes,$tmp);}
	elsif ($line =~ /Decay\s*:(.+)/){$tmp=$1;$tmp =~ s/\s//g;push(@decays,$tmp);}
	elsif ($line =~ /Composite\s*:([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@partons,$tmp);}
	elsif ($line =~ /[Aa]lias[^:]*:([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@partons,$tmp);}
	elsif ($line =~ /[Pp]ol[^:]*1:([^:]+)/){$pol1=$1;$pol1 =~ s/\s//g;}
	elsif ($line =~ /[Pp]ol[^:]*2:([^:]+)/){$pol2=$1;$pol2 =~ s/\s//g;}
	elsif ($line =~ /pdf1\s*:\s*(.+)$/){$pdf1=$1;$pdf1 =~ s/\s//g;}
	elsif ($line =~ /pdf2\s*:\s*(.+)$/){$pdf2=$1;$pdf2 =~ s/\s//g;}
	elsif ($line =~ /[Bb]unch[^:]*[Ss]ize[^:]*:([^:]+)/){$bunch_size = $1;$bunch_size =~ s/\s//g;}
	elsif ($line =~ /[Bb]unch[^:]*[Ll]ength[^:]*:([^:]+)/){$bunch_length = $1;$bunch_length =~ s/\s//g;}
	elsif ($line =~ /[Nn]umber[^:]*[Pp]article[^:]*:([^:]+)/){$bunch_number = $1;$bunch_number =~ s/\s//g;}
	elsif ($line =~ /[Pp]hoton[^:]*[Pp]article[^:]*:([^:]+)/){$photon_particle = $1;$photon_particle =~ s/\s//g;}
	elsif ($line =~ /\|Q\|\s*max[^:]*:([^:]+)/){$photon_Qmax = $1; $photon_Qmax =~ s/\s//g;}
	elsif ($line =~ /[Ii]ncoming\s*particle\s*mass[^:]*:([^:]+)/){$photon_incoming_particle_mass = $1;$photon_incoming_particle_mass =~ s/\s//g;}
	elsif ($line =~ /[Ii]ncoming\s*particle\s*charge[^:]*:([^:]+)/){$photon_incoming_particle_charge = $1;$photon_incoming_particle_charge =~ s/\s//g;}
	elsif ($line =~ /\|Q\^2\|\s*max[^:]*:([^:]+)/){$photon_Q2max = $1;$photon_Q2max =~ s/\s//g;}
	elsif ($line =~ /Pt\s*cut[^:]*proton[^:]*:([^:]+)/){$photon_proton_ptCut = $1;$photon_proton_ptCut =~ s/\s//g;}
	elsif ($line =~ /p1[^:]*:([^:]+)/){$p1=$1;$p1 =~ s/\s//g;$p1def=$p1;}
	elsif ($line =~ /p2[^:]*:([^:]+)/){$p2=$1;$p2 =~ s/\s//g;$p2def=$p2;}
	elsif ($line =~ /[Bb]reit\s*[Ww]igner\s*[Rr]ange[^:]*:([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;$BWrange=$tmp;}
	elsif ($line =~ /[Tt]-channel\s*[Ww]idth[^:]*:([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;$TchannelWidths=$tmp;}
	elsif ($line =~ /[Gg][Ii].*[Tt]-channel[^:]*:([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;$GItchannel=$tmp;}
	elsif ($line =~ /[Gg][Ii].*[Ss]-channel[^:]*:([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;$GIschannel=$tmp;}
	elsif ($line =~ /Parameter\s*:\s*([^=]+)=([^=]+)/){
		$tmp1=$1;$tmp2=$2;
		$tmp1=~ s/\s//g;$tmp2 =~ s/\s//g;
		push(@param_names,$tmp1);
		push(@param_values,$tmp2);
	}
	elsif ($line =~ /Run parameter\s*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_param,$tmp);}
	elsif ($line =~ /Run begin\s*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_begin,$tmp);}
	elsif ($line =~ /Run step size\s*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_step,$tmp);}
	elsif ($line =~ /Run n steps\s*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_n,$tmp);}
	elsif ($line =~ /[Ss]can [Pp]ar[^:]*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_param,$tmp);}
	elsif ($line =~ /[Ss]can [Bb]eg[^:]*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_begin,$tmp);}
	elsif ($line =~ /[Ss]can [Ss]tep [Ss]iz[^:]*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_step,$tmp);}
	elsif ($line =~ /[Ss]can [Nn] [Ss]tep[^:]*:\s*([^\s]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@run_n,$tmp);}
	elsif ($line =~ /[Vv]irt[^:]*W[^:]*Z[^:]*[Dd]ec[^:]*:([^:]*)/){$tmp=$1;$tmp=~s/\s//g;$VVdecay=$tmp;}
	elsif ($line =~ /[Ss][Ll][Hh][Aa][^:]*[Ww][Ii][Dd][Tt][Hh][^:]*:([^:]*)/){$tmp=$1;$tmp=~s/\s//g;$SLHAwidths=$tmp;}
	elsif ($line =~ /parton\s*dist[^:]*:([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;$alphaPDF  = $tmp;}
	elsif ($line =~ /alpha\s*\(MZ\)[^:]*:([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;$alphaMZ  = $tmp;}
	elsif ($line =~ /alpha\s*nf[^:]*:([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;$alphaNF  = int($tmp);}
	elsif ($line =~ /alpha\s*[Oo]rder[^:]*:([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;$alphaOrder  = $tmp;}
	elsif ($line =~ /mb\s*\(mb\)[^:]*:([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;$alphaMbMb  = $tmp;}
	elsif ($line =~ /Mtop\s*\(pole\)[^:]*:([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;$alphaMtp  = $tmp;}
	elsif ($line =~ /alpha\s*Q[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@alphaNumber,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@alphaScale,$tmp);}
	elsif ($line =~ /alpha\s*Q[^:]*:([^:]*)/){push(@alphaNumber,-1);$tmp=$1;$tmp =~ s/\s//g;push(@alphaScale,$tmp);}
	elsif ($line =~ /alpha\s*[Ff]act[^:]*1[^:]*Q[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@alphaFact1Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@alphaFact1Scale,$tmp);}
	elsif ($line =~ /alpha\s*[Ff]act[^:]*1[^:]*Q[^:]*:([^:]*)/){push(@alphaFact1Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@alphaFact1Scale,$tmp);}
	elsif ($line =~ /alpha\s*[Ff]act[^:]*2[^:]*Q[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@alphaFact2Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@alphaFact2Scale,$tmp);}
	elsif ($line =~ /alpha\s*[Ff]act[^:]*2[^:]*Q[^:]*:([^:]*)/){push(@alphaFact2Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@alphaFact2Scale,$tmp);}
	elsif ($line =~ /alpha\s*[Ff]act[^:]*Q[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@alphaFact1Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@alphaFact1Scale,$tmp);}
	elsif ($line =~ /alpha\s*[Ff]act[^:]*Q[^:]*:([^:]*)/){push(@alphaFact1Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@alphaFact1Scale,$tmp);}
	elsif ($line =~ /alpha\s*[Rf]en[^:]*Q[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@alphaRenNumber,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@alphaRenScale,$tmp);}
	elsif ($line =~ /alpha\s*[Rf]en[^:]*Q[^:]*:([^:]*)/){push(@alphaRenNumber,-1);$tmp=$1;$tmp =~ s/\s//g;push(@alphaRenScale,$tmp);}
	elsif ($line =~ /alpha\s*[Ss]how[^:]*Q[^:]*:\s*([0-9]*)\s*:([^:]*)/){push(@alphaShowNumber,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@alphaShowScale,$tmp);}
	elsif ($line =~ /alpha\s*[Ss]how[^:]*Q[^:]*:([^:]*)/){push(@alphaShowNumber,-1);$tmp=$1;$tmp =~ s/\s//g;push(@alphaShowScale,$tmp);}
	elsif ($line =~ /Cut parameter\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){push(@cut_Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@cut_param,$tmp);
								       if($#cut_param>$#cut_invert+1){push(@cut_Number,"False");}
								       if($#cut_param>$#cut_min+1){push(@cut_min,"");}
								       if($#cut_param>$#cut_max+1){push(@cut_max,"");}
								     }
	elsif ($line =~ /Cut parameter\s*:\s*([^:]+)/){push(@cut_Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@cut_param,$tmp);
								       if($#cut_param>$#cut_invert+1){push(@cut_Number,"False");}
								       if($#cut_param>$#cut_min+1){push(@cut_min,"");}
								       if($#cut_param>$#cut_max+1){push(@cut_max,"");}
								     }
	elsif ($line =~ /Cut inver[^:]*:\s*([0-9]*)\s*:\s*([^:]*)/){$tmp=$2;$tmp =~ s/\s//g;push(@cut_invert,$tmp);}
	elsif ($line =~ /Cut inver[^:]*:\s*([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;push(@cut_invert,$tmp);}
	elsif ($line =~ /Cut min\s*:\s*([0-9]*)\s*:\s*([^:]*)/){$tmp=$2;$tmp =~ s/\s//g;push(@cut_min,$tmp);}
	elsif ($line =~ /Cut min\s*:\s*([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;push(@cut_min,$tmp);}
	elsif ($line =~ /Cut max\s*:\s*([0-9]*)\s*:\s*([^:]*)/){$tmp=$2;$tmp =~ s/\s//g;push(@cut_max,$tmp);}
	elsif ($line =~ /Cut max\s*:\s*([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;push(@cut_max,$tmp);}
	elsif ($line =~ /[Dd]ecay\s*[Kk]inematics\s*:\s*([0-9]*)\s*:\s*([^:]+)/){push(@decay_kin_Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@decay_kinematics,$tmp);}
	elsif ($line =~ /[Dd]ecay\s*[Kk]inematics\s*:\s*([^:]+)/){push(@decay_kin_Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@decay_kinematics,$tmp);}
	elsif ($line =~ /[Kk]inematics\s*:\s*([0-9]*)\s*:\s*([^:]+)/){push(@kin_Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@kinematics,$tmp);}
	elsif ($line =~ /[Kk]inematics\s*:\s*([^:]+)/){push(@kin_Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@kinematics,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Mm]om[^:]*\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){push(@decay_reg_Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@decay_reg_mom,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Mm]om[^:]*\s*:\s*([^:]+)/){push(@decay_reg_Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@decay_reg_mom,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Mm]ass\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){$tmp=$2;$tmp =~ s/\s//g;push(@decay_reg_mass,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Mm]ass\s*:\s*([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@decay_reg_mass,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Ww]id[^:]*\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){$tmp=$2;$tmp =~ s/\s//g;push(@decay_reg_width,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Ww]id[^:]*\s*:\s*([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@decay_reg_width,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Pp]ow[^:]*\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){$tmp=$2;$tmp =~ s/\s//g;push(@decay_reg_pow,$tmp);}
	elsif ($line =~ /[Dd]ec[^:]*\s*[Rr]eg[^:]*\s*[Pp]ow[^:]*\s*:\s*([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@decay_reg_pow,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Mm]om[^:]*\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){push(@reg_Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@reg_mom,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Mm]om[^:]*\s*:\s*([^:]+)/){push(@reg_Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@reg_mom,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Mm]ass\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){$tmp=$2;$tmp =~ s/\s//g;push(@reg_mass,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Mm]ass\s*:\s*([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@reg_mass,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Ww]id[^:]*\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){$tmp=$2;$tmp =~ s/\s//g;push(@reg_width,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Ww]id[^:]*\s*:\s*([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@reg_width,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Pp]ow[^:]*\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){$tmp=$2;$tmp =~ s/\s//g;push(@reg_pow,$tmp);}
	elsif ($line =~ /[Rr]eg[^:]*\s*[Pp]ow[^:]*\s*:\s*([^:]+)/){$tmp=$1;$tmp =~ s/\s//g;push(@reg_pow,$tmp);}
	elsif ($line =~ /Dist parameter\s*:\s*([0-9]*)\s*:\s*([^\s]+)/){push(@dist_Number,$1-1);$tmp=$2;$tmp =~ s/\s//g;push(@dist_param,$tmp);}
	elsif ($line =~ /Dist parameter\s*:\s*([^:]+)/){push(@dist_Number,-1);$tmp=$1;$tmp =~ s/\s//g;push(@dist_param,$tmp);}
	elsif ($line =~ /Dist min\s*:\s*([0-9]*)\s*:\s*([^:]*)/){$tmp=$2;$tmp =~ s/\s//g;push(@dist_min,$tmp);}
	elsif ($line =~ /Dist min\s*:\s*([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;push(@dist_min,$tmp);}
	elsif ($line =~ /Dist max\s*:\s*([0-9]*)\s*:\s*([^:]*)/){$tmp=$2;$tmp =~ s/\s//g;push(@dist_max,$tmp);}
	elsif ($line =~ /Dist max\s*:\s*([^:]*)/){$tmp=$1;$tmp =~ s/\s//g;push(@dist_max,$tmp);}
	elsif ($line =~ /Dist title\s*:\s*([0-9]*)\s*:\s*([^:]*)\s*/){$tmp=$2;$tmp =~ s/\n//g;push(@dist_title,$tmp);}
	elsif ($line =~ /Dist title\s*:\s*([^:]*)\s*/){$tmp=$1;$tmp =~ s/\n//g;push(@dist_title,$tmp);}
	elsif ($line =~ /Dist x-title\s*:\s*([0-9]*)\s*:\s*([^:]*)\s*/){$tmp=$2;$tmp =~ s/\n//g;push(@dist_x_title,$tmp);}
	elsif ($line =~ /Dist x-title\s*:\s*([^:]*)\s*/){$tmp=$1;$tmp =~ s/\n//g;push(@dist_x_title,$tmp);}
	elsif ($line =~ /Dist n bins\s*:\s*([0-9]*)\s*:\s*([^:]*)\s*/){$tmp=$2;push(@dist_n_bins,int($tmp));}
	elsif ($line =~ /Dist n bins\s*:\s*([^:]*)\s*/){$tmp=$1;push(@dist_n_bins,int($tmp));}
	elsif ($line =~ /[Nn]um[^:]*[Ee]vent[^:]*:\s*([^\s]+)/){$n_events=$1;}
	elsif ($line =~ /[Ss]ub[^:]*[Ff]ul[^:]*[Ee]v[^:]*:\s*([^\s]+)/){$sub_gen_n=$1;}
	elsif ($line =~ /[Mm]ax[^:]*[Ll]umi[^:]*:\s*([^\s]+)/){$max_lumi=$1;}
	elsif ($line =~ /[Ff]ile\s*[Nn]ame[^:]*:\s*([^\s]+)/){$fileName=$1;}
	elsif ($line =~ /[Ff]ile\s*[Ff]ormat[^:]*:\s*([^\s]+)/){$fileFormat=$1;}
	elsif ($line =~ /[Nn][Tt]uple[^:]*:\s*([^\s]+)/){$ntuple = $1;$ntuple =~ s/\s//g;}
	elsif ($line =~ /[Cc]lean\s*[Uu]p[^:]*:([^:]+)/){$cleanup=$1;$cleanup =~ s/\s//g;}
	elsif ($line =~ /[Rr]e[^:]*[Ss]es[^:]*:([^:]+)/){if ($1 =~ /[Tt]r/){$reuse_sess="True";}}
	elsif ($line =~ /Parallel[^:]*:\s*([^:]+)/){$par_meth=$1;$par_meth =~ s/\n//g;}
	elsif ($line =~ /Que[^:]*:([^:]+)/){$que=$1;$que =~ s/\s//g;}
	elsif ($line =~ /[Ww]alltime[^:]*:([^:]+)/){$walltime=$1; $walltime =~ s/\s//g;}
	elsif ($line =~ /[Mm]emory[^:]*:([^:]+)/  ){$memory=$1;   $memory   =~ s/\s//g;}
	elsif ($line =~ /email[^:]*:([^:]+)/){$email=$1;$email =~ s/\s//g;}
	elsif ($line =~ /[Pp]roject[^:]*:([^:]+)/){$LSFproject=$1; $LSFproject=~s/\s//g;}
	elsif ($line =~ /Max[^:]+cpus[^:]*:\s*([^\s]+)/){$max_cpus=$1; $max_cpus =~ s/\s//g; $max_cpus = int($max_cpus);}
	elsif ($line =~ /Max[^:]+proc[^:]+node[^:]*:\s*([^\s]+)/){$max_ppn=$1; $max_ppn =~ s/\s//g; $max_ppn = int($max_ppn);}
	elsif ($line =~ /Max[^:]+nodes[^:]*:\s*([^\s]+)/){$max_cpus=$1; $max_cpus =~ s/\s//g; $max_cpus = int($max_cpus);}
	elsif ($line =~ /[Nn]ice\s*[Ll]evel[^:]*:\s*([^:]+)/){$nice_level=$1; $nice_level =~ s/\s//g; $nice_level = int($nice_level);}
	elsif ($line =~ /nSess_1\s*:\s*([0-9]*)/){$nSess1=$1;$nSess1 =~ s/\s//g; $nSess1=int($nSess1);}
	elsif ($line =~ /nSess_2\s*:\s*([0-9]*)/){$nSess2=$1;$nSess2 =~ s/\s//g; $nSess2=int($nSess2);}
	elsif ($line =~ /nCalls_1\s*:\s*([0-9]*)/){$nCalls1=$1;$nCalls1 =~ s/\s//g; $nCalls1=int($nCalls1);}
	elsif ($line =~ /nCalls_2\s*:\s*([0-9]*)/){$nCalls2=$1;$nCalls2 =~ s/\s//g; $nCalls2=int($nCalls2);}
	elsif ($line =~ /sub-cubes\s*:\s*([0-9]*)/){$subCubes=$1;$subCubes =~ s/\s//g; $subCubes=int($subCubes);}
	elsif ($line =~ /random\s*search\s*:\s*([0-9]*)/){$randSearch=$1;$randSearch =~ s/\s//g; $randSearch=int($randSearch);}
	elsif ($line =~ /simplex\s*search\s*:\s*([0-9]*)/){$simpSearch=$1;$simpSearch =~ s/\s//g; $simpSearch=int($simpSearch);}
	elsif ($line =~ /max\*N\s*:\s*([^:]*)/){$maxN=$1;$maxN =~ s/\s//g;$maxN=sprintf("%.6f",$maxN);}
	elsif ($line =~ /find\s*new\s*MAX\s*:\s*([0-9]*)/){$findNewMax=$1;$findNewMax =~ s/\s//g; $findNewMax=int($findNewMax);}
	elsif ($line =~ /[Ss]leep\s*[Tt]ime\s*:\s*([0-9]*)/){$sleep_time=$1;$sleep_time =~ s/\s//g; $sleep_time=int($sleep_time);}
	else {print "Warning!: Unrecognized instruction: $line\n";}
	
		
}
close(BATCH_FILE);


####################################################
#     Check $nSess and $nCalls                     #
####################################################
if($nSess1<5){$nSess1=5;}
if($nCalls1<10000){$nCalls1=10000;}
if($nSess2<$nSess1){$nSess2=$nSess1;}
if($nCalls2<$nCalls1){$nCalls2=$nCalls1;}

####################################################
#     Make sure directories are in place.          #
####################################################
if (!(-d "batch_results")){system("mkdir batch_results");}
if (!(-d "batch_results/tmp")){system("mkdir batch_results/tmp");}
if (!(-d $html_dir)){system("mkdir $html_dir");}
if (!(-e "$html_dir/style.css")){print_style_file();}
#if (!(-d "$html_dir/runs")){system("mkdir $html_dir/runs");}
if ((-e "$html_dir/runs")){system("rm -rf $html_dir/runs");}
system("mkdir $html_dir/runs");


#if (-d "$html_dir/help"){system("rm -r $html_dir/help");}
if (!(-d "$html_dir/help")){
	system("mkdir $html_dir/help");
	print_help();
}
#Tell the user to look in html/index for progress
print("Progress information can be found in the html directory.\nSimply open the following link in your browser:\nfile://${html_dir}/index.html\nYou can also view textual progress reports in ${html_dir}/index.txt\n\tand the other .txt files in the html directory.\nEvents will be stored in the batch_results directory.\n\n");
#print "Done printing help\n";
#exit();


####################################################
#           Determine pdf name                     #
####################################################
if   ($pdf1 =~ m/cteq6l1[\s\(]*anti-proton/i)     {$pdf1_name="\"PDT:cteq6l1(anti-proton)\" -2212";}
elsif ($pdf1 =~ m/cteq6l1[\s\(]*proton/i)          {$pdf1_name="\"PDT:cteq6l1(proton)\" 2212";}
elsif ($pdf1 =~ m/cteq6l[\s\(]*anti-proton/i)     {$pdf1_name="\"PDT:cteq6l1(anti-proton)\" -2212";}
elsif ($pdf1 =~ m/cteq6l[\s\(]*proton/i)          {$pdf1_name="\"PDT:cteq6l1(proton)\" 2212";}
elsif ($pdf1 =~ m/NNPDF23_lo_as_0130.LHgrid[\s\(]*anti-proton/i)     {$pdf1_name="\"PDT:NNPDF23_lo_as_0130.LHgrid(anti-proton)\" -2212";}
elsif ($pdf1 =~ m/NNPDF23_lo_as_0130.LHgrid[\s\(]*proton/i)     {$pdf1_name="\"PDT:NNPDF23_lo_as_0130.LHgrid(proton)\" 2212";}
elsif ($pdf1 =~ m/grv98_higherTwist[\s\(]*anti-proton/i)     {$pdf1_name="\"PDT:grv98_higherTwist(anti-proton)\" -2212";}
elsif ($pdf1 =~ m/grv98_higherTwist[\s\(]*proton/i)     {$pdf1_name="\"PDT:grv98_higherTwist(proton)\" 2212";}
elsif ($pdf1 =~ m/NNPDF23_lo_as_0130_qed[\s\(]*anti-proton/i)     {$pdf1_name="\"PDT:NNPDF23_lo_as_0130_qed(anti-proton)\" -2212";}
elsif ($pdf1 =~ m/NNPDF23_lo_as_0130_qed[\s\(]*proton/i)     {$pdf1_name="\"PDT:NNPDF23_lo_as_0130_qed(proton)\" 2212";}
elsif ($pdf1 =~ m/MRST2004qed_proton[\s\(]*anti-proton/i)     {$pdf1_name="\"PDT:MRST2004qed_proton(anti-proton)\" -2212";}
elsif ($pdf1 =~ m/MRST2004qed_proton[\s\(]*proton/i)     {$pdf1_name="\"PDT:MRST2004qed_proton(proton)\" 2212";}
elsif ($pdf1 =~ m/CT10[\s\(]*anti-proton/i)     {$pdf1_name="\"PDT:CT10(anti-proton)\" -2212";}
elsif ($pdf1 =~ m/CT10[\s\(]*proton/i)     {$pdf1_name="\"PDT:CT10(proton)\" 2212";}
elsif ($pdf1 =~ /[Ii][Ss][Rr].*[Bb]eam/)        {$pdf1_name=sprintf("\"Qisr=1.00E0*sqrtS,Beamstr:%.1f,%.3f,%.1E\"",$bunch_size,$bunch_length,$bunch_number);}
elsif ($pdf1 =~ /[Ii][Ss][Rr]/)                 {$pdf1_name="\"Qisr=1.00E0*sqrtS,Beamstr: OFF\"";}
elsif ($pdf1 =~ /[Ee]quiv[^:]*[Pp]hoton/)       {$pdf1_name=sprintf("\"Equiv.Photon(particle= %s |Q|max=%s)\"",$photon_particle,$photon_Qmax);}
elsif ($pdf1 =~ /[Ll]aser[^:]*[Pp]hoton/)       {$pdf1_name="\"Laser photons\" 22";}
elsif ($pdf1 =~ /[Pp]roton[^:]*[Pp]hoton/)      {$pdf1_name=sprintf("\"Proton.Photon(m=%f Ch=%i Q=%f Pt>%f)\"",$photon_incoming_particle_mass,$photon_incoming_particle_charge, $photon_Q2max, $photon_proton_ptCut);}
elsif ($pdf1 =~ /[Oo][Ff][Ff]/)                 {$pdf1_name="\"OFF\"";}
elsif ($pdf1 =~ /[Nn][Oo][Nn][Ee]/)             {$pdf1_name="\"OFF\"";}
elsif (!($pdf1 eq ""))                          {$pdf1_name="\"$pdf1\"";}
else                                            {$pdf1_name="\"OFF\"";}

if   ($pdf2 =~ m/cteq6l1[\s\(]*anti-proton/i)     {$pdf2_name="\"PDT:cteq6l1(anti-proton)\" -2212";}
elsif ($pdf2 =~ m/cteq6l1[\s\(]*proton/i)          {$pdf2_name="\"PDT:cteq6l1(proton)\" 2212";}
elsif ($pdf2 =~ m/cteq6l[\s\(]*anti-proton/i)     {$pdf2_name="\"PDT:cteq6l1(anti-proton)\" -2212";}
elsif ($pdf2 =~ m/cteq6l[\s\(]*proton/i)          {$pdf2_name="\"PDT:cteq6l1(proton)\" 2212";}
elsif ($pdf2 =~ m/NNPDF23_lo_as_0130.LHgrid[\s\(]*anti-proton/i)     {$pdf2_name="\"PDT:NNPDF23_lo_as_0130.LHgrid(anti-proton)\" -2212";}
elsif ($pdf2 =~ m/NNPDF23_lo_as_0130.LHgrid[\s\(]*proton/i)     {$pdf2_name="\"PDT:NNPDF23_lo_as_0130.LHgrid(proton)\" 2212";}
elsif ($pdf2 =~ m/grv98_higherTwist[\s\(]*anti-proton/i)     {$pdf2_name="\"PDT:grv98_higherTwist(anti-proton)\" -2212";}
elsif ($pdf2 =~ m/grv98_higherTwist[\s\(]*proton/i)     {$pdf2_name="\"PDT:grv98_higherTwist(proton)\" 2212";}
elsif ($pdf2 =~ m/NNPDF23_lo_as_0130_qed[\s\(]*anti-proton/i)     {$pdf2_name="\"PDT:NNPDF23_lo_as_0130_qed(anti-proton)\" -2212";}
elsif ($pdf2 =~ m/NNPDF23_lo_as_0130_qed[\s\(]*proton/i)     {$pdf2_name="\"PDT:NNPDF23_lo_as_0130_qed(proton)\" 2212";}
elsif ($pdf2 =~ m/MRST2004qed_proton[\s\(]*anti-proton/i)     {$pdf2_name="\"PDT:MRST2004qed_proton(anti-proton)\" -2212";}
elsif ($pdf2 =~ m/MRST2004qed_proton[\s\(]*proton/i)     {$pdf2_name="\"PDT:MRST2004qed_proton(proton)\" 2212";}
elsif ($pdf2 =~ m/CT10[\s\(]*anti-proton/i)     {$pdf2_name="\"PDT:CT10(anti-proton)\" -2212";}
elsif ($pdf2 =~ m/CT10[\s\(]*proton/i)     {$pdf2_name="\"PDT:CT10(proton)\" 2212";}
elsif ($pdf2 =~ /[Ii][Ss][Rr].*[Bb]eam/)        {$pdf2_name=sprintf("\"Qisr=1.00E0*sqrtS,Beamstr:%.1f,%.3f,%.1E\"",$bunch_size,$bunch_length,$bunch_number);}
elsif ($pdf2 =~ /[Ii][Ss][Rr]/)                 {$pdf2_name="\"Qisr=1.00E0*sqrtS,Beamstr: OFF\"";}
elsif ($pdf2 =~ /[Ee]quiv[^:]*[Pp]hoton/)       {$pdf2_name=sprintf("\"Equiv.Photon(particle= %s |Q|max=%s)\"",$photon_particle,$photon_Qmax);}
elsif ($pdf2 =~ /[Ll]aser[^:]*[Pp]hoton/)       {$pdf2_name="\"Laser photons\" 22";}
elsif ($pdf2 =~ /[Pp]roton[^:]*[Pp]hoton/)      {$pdf2_name=sprintf("\"Proton.Photon(m=%f Ch=%i Q=%f Pt>%f)\"",$photon_incoming_particle_mass,$photon_incoming_particle_charge, $photon_Q2max, $photon_proton_ptCut);}
elsif ($pdf2 =~ /[Oo][Ff][Ff]/)                 {$pdf2_name="\"OFF\"";}
elsif ($pdf2 =~ /[Nn][Oo][Nn][Ee]/)             {$pdf2_name="\"OFF\"";}
elsif (!($pdf2 eq ""))                          {$pdf2_name="\"$pdf2\"";}
else                                            {$pdf2_name="\"OFF\"";}

####################################################
#                BW menu                           #
####################################################
if ($TchannelWidths =~ /[Oo][Nn]/){$TchannelWidths=1;}
else {$TchannelWidths=0;}
if ($GItchannel =~ /[Oo][Nn]/){$GItchannel=1;}
else {$GItchannel=0;}
if ($GIschannel =~ /[Oo][Nn]/){$GIschannel=1;}
else {$GIschannel=0;}


####################################################
#               QCD Scale                          #
####################################################
if ($alphaPDF =~ /[Oo][Nn]/ || $alphaPDF =~ /[Tt][Rr][Uu][Ee]/){$alphaPDF=1;}
else {$alphaPDF=0;}
if ($alphaOrder =~ /[Nn][Nn][Ll][Oo]/){$alphaOrder=3;}
elsif ($alphaOrder =~ /[Nn][Ll][Oo]/){$alphaOrder=2;}
elsif ($alphaOrder =~ /[Ll][Oo]/){$alphaOrder=1;}
else {$alphaOrder=2;}
if($#alphaScale>=0){
  @alphaFact1Scale=@alphaScale;
  @alphaFact1Number=@alphaNumber;
  @alphaFact2Scale=@alphaScale;
  @alphaFact2Number=@alphaNumber;
  @alphaRenScale=@alphaScale;
  @alphaRenNumber=@alphaNumber;
  @alphaShowScale=@alphaScale;
  @alphaShowNumber=@alphaNumber;
}



####################################################
#               Cuts                               #
####################################################
if($#cut_param>$#cut_invert+1){push(@cut_Number,"False");}
if($#cut_param>$#cut_min+1){push(@cut_min,"");}
if($#cut_param>$#cut_max+1){push(@cut_max,"");}


####################################################
#            Determine model number                #
####################################################
my $ni=1;
while($model_num==0&&$ni<1000){
	my $file = "$working_dir/models/prtcls${ni}.mdl";
	if(-e $file){
		open(MDL_FILE,$file) or 
			die("Could not open $file");
		my $line = <MDL_FILE>;
		$line =~ s/\s//g;
		$model_name =~ s/\s//g;
		if($line eq $model_name) {$model_num=$ni;}
		close(MDL_FILE);
	}
	$ni++;
}
if($model_num==0) {die("Could not find model: $model_name.\n");}


####################################################
#                 Load the model                   #
####################################################
my $file = "$working_dir/models/prtcls${model_num}.mdl";
open(MDL_FILE,$file) or
	die ("Could not open $file");
@prtcl_full_names=();
@prtcl_names=();
$model_name = <MDL_FILE>;
$model_name =~ s/\n//g;
LINE: while ($line = <MDL_FILE>){
   if ($line =~ /(Particles|Full  name|=====)/) {next LINE;}
   if ($line =~ /^([^\|]+)\|([^\|]+)\|([^\|]+)\|/) {
   	my $tmp1=$1;my $tmp2=$2;$tmp3=$3;
   	$tmp2 =~ s/\s//g;$tmp3 =~ s/\s//g;
		push(@prtcl_names,$tmp2);	
		push(@prtcl_full_names,$tmp1);		
		if ($tmp2!~/^$tmp3$/) {
			push(@prtcl_names,$tmp3);
			push(@prtcl_full_names,$tmp1);
		}
   }
}
close(MDL_FILE);
#print join(",",@prtcl_names)."\n";

####################################################
#      Read the url of the model                   #
####################################################
my $file = "$working_dir/models/extlib${model_num}.mdl";
if ( -f  $file ) {
open(MDL_FILE,$file);
LINE: while ($line = <MDL_FILE>){
   if ($line =~ /(http:.*)/) {
   	$model_url=$1;
   }
}
close(MDL_FILE);
}

####################################################
#       Read Parameter Values                      #
#           from vars.mdl                          #
#       Change it to the value                     #
#           specified in the batch file.           #
####################################################
open(VARS_FILE,"$working_dir/models/vars${model_num}.mdl")
	or die("Could not open $working_dir/models/vars${model_num}.mdl");
VARS_LINE: while (my $line = <VARS_FILE>){
	if ($line =~ /([^\|]+)\|([^\|]+)\|/){
		$name_tmp = $1;
		$value_tmp = $2;
		$name_tmp =~ s/\s//g;
		$value_tmp =~ s/\s//g;
		if ($name_tmp =~ /[Nn]ame/ || $value_tmp =~ /[Vv]alue/){next VARS_LINE;}
		elsif ($name_tmp =~ /^%/){next VARS_LINE;}
		#print "$name_tmp = $value_tmp\n";
		#printf("%s = %.15E\n",$name_tmp,$value_tmp);
		for(my $j=0;$j<=$#param_names;$j++){
			if ($name_tmp eq $param_names[$j]){$value_tmp=$param_values[$j];}
		}
		push(@vars_names,$name_tmp);
		push(@vars_values,$value_tmp);
	}
}
close(VARS_FILE);


####################################################
#              Print batch details.                #
#       This should be updated.                    #
####################################################
print_request();



####################################################
#           Read the models library                #
####################################################
if (!(-d "Processes")){system("mkdir Processes");}
if (!(-e "Processes/models.txt")){print_init_model_library();}
open(MOD_FILE, "<$working_dir/Processes/models.txt");
LINE: while($line = <MOD_FILE>){
	if ($line =~ /^#/){next LINE;}
	if ($line =~ /([^:]+):([^:]+)/){
		$dir=$1;$mod=$2;
		$dir =~ s/\s//g;
		$mod =~ s/\n//g;
		push(@mod_dirs,$dir);
		push(@mod_names,$mod);
	}
}
close(MOD_FILE);

####################################################
#     Delete directories not in the library        #
####################################################
#@dirs = `ls $working_dir/Processes`;
#DIR: foreach $dir (@dirs){
#	$dir =~ s/\s//g;
#	if ($dir =~ /models.txt/){next DIR;}
#	$in_lib=0;
#	foreach $mod_dir (@mod_dirs){
#		if ($dir eq $mod_dir){$in_lib=1;}
#	}
#	if ($in_lib==0){
#		system("rm -rf $working_dir/Processes/$dir");
#	}
#}
#print join("",@dirs)."\n";


####################################################
#            Determine model MD5SUM                #
#            Respond to changes                    #
####################################################
$model_dir="m$model_num";
$model_base_dir=$model_dir;
$nm=1;
foreach $dir (@mod_dirs){
  if($dir eq $model_dir){$nm=0;}
}
push(@mod_dirs,$model_dir);
push(@mod_names,$model_name);
#Continue setting up directories.
if (!(-d "Processes/$model_dir")){system("mkdir Processes/$model_dir");}
if (!(-d "Processes/$model_dir/models")){system("ln -s $working_dir/models Processes/$model_dir/models");}
#Calculate md5sum of current model.
$prtclMD5SUM = `md5 -q $working_dir/models/prtcls${model_num}.mdl`;
if($prtclMD5SUM ne ""){
  $lgrngMD5SUM = `md5 -q $working_dir/models/lgrng${model_num}.mdl`;
  $funcMD5SUM = `md5 -q $working_dir/models/func${model_num}.mdl`;
  $varsMD5SUM = `md5 -q $working_dir/models/vars${model_num}.mdl`;
  $extlibMD5SUM = `md5 -q $working_dir/models/extlib${model_num}.mdl`;
  $md5ormd5sum=1;
}
else{
  $prtclMD5SUM = `md5sum $working_dir/models/prtcls${model_num}.mdl`;
  $prtclMD5SUM =~ s/^(\w+).*/$1/;
  $lgrngMD5SUM = `md5sum $working_dir/models/lgrng${model_num}.mdl`;
  $lgrngMD5SUM =~ s/^(\w+).*/$1/;
  $funcMD5SUM = `md5sum $working_dir/models/func${model_num}.mdl`;
  $funcMD5SUM =~ s/^(\w+).*/$1/;
  $varsMD5SUM = `md5sum $working_dir/models/vars${model_num}.mdl`;
  $varsMD5SUM =~ s/^(\w+).*/$1/;
  $extlibMD5SUM = `md5sum $working_dir/models/extlib${model_num}.mdl`;
  $extlibMD5SUM =~ s/^(\w+).*/$1/;
}
$prtclMD5SUM =~ s/\s//g;
$lgrngMD5SUM =~ s/\s//g;
$funcMD5SUM =~ s/\s//g;
$varsMD5SUM =~ s/\s//g;
$extlibMD5SUM =~ s/\s//g;
#print "prtcl  : '$prtclMD5SUM'\n";
#print "lgrng  : '$lgrngMD5SUM'\n";
#print "func   : '$funcMD5SUM'\n";
#print "vars   : '$varsMD5SUM'\n";
#print "extlib : '$extlibMD5SUM'\n";

#Read md5sum from Processes/mX/md5sum.txt and compare.
$model_changed=0;
$VandP_changed=0;
if(-e "Processes/$model_dir/md5sum.txt"){
  open(MD5,"Processes/$model_dir/md5sum.txt");
 LINE: while ($line = <MD5>){
    if ($line =~ /prtcl\s*:/){
      $line =~ s/\s*prtcl\s*:\s*(\w+)\s*/$1/;
      $line =~ s/\s//g;
      if($line ne $prtclMD5SUM){
	$model_changed=1;
	print "prtcl$model_num.mdl has changed.\n";
      }
    }
    if ($line =~ /lgrng\s*:/){
      $line =~ s/\s*lgrng\s*:\s*(\w+)\s*/$1/;
      $line =~ s/\s//g;
      if($line ne $lgrngMD5SUM){
	$model_changed=1;
	print "lgrng$model_num.mdl has changed.\n";
      }
    }
    if ($line =~ /func\s*:/){
      $line =~ s/\s*func\s*:\s*(\w+)\s*/$1/;
      $line =~ s/\s//g;
      if($line ne $funcMD5SUM){
	$VandP_changed=1;
	print "func$model_num.mdl has changed.\n";
      }
    }
    if ($line =~ /funcLocal\s*:/){
      $line =~ s/\s*funcLocal\s*:\s*(\w+)\s*/$1/;
      $line =~ s/\s//g;
      $funcLocalMD5SUM=$line;
    }
    if ($line =~ /vars\s*:/){
      $line =~ s/\s*vars\s*:\s*(\w+)\s*/$1/;
      $line =~ s/\s//g;
      if($line ne $varsMD5SUM){
	$VandP_changed=1;
	print "vars$model_num.mdl has changed.\n";
      }
    }
    if ($line =~ /extlib\s*:/){
      $line =~ s/\s*extlib\s*:\s*(\w+)\s*/$1/;
      $line =~ s/\s//g;
      if($line ne $extlibMD5SUM){
	$VandP_changed=1;
	print "extlib$model_num.mdl has changed.\n";
      }
    }
  }
  close(MD5);
}

#If VandP changed, recreate it.
if($VandP_changed==1){
  if(-e "Processes/$model_dir/VandP.so"){`rm -f Processes/$model_dir/VandP.so`;}
  if(-e "Processes/$model_dir/VandP.tgz"){`rm -f Processes/$model_dir/VandP.tgz`;}
}
if (!(-e "Processes/$model_dir/VandP.tgz")){
  make_VandP($model_dir);
  $funcLocalMD5SUMold=$funcLocalMD5SUM;
  if($md5ormd5sum==1){$funcLocalMD5SUM = `md5 -q Processes/$model_dir/funcLocal`;}
  else{
    $funcLocalMD5SUM = `md5sum Processes/$model_dir/funcLocal`;
    $funcLocalMD5SUM =~ s/^(\w+).*/$1/;
  }
  $funcLocalMD5SUM =~ s/\s//g;
  if($funcLocalMD5SUM ne $funcLocalMD5SUMold){
    $model_changed=1;
    if($funcLocalMD5SUMold ne ""){print "funcLocal has changed.\n";}
  }
}

#Write current md5sums to file.
if (!(-d "Processes/$model_dir")){system("mkdir Processes/$model_dir");}
if($model_changed==1 || $VandP_changed==1 || !(-e "Processes/$model_dir/md5sum.txt")){
  open(MD5,">Processes/$model_dir/md5sum.txt");
  print MD5 "prtcl     : $prtclMD5SUM\n";
  print MD5 "lgrng     : $lgrngMD5SUM\n";
  print MD5 "func      : $funcMD5SUM\n";
  print MD5 "funcLocal : $funcLocalMD5SUM\n";
  print MD5 "vars      : $varsMD5SUM\n";
  print MD5 "extlib    : $extlibMD5SUM\n";
  close(MD5);
  open(LIB_FILE, ">$working_dir/Processes/models.txt");
  print LIB_FILE "################################\n";
  print LIB_FILE "#        Models Library        #\n";
  print LIB_FILE "#    Automatically generated   #\n";
  print LIB_FILE "#     Do not edit this file    #\n";
  print LIB_FILE "################################\n";
  for(my $j=0;$j<=$#mod_names;$j++){
    if($model_dir eq $mod_dirs[$j]){
      $mod_names[$j] = $model_name;
    }
    print LIB_FILE "$mod_dirs[$j] : $mod_names[$j]\n";
  }  
  close(LIB_FILE);
}
#Recompile VandP every time because the libraries in extlib may have changed.
compile_VandP($model_dir);

#If model changed, recreate all n_calcheps.
if($model_changed==1 && -d "Processes/$model_dir/Feynman"){
  `rm -rf Processes/$model_dir/Feynman`;
  `rm -rf html/$model_dir/Feynman`;
}
if($model_changed==1 && -d "Processes/$model_dir/unitary"){
  `rm -rf Processes/$model_dir/unitary`;
  `rm -rf html/$model_dir/unitary`;
}

####################################################
#         Make sure the appropriate                #
#          directories are present                 #
#          Respond to Model Changes                #
####################################################
if ($gauge =~ /[Uu]nitary/){$model_dir=$model_dir."/unitary";}
else {$model_dir=$model_dir."/Feynman";}
if (!(-d "Processes/$model_dir")){system("mkdir Processes/$model_dir");}
if ($nm==1){print_lib_index("m$model_num",$model_name);}
if (!(-e "Processes/$model_dir/processes.txt")){print_init_library();}
if (!(-e "batch_results/events.txt")){print_init_event_library();}




####################################################
#         Check that the particles requested       #
#        are actually contained in the model.      #
####################################################
@cmpst_names=();
#First check the composites.
foreach $composite (@partons){
	@pieces1 = split("=",$composite);
	push(@cmpst_names,@pieces1[0]);
	@pieces = split(",",$pieces1[1]);
	#print join(" ",@pieces)."\n";
	foreach $piece (@pieces){
		$in_model=0;
		foreach $particle (@prtcl_names){
			if ($piece eq $particle){
				$in_model=1;
			}
		}
		if ($in_model == 0){
			print_particle_not_found($piece);
			print "Mistake in batch file: The particle name $piece is wrong.\n";
			exit(6);
		}
	}
}

#Next check the processes and decays.
foreach $process ((@processes,@decays)){
	@pieces1 = split("->",$process);
	@pieces = split(",",@pieces1[0]);
	push(@pieces,split(",",@pieces1[1]));
	$pieces[0] =~ s/%//g;
	$pieces[1] =~ s/%//g;
	foreach $piece (@pieces){
		$in_model=0;
		foreach $particle (@prtcl_names){
			if ($piece eq $particle){
				$in_model=1;
			}
		}
		foreach $cmpst_name (@cmpst_names){
			if ($piece eq $cmpst_name){
				$in_model=1;
			}
		}
		if ($piece eq "1*x"||$piece eq "2*x"||$piece eq "3*x"||$piece eq "allDec!"){
			$in_model=1;
		}
		if ($in_model == 0){
			print_particle_not_found($piece);
			print "Mistake in batch file: The particle name $piece is wrong.\n";
			exit(6);
		}
	}
}

#Next check the particle removals.
#Actually, I am removing this code.  I am using the users remove line as is to allow for things like u>2 etc..
#So, composite names cannot be used.
#my @removes=();
#foreach $piece (@rmvs){
#  $in_model=0;
#  foreach $particle (@prtcl_names){
#    if ($piece eq $particle){
#      $in_model=1;
#      $in_removes=0;
#      foreach my $rmv (@removes){
#	if ($piece eq $rmv){$in_removes=1;}
#      }
#      if($in_removes==0){push(@removes,$piece);}
#    }
#  }
#  foreach $composite (@partons){
#    ($cmpst_name,$piecesTmp) = split("=",$composite);
#    if ($piece eq $cmpst_name){
#      $in_model=1;
#      @pieces = split(",",$piecesTmp);
#      foreach my $piece (@pieces){
#	$in_removes=0;
#	foreach my $rmv (@removes){
#	  if ($piece eq $rmv){$in_removes=1;}
#	}
#	if($in_removes==0){push(@removes,$piece);}
#      }
#    }
#  }
#  if ($in_model == 0){
#    print_particle_not_found($piece);
#    exit();
#  }
#}
#print "\n\nRemoves = ".join(",",@removes)."\n";
#exit(0);

####################################################
#              Determine subprocesses.             #
#Run calchep with the full process                 #
#Extract the subprocesses from results/list_prc.txt#
####################################################
#                    2->n                          #
####################################################
print_index(0);print_symbolic();
#Setup directories
if(!(-d "Processes/$model_base_dir/results")){system("mkdir Processes/$model_base_dir/results");}
else{system("rm -fr Processes/$model_base_dir/results/*");}
if(!(-d "Processes/$model_base_dir/tmp")){system("mkdir Processes/$model_base_dir/tmp");}
else{system("rm -f Processes/$model_base_dir/tmp/*");}
#foreach $process (@processes){
for (my $l=0;$l<=$#processes;$l++){
	my $process = $processes[$l];
	#Run Process
	$systemString = "";
	for (my $j=1;$j<$model_num;$j++){$systemString=$systemString."[";}
	$systemString=$systemString."\{\{$process\{";
	
	#Partons
	@pieces1=split(/->/,$process);
	@pieces2=split(/,/,$pieces1[0]);
	@pieces3=split(',',$pieces1[1]);
	@pieces=(@pieces2,@pieces3);
	#Remove duplicates
	my @unique = ();
   my %Seen   = ();
   foreach my $elem ( @pieces ){
   	next if $Seen{ $elem }++;
      push @unique, $elem;
   }
   @pieces=@unique;
	#print join(" ",@pieces)."\n";
	#Add composite definitions to the $systemString
	foreach $piece (@pieces){
		$found_part=0;
		foreach $parton (@partons){
			@part=split(/=/,$parton);
			if ($part[0] eq $piece){
				$systemString=$systemString.$part[1]."\{";
				$found_part=1;
			}
		}
	}
	
	#Add removals
	my $whichRemove=-1;
	my $removeList="";
	for (my $m=0;$m<=$#removes;$m++){
	  if($removesNumber[$m]==$l||$removesNumber[$m]==-1)
	   { 
	      if($whichRemove>=0) {$removeList=$removeList.",";}
	      $removeList= $removeList.$removes[$m];
	      $whichRemove=$m;
	   }
	}
	$systemString=$systemString.$removeList."\{";
	
	#Add { for 2*x etc..
	if ($systemString =~ /\*x/){$systemString=$systemString."\{";}									
	#Finish $systemString			
	#$systemString=$systemString."\{\\8a";  #Old system used tmp/menup.ch
	$systemString=$systemString."[[\{\\8a";  #New: uses results/list_prc.txt.
	#print "$systemString\n";
	
	#Run CH
	if (`ls Processes/$model_base_dir/tmp/`){system("rm -f Processes/$model_base_dir/tmp/*");}
	#$systemString = "./calchep -blind \"$systemString\"";
	#$systemString = "$working_dir/calchep -blind \"$systemString\"";
	$systemString = "$CH_PATH/bin/s_calchep -blind \"$systemString\"";
	$systemString = "cd Processes/$model_base_dir; $systemString";
	#print "$systemString\n";
	$result=system($systemString);
	#print "$result\n";
	if($result!=0){
		print "CalcHEP was unable to generate any subprocesses for $process.\n";
		print "Exiting...\n\n";
		exit(6);
	}
	
	#Extract subprocesses
	#open(MDL_FILE,'tmp/menup.ch'); #Old system used tmp/menup.ch
	open(MDL_FILE, "Processes/$model_base_dir/results/list_prc.txt") or
	  die("Could not open Processes/$model_base_dir/results/list_prc.txt");
	LINE: while (my $line = <MDL_FILE>){
		#while ($line =~ /\|([^\|]+->[^\|]+)\|/){ #Old system used tmp/menup.ch
		#	my $sub = $1; #Old system used tmp/menup.ch
			my $sub = $line;
			$sub =~ s/\s//g;
			push(@subprocesses,$sub);
			push(@subproc_which_proc,$l);
			push(@subproc_dir,"");
			push(@subproc_in_lib,0);
#			if($whichRemove>=0){push(@subremoves,$removes[$whichRemove]);}

#			else {push(@subremoves,"");}
			push(@subremoves,$removeList);   
		#	$line =~ s/\|[^\|]+->[^\|]+\|//; #Old system used tmp/menup.ch
	  	#} #Old system used tmp/menup.ch
	}
	close(MDL_FILE);
	print_index(0);print_symbolic();
}
#exit(0);
print_numerical();
#for (my $j=0;$j<=$#cut_Number;$j++){
#	print "$cut_Number[$j]\n";
#}
#print "\n";
#for (my $j=0;$j<=$#reg_Number;$j++){
#	print "$reg_Number[$j]\n";
#}
#print "\n";
#for (my $j=0;$j<=$#alphaNumber;$j++){
#	print "$alphaNumber[$j]\n";
#}
#print "\n";
#for (my $j=0;$j<=$#dist_Number;$j++){
#	print "$dist_Number[$j]\n";
#}

#exit(0);
####################################################
#              Determine subprocesses.             #
#Run calchep with the full process                 #
#Extract the subprocesses from tmp/menup.ch        #
####################################################
#                    1->n                          #
####################################################
print_index(0);print_symbolic();
#foreach $process (@decays){
for (my $l=0;$l<=$#decays;$l++){
	my $process = $decays[$l];
	#Run Process
	$systemString = "";
	for (my $j=1;$j<$model_num;$j++){$systemString=$systemString."[";}
	$systemString=$systemString."\{\{$process\{";
	
	#Partons
	@pieces1=split(/->/,$process);
	@pieces2=split(/,/,$pieces1[0]);
	@pieces3=split(',',$pieces1[1]);
	@pieces=(@pieces2,@pieces3);
	#Remove duplicates
	my @unique = ();
   my %Seen   = ();
   foreach my $elem ( @pieces ){
   	next if $Seen{ $elem }++;
      push @unique, $elem;
   }
   @pieces=@unique;
   #print join(" ",@pieces)."\n";
	#Add composite definitions to the $systemString
	foreach $piece (@pieces){
		$found_part=0;
		foreach $parton (@partons){
			@part=split(/=/,$parton);
			if ($part[0] eq $piece){
				$systemString=$systemString.$part[1]."\{";
				$found_part=1;
			}
		}
	}
	
	#Add removals
	my $whichRemove=-1;
	my $removeList="";
	for (my $m=0;$m<=$#removesD;$m++){
	  if($removesDNumber[$m]==$l||$removesDNumber[$m]==-1)
	   { 
	      if($whichRemove>=0) {$removeList=$removeList.",";}
	      $removeList= $removeList.$removesD[$m];
	      $whichRemove=$m;
	   }
	}
	$systemString=$systemString.$removeList."\{";
	

	#Finish $systemString
	if ($systemString =~ /\*x/){$systemString=$systemString."\{";}												
	#$systemString=$systemString."\{\\8a";  #Old system used tmp/menup.ch
	$systemString=$systemString."[[\{\\8a";  #New: uses results/list_prc.txt.
	#print "$systemString\n";
	#Run CH
	if (`ls Processes/$model_base_dir/tmp/`){system("rm -f Processes/$model_base_dir/tmp/*");}
	#$systemString = "$working_dir/calchep -blind \"$systemString\"";
	$systemString = "$CH_PATH/bin/s_calchep -blind \"$systemString\"";
	$systemString = "cd Processes/$model_base_dir; $systemString";
	#print "$systemString\n";
	$result=system($systemString);
	#print "$result\n";
	if($result!=0){
		print "CalcHEP was unable to generate any subprocesses for $process.\n";
		print "Exiting...\n\n";
		exit(6);
	}
	
	#Extract subprocesses
	#open(MDL_FILE,'tmp/menup.ch');
	#open(MDL_FILE, 'results/list_prc.txt');
	open(MDL_FILE, "Processes/$model_base_dir/results/list_prc.txt") or
	  die("Could not open Processes/$model_base_dir/results/list_prc.txt");
	LINE: while (my $line = <MDL_FILE>){
		#while ($line =~ /\|([^\|]+->[^\|]+)\|/){
		#	my $sub = $1;
			my $sub = $line;
			$sub =~ s/\s//g;
			push(@decay_subprocesses,$sub);
			push(@decay_subproc_which_decay,$l);
			push(@decay_subproc_dir,"");
			push(@decay_subproc_in_lib,0);
		#	if($whichRemove>=0){push(@decay_subremoves,$removesD[$whichRemove]);}
		#	else {push(@decay_subremoves,"");}
			push(@decay_subremoves,$removeList);
		#	$line =~ s/\|[^\|]+->[^\|]+\|//;
	  	#}
	}
	close(MDL_FILE);
	print_index(0);print_symbolic();
}


####################################################
#              Determine subprocesses.             #
#Run calchep with the full process                 #
#Extract the subprocesses from tmp/menup.ch        #
####################################################
#                   Combine                        #
####################################################
@all_subprocesses = (@subprocesses,@decay_subprocesses);
@all_subremoves   = (@subremoves,@decay_subremoves);
#@all_subproc_dir = (@subproc_dir,@decay_subproc_dir);
#@all_subproc_in_lib = (@subproc_in_lib,@decay_subproc_in_lib);
#print join("\t",@all_subprocesses)."\n";





####################################################
#           Read the process library               #
####################################################
$next_lib_dir=0;
open(PROC_FILE, "<$working_dir/Processes/$model_dir/processes.txt");
LINE: while($line = <PROC_FILE>){
	if ($line =~ /^#/){next LINE;}
	if ($line =~ /([^:]+):([^:]+):([^:]+)/){
	        $dir=$1;$proc=$2;$rmv=$3;
		#print "$line";
		$dir =~ s/\s//g;
		$proc =~ s/\s//g;
		$rmv =~ s/\s//g;
		#print "$dir  $proc\n";
		push(@lib_dirs,$dir);
		push(@lib_procs,$proc);
		push(@lib_removes,$rmv);
		$dir =~ s/p//g;
		if ($dir > $next_lib_dir){$next_lib_dir=$dir;}
	}
	elsif ($line =~ /([^:]+):([^:]+)/){
		$dir=$1;$proc=$2;
		#print "$line";
		$dir =~ s/\s//g;
		$proc =~ s/\s//g;
		#print "$dir  $proc\n";
		push(@lib_dirs,$dir);
		push(@lib_procs,$proc);
		push(@lib_removes,"");
		$dir =~ s/p//g;
		if ($dir > $next_lib_dir){$next_lib_dir=$dir;}
	}
}
#print join(" ",@lib_procs)."\n";
close(PROC_FILE);


####################################################
#     Delete directories not in the library        #
####################################################
@dirs = `ls $working_dir/Processes/$model_dir`;
DIR: foreach $dir (@dirs){
	$dir =~ s/\s//g;
	if ($dir =~ /processes.txt/){next DIR;}
	$in_lib=0;
	foreach $lib_dir (@lib_dirs){
		if ($dir eq $lib_dir){$in_lib=1;}
	}
	if ($in_lib==0){
		system("rm -fr $working_dir/Processes/$model_dir/$dir");
	}
}
#print join("",@dirs)."\n";



####################################################
#           Check if the subprocesses              #
#           are already in the library             #
####################################################
SUBPROC: for (my $j=0;$j<=$#subprocesses;$j++){
	for (my $k=0;$k<=$#lib_procs;$k++){
		if ($subprocesses[$j] eq $lib_procs[$k] && $subremoves[$j] eq $lib_removes[$k]){
			$subproc_dir[$j]=$lib_dirs[$k];
			$subproc_in_lib[$j]=1;
			next SUBPROC;
		}
	}
}
SUBPROC: for (my $j=0;$j<=$#decay_subprocesses;$j++){
	for (my $k=0;$k<=$#lib_procs;$k++){
		if ($decay_subprocesses[$j] eq $lib_procs[$k]  && $decay_subremoves[$j] eq $lib_removes[$k]){
			$decay_subproc_dir[$j]=$lib_dirs[$k];
			$decay_subproc_in_lib[$j]=1;
			next SUBPROC;
		}
	}
}
for (my $k=0;$k<=$#lib_procs;$k++){
	if ("Widths" eq $lib_procs[$k]){
		$widths_dir=$lib_dirs[$k];
		$widths_in_lib=1;
	}
}

#@all_subproc_dir = (@subproc_dir,@decay_subproc_dir);
#@all_subproc_in_lib = (@subproc_in_lib,@decay_subproc_in_lib);
#print join(",",@all_subproc_in_lib)."\n";
print_index(0);print_symbolic();



####################################################
#                                                  #
#                                                  #
#             Symbolic Sessions                    #
#                                                  #
#                                                  #
####################################################
$symb_begin_time = time();


####################################################
#           Create directories for                 #
#         the processes that are not               #
#            in the library.                       #
####################################################
#$next_lib_dir=$#lib_dirs+1;
$next_lib_dir++;

for (my $j=0;$j<=$#subprocesses;$j++){
	if ($subproc_in_lib[$j]==0){
		#Determine name of new directory
		$subproc_dir[$j]="p".$next_lib_dir;
		$next_lib_dir++;
		
		#Create directories and link calchep to each.
		system("mkdir Processes/$model_dir/$subproc_dir[$j]");
		#system("ln -s $working_dir/calchep Processes/$model_dir/$subproc_dir[$j]/calchep");
		create_calchep("Processes/$model_dir/$subproc_dir[$j]/calchep");
		system("ln -s $CH_PATH/bin Processes/$model_dir/$subproc_dir[$j]/bin");
		system("ln -s $working_dir/models Processes/$model_dir/$subproc_dir[$j]/models");
		system("mkdir Processes/$model_dir/$subproc_dir[$j]/tmp");
		system("mkdir Processes/$model_dir/$subproc_dir[$j]/results");
	}
}

for (my $j=0;$j<=$#decay_subprocesses;$j++){
	if ($decay_subproc_in_lib[$j]==0){
		#Determine name of new directory
		$decay_subproc_dir[$j]="p".$next_lib_dir;
		$next_lib_dir++;
		
		#Create directories and link calchep to each.
		system("mkdir Processes/$model_dir/$decay_subproc_dir[$j]");
		#system("ln -s $working_dir/calchep Processes/$model_dir/$decay_subproc_dir[$j]/calchep");
		create_calchep("Processes/$model_dir/$decay_subproc_dir[$j]/calchep");
		system("ln -s $CH_PATH/bin Processes/$model_dir/$decay_subproc_dir[$j]/bin");
		system("ln -s $working_dir/models Processes/$model_dir/$decay_subproc_dir[$j]/models");
		system("mkdir Processes/$model_dir/$decay_subproc_dir[$j]/tmp");
		system("mkdir Processes/$model_dir/$decay_subproc_dir[$j]/results");
	}
}

if ($widths_in_lib==0){
	#Determine name of new directory
	$widths_dir="w";
	
	#Create directories and link calchep to each.
	system("mkdir Processes/$model_dir/$widths_dir");
	#system("ln -s $working_dir/calchep Processes/$model_dir/$widths_dir/calchep");
	#create_calchep("Processes/$model_dir/$widths_dir/calchep");
	system("ln -s $CH_PATH/bin Processes/$model_dir/$widths_dir/bin");
	system("ln -s $working_dir/models Processes/$model_dir/$widths_dir/models");
	#system("mkdir Processes/$model_dir/$widths_dir/tmp");
	#system("mkdir Processes/$model_dir/$widths_dir/results");
}

@all_subproc_dir = (@subproc_dir,@decay_subproc_dir);
@all_subproc_in_lib = (@subproc_in_lib,@decay_subproc_in_lib);
#print join(",",@all_subproc_in_lib)."\n";
print_index(0);print_symbolic();


####################################################
#      Create symbolic job scripts for             #
#         the processes that are not               #
#            in the library.                       #
####################################################
for (my $j=0;$j<=$#all_subprocesses;$j++){
	if ($all_subproc_in_lib[$j]==0){
		open(JOB_FILE,">Processes/$model_dir/$all_subproc_dir[$j]/job_script")
			or die("Couldn't open Processes/$model_dir/$all_subproc_dir[$j]/jobscript.");
		print JOB_FILE "#!/bin/bash\n";
		my $job_name = $all_subprocesses[$j];
		$job_name =~ s/'//g;#Remove '
		if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"job.out",0);}
		elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"job.out");}
		elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}
		print JOB_FILE "cd $working_dir/Processes/$model_dir/$all_subproc_dir[$j]\n";
	
		#Create CH blind string	
		#$systemString = "";
		$systemString = "5[[[\{${max_ppn}\{\}";
		for (my $k=1;$k<$model_num;$k++){$systemString=$systemString."[";}
		if ($gauge =~ /[Uu]nitary/){$systemString=$systemString."\{[\{]";}
		else {$systemString=$systemString."\{";}
		$systemString = $systemString."\{$all_subprocesses[$j]\{";

		$systemString = $systemString."$all_subremoves[$j]\{[\{[[[\{";
		
		$systemString = "./calchep -blind \"$systemString\"";
		$systemString = $systemString."  2>&1 1>  job.o";
		if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "$systemString\n";}
		else {
		        print JOB_FILE "nice -n $nice_level $systemString\n";
		#	#print JOB_FILE	"nice -n $nice_level $systemString  2>&1 1>  job.o &\n";
		#	#print JOB_FILE	"nice -n $nice_level $systemString 1> job.o 2> job.e &\n";
		#	print JOB_FILE "$systemString  2>&1 1>  job.o\n"; 
		#	print JOB_FILE "touch finished\n";
		#	#print JOB_FILE "$systemString  2>&1 1>  job.o &\n"; 
		#	#print JOB_FILE "PID=\$!\n";
		#	#print JOB_FILE "renice $nice_level -p \${PID}  2>&1 1>  /dev/null\n";
                #        #print JOB_FILE "echo \${PID}\n";
		#	#print JOB_FILE "echo \$!\n";
		}
		print JOB_FILE "err=\$?\n";
		print JOB_FILE "if(test \$err -ne 0) then\n";
		print JOB_FILE "\techo CH Error \$err\n";
		print JOB_FILE "fi\n";
		if($cleanup =~ /[Tt]rue/ || $cleanup =~ /[Yy]es/){
		  print JOB_FILE "rm -rf tmp\n";
		  print JOB_FILE "rm -f results/*.a\n";
		}
		print JOB_FILE "touch finished-symbolic\n";
		close(JOB_FILE);
		system("chmod u+x Processes/$model_dir/$all_subproc_dir[$j]/job_script");
	}
}
#exit(0);
if ($widths_in_lib==0){
	open(JOB_FILE,">Processes/$model_dir/$widths_dir/job_script")
		or die("Couldn't open Processes/$model_dir/$widths_dir/jobscript.");
	print JOB_FILE "#!/bin/bash\n";
	if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info("Widths","job.out",0);}
	elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info("Widths","job.out");}
	elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}

	print JOB_FILE "cd $working_dir/Processes/$model_dir/$widths_dir\n";

	#Create CH blind string	
	$systemString = "ln -s ../p1/results results";
	#for (my $k=1;$k<$model_num;$k++){$systemString=$systemString."[";}
	#if ($gauge =~ /[Uu]nitary/){$systemString=$systemString."\{[\{]";}
	#else {$systemString=$systemString."\{";}
	#$systemString = $systemString."\{allDec!->2*x\{\{\{\{[\{[[[\{";
	#$systemString = "./calchep -blind \"$systemString\"";
	$systemString = $systemString."  2>&1 1>  job.o";
	if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "$systemString\n";}
	else {
	        print JOB_FILE "nice -n $nice_level $systemString\n";
	#	#print JOB_FILE	"nice -n $nice_level $systemString  2>&1 1>  job.o &\n";
	#	#print JOB_FILE	"nice -n $nice_level $systemString 1> job.o 2> job.e &\n";
	#	#print JOB_FILE	"$systemString  2>&1 1>  job.o\n"; 
	#	#print JOB_FILE "touch finished\n";
	#	print JOB_FILE	"$systemString  2>&1 1>  job.o &\n"; 
	#	print JOB_FILE "PID=\$!\n";
	#	print JOB_FILE "renice $nice_level -p \${PID}  2>&1 1>  /dev/null\n";
	#	print JOB_FILE "echo \${PID}\n";
	#	print JOB_FILE "echo \$!\n";
	}
	print JOB_FILE "err=\$?\n";
	print JOB_FILE "if(test \$err -ne 0) then\n";
	print JOB_FILE "\techo CH Error \$err\n";
	print JOB_FILE "fi\n";
	print JOB_FILE "echo n_calchep is created\n";
	print JOB_FILE "touch finished-symbolic\n";
	close(JOB_FILE);
	system("chmod u+x Processes/$model_dir/$widths_dir/job_script");
}

#print num_not_in_lib();
#exit();


####################################################
#             Run symbolic jobs                    #
#              Monitor progress                    #
####################################################
#Run all jobs
$cpus_in_use=0;
@begin_times=();
@end_times=();
$widths_begin_time=0;
$widths_end_time=0;
@pids=();
$widths_pid=0;
foreach $subprocess (@all_subprocesses){
	push(@begin_times,0);
	push(@end_times,0);
	push(@pids,0);
}
while (num_not_in_lib()>0){
  #Check to see how many jobs are finished.
  for (my $j=0;$j<=$#all_subprocesses;$j++){
    if($end_times[$j]==0&&$begin_times[$j]!=0){
      if(-e "Processes/$model_dir/$all_subproc_dir[$j]/finished-symbolic") {
	if(-e "Processes/$model_dir/$all_subproc_dir[$j]/results/n_calchep"){
	  $jobs_finished++;
	  $cpus_in_use--;
	  $end_times[$j]=time();
	  push(@lib_dirs,$all_subproc_dir[$j]);
	  push(@lib_procs,$all_subprocesses[$j]);
	  push(@lib_removes,$all_subremoves[$j]);
	  $all_subproc_in_lib[$j]=1;
	  print_library($all_subproc_dir[$j],$all_subprocesses[$j],$all_subremoves[$j]);
	  #print "Eureka!\n";
	}
	elsif(-e "Processes/$model_dir/$all_subproc_dir[$j]/job.out") {
	  open(OUT_FILE,"Processes/$model_dir/$all_subproc_dir[$j]/job.out")
	    or die("Could not open Processes/$model_dir/$all_subproc_dir[$j]/job.out");
	LINE: while ($line = <OUT_FILE>){
	    if($line =~ /CH Error/){
	      $jobs_finished++;
	      $cpus_in_use--;
	      $end_times[$j]="Error";
	      #print "Error!\n";
	      print_symbolic(0);
	      print "Error in symbolic session for $all_subprocesses[$j]\n";
	      print "Please have a look at job.o and job.out in Processes/$model_dir/$all_subproc_dir[$j].\n";
	      #print "Exiting...\n\n";
	      #exit();
	      kill_all_jobs(1);
	      next LINE;
	    }
	  }
	  close(OUT_FILE);
	}
      }
      #Check whether job has been killed by cluster
      elsif(1==2 and $end_times[$j]==0 and (time()-$begin_times[$j])>3){
	my $isRunning = 0;
	if($par_meth =~ /[Pp][Bb][Ss]/){
	  $isRunning = int(`qstat $pids[$j] | wc -l`)-2;
	}
	else{
	  $isRunning = int(`ps -p $pids[$j] | wc -l`)-1;
	}
	if($isRunning<1){
	  print_symbolic(0);
	  print "Error in symbolic session for $all_subprocesses[$j]\n";
	  print "Job has terminated prematurely\n";
	  print "Please have a look at job.o and job.out in Processes/$model_dir/$all_subproc_dir[$j].\n";
	  if($par_meth =~ /[Pp][Bb][Ss]/){
	    print "You may need to increase the walltime requested.\n";
	  }
	  kill_all_jobs(1);
	}
      }
    }
  }
  #Now the widths
  if($widths_end_time==0&&$widths_begin_time!=0&&$widths_in_lib==0){
    if(-e "Processes/$model_dir/$widths_dir/finished-symbolic") {
      if(-e "Processes/$model_dir/$widths_dir/results/n_calchep"){
	$jobs_finished++;
	$cpus_in_use--;
	$widths_end_time=time();
	push(@lib_dirs,$widths_dir);
	push(@lib_procs,"Widths");
	push(@lib_removes,"");
	$widths_in_lib=1;
	print_library($widths_dir,"Widths","");
	#print "Eureka!\n";
      }
      elsif(-e "Processes/$model_dir/$widths_dir/job.out") {
	open(OUT_FILE,"Processes/$model_dir/$widths_dir/job.out")
	  or die("Could not open Processes/$model_dir/$widths_dir/job.out");
      LINE: while ($line = <OUT_FILE>){
	  if($line =~ /CH Error/){
	    $jobs_finished++;
	    $cpus_in_use--;
	    $widths_end_time="Error";
	    #print "Error!\n";
	    print_symbolic(0);
	    print "Error in symbolic session for $widths\n";
	    print "Please have a look at job.o and job.out in Processes/$model_dir/$widths_dir.\n";
	    print "$line\n";
	    #print "Exiting...\n\n";
	    #exit();
	    kill_all_jobs(2);
	  }
	}
	close(OUT_FILE);
      }
    }
    #Check whether job has been killed by cluster
    elsif(1==2 and $end_times[$j]==0 and (time()-$begin_times[$j])>3){
      my $isRunning = 0;
      if($par_meth =~ /[Pp][Bb][Ss]/){
	$isRunning = int(`qstat $pids[$j] | wc -l`)-2;
      }
      else{
	$isRunning = int(`ps -p $pids[$j] | wc -l`)-1;
      }
      if($isRunning<1){
	print_symbolic(0);
	print "Error in symbolic session for $all_subprocesses[$j]\n";
	print "Please have a look at job.o and job.out in Processes/$model_dir/$widths_dir.\n";

	print "Job has terminated prematurely\n";
	if($par_meth =~ /[Pp][Bb][Ss]/){
	  print "You may need to increase the walltime requested.\n";
	}
	kill_all_jobs(1);
      }
    }
  }
  
  #Start new jobs if cpus are available.
  if($cpus_in_use<$max_cpus){
    for (my $j=0;$j<=$#all_subprocesses;$j++){
      if ($begin_times[$j]==0&&$cpus_in_use<$max_cpus&&$all_subproc_in_lib[$j]==0){
	chdir("Processes/$model_dir/$all_subproc_dir[$j]/");
	if($par_meth =~ /[Pp][Bb][Ss]/){
	  $pids[$j]=0;
	  while($pids[$j]==0){
	    sleep 0.1;
	    $pids[$j]=`qsub job_script`;
	    $pids[$j] =~ s/([^\.]+)\..*/$1/;
	  }
	}
	elsif($par_meth =~ /[Ll][Ss][Ff]/){
	  $pids[$j]=0;
	  #while($pids[$j]==0){
	  #sleep 0.1;
	  $pids[$j]=`bsub < job_script`;
	  $pids[$j] =~ s/\s//g;
	  #print "pids[$j]=$pids[$j]\n";
	  #}
	}
	elsif($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
	  $pids[$j]=0;
	  #while($pids[$j]==0){
	  #sleep 0.1;
	  $pids[$j]=`sbatch job_script`;
	  $pids[$j] =~ s/.*allocation\s*//; # I don't know if this will work yet.
	  #}
	}
	else {
	  #$pids[$j]=`./job_script  2>&1 1>  job.out & \n echo \$!`;
	  system("./job_script 2>&1 1> job.out & \n echo \$! 2>&1 1> pid");
	  $pids[$j]=`more pid`;
	}
	$pids[$j] =~ s/\s//g;
	chdir("$working_dir");
	$begin_times[$j]=time();
	$cpus_in_use++;
      }
    }
    #Now the widths
    if ($cpus_in_use<$max_cpus&&$widths_begin_time==0&&$cpus_in_use<$max_cpus&&$widths_in_lib==0){
      chdir("Processes/$model_dir/$widths_dir/");
      if($par_meth =~ /[Pp][Bb][Ss]/){
	$widths_pid=0;
	while($widths_pid==0){
	  sleep 0.1;
	  $widths_pid=`qsub job_script`;
	  $widths_pid =~ s/([^\.]+)\..*/$1/;
	}
      }
      elsif($par_meth =~ /[Ll][Ss][Ff]/){
	$widths_pid=0;
	#while($widths_pid==0){
	#sleep 0.1;
	$widths_pid=`bsub < job_script`;
	$widths_pid =~ s/\s//g;
	#print "widths_pid=$widths_pid\n";
	#}
      }
      if($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
	$widths_pid=0;
	#while($widths_pid==0){
	#sleep 0.1;
	$widths_pid=`sbatch job_script`;
	$widths_pid =~ s/.*allocation\s*//; # I don't know if this will work yet.
	#}
      }
      else {
	#$widths_pid=`./job_script  2>&1 1>  job.out & \n echo \$!`;
	system("./job_script 2>&1 1> job.out & \n echo \$! 2>&1 1> pid");
	$widths_pid =`more pid`;
      }
      $widths_pid =~ s/\s//g;
      chdir("$working_dir");
      $widths_begin_time=time();
      $cpus_in_use++;
    }
  }
  
  sleep $sleep_time;
  
  #print num_not_in_lib()."\n";
  print_index(0);print_symbolic(0);
}
$symb_end_time=time();
print_index(0);print_symbolic(0);




####################################################
#                                                  #
#                                                  #
#             Numerical Sessions                   #
#                                                  #
#                                                  #
####################################################
$cs_begin_time = time();
#Remove $fileName-cs.png if present.
if(-e "batch_results/$fileName-cs.jpg"){system("rm batch_results/$fileName-cs.jpg");}
if(-e "batch_results/$fileName-cs.dat"){system("rm batch_results/$fileName-cs.dat");}
####################################################
#Create an array with all the steps in it.         #
####################################################
@step = ();
for (my $j=0;$j<=$#run_param;$j++){
	if ($#step<0){
		for (my $k=0;$k<$run_n[$j];$k++){
			@tmp = ();
			push(@tmp,$k);
			push(@step,[@tmp]);
		}
	}
	else {
		@step_tmp = @step;
		@step = ();
		for (my $k=0;$k<$run_n[$j];$k++){
			for (my $l=0;$l<=$#step_tmp;$l++){
				@tmp = @{$step_tmp[$l]};
				push(@tmp,$k);
				push(@step,[@tmp]);
			}
		}
	}
}
#for (my $j=0;$j<=$#step;$j++){
#	@step_tmp = @{$step[$j]};
#	print "@step_tmp\n";
#}


##############################################################
#Create the directories and job scripts for the subprocesses.#
##############################################################
for (my $k=0;$k<=$#subprocesses;$k++){
	my $subprocess = $subprocesses[$k];
	my $dir_name = "$working_dir/Processes/$model_dir/$subproc_dir[$k]";
	#print $dir_name;
	chdir("$dir_name/results/");
	opendir(DIR,".");
	my @sos = grep(/\.so/,readdir(DIR));#`ls *.so`;
	closedir(DIR);
	opendir(DIR,".");
	my @as = grep(/\.a/,readdir(DIR));#`ls *.a`;
	closedir(DIR);
	chdir("$dir_name");
	if ($#step<0){
		chdir($dir_name);
		if (-d "single" && $reuse_sess eq "False"){system("rm -rf single");}
		if(!(-d "single")){system("mkdir single");}
		chdir("single");
		#Link the executables
		if(!(-e "n_calchep")){system("ln -s ../results/n_calchep n_calchep");}
		foreach $so (@sos){
		  if(!(-e "$so")){system("ln -s ../results/$so $so");}
		}
		foreach $a (@as){
			if(!(-e "$a")){system("ln -s ../results/$a $a");}
		}

		if(!(-d "aux")){system("mkdir aux");}
                if(!(-d "aux/results")){system("mkdir aux/results");}
                if(!(-d "aux/tmp")){system("mkdir aux/tmp");}
                if(!(-e "aux/so_generated")){system("ln -s ../../results/aux/so_generated aux/so_generated");}
                if(!(-e "aux/models")){system("ln -s ../../results/aux/models aux/models");}

		#Create and update session.dat
		if($reuse_sess eq "True"){
		  if(-e "session.dat"){system("./n_calchep -blind \"[[[[[[[[[\{[[[[[[\{0\"");}
		}
 		else{
		  if(-e "session.dat"){system("rm session.dat*");}
		  system("./n_calchep -blind \'\\8a\'");
		  update_session("$dir_name/single",$k,-1);
#!		  system("./n_calchep -blind \'\\8a\'");
		}
		
		#Create job script
		open(JOB_FILE,">job_script")
			or die("Couldn't open $dir_name/single/jobscript.");
		print JOB_FILE "#!/bin/bash\n";
		my $job_name = $subprocess;
		$job_name =~ s/'//g;#'
		if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"cs.out",1);}
		elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"cs.out");}
		elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"cs.out");}
		print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
		print JOB_FILE "cd $dir_name/single/\n";
		#$systemString = "$CH_PATH/bin/run_vegas";
		if($reuse_sess eq "True"){
		  $systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
		}
		else{
		  $systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[\{[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
		}
		$systemString = $systemString."  2>&1 1>  cs.o";
		if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "$systemString\n";}
		elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
		       print JOB_FILE "nice -n $nice_level $systemString\n";
		}
		print JOB_FILE "err=\$?\n";
		print JOB_FILE "if(test \$err -eq 123) then\n";
		print JOB_FILE "\techo 0.0E+0 0.0E+0 > cs.o\n";
		print JOB_FILE "elif(test \$err -ne 0) then\n";
		print JOB_FILE "\techo CH Error \$err\n";
		print JOB_FILE "else\n";
		print JOB_FILE "\tres=`grep \"< >\"  prt_1 |tail -1`\n";
		print JOB_FILE "\tres=`echo \$res| cut -f3,4 -d\" \"`\n";
		print JOB_FILE "\techo \$res 2>&1 1> cs.o\n";
		print JOB_FILE "fi\n";
		print JOB_FILE "touch finished-cross-section\n";
		close(JOB_FILE);
		system("chmod u+x job_script");
		#print ".";
	}
	else {
		for (my $j=0;$j<=$#step;$j++){
			my @step_tmp = @{$step[$j]};
			my $subdir_name = "";
			for (my $l=0;$l<=$#run_param;$l++){
				$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
					$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			}
			#print "\t$subdir_name";
			chdir($dir_name);
			if (-d $subdir_name && $reuse_sess eq "False"){system("rm -rf $subdir_name");}
			if (!(-d $subdir_name)){system("mkdir $subdir_name");}
			chdir($subdir_name);
			#Link the executables
			if(!(-e "n_calchep")){system("ln -s ../results/n_calchep n_calchep");}
			foreach $so (@sos){
				if(!(-e "$so")){system("ln -s ../results/$so $so");}
			}
			foreach $a (@as){
				if(!(-e "$a")){system("ln -s ../results/$a $a");}
			}
			
			if(!(-d "aux")){system("mkdir aux");}
                	if(!(-d "aux/results")){system("mkdir aux/results");}
                	if(!(-d "aux/tmp")){system("mkdir aux/tmp");}
                	if(!(-e "aux/so_generated")){system("ln -s ../../results/aux/so_generated aux/so_generated");}
               	 	if(!(-e "aux/models")){system("ln -s ../../results/aux/models aux/models");}

 			#Create and update session.dat
			if($reuse_sess eq "True"){
			  if(-e "session.dat"){system("./n_calchep -blind \"[[[[[[[[[\{[[[[[[\{0\"");}
			}
			else{
			  if(-e "session.dat"){system("rm session.dat*");}
			  system("./n_calchep -blind \'\\8a\'");
			  #Before updating the session, update the numerical values in @vars_values.
			  for(my $l=0;$l<=$#vars_names;$l++){
			    for(my $m=0;$m<=$#param_names;$m++){
			      if($vars_names[$l] eq $param_names[$m]){$vars_values[$l] = $param_values[$m];}
			    }
			    for(my $m=0;$m<=$#run_param;$m++){
			      my $run_value = $run_begin[$m]+$run_step[$m]*$step_tmp[$m];
			      $vars_values[$l] =~ s/${run_param[$m]}/($run_value)/g; 
			      if($vars_names[$l] eq $run_param[$m]){$vars_values[$l] = $run_value;} 
			    }
			    $vars_values[$l] = eval($vars_values[$l]);
			  }
			  #Also update momenta
			  $p1 = $p1def;
			  $p2 = $p2def;
			  for(my $m=0;$m<=$#run_param;$m++){
			    my $run_value = $run_begin[$m]+$run_step[$m]*$step_tmp[$m];
			    $p1 =~ s/${run_param[$m]}/($run_value)/g; 
			    $p2 =~ s/${run_param[$m]}/($run_value)/g; 
			    if($p1 eq $run_param[$m]){$p1 = $run_value;} 
			    if($p2 eq $run_param[$m]){$p2 = $run_value;} 
			  }
			  $p1 = eval($p1);
			  $p2 = eval($p2);
			  update_session("$dir_name/$subdir_name",$k,$j);
#!			  system("./n_calchep -blind \'\\8a\'");
			}

			#Create job script
			open(JOB_FILE,">job_script")
			or die("Couldn't open $dir_name/$subdir_name/jobscript.");
			print JOB_FILE "#!/bin/bash\n";
			my $job_name = $subprocess;
			$job_name =~ s/'//g;#'
			if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"cs.out",1);}
			elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"cs.out");}
			elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"cs.out");}
			print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
			print JOB_FILE "cd $dir_name/$subdir_name/\n";
			#for (my $l=0;$l<=$#run_param;$l++){
			#	printf JOB_FILE "$CH_PATH/bin/set_param %s %s\n", $run_param[$l], 
			#		$run_begin[$l]+$run_step[$l]*$step_tmp[$l];
			#}
			#$systemString = "$CH_PATH/bin/run_vegas";
			if($reuse_sess eq "True"){
			  $systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
			}
			else{
			  $systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[\{[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
			}
			$systemString = $systemString."  2>&1 1>  cs.o";
			if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "$systemString\n";}
			elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
			       print JOB_FILE "nice -n $nice_level $systemString\n";
			#	#print JOB_FILE	"nice -n $nice_level $systemString  2>&1 1>  cs.o &\n";
			#	#print JOB_FILE	"nice -n $nice_level $systemString 1> cs.o 2> cs.e &";
			#       print JOB_FILE	"$systemString  2>&1 1>  cs.o &\n"; 
			#	print JOB_FILE "PID=\$!\n";
			#	print JOB_FILE "renice $nice_level -p \${PID}  2>&1 1>  /dev/null\n";
			#	print JOB_FILE "echo \${PID}\n";
			#	#print JOB_FILE "echo \$!\n";
			}
			print JOB_FILE "err=\$?\n";
			print JOB_FILE "if(test \$err -eq 123) then\n";
			print JOB_FILE "\techo 0.0E+0 0.0E+0> cs.o\n";
			print JOB_FILE "elif(test \$err -ne 0) then\n";
			print JOB_FILE "\techo CH Error \$err\n";
			print JOB_FILE "else\n";
			print JOB_FILE "\tres=`grep \"< >\"  prt_1 |tail -1`\n";
			print JOB_FILE "\tres=`echo \$res| cut -f3,4 -d\" \"`\n";
			print JOB_FILE "\techo \$res 2>&1 1> cs.o\n";
			print JOB_FILE "fi\n";
			print JOB_FILE "touch finished-cross-section\n";
			close(JOB_FILE);
			system("chmod u+x job_script");
			chdir("$dir_name/");
			#print ".";
		}
	}
	#print "\n\n";
}
########################################################
#Create the directories and job scripts for the decays.#
########################################################
for (my $k=0;$k<=$#decay_subprocesses;$k++){
  $subprocess = $decay_subprocesses[$k];
  $dir_name = "$working_dir/Processes/$model_dir/$decay_subproc_dir[$k]";
  #print $dir_name;
  chdir("$dir_name/results/");
  opendir(DIR,".");
  my @sos = grep(/\.so/,readdir(DIR));#`ls *.so`;
  closedir(DIR);
  opendir(DIR,".");
  my @as = grep(/\.a/,readdir(DIR));#`ls *.a`;
  close(DIR);
  chdir("$dir_name");
  if ($#step<0){
    chdir($dir_name);
    if (-d "single" && $reuse_sess eq "False"){system("rm -rf single");}
    if(!(-d "single")){system("mkdir single");}
    chdir("single");
    #Link the executables
    if(!(-e "n_calchep")){system("ln -s ../results/n_calchep n_calchep");}
    foreach $so (@sos){
      if(!(-e "$so")){system("ln -s ../results/$so $so");}
    }
    foreach $a (@as){
      if(!(-e "$a")){system("ln -s ../results/$a $a");}
    }
    
    #AB system("ln -s ../results/aux aux");
    if(!(-d "aux")){system("mkdir aux");}
    if(!(-d "aux/results")){system("mkdir aux/results");}
    if(!(-d "aux/tmp")){system("mkdir aux/tmp");}
    if(!(-e "aux/so_generated")){system("ln -s ../../results/aux/so_generated aux/so_generated");}
    if(!(-e "aux/models")){system("ln -s ../../results/aux/models aux/models");}

    #Create and update session.dat
    if($reuse_sess eq "True"){
      if(-e "session.dat"){system("./n_calchep -blind \"[[[[[[[[[\{[[[[[[\{0\"");}
    }
    else{
      if(-e "session.dat"){system("rm session.dat*");}
      system("./n_calchep -blind \'\\8a\'");
      update_decay_session("$dir_name/single",$k);
#!      system("./n_calchep -blind \'\\8a\'");
    }
    
    #Create job script
    open(JOB_FILE,">job_script")
      or die("Couldn't open $dir_name/single/jobscript.");
    print JOB_FILE "#!/bin/bash\n";
    my $job_name = $subprocess;
    $job_name =~ s/'//g;#'
    if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"cs.out",0);}
    elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"cs.out");}
    elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"cs.out");}
    print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
    print JOB_FILE "cd $dir_name/single/\n";
    if($resue_sess eq "True"){
      $systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
    }
    else{
      $systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[\{[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
    }
    $systemString = $systemString."  2>&1 1>  cs.o";
    if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "        $systemString\n";}
    elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
      print JOB_FILE "nice -n $nice_level $systemString\n";
    }
    print JOB_FILE "err=\$?\n";
    print JOB_FILE "if(test \$err -eq 123) then\n";
    print JOB_FILE "\techo 0.0E+0 0.0E+0 > cs.o\n";
    print JOB_FILE "elif(test \$err -ne 0) then\n";
    print JOB_FILE "\techo CH Error \$err\n";
    print JOB_FILE "else\n";
    print JOB_FILE "\tres=`grep \"< >\"  prt_1 |tail -1`\n";
    print JOB_FILE "\tres=`echo \$res| cut -f3,4 -d\" \"`\n";
    print JOB_FILE "\techo \$res 2>&1 1> cs.o\n";
    print JOB_FILE "fi\n";
    print JOB_FILE "touch finished-cross-section\n";
    close(JOB_FILE);
    system("chmod u+x job_script");
    #print ".";
  }
  else {
    for (my $j=0;$j<=$#step;$j++){
      @step_tmp = @{$step[$j]};
      $subdir_name = "";
      for (my $l=0;$l<=$#run_param;$l++){
	$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
			       $run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
      }
      #print "\t$subdir_name";
      chdir($dir_name);
      if (-d $subdir_name && $reuse_sess eq "False"){system("rm -rf $subdir_name");}
      if (!(-d $subdir_name)){system("mkdir $subdir_name");}
      chdir($subdir_name);
      #Link the executables
      if(!(-e "n_calchep")){system("ln -s ../results/n_calchep n_calchep");}
      foreach $so (@sos){
	if(!(-e "$so")){system("ln -s ../results/$so $so");}
      }
      foreach $a (@as){
	if(!(-e "$a")){system("ln -s ../results/$a $a");}
      }
      
      if(!(-d "aux")){system("mkdir aux");}
      if(!(-d "aux/results")){system("mkdir aux/results");}
      if(!(-d "aux/tmp")){system("mkdir aux/tmp");}
      if(!(-e "aux/so_generated")){system("ln -s ../../results/aux/so_generated aux/so_generated");}
      if(!(-e "aux/models")){system("ln -s ../../results/aux/models aux/models");}

      #Create and update session.dat
      if($reuse_sess eq "True"){
	if(-e "session.dat"){system("./n_calchep -blind \"[[[[[[[[[\{[[[[[[\{0\"");}
      }
      else{
	if(-e "session.dat"){system("rm session.dat*");}
	system("./n_calchep -blind \'\\8a\'");
	#Before updating the session, update the numerical values in @vars_values.
	for(my $l=0;$l<=$#vars_names;$l++){
	  for(my $m=0;$m<=$#param_names;$m++){
	    if($vars_names[$l] eq $param_names[$m]){$vars_values[$l] = $param_values[$m];}
	  }
	  for(my $m=0;$m<=$#run_param;$m++){
	    my $run_value = $run_begin[$m]+$run_step[$m]*$step_tmp[$m];
	    $vars_values[$l] =~ s/${run_param[$m]}/($run_value)/g;
	    if($vars_names[$l] eq $run_param[$m]){$vars_values[$l] = $run_value;}
	  }
	  $vars_values[$l] = eval($vars_values[$l]);
	}
	update_decay_session("$dir_name/$subdir_name",$k);
	system("./n_calchep -blind \'\\8a\'");
      }
      
      #Create job script
      open(JOB_FILE,">job_script")
	or die("Couldn't open $dir_name/$subdir_name/jobscript.");
      print JOB_FILE "#!/bin/bash\n";
      my $job_name = $subprocess;
      $job_name =~ s/'//g;#'
      if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"cs.out",0);}
      elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"cs.out");}
      elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"cs.out");}
      print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
      print JOB_FILE "cd $dir_name/$subdir_name/\n";
      #for (my $l=0;$l<=$#run_param;$l++){
      #    printf JOB_FILE "$CH_PATH/bin/set_param %s %s\n", $run_param[$l], 
      #    $run_begin[$l]+$run_step[$l]*$step_tmp[$l];
      #}
      if($reuse_sess eq "True"){
	$systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
      }
      else{
	$systemString = "./n_calchep -blind \"[[[[[[[[[\{\{$nSess1\{[\{$nCalls1\{[[\{[[\{[\{]]]]]]\{$nSess2\{[\{$nCalls2\{[[\{0\"";
      }
      $systemString = $systemString."  2>&1 1>  cs.o";
      if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "        $systemString\n";}
      elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
	print JOB_FILE "nice -n $nice_level $systemString\n";
      }
      print JOB_FILE "err=\$?\n";
      print JOB_FILE "if(test \$err -eq 123) then\n";
      print JOB_FILE "\techo 0.0E+0 0.0E+0 > cs.o\n";
      print JOB_FILE "elif(test \$err -ne 0) then\n";
      print JOB_FILE "\techo CH Error \$err\n";
      print JOB_FILE "else\n";
      print JOB_FILE "\tres=`grep \"< >\"  prt_1 |tail -1`\n";
      print JOB_FILE "\tres=`echo \$res| cut -f3,4 -d\" \"`\n";
      print JOB_FILE "\techo \$res 2>&1 1> cs.o\n";
      print JOB_FILE "fi\n";
      print JOB_FILE "touch finished-cross-section\n";
      close(JOB_FILE);
      system("chmod u+x job_script");
      chdir("$dir_name/");
      #print ".";
    }
  }
  #print "\n\n";
}
#print "Done Testing.\n";
#exit();


########################################################
#                                                      #
#          Estimate the cross sections                 #
#                                                      #
########################################################


#########################
#Monitor the progress   #
#Start jobs as necessary#
#########################
@procs_finished=();
$runs_finished=0;
$cpus_in_use=0;
@begin_times=();
@end_times=();
@nevents=();
$jobs_finished=0;
@pids=();
push(@final_cs,0);
print_numerical(0);
###############################
#If a single run is requested.#
###############################
if ($#step<0){
	foreach $subprocess (@all_subprocesses){
		push(@begin_times,0);
		push(@end_times,0);
		push(@pids,0);
		push(@nevents,0);
		push(@cs,0);
	}
	while ($jobs_finished<$#all_subprocesses+1){
		#Check to see how many jobs are finished.
		for (my $j=0;$j<=$#all_subprocesses;$j++){
			if($end_times[$j]==0&&$begin_times[$j]!=0){
				$dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single";
				if(-e "$dir_name/finished-cross-section"){
				  if(-e "$dir_name/cs.o") {
				    open(OUT_FILE,"$dir_name/cs.o")
				      or die("Could not open $dir_name/cs.o");
				    while ($line = <OUT_FILE>){
				      if($line =~ /^(-*[0-9]+\.[0-9]+E[\+-][0-9]+)\s+([0-9]+\.[0-9]+E[\+-][0-9]+)\s*$/){
					$cs[$j]=$1;
					$unc[$j]=$2;
					$jobs_finished++;
					$cpus_in_use--;
					$end_times[$j]=time();
					$line =~ s/\s//g;
					#printf "%f\n",1000*$cs[$j];
					#print "Eureka!\n";
				      }
				    }
				    close(OUT_FILE);
				  }
				  if(-e "$dir_name/cs.out") {
				    open(OUT_FILE,"$dir_name/cs.out")
				      or die("Could not open $dir_name/cs.out");
				    while ($line = <OUT_FILE>){
				      if($line =~ /CH Error/){
					$jobs_finished++;
					$cpus_in_use--;
					$end_times[$j]="Error";
					#print "Error! in $all_subprocesses[$j]\n";
					print_numerical(0);
					print "Error in calculation of cross section for $all_subprocesses[$j]\n";
					print "Please have a look at cs.o and cs.out in Processes/$model_dir/$all_subproc_dir[$j]/single.\n";
	                                system("cat Processes/$model_dir/$all_subproc_dir[$j]/single/cs.out");  #!

					#print "Exiting...\n\n";
					#exit();
					kill_all_jobs(3);
				      }
				    }
				    close(OUT_FILE);
				  }
				}
				#Check whether job has been killed by cluster
				elsif(1==2 and $end_times[$j]==0 and (time()-$begin_times[$j])>3){
				  my $isRunning = 0;
				  if($par_meth =~ /[Pp][Bb][Ss]/){
				    $isRunning = int(`qstat $pids[$j] | wc -l`)-2;
				  }
				  else{
				    $isRunning = int(`ps -p $pids[$j] | wc -l`)-1;
				  }
				  if($isRunning<1){
				    print_numerical(0);
				    print "Error in calculation of cross section for $all_subprocesses[$j]\n";
				    print "Please have a look at cs.o and cs.out in Processes/$model_dir/$all_subproc_dir[$j]/single.\n";
				    system("cat Processes/$model_dir/$all_subproc_dir[$j]/single/cs.out");  #!
				    print "Job has terminated prematurely\n";
				    if($par_meth =~ /[Pp][Bb][Ss]/){
				      print "You may need to increase the walltime requested.\n";
				    }
				    kill_all_jobs(3);
				  }
				}
			      }
		      }
		
		#Start new jobs if cpus are available.
		if($cpus_in_use<$max_cpus){
			for (my $j=0;$j<=$#all_subprocesses;$j++){
				if ($begin_times[$j]==0&&$cpus_in_use<$max_cpus){
					$dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single";
					chdir($dir_name);
					if($par_meth =~ /[Pp][Bb][Ss]/){
						$pids[$j]=0;
						while($pids[$j]==0){
							sleep 0.1;
							$pids[$j]=`qsub job_script`;
							$pids[$j] =~ s/([^\.]+)\..*/$1/;
						}
					}
					elsif($par_meth =~ /[Ll][Ss][Ff]/){
						$pids[$j]=0;
						#while($pids[$j]==0){
							#sleep 0.1;
							$pids[$j]=`bsub < job_script`;
							$pids[$j] =~ s/\s//g;
						        #print "pids[$j]=$pids[$j]\n";
						#}
					}
					if($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
					  $pids[$j]=0;
					  #while($pids[$j]==0){
					  #sleep 0.1;
					  $pids[$j]=`sbatch job_script`;
					  $pids[$j] =~ s/.*allocation\s*//; # I don't know if this will work yet.
					  #}
					}
					elsif($par_meth =~ /this/ || $par_meth =~ /local/){
						#print "$pids[$j]\n";
						#$pids[$j]=`./job_script  2>&1 1>  cs.out & \n echo \$!`;
						system("./job_script 2>&1 1> cs.out & \n echo \$! 2>&1 1> pid");
						$pids[$j]=`more pid`;
					        #print "$pids[$j]\n";
					}
					$pids[$j] =~ s/\s//g;
					chdir($working_dir);
					$begin_times[$j]=time();
					$cpus_in_use++;
				}
			}
		}
		
	
	print_index(1);print_numerical(0);
	sleep $sleep_time;
	}
$runs_finished=1;
combine_distributions(0);
}
#################################
#If multiple runs are requested.#
#################################
else {
	my @begin_tmp=();
	my @end_tmp=();
	my @cs_tmp=();
	my @pids_tmp=();
	my @nevents_tmp=();
	for (my $k=0;$k<=step;$k++){
		push(@begin_tmp,0);
		push(@end_tmp,0);
		push(@cs_tmp,0);
		push(@cs_tot,0);
		push(@final_cs,0);
		push(@pids_tmp,0);
		push(@nevents_tmp,0);
		push(@procs_finished,0);
	}
	foreach $subprocess (@all_subprocesses){
		push(@begin_times,[@begin_tmp]);
		push(@end_times,[@end_tmp]);
		push(@cs,[@cs_tmp]);
		push(@pids,[@pids_tmp]);
		push(@nevents,[@nevents_tmp]);
	}
	while ($runs_finished<$#step+1){
	  #Check to see how many jobs are finished.
	  for (my $k=0;$k<=$#step;$k++){
	    @step_tmp = @{$step[$k]};
	    $subdir_name = "";
	    for (my $l=0;$l<=$#run_param;$l++){
	      $subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
				     $run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
	    }		
	    for (my $j=0;$j<=$#all_subprocesses;$j++){
	      if($end_times[$j][$k]==0&&$begin_times[$j][$k]!=0){
		$dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name";
		if(-e "$dir_name/finished-cross-section"){
		  if(-e "$dir_name/cs.o") {
		    open(OUT_FILE,"$dir_name/cs.o")
		      or die("Could not open $dir_name/cs.o");
		    while ($line = <OUT_FILE>){
		      if($line =~ /^(-*[0-9]+\.[0-9]+E[\+-][0-9]+)\s+([0-9]+\.[0-9]+E[\+-][0-9]+)\s*$/){
			$cs[$j][$k]=$1;
			$unc[$j][$k]=$2;
			$procs_finished[$k]++;
			$cpus_in_use--;
			$end_times[$j][$k]=time();
			$line =~ s/\s//g;
			if ($procs_finished[$k]>$#all_subprocesses){
			  combine_distributions($k);
			  $procs_finished[$k]=0;
			  $runs_finished++;
			  for(my $l=0;$l<=$#all_subprocesses;$l++){
			    $cs_tot[$k]=$cs_tot[$k]+$cs[$l][$k];
			  }
			  print_index(1);if($runs_finished>2){generate_cs_plot();}print_numerical(0);
			}
			#print "Eureka!\n";
		      }
		    }
		    close(OUT_FILE);
		  }
		  if(-e "$dir_name/cs.out") {
		    open(OUT_FILE,"$dir_name/cs.out")
		      or die("Could not open $dir_name/cs.out");
		    while ($line = <OUT_FILE>){
		      if($line =~ /CH Error/){
			$procs_finished[$k]++;
			if ($procs_finished[$k]>$#all_subprocesses){
			  $procs_finished[$k]=0;
			  $runs_finished++;
			}
			$cpus_in_use--;
			$end_times[$j][$k]="Error";
			#print "Error! in $all_subprocesses[$j]\n";
			print_numerical(0);
			print "Error in calculation of cross section for $all_subprocesses[$j]\n\tfor run $subdir_name.\n";
			print "Please have a look at cs.o and cs.out in Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name.\n";
			#print "Exiting...\n\n";
			#exit();
			kill_all_jobs(3);
		      }
		    }
		    close(OUT_FILE);
		  }
		}
		#Check whether job has been killed by cluster
		elsif(1==2 and $end_times[$j][$k]==0 and (time()-$begin_times[$j][$k])>3){
		  my $isRunning = 0;
		  if($par_meth =~ /[Pp][Bb][Ss]/){
		    $isRunning = int(`qstat $pids[$j][$k] | wc -l`)-2;
		  }
		  else{
		    $isRunning = int(`ps -p $pids[$j][$k] | wc -l`)-1;
		  }
		  if($isRunning<1){
		    print_numerical(0);
		    print "Error in calculation of cross section for $all_subprocesses[$j]\n\tfor run $subdir_name.\n";
		    print "Please have a look at cs.o and cs.out in Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name.\n";
		    print "Job has terminated prematurely\n";
		    if($par_meth =~ /[Pp][Bb][Ss]/){
		      print "You may need to increase the walltime requested.\n";
		    }
		    kill_all_jobs(3);
		  }
		}
		
	      }
	    }
	  }
	  
		
		#Start new jobs if cpus are available.
		if($cpus_in_use<$max_cpus){
			for (my $k=0;$k<=$#step;$k++){
				@step_tmp = @{$step[$k]};
				$subdir_name = "";
				for (my $l=0;$l<=$#run_param;$l++){
					$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
						$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
				}		
				for (my $j=0;$j<=$#all_subprocesses;$j++){
					if ($begin_times[$j][$k]==0&&$cpus_in_use<$max_cpus){
						$dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name";
						chdir($dir_name);
						if($par_meth =~ /[Pp][Bb][Ss]/){
							$pids[$j][$k]=0;
							while($pids[$j][$k]==0){
								sleep 0.1;
								$pids[$j][$k]=`qsub job_script`;
								$pids[$j][$k] =~ s/([^\.]+)\..*/$1/;
							}
						}
						elsif($par_meth =~ /[Ll][Ss][Ff]/){
							$pids[$j][$k]=0;
							#while($pids[$j][$k]==0){
								#sleep 0.1;
								$pids[$j][$k]=`bsub < job_script`;
								$pids[$j][$k] =~ s/\s//g;
							        #print "pids[$j][$k]=$pids[$j][$k]\n";
							#}
						}
						if($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
						  $pids[$j][$k]=0;
						  #while($pids[$j][$k]==0){
						  #sleep 0.1;
						  $pids[$j][$k]=`sbatch job_script`;
						  $pids[$j][$k] =~ s/.*allocation\s*//; # I don't know if this will work yet.
						  #}
						}
						elsif($par_meth =~ /this/ || $par_meth =~ /local/){
							#$pids[$j][$k] =`./job_script  2>&1 1>  cs.out & \n echo \$!`;
						        system("./job_script 2>&1 1> cs.out & \n echo \$! 2>&1 1> pid");
            						$pids[$j][$k]=`more pid`;
						}
						$pids[$j][$k] =~ s/\s//g;
						chdir($working_dir);
						$begin_times[$j][$k]=time();
						$cpus_in_use++;
					}
				}
			}
		}
		
	print_index(1);print_numerical(0);
	sleep $sleep_time;
	}	
}
$cs_end_time = time();
print_index(1);print_numerical(0);
#exit();
if($n_events==0){
	if($cleanup =~ /[Tt]rue/ || $cleanup =~ /[Yy]es/){Cleanup();}
	chdir($working_dir);
	if (!(-d "batch_results")){system("mkdir batch_results");}

    if ((-d "batch_results/${fileName}")){system("rm -rf batch_results/${fileName} ");}
    system("mkdir batch_results/${fileName}");
    system("mkdir  batch_results/${fileName}/html");

    system("cp -r html/runs  html/request.html html/symbolic.* html/numerical.* html/index.* batch_results/$fileName/html");
    system("cd  batch_results; cp  ${fileName}*.jpg ${fileName}*.lhe.gz ${fileName} 2>/dev/null; true");
    system("cd  batch_results; mv  ${fileName}*.dat ${fileName}*.distr  events.txt plot*.tab ${fileName} 2>/dev/null; true");


    
	print_index(1.5);
	if($#step>=0) {generate_cs_plot();}
	print_numerical(0.5);
	exit(0);
} 


########################################################
#                                                      #
#               Generate Events                        #
#                                                      #
########################################################
$events_begin_time=time();
@nevents=();
@nevents_final=();
if ($#step<0){
	foreach $subprocess (@all_subprocesses){
		push(@nevents,0);
	}
	$nevents_final[0]=0;
}
else {
	my @nevents_tmp=();
	for (my $k=0;$k<=step;$k++){
		push(@nevents_tmp,0);
		push(@nevents_final,0);
	}
	foreach $subprocess (@all_subprocesses){
		push(@nevents,[@nevents_tmp]);
	}
}		
########################################################
#    Update the job scripts for the subprocesses       #
########################################################
for (my $k=0;$k<=$#subprocesses;$k++){
	my $dir_name = "$working_dir/Processes/$model_dir/$subproc_dir[$k]";
	if ($#step<0){
		chdir("$dir_name/single");
		#Create job script
		open(JOB_FILE,">job_script")
			or die("Couldn't open $dir_name/single/jobscript.");
		print JOB_FILE "#!/bin/bash\n";
		my $job_name = $subprocesses[$k];
		$job_name =~ s/'//g;#'
		if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"job.out",1);}
		elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"job.out");}
		elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}
		print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
		print JOB_FILE "cd $dir_name/single/\n";
		#print JOB_FILE "./n_calchep -blind \"[[[[[[[[[\{\{0\{[[\{0\{\\8a\"\n";
		#print JOB_FILE "./n_calchep -blind \"[[[[[[[[[\{\{0\{0\"\n";
		zero_nSess("$dir_name/single");
		my $total_cs=0;
		for (my $l=0;$l<=$#subprocesses;$l++){$total_cs = $total_cs + $cs[$l];}
		if($total_cs==0) {print "Warning:  cs=0  Cannot generate events!\n";}
		elsif($total_cs*$max_lumi<1) {print "Warning:  cs is too low!\n  Please increase Max Lumi parameter in batch file if you want to generate the requested number of events.\n";}
		$nevents[$k] = int($n_events*$cs[$k]/$total_cs);
		if($nevents[$k]<10){$nevents[$k]=10;}
		$nevents[$k] = $nevents[$k]+5*int(sqrt($nevents[$k]));
		if($sub_gen_n =~ /[Tt]rue/){$nevents[$k] = $n_events;}
		if($cs[$k]==0||$cs[$k]*$max_lumi<1) {$nevents[$k]=0;}
		#my $systemString = sprintf ("$CH_PATH/bin/subproc_cycle 1E+50 %d",$nevents[$k]);
		my $systemString = "./n_calchep -blind \"[[[[[[[[[{[[[[[[[[[{${nevents[$k]}{[{0\"";
		if($nevents[$k]==0){$systemString="echo \"cs=0\"";}
		$systemString = $systemString."  2>&1 1>  job.o";
		if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "$systemString\n";}
		elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
		       print JOB_FILE "nice -n $nice_level $systemString\n";
		#	#print JOB_FILE	"nice -n $nice_level $systemString  2>&1 1>  job.o &\n";
		#	#print JOB_FILE	"nice -n $nice_level $systemString 1> job.o 2> job.e &";
		#	print JOB_FILE	"$systemString  2>&1 1>  job.o &\n"; 
		#	print JOB_FILE "PID=\$!\n";
		#	print JOB_FILE "renice $nice_level -p \${PID}  2>&1 1>  /dev/null\n";
                #        print JOB_FILE "echo \${PID}\n";
		#	#print JOB_FILE "echo \$!\n";
		}
		print JOB_FILE "err=\$?\n";
		print JOB_FILE "if(test \$err -eq 123) then\n";
		print JOB_FILE "\techo Done.\n";
		print JOB_FILE "elif(test \$err -ne 0) then\n";
		print JOB_FILE "\techo CH Error \$err\n";
		print JOB_FILE "fi\n";
		print JOB_FILE "touch finished-events\n";
		close(JOB_FILE);
		system("chmod u+x job_script");
	}
	else {
		for (my $j=0;$j<=$#step;$j++){
			my @step_tmp = @{$step[$j]};
			my $subdir_name = "";
			for (my $l=0;$l<=$#run_param;$l++){
				$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
					$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			}
			#print "\t$subdir_name";
			chdir("$dir_name/$subdir_name");
			#Create job script
			open(JOB_FILE,">job_script")
			or die("Couldn't open $dir_name/$subdir_name/jobscript.");
			print JOB_FILE "#!/bin/bash\n";
			my $job_name = $subprocesses[$k];
			$job_name =~ s/'//g;#'
			if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"job.out",1);}
			elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"job.out");}
			elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}
			print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
			print JOB_FILE "cd $dir_name/$subdir_name/\n";
			#print JOB_FILE "./n_calchep -blind \"[[[[[[[[[\{\{0\{[[\{0\{\\8a\"\n";
			#print JOB_FILE "./n_calchep -blind   \"[[[[[[[[[\{\{0\{0\"\n";
			zero_nSess("$dir_name/$subdir_name");
			#for (my $l=0;$l<=$#run_param;$l++){
			#	printf JOB_FILE "$CH_PATH/bin/set_param %s %s\n", $run_param[$l], 
			#		$run_begin[$l]+$run_step[$l]*$step_tmp[$l];
			#}
			my $total_cs=0;
			for (my $l=0;$l<=$#subprocesses;$l++){$total_cs = $total_cs + $cs[$l][$j];}
			if($total_cs==0) {print "Warning:  cs=0  Cannot generate events!\n";}
			elsif($total_cs*$max_lumi<1) {print "Warning:  cs is too low!\n  Please increase Max Lumi parameter in batch file if you want to generate the requested number of events.\n";}
			$nevents[$k][$j] = int($n_events*$cs[$k][$j]/$total_cs);
			if($nevents[$k][$j]<10){$nevents[$k][$j]=10;}
			$nevents[$k][$j] = $nevents[$k][$j]+5*int(sqrt($nevents[$k][$j]));
			if($sub_gen_n =~ /[Tt]rue/){$nevents[$k][$j] = $n_events;}
			if($cs[$k][$j]==0||$cs[$k][$j]*$max_lumi<1) {$nevents[$k][$j]=0;}
			#my $systemString = sprintf ("$CH_PATH/bin/subproc_cycle 1E+50 %d",$nevents[$k][$j]);
			my $systemString = "./n_calchep -blind \"[[[[[[[[[{[[[[[[[[[{${nevents[$k][$j]}{[{0\"";
			if($nevents[$k][$j]==0){$systemString="echo \"cs=0\"";}
			$systemString = $systemString."  2>&1 1>  job.o";
			if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "$systemString\n";}
		        elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
			       print JOB_FILE "nice -n $nice_level $systemString\n";
			#	#print JOB_FILE	"nice -n $nice_level $systemString  2>&1 1>  job.o &\n";
			#	#print JOB_FILE	"nice -n $nice_level $systemString 1> job.o 2> job.e &";
			#	print JOB_FILE	"$systemString  2>&1 1>  job.o &\n"; 
			#	print JOB_FILE "PID=\$!\n";
			#	print JOB_FILE "renice $nice_level -p \${PID}  2>&1 1>  /dev/null\n";
			#	print JOB_FILE "echo \${PID}\n";
			#	#print JOB_FILE "echo \$!\n";
			}
			print JOB_FILE "err=\$?\n";
			print JOB_FILE "if(test \$err -eq 123) then\n";
			print JOB_FILE "\techo Done.\n";
			print JOB_FILE "elif(test \$err -ne 0) then\n";
			print JOB_FILE "\techo CH Error \$err\n";
			print JOB_FILE "fi\n";
			print JOB_FILE "touch finished-events\n";
			close(JOB_FILE);
			system("chmod u+x job_script");
		}
	}
}

########################################################
# Update the job scripts for the decays.               #
########################################################
for (my $k=0;$k<=$#decay_subprocesses;$k++){
	$subprocess = $decay_subprocesses[$k];
	$dir_name = "$working_dir/Processes/$model_dir/$decay_subproc_dir[$k]";
	#print $dir_name;
	chdir("$dir_name/results/");
	opendir(DIR,".");
	my @sos = grep(/\.so/,readdir(DIR));#`ls *.so`;
	closedir(DIR);
	opendir(DIR,".");
	my @as = grep(/\.a/,readdir(DIR));#`ls *.a`;
	close(DIR);
	chdir("$dir_name");
	if ($#step<0){
		chdir("$dir_name/single");
		#Create job script
		open(JOB_FILE,">job_script")
			or die("Couldn't open $dir_name/single/jobscript.");
		print JOB_FILE "#!/bin/bash\n";
		my $job_name = $subprocess;
		$job_name =~ s/'//g;#'
		if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"job.out",0);}
		elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"job.out");}
		elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}
		print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
		print JOB_FILE "cd $dir_name/single/\n";
		$nevents[$#subprocesses+$k+1] = int(5.1*$n_events);
		if($cs[$#subprocesses+$k+1]==0) {$nevents[$#subprocesses+$k+1]=0;}
		#my $systemString = sprintf ("$CH_PATH/bin/subproc_cycle %d",$nevents[$#subprocesses+$k+1]);
		my $systemString = "./n_calchep -blind \"[[[[[[[[[{[[[[[[[[[{${nevents[$#subprocesses+$k+1]}{[{0\"";
		if($nevents[$#subprocesses+$k+1]==0){$systemString = "echo \"width=0\"";}
		$systemString = $systemString."  2>&1 1>  job.o";
		if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "        $systemString\n";}
		elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
		        print JOB_FILE "nice -n $nice_level $systemString\n";
		}
		print JOB_FILE "err=\$?\n";
		print JOB_FILE "if(test \$err -eq 123) then\n";
		print JOB_FILE "\techo Done.\n";
		print JOB_FILE "elif(test \$err -ne 0) then\n";
		print JOB_FILE "\techo CH Error \$err\n";
		print JOB_FILE "fi\n";
		print JOB_FILE "touch finished-events\n";
		close(JOB_FILE);
		system("chmod u+x job_script");
		#print ".";
	}
	else {
		for (my $j=0;$j<=$#step;$j++){
			@step_tmp = @{$step[$j]};
			$subdir_name = "";
			for (my $l=0;$l<=$#run_param;$l++){
				$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
					$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			}
			#print "\t$subdir_name";
			chdir("$dir_name/$subdir_name");
			#Create job script
			open(JOB_FILE,">job_script")
			or die("Couldn't open $dir_name/$subdir_name/jobscript.");
			print JOB_FILE "#!/bin/bash\n";
			my $job_name = $subprocess;
			$job_name =~ s/'//g;#'
			if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"job.out",0);}
			elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"job.out");}
			elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}
			print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
			print JOB_FILE "cd $dir_name/$subdir_name/\n";
			$nevents[$#subprocesses+$k+1][$j] = int(5.1*$n_events);
			if($cs[$#subprocesses+$k+1][$j]==0) {$nevents[$#subprocesses+$k+1][$j]=0;}
			#my $systemString = sprintf ("$CH_PATH/bin/subproc_cycle %d",$nevents[$#subprocesses+$k+1][$j]);
			my $systemString = "./n_calchep -blind \"[[[[[[[[[{[[[[[[[[[{${nevents[$#subprocesses+$k+1][$j]}{[{0\"";
			if($nevents[$#subprocesses+$k+1][$j]==0){$systemString="echo \"width=0\"";}
			$systemString = $systemString."  2>&1 1>  job.o";
			if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "        $systemString\n";}
			elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
			       print JOB_FILE "nice -n $nice_level $systemString\n";
			}
			print JOB_FILE "err=\$?\n";
			print JOB_FILE "if(test \$err -eq 123) then\n";
			print JOB_FILE "\techo Done.\n";
			print JOB_FILE "elif(test \$err -ne 0) then\n";
			print JOB_FILE "\techo CH Error \$err\n";
			print JOB_FILE "fi\n";
			print JOB_FILE "touch finished-events\n";
			close(JOB_FILE);
			system("chmod u+x job_script");
			chdir("$dir_name/");
			#print ".";
		}
	}
	#print "\n\n";
}

########################################################
#Create the directories and job scripts for the widths.#
########################################################
$subprocess = "Widths";
$dir_name = "$working_dir/Processes/$model_dir/$widths_dir";
#print $dir_name;
chdir("$dir_name/results/");
opendir(DIR,".");
my @sos = grep(/\.so/,readdir(DIR));#`ls *.so`;
closedir(DIR);
opendir(DIR,".");
my @as = grep(/\.a/,readdir(DIR));#`ls *.a`;
close(DIR);
chdir("$dir_name");
if ($#step<0){
	chdir($dir_name);
	if (-d "single"){system("rm -rf single");}
	system("mkdir single");
	chdir("single");
	#Link the executables
	#system("ln -s $dir_name/results/n_calchep n_calchep");
	system("ln -s ../results/n_calchep n_calchep");
	foreach $so (@sos){
		#system("ln -s $dir_name/results/$so $so");
		system("ln -s ../results/$so $so");
	}
	foreach $a (@as){
		#system("ln -s $dir_name/results/$a $a");
		system("ln -s ../results/$a $a");
	}
	#system("ln -s $dir_name/results/extern.h extern.h");
	#system("ln -s $dir_name/results/aux aux");
	
	#AB system("ln -s ../results/aux aux");
	system("mkdir aux");
        system("mkdir aux/results");
        system("mkdir aux/tmp");  
        system("ln -s ../../results/aux/so_generated aux/so_generated");
        system("ln -s ../../results/aux/models aux/models");

 	#system("ln -s $dir_name/results/autoprot.h autoprot.h");
 	#system("ln -s ../results/autoprot.h autoprot.h");
	#system("ln -s $dir_name/results/EXTLIB EXTLIB");
	#system("ln -s ../results/EXTLIB EXTLIB");
	#Create and update session.dat
	system("./n_calchep -blind \'\\8a\'");
	#system("./n_calchep -blind \'[[[[[[[[[{[{\\8e0{[{5{[{\\8e0{}[{{\\8e0{\\8a\'");
	update_decay_session("$dir_name/single",-1);
#!	system("./n_calchep -blind \'\\8a\'");
		#Create job script
	open(JOB_FILE,">job_script")
		or die("Couldn't open $dir_name/single/jobscript.");
	print JOB_FILE "#!/bin/bash\n";
	my $job_name = $subprocess;
	$job_name =~ s/'//g;#'
	if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"job.out",0);}
	elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"job.out");}
	elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}
	print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
	print JOB_FILE "cd $dir_name/single/\n";
	#my $systemString = sprintf ("./n_calchep -blind \"[[[[[[[[[[[\{[[[[[[\{\\8a\"");
	my $systemString = sprintf ("./n_calchep -blind \"[[[{[[{{}0\"");#Includes 1->3 decays
	$systemString = $systemString."  2>&1 1>  job.o";
	if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "        $systemString\n";}
	elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
	       print JOB_FILE "nice -n $nice_level $systemString\n";
	#	#print JOB_FILE	"        nice -n $nice_level $systemString  2>&1 1>  job.o &\n";
	#	#print JOB_FILE	"nice -n $nice_level $systemString 1> job.o 2> job.e &";
	#	print JOB_FILE "         $systemString  2>&1 1>  job.o &\n"; 
	#	print JOB_FILE "         PID=\$!\n";
	#	print JOB_FILE "         renice $nice_level -p \${PID}  2>&1 1>  /dev/null\n";
	#	print JOB_FILE "         echo \${PID}\n";
	#	#print JOB_FILE "         echo \$!\n";
	}
	print JOB_FILE "err=\$?\n";
	print JOB_FILE "if(test \$err -eq 123) then\n";
	print JOB_FILE "\techo Done.\n";
	print JOB_FILE "elif(test \$err -ne 0) then\n";
	print JOB_FILE "\techo CH Error \$err\n";
	print JOB_FILE "fi\n";
	print JOB_FILE "touch finished-events\n";
	close(JOB_FILE);
	system("chmod u+x job_script");
	#print ".";
}
else {
	for (my $j=0;$j<=$#step;$j++){
		@step_tmp = @{$step[$j]};
		$subdir_name = "";
		for (my $l=0;$l<=$#run_param;$l++){
			$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
				$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
		}
		#print "\t$subdir_name";
		chdir($dir_name);
		if (-d $subdir_name){system("rm -rf $subdir_name");}
		system("mkdir $subdir_name");
		chdir($subdir_name);
		#Link the executables
		#system("ln -s $dir_name/results/n_calchep n_calchep");
		system("ln -s ../results/n_calchep n_calchep");
		foreach $so (@sos){
			#system("ln -s $dir_name/results/$so $so");
			system("ln -s ../results/$so $so");
		}
		foreach $a (@as){
			#system("ln -s $dir_name/results/$a $a");
			system("ln -s ../results/$a $a");
		}
		#system("ln -s $dir_name/results/extern.h extern.h");
		#system("ln -s $dir_name/results/aux aux");
		#system("ln -s ../results/aux aux");
		
		#AB system("cp -r ../results/aux aux");
		system("mkdir aux");
                system("mkdir aux/results");
                system("mkdir aux/tmp");  
                system("ln -s ../../results/aux/so_generated aux/so_generated");
                system("ln -s ../../results/aux/models aux/models");

 		#system("ln -s $dir_name/results/autoprot.h autoprot.h");
 		#system("ln -s ../results/autoprot.h autoprot.h");
		#system("ln -s $dir_name/results/EXTLIB EXTLIB");
		#system("ln -s ../results/EXTLIB EXTLIB");
		#Create and update session.dat
		system("./n_calchep -blind \'\\8a\'");
		#system("./n_calchep -blind \'[[[[[[[[[[{{10000{\\8a\'");
		#Before updating the session, update the numerical values in @vars_values.
		for(my $l=0;$l<=$#vars_names;$l++){
		  for(my $m=0;$m<=$#param_names;$m++){
		    if($vars_names[$l] eq $param_names[$m]){$vars_values[$l] = $param_values[$m];}
		  }
		  for(my $m=0;$m<=$#run_param;$m++){
		    my $run_value = $run_begin[$m]+$run_step[$m]*$step_tmp[$m];
		    $vars_values[$l] =~ s/${run_param[$m]}/($run_value)/g;
		    if($vars_names[$l] eq $run_param[$m]){$vars_values[$l] = $run_value;}
		  }
		  $vars_values[$l] = eval($vars_values[$l]);
		}
		update_decay_session("$dir_name/$subdir_name",-1);
!#		system("./n_calchep -blind \'\\8a\'");

		#Create job script
		open(JOB_FILE,">job_script")
		or die("Couldn't open $dir_name/$subdir_name/jobscript.");
		print JOB_FILE "#!/bin/bash\n";
		my $job_name = "Widths";
		$job_name =~ s/'//g;#'
		if($par_meth=~/[Pp][Bb][Ss]/){write_PBS_info($job_name,"job.out",0);}
		elsif($par_meth=~/[Ll][Ss][Ff]/){write_LSF_info($job_name,"job.out");}
		elsif($par_meth=~/[Ss][Ll][Uu][Rr][Mm]/){write_SLURM_info($job_name,"job.out");}
		print JOB_FILE "LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH\n";
		print JOB_FILE "cd $dir_name/$subdir_name/\n";
		#for (my $l=0;$l<=$#run_param;$l++){
		#	printf JOB_FILE "$CH_PATH/bin/set_param %s %s\n", $run_param[$l], 
		#		$run_begin[$l]+$run_step[$l]*$step_tmp[$l];
		#}
		#my $systemString = sprintf ("./n_calchep -blind \"[[[[[[[[[[[\{[[[[[[\{\\8a\"");
		my $systemString = sprintf ("./n_calchep -blind \"[[[{[[{{}0\"");#Includes 1->3 decays
		$systemString = $systemString."  2>&1 1>  job.o";
		if ($par_meth =~ /[Pp][Bb][Ss]/ || $par_meth =~ /[Ll][Ss][Ff]/ || $par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){print JOB_FILE "        $systemString\n";}
		elsif ($par_meth =~ /this/ || $par_meth =~ /local/){
		       print JOB_FILE "nice -n $nice_level $systemString\n";
		#	#print JOB_FILE	"        nice -n $nice_level $systemString  2>&1 1>  job.o &\n";
		#	#print JOB_FILE	"nice -n $nice_level $systemString 1> job.o 2> job.e &";
		#	print JOB_FILE "         $systemString  2>&1 1>  job.o &\n"; 
		#	print JOB_FILE "         PID=\$!\n";
		#	print JOB_FILE "         renice $nice_level -p \${PID}  2>&1 1>  /dev/null\n";
                #        print JOB_FILE "         echo \${PID}\n";
		#	#print JOB_FILE "        echo \$!\n";
		}
		print JOB_FILE "err=\$?\n";
		print JOB_FILE "if(test \$err -eq 123) then\n";
		print JOB_FILE "\techo Done.\n";
		print JOB_FILE "elif(test \$err -ne 0) then\n";
		print JOB_FILE "\techo CH Error \$err\n";
		print JOB_FILE "fi\n";
		print JOB_FILE "touch finished-events\n";
		close(JOB_FILE);
		system("chmod u+x job_script");
		chdir("$dir_name/");
		#print ".";
	}
}
#print "\n\n";




#########################
#Monitor the progress   #
#Start jobs as necessary#
#########################
@procs_finished=();
$runs_finished=0;
$cpus_in_use=0;
@begin_times=();
@end_times=();
$widths_begin_time=0;
$widths_end_time=0;
@pids=();
$widths_pid=0;
#@nevents=();
@nevents_finished=();
$jobs_finished=0;
###############################
#If a single run is requested.#
###############################
if ($#step<0){
	push(@event_filenames,"");
	push(@dist_filenames,"");
	foreach $subprocess (@all_subprocesses){
		push(@begin_times,0);
		push(@end_times,0);
		push(@pids,0);
		#push(@nevents,0);
		push(@nevents_finished,0);
	}
	while ($jobs_finished<$#all_subprocesses+2){
	  #Check to see how many jobs are finished.
	  for (my $j=0;$j<=$#all_subprocesses;$j++){
	    if($end_times[$j]==0&&$begin_times[$j]!=0){
	      $dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single";
	      if(-e "$dir_name/finished-events"){
		if(-e "$dir_name/events_1.txt"){
		  $nevents_finished[$j]=`wc -l $dir_name/events_1.txt`;#print "$nevents_finished[$j]\n";
		  $nevents_finished[$j] =~ s/^\s*([0-9]*).*/$1/;#print "$nevents_finished[$j]\n";
		  $nevents_finished[$j] = int($nevents_finished[$j])-11;#print "$nevents_finished[$j]\n\n";
		  #print "$nevents_finished[$j]:\n";
		}
		if(-e "$dir_name/job.o") {
		  $jobs_finished++;
		  $cpus_in_use--;
		  $end_times[$j]=time();
		  #print "Eureka!\n";
		}
		
		if(-e "$dir_name/job.out") {
		  open(OUT_FILE,"$dir_name/job.out")
		    or die("Could not open $dir_name/job.out");
		  while ($line = <OUT_FILE>){
		    if($line =~ /CH Error/){
		      $jobs_finished++;
		      $cpus_in_use--;
		      $end_times[$j]="Error";
		      #print "Error! in $all_subprocesses[$j]\n";
		      print_numerical(1);
		      print "Error in generation of events for $all_subprocesses[$j].\n";
		      print "Please have a look at job.o and job.out in $dir_name.\n";
		      #print "Exiting...\n\n";
		      #exit();
		      kill_all_jobs(4); 
		    }
		  }
		  close(OUT_FILE);
		}
	      }
	      #Check whether job has been killed by cluster
	      elsif(1==2 and $end_times[$j]==0 and (time()-$begin_times[$j])>3){
		my $isRunning = 0;
		if($par_meth =~ /[Pp][Bb][Ss]/){
		  $isRunning = int(`qstat $pids[$j] | wc -l`)-2;
		}
		else{
		  $isRunning = int(`ps -p $pids[$j] | wc -l`)-1;
		}
		if($isRunning<1){
		  print_numerical(1);
		  print "Error in generation of events for $all_subprocesses[$j].\n";
		  print "Please have a look at job.o and job.out in $dir_name.\n";
		  print "Job has terminated prematurely\n";
		  if($par_meth =~ /[Pp][Bb][Ss]/){
		    print "You may need to increase the walltime requested.\n";
		  }
		  kill_all_jobs(4);
		}
	      }
	    }
	  }
	  #Now the widths
	  if($widths_end_time==0&&$widths_begin_time!=0){
	    $dir_name = "$working_dir/Processes/$model_dir/$widths_dir/single";
	    if(-e "$dir_name/finished-events" && -e "$dir_name/decaySLHA_1.txt") {
	      $jobs_finished++;
	      $cpus_in_use--;
	      $widths_end_time=time();
	    }
	  }
		
		#Start new jobs if cpus are available.
		if($cpus_in_use<$max_cpus){
			for (my $j=0;$j<=$#all_subprocesses;$j++){
				if ($begin_times[$j]==0&&$cpus_in_use<$max_cpus){
					$dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single";
					chdir($dir_name);
					if($par_meth =~ /[Pp][Bb][Ss]/){
						$pids[$j]=0;
						while($pids[$j]==0){
							sleep 0.1;
							$pids[$j]=`qsub job_script`;
							$pids[$j] =~ s/([^\.]+)\..*/$1/;
						}
					}
					elsif($par_meth =~ /[Ll][Ss][Ff]/){
						$pids[$j]=0;
						#while($pids[$j]==0){
							#sleep 0.1;
							$pids[$j]=`bsub < job_script`;
							$pids[$j] =~ s/\s//g;
						        #print "pids[$j]=$pids[$j]\n";
						#}
					}
					if($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
					  $pids[$j]=0;
					  #while($pids[$j]==0){
					  #sleep 0.1;
					  $pids[$j]=`sbatch job_script`;
					  $pids[$j] =~ s/.*allocation\s*//; # I don't know if this will work yet.
					  #}
					}
					elsif($par_meth =~ /this/ || $par_meth =~ /local/){
						#$pids[$j]=`./job_script  2>&1 1>  job.out & \n echo \$!`;
					        system("./job_script 2>&1 1> job.out & \n echo \$! 2>&1 1> pid");
						$pids[$j]=`more pid`;
					}
					$pids[$j] =~ s/\s//g;
					chdir($working_dir);
					$begin_times[$j]=time();
					$cpus_in_use++;
				}
			}
			#Now the widths
			if ($widths_begin_time==0&&$cpus_in_use<$max_cpus){
				$dir_name = "$working_dir/Processes/$model_dir/$widths_dir/single";
				chdir($dir_name);
				if($par_meth =~ /[Pp][Bb][Ss]/){
					$widths_pid=0;
					while($widths_pid==0){
						sleep 0.1;
						$widths_pid=`qsub job_script`;
						$widths_pid =~ s/([^\.]+)\..*/$1/;
					}
				}
				elsif($par_meth =~ /[Ll][Ss][Ff]/){
					$widths_pid=0;
					#while($widths_pid==0){
						#sleep 0.1;
						$widths_pid=`bsub < job_script`;
						$widths_pid =~ s/\s//g;
					        #print "widths_pid=$widths_pid\n";
					#}
				}
				if($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
				  $widths_pid=0;
				  #while($widths_pid==0){
				  #sleep 0.1;
				  $widths_pid =`sbatch job_script`;
				  $widths_pid =~ s/.*allocation\s*//; # I don't know if this will work yet.
				  #}
				}
				elsif($par_meth =~ /this/ || $par_meth =~ /local/){
					#$widths_pid=`./job_script  2>&1 1>  job.out & \n echo \$!`;
				        system("./job_script 2>&1 1> job.out & \n echo \$! 2>&1 1> pid");
					$widths_pid =`more pid`;
				}
				$widths_pid =~ s/\s//g;
				chdir($working_dir);
				$widths_begin_time=time();
				$cpus_in_use++;
			}
		}
		
	print_index(2);print_numerical(1);
	sleep $sleep_time;
	}
$runs_finished=1;
combine_distributions(0);
combine_events(0);
}
#################################
#If multiple runs are requested.#
#################################
else {
	my @begin_tmp=();
	my @end_tmp=();
	#my @cs_tmp=();
	my @pids_tmp=();
	#my @nevents_tmp=();
	my @nevents_finished_tmp=();
	@widths_begin_times=();
	@widths_end_times=();
	@widths_pids=();
	for (my $k=0;$k<=step;$k++){
		push(@begin_tmp,0);
		push(@end_tmp,0);
		#push(@cs_tmp,0);
		push(@cs_tot,0);
		push(@pids_tmp,0);
		#push(@nevents_tmp,0);
		push(@nevents_finished_tmp,0);
		push(@event_filenames,"");
		push(@dist_filenames,"");
		push(@procs_finished,0);
		push(@widths_begin_times,0);
		push(@widths_end_times,0);
		push(@widths_pids,0);
	}
	foreach $subprocess (@all_subprocesses){
		push(@begin_times,[@begin_tmp]);
		push(@end_times,[@end_tmp]);
		#push(@cs,[@cs_tmp]);
		push(@pids,[@pids_tmp]);
		#push(@nevents,[@nevents_tmp]);
		push(@nevents_finished,[@nevents_finished_tmp]);
	}
	while ($runs_finished<$#step+1){
		#Check to see how many jobs are finished.
		for (my $k=0;$k<=$#step;$k++){
		  @step_tmp = @{$step[$k]};
		  $subdir_name = "";
		  for (my $l=0;$l<=$#run_param;$l++){
		    $subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
					   $run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
		  }		
		  for (my $j=0;$j<=$#all_subprocesses;$j++){
		    if($end_times[$j][$k]==0&&$begin_times[$j][$k]!=0){
		      $dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name";
		      if(-e "$dir_name/finished-events"){
			if(-e "$dir_name/events_1.txt"){
			  $nevents_finished[$j][$k] =`wc -l $dir_name/events_1.txt`;
			  $nevents_finished[$j][$k] =~ s/^\s*([0-9]*).*/$1/;
			  $nevents_finished[$j][$k] = int($nevents_finished[$j][$k])-11;
			}
			if(-e "$dir_name/job.o") {
			  $procs_finished[$k]++;
			  $cpus_in_use--;
			  $end_times[$j][$k]=time();
			  if ($procs_finished[$k]>$#all_subprocesses+1){
			    combine_distributions($k);
			    combine_events($k);
			    $procs_finished[$k]=0;
			    $runs_finished++;
			    print_index(2);if($runs_finished>2&&$#step>=0){generate_cs_plot();}print_numerical(1);
			  }
			  #print "Eureka!\n";
			}
			if(-e "$dir_name/job.out") {
			  open(OUT_FILE,"$dir_name/job.out")
			    or die("Could not open $dir_name/job.out");
			  while ($line = <OUT_FILE>){
			    if($line =~ /CH Error/){
			      $procs_finished[$k]++;
			      if ($procs_finished[$k]>$#all_subprocesses+1){
				$procs_finished[$k]=0;
				$runs_finished++;
			      }
			      $cpus_in_use--;
			      $end_times[$j][$k]="Error";
			      #print "Error! in $all_subprocesses[$j]\n";
			      print_numerical(1);
			      print "Error in generation of events for $all_subprocesses[$j]\n\tfor run $dir_name.\n";
			      print "Please have a look at job.o and job.out in $dir_name.\n";
			      #print "Exiting...\n\n";
			      #exit();
			      kill_all_jobs(4);
			    }
			  }
			  close(OUT_FILE);
			}
		      }
		      #Check whether job has been killed by cluster
		      elsif(1==2 and $end_times[$j][$k] and (time()-$begin_times[$j][$k])>3){
			my $isRunning = 0;
			if($par_meth =~ /[Pp][Bb][Ss]/){
			  $isRunning = int(`qstat $pids[$j][$k] | wc -l`)-2;
			}
			else{
			  $isRunning = int(`ps -p $pids[$j][$k] | wc -l`)-1;
			}
			if($isRunning<1){
			  print_numerical(1);
			  print "Error in generation of events for $all_subprocesses[$j]\n\tfor run $dir_name.\n";
			  print "Please have a look at job.o and job.out in $dir_name.\n";
			  print "Job has terminated prematurely\n";
			  if($par_meth =~ /[Pp][Bb][Ss]/){
			    print "You may need to increase the walltime requested.\n";
			  }
			  kill_all_jobs(4);
			}
		      }
		    }
		  }
		  #Now for the widths
		  if($widths_end_times[$k]==0&&$widths_begin_times[$k]!=0){
		    $dir_name = "$working_dir/Processes/$model_dir/$widths_dir/$subdir_name";
		    if(-e "$dir_name/finished-events" && -e "$dir_name/decaySLHA_1.txt") {
		      $procs_finished[$k]++;
		      $cpus_in_use--;
		      $widths_end_times[$k]=time();
		      if ($procs_finished[$k]>$#all_subprocesses+1){
			combine_distributions($k);
			combine_events($k);
			$procs_finished[$k]=0;
			$runs_finished++;
			print_index(2);print_numerical(1);
		      }
		    }
		  }
		}
		
		
		#Start new jobs if cpus are available.
		if($cpus_in_use<$max_cpus){
			for (my $k=0;$k<=$#step;$k++){
				@step_tmp = @{$step[$k]};
				$subdir_name = "";
				for (my $l=0;$l<=$#run_param;$l++){
					$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
						$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
				}		
				for (my $j=0;$j<=$#all_subprocesses;$j++){
					if ($begin_times[$j][$k]==0&&$cpus_in_use<$max_cpus){
						$dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name";
						chdir($dir_name);
						if($par_meth =~ /[Pp][Bb][Ss]/){
							$pids[$j][$k]=0;
							while($pids[$j][$k]==0){
								sleep 0.1;
								$pids[$j][$k]=`qsub job_script`;
								$pids[$j][$k] =~ s/([^\.]+)\..*/$1/;
							}
						}
						elsif($par_meth =~ /[Ll][Ss][Ff]/){
							$pids[$j][$k]=0;
							#while($pids[$j][$k]==0){
								#sleep 0.1;
								$pids[$j][$k]=`bsub < job_script`;
								$pids[$j][$k] =~ s/\s//g;
							        #print "pids[$j][$k]=$pids[$j][$k]\n";
							#}
						}
						if($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
						  $pids[$j][$k]=0;
						  #while($pids[$j][$k]==0){
						  #sleep 0.1;
						  $pids[$j][$k] =`sbatch job_script`;
						  $pids[$j][$k] =~ s/.*allocation\s*//; # I don't know if this will work yet.
						  #}
						}
						elsif($par_meth =~ /this/ || $par_meth =~ /local/){
							#$pids[$j][$k] =`./job_script  2>&1 1>  job.out & \n echo \$!`;
						        system("./job_script 2>&1 1> job.out & \n echo \$! 2>&1 1> pid");
							$pids[$j][$k] =`more pid`;
						}
							$pids[$j][$k] =~ s/\s//g;
						chdir($working_dir);
						$begin_times[$j][$k]=time();
						$cpus_in_use++;
					}
				}
				#Now for the widths
				if ($widths_begin_times[$k]==0&&$cpus_in_use<$max_cpus){
					$dir_name = "$working_dir/Processes/$model_dir/$widths_dir/$subdir_name";
					chdir($dir_name);
					if($par_meth =~ /[Pp][Bb][Ss]/){
						$widths_pids[$k]=0;
						while($widths_pids[$k]==0){
							sleep 0.1;
							$widths_pids[$k]=`qsub job_script`;
							$widths_pids[$k] =~ s/([^\.]+)\..*/$1/;
						}
					}
					elsif($par_meth =~ /[Ll][Ss][Ff]/){
						$widths_pids[$k]=0;
						#while($widths_pids[$k]==0){
							#sleep 0.1;
							$widths_pids[$k]=`bsub < job_script`;
							$widths_pids[$k] =~ s/\s//g;
						        #print "widths_pids[$k]=$widths_pids[$k]\n";
						#}
					}
					if($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){
					  $widths_pids[$j]=0;
					  #while($widths_pids[$j]==0){
					  #sleep 0.1;
					  $widths_pids[$j]=`sbatch job_script`;
					  $widths_pids[$j] =~ s/.*allocation\s*//; # I don't know if this will work yet.
					  #}
					}
					elsif($par_meth =~ /this/ || $par_meth =~ /local/){
						#$widths_pids[$k] =`./job_script  2>&1 1>  job.out & \n echo \$!`;
					        system("./job_script 2>&1 1> job.out & \n echo \$! 2>&1 1> pid");
						$widths_pids[$k]=`more pid`;
					}
					$widths_pids[$k] =~ s/\s//g; 
					chdir($working_dir);
					$widths_begin_times[$k]=time();
					$cpus_in_use++;
				}
			}
		}
		
		print_index(2);print_numerical(1);
		sleep $sleep_time;
	}	
}
$events_end_time = time();
print_index(2);
if($#step>=0) {generate_cs_plot();}
print_numerical(1);



#Done!!!
if($cleanup =~ /[Tt]rue/ || $cleanup =~ /[Yy]es/){Cleanup();}
print_index(3);
if($#step>=0) {generate_cs_plot();}
print_numerical(2);


chdir($working_dir);
if (!(-d "batch_results")){system("mkdir batch_results");}
if (!(-e "Events")){system("ln -s  batch_results Events");}

if ((-d "batch_results/${fileName}")){system("rm -rf batch_results/${fileName} ");}
system("mkdir  batch_results/$fileName ");
system("mkdir  batch_results/$fileName/html");

system("cp -r html/runs  html/request.html html/symbolic.*  html/numerical.*  html/index.*  batch_results/$fileName/html");
system("cd  batch_results; cp  ${fileName}*.jpg ${fileName}*.distr ${fileName}*.lhe.gz events.txt plot*.tab $fileName 2>/dev/null; true");

 


#END OF RUN #









####################################################
#                                                  #
#              Functions                           #
#                                                  #
####################################################

####################################################
#         Create plot of final cross sections      #
####################################################
sub generate_cs_plot {
  chdir("$working_dir/batch_results/tmp/");
  open(GP_DAT,">gnuplot_dat");
  my $min=$final_cs[0], $max=$min;
  my @min_param=();
  my @max_param=();
  for(my $l=0;$l<=$#run_param;$l++){
    $min_param[$l]=$run_begin[$l];
    $max_param[$l]=$run_begin[$l];
  }
  for (my $k=0;$k<=$#step;$k++){
    my @step_tmp = @{$step[$k]};
    for (my $l=0;$l<=$#run_param;$l++){
      my $param_value=$run_begin[$l]+$run_step[$l]*$step_tmp[$l];
      printf GP_DAT "%.5g\t", $param_value;
      if($param_value<$min_param[$l]){$min_param[$l]=$param_value;}
      if($param_value>$max_param[$l]){$max_param[$l]=$param_value;}
    }
    printf GP_DAT "%.5g\n", 1000*$final_cs[$k];
    if($final_cs[$k]>0&&$final_cs[$k]<$min){$min=$final_cs[$k];}
    if($final_cs[$k]>0&&$final_cs[$k]>$max){$max=$final_cs[$k];}
  }
  close(GP_DAT);
  open(GP_INST,">gnuplot_instructions");
  print GP_INST "set term jpeg transparent medium #ffffff #000000\n";
  print GP_INST "set key off\n";
  print GP_INST "set mxtics\n";
  print GP_INST "set mytics\n";
  print GP_INST "set output 'gnuplot.jpg'\n";
  
  if($#run_param==0){
    if($min_param[0]!=0){if($max_param[0]/$min_param[0]>100){print GP_INST "set logscale x\n";}}
    if($min!=0&&$max/$min>100){print GP_INST "set logscale y\n";}
    print GP_INST "set ylabel 'cs (fb)'\n";
    print GP_INST "set xlabel '$run_param[0]'\n";
    print GP_INST "plot 'gnuplot_dat' using 1:2 with lines\n";
  }
  elsif($#run_param==1){
    if($min_param[0]!=0){if($max_param[0]/$min_param[0]>100){print GP_INST "set logscale x\n";}}
    if($min!=0&&$max/$min>100){print GP_INST "set logscale y\n";}
    print GP_INST "set ylabel 'cs (fb)'\n";
    print GP_INST "set xlabel '$run_param[0]'\n";
    print GP_INST "plot 'gnuplot_dat' using 1:(\$2==500?\$3:0) with lines";
    print GP_INST ", 'gnuplot_dat' using 1:(\$2==1000?\$3:0) with lines";
    print GP_INST ", 'gnuplot_dat' using 1:(\$2==1500?\$3:0) with lines\n";
  }
  close(GP_INST);
  if($#run_param<2){  
#system("cat gnuplot_dat");
    system("gnuplot gnuplot_instructions");
    system("cp gnuplot_dat $working_dir/batch_results/$fileName-cs.dat");
    system("cp gnuplot.jpg $working_dir/batch_results/$fileName-cs.jpg");
  }
}


####################################################
#         Make sure VandP is present               #
#         Thanks to Sasha Pukhov                   #
####################################################
sub make_VandP {
  #print "Generating shared VandP.\n";
  my $dir="Processes/$_[0]";
  if(!(-d $dir)){system("mkdir $dir");}
  if(!(-d "$dir/results")){system("mkdir $dir/results");}
  if(!(-d "$dir/models")){system("ln -s $working_dir/models $dir/models");}
  system("cd $dir; $CH_PATH/bin/make_VandP ./models $model_num 5  2>&1 1>  log");
  open(MAKEFILE,">$dir/Makefile");
  print MAKEFILE <<ENDMK;
CALCHEP:=$CH_PATH
WORK:=$working_dir
include \$(CALCHEP)/FlagsForMake
include EXTLIBmake
ifneq (\$(SONAME),)
   soname_VandP := \$(SONAME)../../../VandP.so
else
   soname_VandP :=
endif

ifneq (\$(LHAPDFPATH),)
  EXTLIB := -L\$(LHAPDFPATH) -lLHAPDF \$(EXTLIB)
endif

VandP.so:VandP.c \$(DEPEND) models/extlib$model_num.mdl
\t\$(CC) \$(CFLAGS)  -shared -o VandP.so \$(soname_VandP) VandP.c \$(CALCHEP)/include/VandPgate.c  \$(EXTLIB) \$(CALCHEP)/lib/dynamic_me.a  \$(CALCHEP)/lib/libSLHAplus.a \$(CALCHEP)/lib/ntools.a \$(CALCHEP)/lib/serv.a \$(CALCHEP)/lib/dummy.a  -lm \$(lQuad) -lpthread
ENDMK
  close(MAKEFILE);
#  system("make -C $dir");
#  if(!(-x "$dir/VandP.so")){
#    print "Generation of VandP.so failed.\nQuitting.\n";
#    exit(6);
#  }
  `cd $dir; tar czf VandP.tgz VandP.c EXTLIBmake Makefile funcLocal autoprot.h`;
  #print "Done generating shared VandP.\n";
}

sub compile_VandP {
  #print "Compiling shared VandP.\n";
  my $dir="Processes/$_[0]";
  if(-e "$dir/VandP.so"){
    system("rm -f $dir/VandP.so");
  }
  system("cd $dir;tar xzf VandP.tgz");
  system("make -C $dir  2>&1 1>  $dir/compile.log");
  if(!(-x "$dir/VandP.so")){
    print "Compilation of VandP.so failed.\nPlease have a look at $dir/compile.log.\nQuitting.\n";
    exit(6);
  }
  #print "Done compiling shared VandP.\n";
}

####################################################
#	           Cleanup                         #
####################################################
sub Cleanup {
  my $dir_name="";
  #Cleanup VandP.so stuff
  $dir_name = "$working_dir/Processes/$model_base_dir";
  if(-e "$dir_name/EXTLIBmake"){`rm -f $dir_name/EXTLIBmake`;}
  if(-e "$dir_name/EXTLIBsh"){`rm -f $dir_name/EXTLIBsh`;}
  if(-e "$dir_name/Makefile"){`rm -f $dir_name/Makefile`;}
  if(-e "$dir_name/VandP.c"){`rm -f $dir_name/VandP.c`;}
  if(-e "$dir_name/autoprot.h"){`rm -f $dir_name/autoprot.h`;}
  if(-e "$dir_name/funcLocal"){`rm -f $dir_name/funcLocal`;}
  if(-e "$dir_name/log"){`rm -f $dir_name/log`;}
  if(-e "$dir_name/compile.log"){`rm -f $dir_name/compile.log`;}
  if(-d "$dir_name/results"){`rm -rf $dir_name/results`;}
  if(-d "$dir_name/tmp"){`rm -rf $dir_name/tmp`;}
  #Cleanup the symbolic dirs.
  for (my $j=0;$j<=$#all_subprocesses;$j++){
    $dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]";
    if(-e "$dir_name/calchep"){`rm -f $dir_name/calchep`;}
    if(-e "$dir_name/job_script"){`rm -f $dir_name/job_script`;}
    if(-e "$dir_name/results/autoprot.h"){`rm -f $dir_name/results/autoprot.h`;}
    if(-e "$dir_name/results/EXTLIB"){`rm -f $dir_name/results/EXTLIB`;}
    if(-e "$dir_name/results/EXTLIBmake"){`rm -f $dir_name/results/EXTLIBmake`;}
    if(-e "$dir_name/finished-symbolic"){`rm -f $dir_name/finished-symbolic`;}
    if(-e "$dir_name/job.o"){`rm -f $dir_name/job.o`;}
    if(-e "$dir_name/job.out"){`rm -f $dir_name/job.out`;}
    if(-d "$dir_name/tmp"){`rm -rf $dir_name/tmp`;}
    if(-e "$dir_name/results/proclib_0.a"){`rm -f $dir_name/results/*.a`;}
    if(-d "$dir_name/models"){`rm $dir_name/models`;}
    if(-d "$dir_name/bin"){`rm $dir_name/bin`;}
  }
  $dir_name = "$working_dir/Processes/$model_dir/w";
  if(-e "$dir_name/calchep"){`rm -f $dir_name/calchep`;}
  if(-e "$dir_name/job_script"){`rm -f $dir_name/job_script`;}
  if(-e "$dir_name/results/EXTLIBmake"){`rm -f $dir_name/results/EXTLIBmake`;}
  if(-e "$dir_name/finished-symbolic"){`rm -f $dir_name/finished-symbolic`;}
  if(-e "$dir_name/job.o"){`rm -f $dir_name/job.o`;}
  if(-e "$dir_name/job.out"){`rm -f $dir_name/job.out`;}
  if(-d "$dir_name/tmp"){`rm -rf $dir_name/tmp`;}
  if(-d "$dir_name/models"){`rm $dir_name/models`;}
  if(-d "$dir_name/bin"){`rm $dir_name/bin`;}
  
  #Next cleanup the numerical dirs.
  #No scans
  if ($#step<0){
    for (my $j=0;$j<=$#all_subprocesses;$j++){
      $dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]";
      if(-d "$dir_name/single"){`rm -rf $dir_name/single`;}
    }
    $dir_name = "$working_dir/Processes/$model_dir/w";
      if(-d "$dir_name/single"){`rm -rf $dir_name/single`;}
  }
  #Scans
  else{
    for (my $k=0;$k<=$#step;$k++){
      @step_tmp = @{$step[$k]};
      $subdir_name = "";
      for (my $l=0;$l<=$#run_param;$l++){
	$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
			       $run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
      }		
      for (my $j=0;$j<=$#all_subprocesses;$j++){
	$dir_name = "$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name";
	if(-d "$dir_name"){`rm -rf $dir_name`;}
      }
      $dir_name = "$working_dir/Processes/$model_dir/w/$subdir_name";
      if(-d "$dir_name"){`rm -rf $dir_name`;}
    }
  }
  #Finally the batch_results/tmp dir.
  if(-d "$working_dir/batch_results/tmp"){`rm -rf $working_dir/batch_results/tmp`;}
}


####################################################
#		Catch Kill Signal                  #
####################################################
sub Handler {
  print "\nCaught kill -2 (Ctrl-c) signal.\n";
  kill_all_jobs(5);
}


####################################################
#                  Kill all jobs                   #
####################################################
sub kill_all_jobs {
  print "Killing all jobs and quitting.\n";
  if($#step<0){
    for(my $j=0;$j<=$#all_subprocesses;$j++){
      if($end_times[$j]==0&&$begin_times[$j]!=0){
	if($par_meth =~ /[Pp][Bb][Ss]/){`qdel $pids[$j]`;}
	elsif($par_meth =~ /[Ll][Ss][Ff]/){`bkill $pids[$j]`;}
	elsif($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){`scancel $pids[$j]`;}
	else{`pkill -9 $pids[$j]`;}
      }
    }  
  }
  else{
    for (my $k=0;$k<=$#step;$k++){
      for(my $j=0;$j<=$#all_subprocesses;$j++){
	if($end_times[$j][$k]==0&&$begin_times[$j][$k]!=0){
	  if($par_meth =~ /[Pp][Bb][Ss]/){`qdel $pids[$j][$k]`;}
	  elsif($par_meth =~ /[Ll][Ss][Ff]/){`bkill $pids[$j][$k]`;}
	  elsif($par_meth =~ /[Ss][Ll][Uu][Rr][Mm]/){`scancel $pids[$j][$k]`;}
	  else{`pkill -9 $pids[$j][$k]`;}
	}
      }  
    }
  }
  #1 - symbolic jobs
  #2 - width symbolic job
  #3 - cross section calculation
  #4 - event generation
  #5 - kill signal caught
  #6 - Other error
  #7 - event_mixer
  exit($_[0]);
}


####################################################
#            Num of procs not in lib               #
####################################################
sub num_not_in_lib {
	my $result=0;
	for (my $j=0;$j<=$#all_subproc_in_lib;$j++){
		if ($all_subproc_in_lib[$j]==0){$result++;}
	}
	if($widths_in_lib==0){$result++;}
	return $result;
}


####################################################
#            Create calchep file                   #
#            Thanks to Sasha Pukhov                #
####################################################
sub create_calchep {
  open(CALCHEP,">$_[0]");
print CALCHEP <<ENDCH;
#!/bin/bash
LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$LHAPDFPATH
CALCHEP=$CH_PATH
export CALCHEP
WORK=`pwd`
export WORK
. \$CALCHEP/FlagsForSh

\$CALCHEP/bin/s_calchep \$*
if(test \$? -ne 22) then echo error in C-code generation; exit 1 ;fi
\$CALCHEP/bin/s_calchep -blind "[{{[{0" 
if(test -x results/n_calchep) then 
   echo n_calchep is created
   exit 0
else 
   echo error in n_calchep linking
    exit 3 
fi   

ENDCH
  close(CALCHEP);
  system("chmod u+x $_[0]");
}

sub create_calchep_old {
	open(CALCHEP,">$_[0]");
	print CALCHEP ":\nCALCHEP=$CH_PATH\n";
	print CALCHEP <<ENDCH;
export CALCHEP

. \$CALCHEP/FlagsForSh

while :
do 
  \$CALCHEP/bin/s_calchep \$*
  err=\$?
  case \$err in 
     0) exit;; 
    20) ;;
    22)
         \$CALCHEP/bin/s_calchep -blind "[{{[{0" 
         err=\$?
         if(test \$err -eq 0) then
           echo n_calchep is created
         else 
           echo n_calchep is not created. 
         fi 
         break;;
     *) echo CalcHEP has finished with error code \$err
      break 
  esac 
done 	
ENDCH
	close(CALCHEP);
	system("chmod u+x $_[0]");
}

################################################################
#PBS specific job script                                       #
################################################################
sub write_PBS_info { 
  if(length($que)>0){print JOB_FILE "#PBS -q $que\n";}
  
  #Turn walltime into string with minutes.
  my $wall_hrs=int($walltime);
  my $wall_mins=int((60*$walltime)%60);
  my $PBSwalltime=sprintf("%i:%02i:00",$wall_hrs,$wall_mins);

  if($walltime>0&&$memory>0){print JOB_FILE "#PBS -l walltime=$PBSwalltime -l mem=${memory}gb\n";}
  elsif($walltime>0){print JOB_FILE "#PBS -l walltime=$PBSwalltime\n";}
  elsif($memory>0){print JOB_FILE "#PBS -l mem=${memory}gb\n";}
  my $job_name = $_[0];
  $job_name =~ s/'//g;#'
  if($_[2]>0){print JOB_FILE "#PBS -l nodes=1:ppn=$max_ppn\n";}
  print JOB_FILE "#PBS -N $_[0]\n";
  print JOB_FILE "#PBS -o $_[1]\n";
  print JOB_FILE "#PBS	-j oe\n";
  #print JOB_FILE "#PBS -e cs.e\n\n";
  if($email =~ /@/){
    print JOB_FILE "#PBS	-m a\n";
    print JOB_FILE "#PBS -M $email\n";
  }
  print JOB_FILE "#PBS -V\n";
  print JOB_FILE "\n";
}

################################################################
#LSF specific job script                                       #
################################################################
sub write_LSF_info { 
  if(length($que)>0){print JOB_FILE "#BSUB -q $que\n";}
  if($LSFproject ne ""){print JOB_FILE "#BSUB -P $LSFproject\n";}
  
  #Turn walltime into string with minutes.
  my $wall_hrs=int($walltime);
  my $wall_mins=int((60*$walltime)%60);
  my $LSFwalltime=sprintf("%i:%02i",$wall_hrs,$wall_mins);
  if($walltime>0){print JOB_FILE "#BSUB -c $LSFwalltime\n";}

  my $LSFmem=1000*$memory;
  if($memory>0){print JOB_FILE "#BSUB -R \"mem>$LSFmem\"\n";}
  my $job_name = $_[0];
  $job_name =~ s/'//g;#'
  print JOB_FILE "#BSUB -J $_[0]\n";
  print JOB_FILE "#BSUB -o $_[1]\n";
  if($email =~ /@/){print JOB_FILE "#BSUB -u $email\n";}
  print JOB_FILE "#BSUB -V\n";
  print JOB_FILE "\n";
}


################################################################
#SLURM specific job script                                     #
################################################################
#https://computing.llnl.gov/linux/slurm/quickstart.html
#http://manpages.ubuntu.com/manpages/jaunty/man1/sbatch.1.html
sub write_SLURM_info { 
  #if(length($que)>0){print JOB_FILE "#PBS -q $que\n";} #I don't know how to choose a specific queue in SLURM yet.
  
  #Turn walltime into string with minutes.
  my $wall_hrs=int($walltime);
  my $wall_mins=int((60*$walltime)%60);
  my $PBSwalltime=sprintf("%i:%02i:00",$wall_hrs,$wall_mins);
  if($walltime>0){print JOB_FILE "#SBATCH --time=$PBSwalltime\n";}

  if($memory>0){print JOB_FILE "#SBATCH --mem=${memory}gb\n";}
  my $job_name = $_[0];
  $job_name =~ s/'//g;#'
  print JOB_FILE "#SBATCH --job-name=$_[0]\n";
  print JOB_FILE "#SBATCH --output=$_[1]\n";
  print JOB_FILE "#SBATCH --error=$_[1]\n";
  #print JOB_FILE "#SBATCH	-j oe\n";
  #print JOB_FILE "#SBATCH -e cs.e\n\n";# I don't know how to have SLURM put error in the same file.
  if($email =~ /@/){
    print JOB_FILE "#SBATCH --mail-type=FAIL\n";
    print JOB_FILE "#SBATCH --mail-user=$email\n";
  }
  print JOB_FILE "\n";
}


################################################################
#Update the session.dat files                                  #
################################################################
sub zero_nSess {
  my $dir_name = $_[0];
  system("mv $dir_name/session.dat $dir_name/session.dat-cs");
  open(SESSION_FILE,"$dir_name/session.dat-cs");
  open(NEW_SESSION_FILE, ">$dir_name/session.dat");
 SESSION_LINE: while (my $line = <SESSION_FILE>){
    if($line =~ /#Vegas_calls/){$line ="#Vegas_calls ${nCalls1}x0 ${nCalls2}x0\n";}
    print NEW_SESSION_FILE $line;	
  }
  close(NEW_SESSION_FILE);
  close(SESSION_FILE);
}
sub update_session {
	my $dir_name = $_[0];
	#print "$working_dir/Processes/$dir_name/results/\n";
	#system("pwd");
	#system("./n_calchep -blind \'\\8a\'");
	system("mv $dir_name/session.dat $dir_name/session.dat-old");
	open(SESSION_FILE,"$dir_name/session.dat-old");
	open(NEW_SESSION_FILE, ">$dir_name/session.dat");
	my $init_section=0;
	my $param_section=0;
	my $BW_section=0;
	my $cuts_section=0;
	my $kinematics_section=0;
	my $reg_section=0;
	my $dists_section=0;
	my $qcdscales_section=0;
	my $composite_section=0;
	SESSION_LINE: while (my $line = <SESSION_FILE>){
		if    ($line =~ /#Initial_state/){$init_section=1;}
		elsif ($line =~ /Physical_Parameters/){$param_section=1;$init_section=0;}
		elsif ($line =~ /----/){$param_section=0;}
		elsif ($line =~ /#Breit-Wigner/){$BW_section=1;}
		elsif ($line =~ /#VVdecays/){$BW_section=0;}
		elsif ($line =~ /#Kinematical_scheme/){$kinematics_section=1;$BW_section=0;}
		elsif ($line =~ /#Cuts/){$cuts_section=1;$kinematics_section=0;}
		elsif ($line =~ /#Regularization/){$reg_section=1;}
		elsif ($line =~ /#Distributions/){$dists_section=1;$cuts_section=0;$reg_section=0;$kinematics_section=0;}
		elsif ($line =~ /#QCDscales/){$qcdscales_section=1;}
		elsif ($line =~ /#Vegas/){$qcdscales_section=0;}
		elsif ($line =~ /#Composites/){$composite_section=1;$qcdscales_section=0;}
		elsif ($line =~ /========/){$dists_section=0;$cuts_section=0;$reg_section=0;$composite_section=0;}
		
		if ($init_section==1){
			printf NEW_SESSION_FILE "#Initial_state  inP1=%.6E  inP2=%.6E\n",
				$p1,$p2;
			printf NEW_SESSION_FILE " Polarizations= { %.6E  %.6E }\n", $pol1, $pol2;
			printf NEW_SESSION_FILE "  StrFun1=%s\n", $pdf1_name;
			printf NEW_SESSION_FILE "  StrFun2=%s\n\n", $pdf2_name;
			$init_section=2;
		}
		if ($param_section==1){
			print NEW_SESSION_FILE "#Physical_Parameters \n";
			for(my $j=0;$j<=$#vars_names;$j++){
				printf NEW_SESSION_FILE "%10s = %.15E\n",$vars_names[$j], $vars_values[$j];
			}
			$param_section=2;
		}
		if ($BW_section==1){
		  print NEW_SESSION_FILE "#Breit-Wigner BW range    $BWrange\n";
		  print NEW_SESSION_FILE "t-channel widths $TchannelWidths\n";
		  print NEW_SESSION_FILE "GI trick in s-  $GIschannel\n";
		  print NEW_SESSION_FILE "GI trick in t-  $GItchannel\n";
		  $BW_section=2;
		}
		if ($kinematics_section==1){
			#First find out if the user defined kinematics for this process.
			#If not, set kinematics section to 0.
			#Otherwise, print the kinematics.
			my $kin_defined=0;
			for(my $j=0;$j<=$#kinematics;$j++){
				if ($kin_Number[$j]==$subproc_which_proc[$_[1]]||$kin_Number[$j]==-1){
					$kin_defined=1;
				}
			}
			if ($kin_defined==0){$kinematics_section=0;}
			else {
				$kinematics_section=2;
				print NEW_SESSION_FILE "#Kinematical_scheme\n";
				for(my $j=0;$j<=$#kinematics;$j++){
					if ($kin_Number[$j]==$subproc_which_proc[$_[1]]||$kin_Number[$j]==-1){
						my $new_kinematics="";
						my @kin_pieces = split(/->/,$kinematics[$j]);
						if ($kin_pieces[0] eq "12"){$new_kinematics="12 -> ";}
						else {$new_kinematics=renumber_parts($kin_pieces[0],$_[1])." -> ";}
						my @kin2_pieces = split(/,/,$kin_pieces[1]);
						foreach my $kin2_piece (@kin2_pieces){
							$new_kinematics=$new_kinematics.renumber_parts($kin2_piece,$_[1])." , ";
						}
						$new_kinematics = substr($new_kinematics,0,length($new_kinematics)-3);
						print NEW_SESSION_FILE "$new_kinematics\n";
					}
				}
			}
		}
		if ($composite_section==1){
			print NEW_SESSION_FILE "#Composites \n";
			print NEW_SESSION_FILE "*** Table ***\n";
			print NEW_SESSION_FILE " Composites  \n";
			#Determine the length of the fields
			my $len0=0, $len1=0;
			foreach $composite (@partons){
			  my @pieces=split("=",$composite);
			  $len0=( $len0 >= length($pieces[0]) ? $len0 : length($pieces[0]) );
			  $len1=( $len1 >= length($pieces[1]) ? $len1 : length($pieces[1]) );
			  #print "\n$composite\n";
			  #print "length(pieces[0])=".length($pieces[0])."\tlen0=$len0".
			  #  "\tlength(pieces[1])=".length($pieces[1])."\tlen1=$len1\n";
			}
			$len0=( $len0 >= 8 ? $len0 : 8 );
			$len1=( $len1 >= 63 ? $len1 : 63 );
			my $formstring = "%-${len0}s|%-${len1}s\n";
			my $headFormString = "%-${len0}s|%-${len1}s%s\n";
			#print "Final : len0=$len0\tlen1=$len1\n$headFormString\n$formstring\n\n";
			printf NEW_SESSION_FILE $headFormString, "  Name  ","> Comma separated list of particles","<|";
			#print join("\t",@partons)."\n";
			foreach $composite (@partons){
			  my @pieces=split("=",$composite);
			  printf NEW_SESSION_FILE $formstring, $pieces[0],$pieces[1];
			}
			$composite_section=2;
		}
		if ($cuts_section==1){
			print NEW_SESSION_FILE "#Cuts\n";
			print NEW_SESSION_FILE "*** Table ***\n";
			print NEW_SESSION_FILE " Cuts\n";
			print NEW_SESSION_FILE "!|  Parameter  |> Min bound <|> Max bound <|\n";
			for(my $j=0;$j<=$#cut_param;$j++){
				#print "$_[1] : $subproc_which_proc[$_[1]]\n";
				if ($cut_Number[$j]==$subproc_which_proc[$_[1]]||$cut_Number[$j]==-1){
					#my @tmp_cut_param=rename_parts($cut_param[$j],$_[1]);
					my @tmp_cut_param=($cut_param[$j]);
					my $tmp_invert="";
					if($cut_invert[$j] =~ /[Tt][Rr][Uu][Ee]/) {$tmp_invert="!|";}
					else {$tmp_invert=" |";}
					my $tmp_cut_min=update_min_max($cut_min[$j],$_[2]);
					my $tmp_cut_max=update_min_max($cut_max[$j],$_[2]);
					#print "\t$cut_param[$j] -> {".join(",",@tmp_cut_param)."}\n";
					for(my $k=0;$k<=$#tmp_cut_param;$k++){
						printf NEW_SESSION_FILE 
							"%s%-13s|%-13s|%-13s|\n",$tmp_invert,$tmp_cut_param[$k],$tmp_cut_min,$tmp_cut_max;
					}
				}
			}
			$cuts_section=2;
		}
		if ($reg_section==1){
			print NEW_SESSION_FILE "#Regularization\n";
			print NEW_SESSION_FILE "*** Table ***\n";
			print NEW_SESSION_FILE " Regularization\n";
			print NEW_SESSION_FILE " Momentum    |> Mass  <|> Width <| Power|\n";
			for(my $j=0;$j<=$#reg_mom;$j++){
				if ($reg_Number[$j]==$subproc_which_proc[$_[1]]||$reg_Number[$j]==-1){
					printf NEW_SESSION_FILE "%-13s|%-9s|%-9s|%-6s|\n",
						renumber_parts($reg_mom[$j],$_[1]),$reg_mass[$j],$reg_width[$j],$reg_pow[$j];
				}
			}
			$reg_section=2;
		}
		if ($dists_section==1){
			print NEW_SESSION_FILE "#Distributions \n";
			print NEW_SESSION_FILE "*** Table ***\n";
			print NEW_SESSION_FILE "Distributions\n";
			print NEW_SESSION_FILE "Parameter_1|> Min_1  <|> Max_1  <|Parameter_2|> Min_2  <|> Max_2  <|\n";
			for(my $j=0;$j<=$#dist_param;$j++){
				#print "$_[1] : $subproc_which_proc[$_[1]]\n";
				if ($dist_Number[$j]==$subproc_which_proc[$_[1]]||$dist_Number[$j]==-1){
					#my @tmp_dist_param = rename_parts($dist_param[$j],$_[1]);
					my @tmp_dist_param = ($dist_param[$j]);
					my $tmp_dist_min=update_min_max($dist_min[$j],$_[2]);
					my $tmp_dist_max=update_min_max($dist_max[$j],$_[2]);
					#print "\t$dist_param[$j] -> {".join(",",@tmp_dist_param)."}\n";
					for ($k=0;$k<=$#tmp_dist_param;$k++){
						printf NEW_SESSION_FILE 
							"%-11s|%-10s|%-10s|%-11s|%-10s|%-10s|\n",$tmp_dist_param[$k],$tmp_dist_min,$tmp_dist_max,"","","";
					}
				}
			}
			$dists_section=2;
		}
		if ($qcdscales_section==1){
			print NEW_SESSION_FILE "#QCDscales\n";
			my $aScale = "M12";
			for (my $l=0;$l<=$#alphaRenScale;$l++){
			  if ($alphaRenNumber[$l]==$subproc_which_proc[$_[1]]||$alphaRenNumber[$l]==-1){
			    $aScale=renumber_Mparts($alphaRenScale[$l],$_[1]);
			  }
			}
			printf NEW_SESSION_FILE " Renormalization %s\n", $aScale;
						
			$aScale = "M12";
			for (my $l=0;$l<=$#alphaFact1Scale;$l++){
			  if ($alphaFact1Number[$l]==$subproc_which_proc[$_[1]]||$alphaFact1Number[$l]==-1){
			    $aScale=renumber_Mparts($alphaFact1Scale[$l],$_[1]);
			  }
			}
			printf NEW_SESSION_FILE  " Factorization1 %s\n", $aScale;
			$aScale = "Qpdf1";
			for (my $l=0;$l<=$#alphaFact2Scale;$l++){
			  if ($alphaFact2Number[$l]==$subproc_which_proc[$_[1]]||$alphaFact2Number[$l]==-1){
			    $aScale=renumber_Mparts($alphaFact2Scale[$l],$_[1]);
			  }
			}
			printf NEW_SESSION_FILE  " Factorization2  %s\n", $aScale;
			$aScale = "Qren";
			for (my $l=0;$l<=$#alphaShowScale;$l++){
			  if ($alphaShowNumber[$l]==$subproc_which_proc[$_[1]]||$alphaShowNumber[$l]==-1){
			    $aScale=renumber_Mparts($alphaShowScale[$l],$_[1]);
			  }
			}
			printf NEW_SESSION_FILE  " Showering  %s\n", $aScale;
			    

			$qcdscales_section=2;
		}
		if ($init_section==0&&$param_section==0&&$BW_section==0&&$cuts_section==0&& $reg_section==0 && $kinematics_section==0 && $dists_section==0&&$qcdscales_section==0&&$composite_section==0){
			if($line =~ /#Vegas_calls/){$line ="#Vegas_calls ${nCalls1}x${nSess1} ${nCalls2}x${nSess2}\n";}
			if($line =~ /#Parallelization/){$line ="#Parallelization $max_ppn\n";}
			if($line =~ /#Events/){$line = "#Events $subCubes $unWeighted 10000 \n";}
			if($line =~ /#VVdecays/ && ($VVdecay =~ /[Oo][Ff][Ff]/ || $VVdecay =~ /[Ff][Aa][Ll][Ss][Ee]/))
			  {$line = "#VVdecays  0\n";}
			if($line =~ /#SLHAwidth/ && ($SLHAwidths =~ /[Oo][Ff][Ff]/ || $SLHAwidths =~ /[Ff][Aa][Ll][Ss][Ee]/))
			  {$line = "#SLHAwidth  0\n";}
			
			$randTime++;
			my $randSeed = sprintf ("%x",$randTime);
			while (length($randSeed)<12){$randSeed="1".$randSeed;}
			$randSeed=uc($randSeed);
			#print "$randSeed\n";
			$line =~ s/#Random [0-9A-Z]+/#Random $randSeed/;
			
			if ($line =~ /#alphaQCD alphaPDF/){
			  $line =sprintf ("#alphaQCD alphaPDF=%i alpha(MZ)=%.6E NF=%i Order=%i MbMb=%.6E Mtp=%.6E\n",
					  $alphaPDF,$alphaMZ,$alphaNF,$alphaOrder,$alphaMbMb,$alphaMtp);
			}
			print NEW_SESSION_FILE $line;	
		}
	}
	close(SESSION_FILE);
	close(NEW_SESSION_FILE);
	system("cp $dir_name/session.dat $dir_name/session.dat-start");
}


################################################################
#  Renumber cut, distribution, regularization and kinematics   # 
#  according to particle order in current process.             #
################################################################
sub renumber_Mparts {
  my $MtermOn=0;
  my $Mterm="";
  my $StermOn=0;
  my $Sterm="";
  my $TtermOn=0;
  my $Tterm="";
  my $ZtermOn=0;
  my $Zterm="";
 
  my $Rterm="";
  for(my $i=0;$i<length($_[0]);$i++){
    my $cur_symb = substr($_[0],$i,1);
    if($cur_symb =~ /M/){$MtermOn=1;$Mterm=$Mterm.$cur_symb;}
    elsif($MtermOn==1 and $cur_symb =~ /[0-9]/){$Mterm=$Mterm.$cur_symb;}
    elsif($MtermOn==1){
      $Mterm=$Mterm.$cur_symb;
      $Rterm=$Rterm.renumber_parts($Mterm,$_[1]);
      $MtermOn=0;
      $Mterm="";
    }
#<#AB insetion begin ###########    
    elsif($cur_symb =~ /S/){$StermOn=1;$Sterm=$Sterm.$cur_symb;}
    elsif($StermOn==1 and $cur_symb =~ /[0-9]/){$Sterm=$Sterm.$cur_symb;}
    elsif($StermOn==1){
      $Sterm=$Sterm.$cur_symb;
      $Rterm=$Rterm.renumber_parts($Sterm,$_[1]);
      $StermOn=0;
      $Sterm="";
    }
    elsif($cur_symb =~ /T/){$TtermOn=1;$Tterm=$Tterm.$cur_symb;}
    elsif($TtermOn==1 and $cur_symb =~ /[0-9]/){$Tterm=$Tterm.$cur_symb;}
    elsif($TtermOn==1){
      $Tterm=$Tterm.$cur_symb;
      $Rterm=$Rterm.renumber_parts($Tterm,$_[1]);
      $TtermOn=0;
      $Tterm="";
    }
    elsif($cur_symb =~ /Z/){$ZtermOn=1;$Zterm=$Zterm.$cur_symb;}
    elsif($ZtermOn==1 and $cur_symb =~ /[0-9]/){$Zterm=$Zterm.$cur_symb;}
    elsif($ZtermOn==1){
      $Zterm=$Zterm.$cur_symb;
      $Rterm=$Rterm.renumber_parts($Zterm,$_[1]);
      $ZtermOn=0;
      $Zterm="";
    }
#>#AB insetion end ###########
    else {$Rterm=$Rterm.$cur_symb;}
  }
  if(length($Mterm)>0){
    $Mterm=$Mterm.$cur_symb;
    $Rterm=$Rterm.renumber_parts($Mterm,$_[1]);
  }
#<#AB insetion begin ###########    
  if(length($Sterm)>0){
    $Sterm=$Sterm.$cur_symb;
    $Rterm=$Rterm.renumber_parts($Sterm,$_[1]);
  }
  if(length($Tterm)>0){
    $Tterm=$Tterm.$cur_symb;
    $Rterm=$Rterm.renumber_parts($Tterm,$_[1]);
  }
  if(length($Zterm)>0){
    $Zterm=$Zterm.$cur_symb;
    $Rterm=$Rterm.renumber_parts($Zterm,$_[1]);
  }
#>#AB insetion end ###########
  return $Rterm;
}


sub renumber_parts {
	my $new_param_name = "";
	my $proc="";
	my $subproc="";
	if($_[1]<=$#subprocesses){
		$proc=$processes[$subproc_which_proc[$_[1]]];
		$subproc=$subprocesses[$_[1]];
	}
	else{
		$proc=$decays[$decay_subproc_which_decay[$_[1]-$#subprocesses-1]];
		$subproc=$decay_subprocesses[$_[1]-$#subprocesses-1];
	}
	#print "$proc\t$subproc\n";	
	#print "";
	for (my $i=0;$i<length($_[0]);$i++){
		my $cur_num = substr($_[0],$i,1);
		my $part_num=0;
		if ($cur_num =~ /M/){$new_param_name=$new_param_name."M";$part_num=1;}
		elsif ($cur_num =~ /[1-2]/){$new_param_name=$new_param_name.$cur_num;}
		#elsif ($cur_num =~ /[a-zA-Z\(\),\/]/){$new_param_name=$new_param_name.$cur_num;$part_num=0;}
		elsif ($cur_num =~ /[^\d]/){$new_param_name=$new_param_name.$cur_num;$part_num=0;}
		elsif ($cur_num =~ /[0-9]/&&$part_num==1){$new_param_name=$new_param_name.$cur_num;}
		elsif ($cur_num =~ /[0-9]/&&$part_num==0) {
			#Determine what particle this is.
			my @pieces1 = split("->",$proc);
			my @pieces = split(",",@pieces1[0]);
			push(@pieces,split(",",@pieces1[1]));
			my $cmpst_tmp=$pieces[$cur_num-1];
			my $cmpst_num_tmp=1;
			my $start=2;if($_[1]>$#subprocesses){$start=1;}
			for (my $j=$start;$j<$cur_num-1;$j++){
				if ($cmpst_tmp eq $pieces[$j]){$cmpst_num_tmp++;}
			}
			#Determine what particles it corresponds with if composite.
			my @partons_tmp=();
			#print "$cmpst_tmp\t";
			for (my $j=0;$j<=$#cmpst_names;$j++){
				if ($cmpst_tmp eq $cmpst_names[$j]){
					@pieces1 = split("=",$partons[$j]);
					@pieces = split(",",$pieces1[1]);
					push(@partons_tmp,@pieces);
				}		
			}
			if ($#partons_tmp<0){push(@partons_tmp,$cmpst_tmp);}
			#print "\t".join(",",@partons_tmp)."\t";
			#Determine the position of the particle in the subprocess.
			my $cur_cmpst_num=1;
			@pieces1 = split("->",$subproc);
			@pieces = split(",",@pieces1[0]);
			push(@pieces,split(",",@pieces1[1]));
			for (my $j=$start;$j<=$#pieces;$j++){
				#print "\n$pieces[$j]\n\t";
				for (my $k=0;$k<=$#partons_tmp;$k++){
					#print "$partons_tmp[$k]\t";
					if ($pieces[$j] eq $partons_tmp[$k]){
				  	        if ($cur_cmpst_num == $cmpst_num_tmp){$new_param_name=$new_param_name.($j+1);$cur_cmpst_num++;}#print "$cur_num -> ".($j+1)."\n";}
						else {$cur_cmpst_num++;}
					}
				}
			}		
			
		}
	}
	#print "$subprocesses[$_[1]]\n";
	#print "\t$_[0] -> $new_param_name\n";
	if (defined $options{r}){return $_[0];}
	else {return $new_param_name;}
}


################################################################
#  Rename cut and distribution names                           # 
#  according to particles in current process.                  #
#  Superseded by composites in gui.                            #
################################################################
sub rename_parts_not_used_anymore {
	my @new_names=();
	if (defined $options{n}){
		push(@new_names,renumber_parts($_[0]));
		return @new_names;
	}
	elsif ($_[0] =~ /^U/){#User defined.
		return $_[0];
	}
	
	my @begin = split(/\(/,$_[0]);
	my @end = split(/\)/,$begin[1]);
	my @parts = split(",",$end[0]);
	my @f_pieces = ();
	my %count = ();
	
	#print "";
	for (my $i=0;$i<=$#parts;$i++){
		my @i_pieces = ();
		my $cmpst_tmp=$parts[$i];
		#Determine what particles it corresponds with if composite.
		my @partons_tmp=();
		#print "\nparts[$i]=$cmpst_tmp : \t";
		for (my $j=0;$j<=$#cmpst_names;$j++){
			if ($cmpst_tmp eq $cmpst_names[$j]){
				@pieces1 = split("=",$partons[$j]);
				@pieces = split(",",$pieces1[1]);
				push(@partons_tmp,@pieces);
			}		
		}
		if ($#partons_tmp<0){push(@partons_tmp,$cmpst_tmp);}
		#print "\t".join(",",@partons_tmp)."\t";
		
		#Determine the particles in the subprocess.
		@pieces1 = split("->",$subprocesses[$_[1]]);
		@pieces = split(",",@pieces1[1]);
		for (my $j=0;$j<=$#pieces;$j++){
			#Count the number of each.
			#$count{$pieces[$j]}++;
			#print "\npieces[$j]=$pieces[$j]\n\t";
			for (my $k=0;$k<=$#partons_tmp;$k++){
				#print "parton_tmp[$k]=$partons_tmp[$k]\t";
				if ($pieces[$j] eq $partons_tmp[$k]){
					push(@i_pieces,$pieces[$j]);
				}
			}
		}		
		push(@f_pieces,join(",",@i_pieces));
		
	}
	#print "\tN(f_pieces)=".($#f_pieces+1).": f_pieces=".join(",",@f_pieces)."\n";
	
	#Count the number of each particle.
	@pieces1 = split("->",$subprocesses[$_[1]]);
	@pieces = split(",",@pieces1[1]);
	for (my $j=0;$j<=$#pieces;$j++){
		$count{$pieces[$j]}++;
	}
				
	#Combine the particles in all nonduplicate ways.
	#1 parameter
	if($#f_pieces==0){
		my @parts1=split(",",$f_pieces[0]);
		for(my $i=0;$i<=$#parts1;$i++){
			my %count_tmp = ();
			$count_tmp{$parts1[$i]}++;
			if($count{$parts1[$i]}>=$count_tmp{$parts1[$i]}){
				push(@new_names,$begin[0]."(".$parts1[$i].")");
			}
		}		
	}
	#2 parameters
	elsif($#f_pieces==1){
		my @parts1=split(",",$f_pieces[0]);#print "parts1=".join(",",@parts1)."\n";
		my @parts2=split(",",$f_pieces[1]);#print "parts2=".join(",",@parts2)."\n";
		for(my $i=0;$i<=$#parts1;$i++){
			for(my $j=0;$j<=$#parts2;$j++){
				my %count_tmp = ();
				$count_tmp{$parts1[$i]}++;
				$count_tmp{$parts2[$j]}++;
				#if(($parts1[$i] ne $parts2[$j]) || $count{$parts1[$i]}){
				if(	$count{$parts1[$i]}>=$count_tmp{$parts1[$i]} && 
						$count{$parts2[$j]}>=$count_tmp{$parts2[$j]} 
						){
					my @tmp_parts=sort($parts1[$i],$parts2[$j]);
					if($begin[0] eq "A" or $begin[0] eq "C" or $begin[0] eq "P"){
					  @tmp_parts=($parts1[$i]);
					  push(@tmp_parts,sort($parts2[$j]));
					}
					push(@new_names,$begin[0]."(".join(",",@tmp_parts).")");
				}
			}
		}		
	}
	#3 parameters
	elsif($#f_pieces==2){
		my @parts1=split(",",$f_pieces[0]);
		my @parts2=split(",",$f_pieces[1]);
		my @parts3=split(",",$f_pieces[2]);
		for(my $i=0;$i<=$#parts1;$i++){
			for(my $j=0;$j<=$#parts2;$j++){
				for(my $k=0;$k<=$#parts3;$k++){
					my %count_tmp = ();
					$count_tmp{$parts1[$i]}++;
					$count_tmp{$parts2[$j]}++;
					$count_tmp{$parts3[$k]}++;
					#print "$parts1[$i] : $count{$parts1[$i]} : $count_tmp{$parts1[$i]}\n";
					#print "$parts2[$j] : $count{$parts2[$j]} : $count_tmp{$parts2[$j]}\n";
					#print "$parts3[$k] : $count{$parts3[$k]} : $count_tmp{$parts3[$k]}\n";
					#if($parts1[$i] ne $parts2[$j]&& $parts1[$i] ne $parts3[$k]&& $parts2[$j] ne $parts3[$k]){
					if(	$count{$parts1[$i]}>=$count_tmp{$parts1[$i]} && 
							$count{$parts2[$j]}>=$count_tmp{$parts2[$j]} &&
							$count{$parts3[$k]}>=$count_tmp{$parts3[$k]} 
							){
						my @tmp_parts=sort($parts1[$i],$parts2[$j],$parts3[$k]);
						if($begin[0] eq "A" or $begin[0] eq "C" or $begin[0] eq "P"){
						  @tmp_parts=($parts1[$i]);
						  push(@tmp_parts,sort($parts2[$j],$parts3[$k]));
						}
						push(@new_names,$begin[0]."(".join(",",@tmp_parts).")");
					}
				}
			}
		}		
	}
	#4 parameters
	elsif($#f_pieces==3){
		my @parts1=split(",",$f_pieces[0]);
		my @parts2=split(",",$f_pieces[1]);
		my @parts3=split(",",$f_pieces[2]);
		my @parts4=split(",",$f_pieces[3]);
		for(my $i=0;$i<=$#parts1;$i++){
			for(my $j=0;$j<=$#parts2;$j++){
				for(my $k=0;$k<=$#parts3;$k++){
					for(my $l=0;$l<=$#parts4;$l++){
						my %count_tmp = ();
						$count_tmp{$parts1[$i]}++;
						$count_tmp{$parts2[$j]}++;
						$count_tmp{$parts3[$k]}++;
						$count_tmp{$parts4[$l]}++;
						#if($parts1[$i] ne $parts2[$j]&& $parts1[$i] ne $parts3[$k]&& $parts1[$i] ne $parts4[$l]&&
						if(	$count{$parts1[$i]}>=$count_tmp{$parts1[$i]} && 
								$count{$parts2[$j]}>=$count_tmp{$parts2[$j]} &&
								$count{$parts3[$k]}>=$count_tmp{$parts3[$k]} &&
								$count{$parts4[$l]}>=$count_tmp{$parts4[$l]} 
								){
							my @tmp_parts=sort($parts1[$i],$parts2[$j],$parts3[$k],$parts4[$l]);
							if($begin[0] eq "A" or $begin[0] eq "C" or $begin[0] eq "P"){
							  @tmp_parts=($parts1[$i]);
							  push(@tmp_parts,sort($parts2[$j],$parts3[$k],$parts4[$l]));
							}
							push(@new_names,$begin[0]."(".join(",",@tmp_parts).")");
						}
					}
				}
			}
		}		
	}
	if($#f_pieces>3){
		print "The number of arguments in $_[0] is more than I can currently handle.\n";
		exit();
	}
	
	#Remove duplicates
	my @unique = ();
   my %Seen   = ();
   foreach my $elem ( @new_names ){
   	next if $Seen{ $elem }++;
   	push @unique, $elem;
   }

	
	#print "\t$_[0] -> {".join(",",@unique)."}\n";
	
	return @unique;
}


################################################################
#  Update cut and distribution min and max                     # 
#  according to parameters being run over.                     #
################################################################
sub update_min_max {
	my $new_value=$_[0];
	#Determine run parameter values.
	my @step_tmp = @{$step[$_[1]]};
	for (my $l=0;$l<=$#run_param;$l++){
		my $run_value = $run_begin[$l]+$run_step[$l]*$step_tmp[$l];
		$new_value =~ s/${run_param[$l]}/($run_value)/g;
		#printf "%s -> %s\n", $_[0], $new_value; 
	}
	
	return $new_value;
}

################################################################
#Update the decay session.dat files                            #
################################################################
sub update_decay_session {
	my $dir_name = $_[0];
	#print "$working_dir/Processes/$dir_name/results/\n";
	#system("pwd");
	#system("./n_calchep -blind \'[[[[[[[[[[{{10000{\\8a\'");
	system("mv $dir_name/session.dat $dir_name/session.dat-old");
	open(SESSION_FILE,"$dir_name/session.dat-old");
	open(NEW_SESSION_FILE, ">$dir_name/session.dat");
	my $param_section=0;
	my $kinematics_section=0;
	my $reg_section=0;
	my $cuts_section=0;
	SESSION_LINE: while (my $line = <SESSION_FILE>){
		if ($line =~ /Physical_Parameters/){$param_section=1;}
		elsif ($line =~ /----/){$param_section=0;}
		elsif ($line =~ /#Kinematical_scheme/){$kinematics_section=1;}
		elsif ($line =~ /#Cuts/){$kinematics_section=0;$cuts_section=1;}
		elsif ($line =~ /#Regularization/){$reg_section=1;}
		elsif ($line =~ /========/){$reg_section=0;$cuts_section=0;}
		
		if ($param_section==1){
			print NEW_SESSION_FILE "#Physical_Parameters \n";
			for(my $j=0;$j<=$#vars_names;$j++){
				printf NEW_SESSION_FILE "%10s = %.15E\n",$vars_names[$j], $vars_values[$j];
			}
			$param_section=2;
		}
		#Kinematics
		if ($kinematics_section==1){
			#First find out if the user defined kinematics for this process.
			#If not, set kinematics section to 0.
			#Otherwise, print the kinematics.
			my $kin_defined=0;
			for(my $j=0;$j<=$#decay_kinematics;$j++){
				if ($decay_kin_Number[$j]==$decay_subproc_which_decay[$_[1]]||$decay_kin_Number[$j]==-1){
					$kin_defined=1;
				}
			}
			if ($kin_defined==0 || $_[1]==-1){$kinematics_section=0;}
			else {
				$kinematics_section=2;
				print NEW_SESSION_FILE "#Kinematical_scheme\n";
				for(my $j=0;$j<=$#decay_kinematics;$j++){
					if ($decay_kin_Number[$j]==$decay_subproc_which_decay[$_[1]]||$decay_kin_Number[$j]==-1){
						my $new_kinematics="";
						my @kin_pieces = split(/->/,$decay_kinematics[$j]);
						if ($kin_pieces[0] eq "1"){$new_kinematics="1 -> ";}
						else {$new_kinematics=renumber_parts($kin_pieces[0],$_[1]+$#subprocesses+1)." -> ";}
						my @kin2_pieces = split(/,/,$kin_pieces[1]);
						foreach my $kin2_piece (@kin2_pieces){
							$new_kinematics=$new_kinematics.renumber_parts($kin2_piece,$_[1]+$#subprocesses+1)." , ";
						}
						$new_kinematics = substr($new_kinematics,0,length($new_kinematics)-3);
						print NEW_SESSION_FILE "$new_kinematics\n";
					}
				}
			}
		}
		if ($reg_section==1){
			print NEW_SESSION_FILE "#Regularization\n";
			print NEW_SESSION_FILE "*** Table ***\n";
			print NEW_SESSION_FILE " Regularization\n";
			print NEW_SESSION_FILE " Momentum    |> Mass  <|> Width <| Power|\n";
			for(my $j=0;$j<=$#decay_reg_mom;$j++){
				if ($decay_reg_Number[$j]==$decay_subproc_which_proc[$_[1]]||$decay_reg_Number[$j]==-1){
					printf NEW_SESSION_FILE "%-13s|%-9s|%-9s|%-6s|\n",
						renumber_parts($decay_reg_mom[$j],$_[1]),$decay_reg_mass[$j],$decay_reg_width[$j],$decay_reg_pow[$j];
				}
			}
			$reg_section=2;
		}
		if ($cuts_section==1){
		  print NEW_SESSION_FILE "#Cuts\n";
		  print NEW_SESSION_FILE "*** Table ***\n";
		  print NEW_SESSION_FILE " Cuts\n";
		  print NEW_SESSION_FILE "!|  Parameter  |> Min bound <|> Max bound <|\n";
		  $cuts_section=2;
		}
		#$param_section=0;
		if ($param_section==0 && $kinematics_section==0 && $reg_section==0 && $cuts_section==0){
			if($line =~ /#Vegas_calls/){$line = "#Vegas_calls ${nCalls1}x${nSess1} ${nCalls2}x${nSess2}\n";}
			if($line =~ /#Parallelization:/){$line ="#Parallelization: 0\n";}
			if($line =~ /#Events/){$line = "#Events $subCubes $unWeighted 10000\n";}
			if($line =~ /#VVdecays/ && ($VVdecay =~ /[Oo][Ff][Ff]/ || $VVdecay =~ /[Ff][Aa][Ll][Ss][Ee]/))
			  {$line = "#VVdecays  0\n";}
			if($line =~ /#SLHAwidth/ && ($SLHAwidths =~ /[Oo][Ff][Ff]/ || $SLHAwidths =~ /[Ff][Aa][Ll][Ss][Ee]/))
			  {$line = "#SLHAwidth  0\n";}

			$randTime++;
			my $randSeed = sprintf ("%x",$randTime);
			while (length($randSeed)<12){$randSeed="1".$randSeed;}
			$randSeed=uc($randSeed);
			#print "$randSeed\n";
			$line =~ s/#Random [0-9A-Z]+/#Random $randSeed/;
			
			print NEW_SESSION_FILE $line;
		}
	}
	close(SESSION_FILE);
	close(NEW_SESSION_FILE);
	system("cp $dir_name/session.dat $dir_name/session.dat-start");
	
}



####################################################
#                                                  #
#           Combine Events                         #
#                                                  #
####################################################
sub combine_events {
	my @contents=`ls $working_dir/batch_results/tmp`;
	if ($#contents>=0){system("rm -f $working_dir/batch_results/tmp/*");}
	my $subdir_name = "";
	for (my $j=0;$j<=$#all_subprocesses;$j++){
		my $dir_name="$working_dir/Processes/$model_dir/$all_subproc_dir[$j]";
		$subdir_name="";
		if ($#step<0){$subdir_name="single";}
		else{
		  #Before combining events, update the numerical values in @vars_values.
		  for(my $l=0;$l<=$#vars_names;$l++){
		    for(my $m=0;$m<=$#param_names;$m++){
		      if($vars_names[$l] eq $param_names[$m]){$vars_values[$l] = $param_values[$m];}
		    }
		    for(my $m=0;$m<=$#run_param;$m++){
		      my $run_value = $run_begin[$m]+$run_step[$m]*$step_tmp[$m];
		      $vars_values[$l] =~ s/${run_param[$m]}/($run_value)/g;
		      if($vars_names[$l] eq $run_param[$m]){$vars_values[$l] = $run_value;}
		    }
		    $vars_values[$l] = eval($vars_values[$l]);
		  }
			my @step_tmp = @{$step[$_[0]]};
			for (my $l=0;$l<=$#run_param;$l++){
				$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
					$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			#	for (my $k=0;$k<=$#vars_names;$k++){
			#		if ($vars_names[$k] eq $run_param[$l]){$vars_values[$k]=$run_begin[$l]+$run_step[$l]*$step_tmp[$l];}
			#	}
			}
		}
		$dir_name=$dir_name."/$subdir_name";
		if(-e "$dir_name/events_1.txt"){
		  $systemString = "ln -s $dir_name/events_1.txt 	$working_dir/batch_results/tmp/events_$j.txt";
		  system($systemString);
		}
	}
	#$systemString = "ln -s $dir_name/../results/qNumbers 	$working_dir/batch_results/tmp/qNumbers";
	#system($systemString);
	#Now for the widths
	my $dir_name="$working_dir/Processes/$model_dir/$widths_dir";
	$subdir_name="";
	if ($#step<0){$subdir_name="single";}
	else{
	  #Before combining events, update the numerical values in @vars_values.
	  for(my $l=0;$l<=$#vars_names;$l++){
	    for(my $m=0;$m<=$#param_names;$m++){
	      if($vars_names[$l] eq $param_names[$m]){$vars_values[$l] = $param_values[$m];}
	    }
	    for(my $m=0;$m<=$#run_param;$m++){
	      my $run_value = $run_begin[$m]+$run_step[$m]*$step_tmp[$m];
	      $vars_values[$l] =~ s/${run_param[$m]}/($run_value)/g;
	      if($vars_names[$l] eq $run_param[$m]){$vars_values[$l] = $run_value;}
	    }
	    $vars_values[$l] = eval($vars_values[$l]);
	  }
		my @step_tmp = @{$step[$_[0]]};
		for (my $l=0;$l<=$#run_param;$l++){
			$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
				$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			#for (my $k=0;$k<=$#vars_names;$k++){
			#	if ($vars_names[$k] eq $run_param[$l]){$vars_values[$k]=$run_begin[$l]+$run_step[$l]*$step_tmp[$l];}
			#}
		}
	}
	$dir_name=$dir_name."/$subdir_name";
	$systemString = "ln -s $dir_name/decaySLHA_1.txt 	$working_dir/batch_results/tmp/decaySLHA.txt";
	system($systemString);
	
	#Print the batch file details.
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
	if ($fileName eq ""){
		$event_filenames[$_[0]] = sprintf "%4d-%02d-%02d-%s",$year+1900,$mon+1,$mday,$subdir_name;
	}
	else {
		$event_filenames[$_[0]] = sprintf "%s-%s",$fileName,$subdir_name;
	}
	print_run_details($event_filenames[$_[0]]);
	
	#Run event_mixer
	chdir("$working_dir/batch_results/tmp/");
        #print($n_events); 
	my $command=sprintf "nice -n $nice_level $CH_PATH/bin/event_mixer %G $n_events .  2>&1 1>  event_mixer.o", $max_lumi;
	#$command="nice -n $nice_level $CH_PATH/bin/event_mixer $n_events .  2>&1 1>  event_mixer.o";
	#print "$command\n";
	system($command);
	
	#Count the number of lines
	#$nevents_final[$_[0]] =`wc -l $working_dir/batch_results/tmp/event_mixer.out`;
	#$nevents_final[$_[0]] =~ s/([0-9]*).*/$1/;
	#$nevents_final[$_[0]] = int($nevents_final[$_[0]])-1;
	$nevents_final[$_[0]] = $n_events;
	
	#Read the final cs.
	open(MIXER_FILE,"$working_dir/batch_results/tmp/event_mixer.o")
	  or die("Couldn't open $working_dir/batch_results/tmp/event_mixer.o.");
	while (my $line = <MIXER_FILE>){
	  #if($line =~ /total cross section\s*([^\s]*)/){$final_cs[$_[0]]=$1;}
	  if($line =~ /\s*([0-9E\+-\.]*)\s*-total cross section/){$final_cs[$_[0]]=$1;}
	  if($line =~ /[Ee]rror/){
	    print "Error in event mixing:\n$line";
	    kill_all_jobs(7);
	  }
	}
	close(MIXER_FILE);
	
	
	#Add batch details and rename
	#Plain format has been removed from event_mixer.
	#if ($fileFormat =~ /plain/){
	#	my $nt_filename = $event_filenames[$_[0]];
	#	$event_filenames[$_[0]] = sprintf "%s.out",$event_filenames[$_[0]];
	#	system("cat $working_dir/batch_results/tmp/run_details.txt $working_dir/batch_results/tmp/event_mixer.out > $working_dir/batch_results/$event_filenames[$_[0]]");
	#	if (-e "$CH_PATH/bin/nt_maker"){
	#		system("nice -n $nice_level $CH_PATH/bin/nt_maker  2>&1 1>  nt_maker.o");
	#		#system ("rm $working_dir/batch_results/$nt_filename-*.nt");
	#		opendir(DIR,"$working_dir/batch_results/tmp/");
	#		my @nts = grep(/\.nt/,readdir(DIR));
	#		closedir(DIR);
	#		my $j=0;
	#		foreach $nt (@nts){
	#			$j++;
	#			system("cp $working_dir/batch_results/tmp/$nt $working_dir/batch_results/${nt_filename}-$j.nt");
	#		}
	#		
	#	}
	#}
	#else {
	#	$event_filenames[$_[0]] = sprintf "%s.lhe",$event_filenames[$_[0]];
	#	system("cat $working_dir/batch_results/tmp/run_details.txt $working_dir/batch_results/tmp/event_mixer.lhe > $working_dir/batch_results/$event_filenames[$_[0]]");
	#}
	#Only LHE format is now supported.  
	#nt maker now works on LHE format.
	my $nt_filename = $event_filenames[$_[0]];
	if ((-e "$CH_PATH/bin/nt_maker")&&$ntuple =~ /[Tt]rue/){
		system("nice -n $nice_level $CH_PATH/bin/nt_maker $working_dir/batch_results/tmp/event_mixer.lhe  2>&1 1>  nt_maker.o");
		#system ("rm $working_dir/batch_results/$nt_filename-*.nt");
		opendir(DIR,"$working_dir/batch_results/tmp/");
		my @nts = grep(/\.nt/,readdir(DIR));
		closedir(DIR);
		my $j=0;
		foreach $nt (@nts){
			$j++;
			system("cp $working_dir/batch_results/tmp/$nt $working_dir/batch_results/${nt_filename}-$j.nt");
		}	
	}	
	$event_filenames[$_[0]] = sprintf "%s.lhe",$event_filenames[$_[0]];
#	system("cat $working_dir/batch_results/tmp/run_details.txt $working_dir/batch_results/tmp/event_mixer.lhe > $working_dir/batch_results/$event_filenames[$_[0]]");
	if(-e "$working_dir/batch_results/$event_filenames[$_[0]].gz"){system("rm -f $working_dir/batch_results/$event_filenames[$_[0]].gz");}
	system("mv $working_dir/batch_results/tmp/event_mixer.lhe  $working_dir/batch_results/$event_filenames[$_[0]]");
	system("gzip  $working_dir/batch_results/$event_filenames[$_[0]]");
		
	print_event_library($event_filenames[$_[0]]);
	
	
}


####################################################
#                                                  #
#           Combine Distributions                  #
#                                                  #
####################################################
sub combine_distributions {
	#Make a list of the distribution synonyms
	my @tmp_dist_params=();
	for(my $j=0;$j<=$#dist_param;$j++){
		my @tmp_tmp_dist_params=();
		for(my $k=0;$k<=$#subprocesses;$k++){
		  #@tmp_tmp_dist_params=(@tmp_tmp_dist_params,rename_parts($dist_param[$j],$k));
		  @tmp_tmp_dist_params=(@tmp_tmp_dist_params,$dist_param[$j]);
		}
		#Remove duplicates
		my @unique = ();
	   my %Seen   = ();
   	foreach my $elem ( @tmp_tmp_dist_params ){
   		next if $Seen{ $elem }++;
   		push @unique, $elem;
   	}
   	#Add unique synonyms to list
   	#print "$dist_param[$j] -> {".join(",",@unique)."}\n";
   	push(@tmp_dist_params,[@unique]);
	}
	#print "Test 1\n";
			
	
	#Link the distribution files
	my $sum_distr_command="nice -n $nice_level $CH_PATH/bin/sum_distr";
	if ($#subprocesses==0){$sum_distr_command="nice -n $nice_level more";}
	my @contents=`ls $working_dir/batch_results/tmp`;
	if ($#contents>=0){system("rm -f $working_dir/batch_results/tmp/*");}
	my $subdir_name = "";
	my $ncsg0=0;
	for (my $j=0;$j<=$#subprocesses;$j++){
	  if(($#step<0 and $cs[$j]>0) or ($#step>=0 and $cs[$j][$_[0]]>0)){
	    $ncsg0++;
	    #Determine directory
	    my $dir_name="$working_dir/Processes/$model_dir/$all_subproc_dir[$j]";
	    $subdir_name="";
	    if ($#step<0){$subdir_name="single";}
	    else{
	      #Before combining distributions, update the numerical values in @vars_values.
	      for(my $l=0;$l<=$#vars_names;$l++){
		for(my $m=0;$m<=$#param_names;$m++){
		  if($vars_names[$l] eq $param_names[$m]){$vars_values[$l] = $param_values[$m];}
		}
		for(my $m=0;$m<=$#run_param;$m++){
		  my $run_value = $run_begin[$m]+$run_step[$m]*$step_tmp[$m];
		  $vars_values[$l] =~ s/${run_param[$m]}/($run_value)/g;
		  if($vars_names[$l] eq $run_param[$m]){$vars_values[$l] = $run_value;}
		}
		$vars_values[$l] = eval($vars_values[$l]);
	      }
	      my @step_tmp = @{$step[$_[0]]};
	      for (my $l=0;$l<=$#run_param;$l++){
		$subdir_name = sprintf("%s%s%s",$subdir_name, $run_param[$l], 
				       $run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
		#for (my $k=0;$k<=$#vars_names;$k++){
		#  if ($vars_names[$k] eq $run_param[$l]){$vars_values[$k]=$run_begin[$l]+$run_step[$l]*$step_tmp[$l];}
		#}
	      }
	    }
	    $dir_name=$dir_name."/$subdir_name";
	    #rename distributions according to synonyms
	    open(DIST_FILE,"$dir_name/distr_1");
	    open(NEW_DIST_FILE, ">$dir_name/new_distr_1");
	  DIST_LINE: while (my $line = <DIST_FILE>){
	      #print $line;
	      for(my $k=0;$k<=$#dist_param;$k++){
		my @tmp_tmp_dist_params = @{$tmp_dist_params[$k]};
		#print "$dist_param[$k] -> {".join(",",@tmp_tmp_dist_params)."}\n";
		foreach my $param (@tmp_tmp_dist_params){
		  $param =~ s/\(/\\(/g;
		  $param =~ s/\)/\\)/g;
		  $param =~ s/([.+*?])/\\$1/g;
		  #print "$param -> $dist_param[$k]\n";
		  #$line =~ s/q($param)/$dist_param[$k]/g;
		  $line =~ s/$param/$dist_param[$k]/g;
		}
	      }
	      print NEW_DIST_FILE $line;
	    }
	    close(DIST_FILE);
	    close(NEW_DIST_FILE);
	    #Link distribution
	    $systemString = "ln -s $dir_name/new_distr_1 	$working_dir/batch_results/tmp/distr_$j";
	    $sum_distr_command = $sum_distr_command." distr_$j";
	    system($systemString);
	    #print "Test $j\n";
	  }
	}
	
	#Run sum_distr
	chdir("$working_dir/batch_results/tmp/");
	$sum_distr_command = $sum_distr_command." > distr";
	if($ncsg0==1){
	  my $k=0;
	  for(my $j=0;$j<=$#subprocesses;$j++){
	    if(($#step<0 and $cs[$j]>0) or ($#step>=0 and $cs[$j][$_[0]]>0)){$k=$j;}
	  }
	  $sum_distr_command = "cp distr_$k distr";
	}
	#print "$sum_distr_command\n";
	system($sum_distr_command);
	
	#Choose an appropriate name and copy to batch_results directory
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
	if ($fileName eq ""){
		$dist_filenames[$_[0]] = sprintf "%4d-%02d-%02d-%s.distr",$year+1900,$mon+1,$mday,$subdir_name;
	}
	else {
		$dist_filenames[$_[0]] = sprintf "%s-%s.distr",$fileName,$subdir_name;
	}
	$system_string="cp distr $working_dir/batch_results/$dist_filenames[$_[0]]";
	system($system_string);
	
	
	#Plot using gnuplot.
	if($#dist_param>=0){
	  open(GP_INST,">gnuplot_instructions");
	  print GP_INST "set term jpeg transparent medium #ffffff #000000 #000000 #add8e6 #add8e6 #000000\n";
	  print GP_INST "set key off\n";
	  print GP_INST "set mxtics\n";
	  print GP_INST "set mytics\n\n";
	  #Parameter values
	  for (my $j=0;$j<=$#vars_names;$j++){
	    if (!($vars_names[$j] =~ /^\s*\*/)){print GP_INST "$vars_names[$j]=$vars_values[$j]\n";}
	  }
	  print GP_INST "\n"; 
	  my $i=0;
	  my @tmp_plot_filenames=();
	  my $copy_string="";
	  for(my $j=0;$j<=$#dist_param;$j++){
	    #my @tmp_dist_param = rename_parts($dist_param[$j],$_[1]);
	    my @tmp_dist_param = ($dist_param[$j]);
	    for ($k=0;$k<=$#tmp_dist_param;$k++){
	      $i++;
	      #$system_string="$CH_PATH/bin/show_distr -blind  '\\06".$dist_param[$j]."{{\\06 ".$dist_n_bins[$j]." {{ [[[{0'   distr";
	      #$system_string="$CH_PATH/bin/show_distr -blind  'f".$dist_param[$j]."{{f ".$dist_n_bins[$j]." "."{{{[[[[{[[[[{0'   distr";
	      $system_string="$CH_PATH/bin/show_distr -blind  'f".$dist_param[$j]."{{f ".$dist_n_bins[$j]." "."{{ [[[[[{{0'   distr";
	      #print "$system_string\n";
	      system($system_string);
	      my $min = $dist_min[$j];
	      my $max = $dist_max[$j];
	      if ($#step>-1){
		$min = update_min_max($dist_min[$j],$_[0]);
		$max = update_min_max($dist_max[$j],$_[0]);
	      }
	      print GP_INST "\nset title '$dist_title[$j]'\n";
	      print GP_INST "set xlabel '$dist_x_title[$j]'\n";
	      #print GP_INST "set ylabel 'sigma/bin (fb)'\n\n";#Appropriate for cs/bin
	      print GP_INST "set ylabel 'dsigma(fb)/d$dist_x_title[$j]'\n\n";
	      print GP_INST "set output 'distr_$i.jpg'\n";
	      print GP_INST "min = $min\n";
	      print GP_INST "max = $max\n";
	      print GP_INST "bin_size = (max-min)/$dist_n_bins[$j].0\n";
	      #cs/bin
	      #print GP_INST "plot[min:max] ".
	      #	"'plot_$i.txt' using (min+\$0*bin_size+(bin_size/2)):(1000*(\$1-\$2)*bin_size) with histeps,".
	      #	"'plot_$i.txt' using (min+\$0*bin_size+(bin_size/2)):(1000*(\$1+\$2)*bin_size) with histeps,".
	      #	"'plot_$i.txt' using (min+\$0*bin_size+(bin_size/2)):(1000*\$1*bin_size) with histeps\n";
	      #differential cs
	      print GP_INST "plot[min:max] ".
		"'plot_$i.tab' using (min+\$0*bin_size+(bin_size/2)):(1000*(\$1-\$2)) with histeps,".
		"'plot_$i.tab' using (min+\$0*bin_size+(bin_size/2)):(1000*(\$1+\$2)) with histeps,".
		"'plot_$i.tab' using (min+\$0*bin_size+(bin_size/2)):(1000*\$1) with histeps\n";
	      #Create filename.
	      my $tmp_plot_filename="";
	      #math!			my $tmp_plot_filename_math="";
	      my $tmp_plot_filename_tab="";
	      if ($fileName eq ""){
		$tmp_plot_filename = sprintf "%4d-%02d-%02d-%s_$i.jpg",$year+1900,$mon+1,$mday,$subdir_name;
		#math!				$tmp_plot_filename_math = sprintf "%4d-%02d-%02d-%s_$i.math",$year+1900,$mon+1,$mday,$subdir_name;
		$tmp_plot_filename_tab = sprintf "%4d-%02d-%02d-%s_$i.tab",$year+1900,$mon+1,$mday,$subdir_name;
	      }
	      else {
		$tmp_plot_filename = sprintf "%s-%s_$i.jpg",$fileName,$subdir_name;
		#math!				$tmp_plot_filename_math = sprintf "%s-%s_$i.math",$fileName,$subdir_name;
		$tmp_plot_filename_txt = sprintf "%s-%s_$i.tab",$fileName,$subdir_name;
	      }
	      push(@tmp_plot_filenames,$tmp_plot_filename);
	      $copy_string=$copy_string."cp distr_$i.jpg $working_dir/batch_results/$tmp_plot_filename;";
	      #math!			$copy_string=$copy_string."cp plot_$i.math $working_dir/batch_results/$tmp_plot_filename_math;";
	      $copy_string=$copy_string."cp plot_$i.tab $working_dir/batch_results/$tmp_plot_filename_tab;";
	    }
	  }
	  close(GP_INST);
	  #system("cat  gnuplot_instructions; echo ======");
	  #system("cat plot_$i.tab; echo ====");
	  
	  $system_string="gnuplot gnuplot_instructions";
	  system($system_string);
	  system($copy_string);
	  #system("cp gnuplot_instructions ~/physics/CalcHEP/ch_2.5.6/gnuplot_instructions.tmp"); #for debugging
	  system("cp gnuplot_instructions gnuplot_instructions.template"); 
	  
	  @plot_filenames[$_[0]]=[@tmp_plot_filenames];
	}
	
	
	
}



####################################################
#            Print Events Library                  #
####################################################
sub print_init_event_library {
	open(LIB_FILE, ">$working_dir/batch_results/events.txt");
	print LIB_FILE "################################\n";
	print LIB_FILE "#        Events Library        #\n";
	print LIB_FILE "#    Automatically generated   #\n";
	print LIB_FILE "#     Do not edit this file    #\n";
	print LIB_FILE "################################\n";
	close(LIB_FILE);
}
sub print_event_library {
	open(LIB_FILE, ">>$working_dir/batch_results/events.txt");
	print LIB_FILE "$_[0]\n";
	close(LIB_FILE);
	

	#List contents of batch_results directory.
	opendir(DIR,"$working_dir/batch_results/");
	my @lhes = grep(/\.lhe.gz/,readdir(DIR));
	closedir(DIR);
	opendir(DIR,"$working_dir/batch_results/");
	my @outs = grep(/\.out/,readdir(DIR));
	closedir(DIR);
	my @event_lib_filenames = (@lhes,@outs);
	@event_lib_filenames = sort @event_lib_filenames;
	opendir(DIR,"$working_dir/batch_results/");
	my @nts = grep(/\.nt/,readdir(DIR));
	closedir(DIR);
	opendir(DIR,"$working_dir/batch_results/");
	my @distrs = grep(/\.distr/,readdir(DIR));
	closedir(DIR);
	my %event_lib_dates = ();
	foreach $event_lib_filename (@event_lib_filenames){
		$event_lib_dates{$event_lib_filename}=ctime(stat("$working_dir/batch_results/$event_lib_filename")->mtime);
	}
	
	
	
	
						
	#my @event_lib_filenames=();
	#open(LIB_FILE, "$working_dir/batch_results/events.txt");
	#LINE: while($line = <LIB_FILE>){
	#	if ($line =~ /^#/){next LINE;}
	#	$line =~ s/\s//g;
	#	push (@event_lib_filenames,$line);
	#}
	#close(LIB_FILE);
	#@event_lib_filenames=reverse(@event_lib_filenames);
	
	#Write library.html
	open(HTML_FILE, ">$html_dir/events.html");
	print HTML_FILE "<html>\n";
   print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Events Library</title>\n";
   print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
   print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   print HTML_FILE "<body>\n";
   ############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
	
   print HTML_FILE "<div id='main'>\n";
   print HTML_FILE "\t<h1>CalcHEP Events Library</h1>\n";
   print HTML_FILE "\t<table>\n";
   print HTML_FILE "\t\t<tr><th>Date</th><th>LHE</th><th>plain</th><th>Ntuple</th></tr>\n";
   #foreach $filename_tmp (@event_lib_filenames){
   #	print HTML_FILE "\t\t<tr><td><a href='$working_dir/batch_results/$filename_tmp'>$filename_tmp</a></td></tr>\n";
	#}
	foreach $event_lib_filename (@event_lib_filenames){
		if ($event_lib_filename =~ /\.lhe.gz$/){
			print HTML_FILE "\t\t<tr><td>$event_lib_dates{$event_lib_filename}</td><td><a href='$working_dir/batch_results/$event_lib_filename'>$event_lib_filename</a></td></tr>\n";
		}
		elsif ($event_lib_filename =~ /\.out$/){
			my @out_nts = ();
			my $short_filename = $event_lib_filename;
			$short_filename =~ s/([^\.]+).out/$1/;
			foreach $nt (@nts){
				my $short_nt = $nt;
				$short_nt =~ s/([^\.]+)-[0-9]+.nt/$1/;
				if ($short_nt eq $short_filename){ push(@out_nts,$nt);}
			}
			print HTML_FILE "\t\t<tr><td>$event_lib_dates{$event_lib_filename}</td><td></td><td><a href='$working_dir/batch_results/$event_lib_filename'>$event_lib_filename</a></td><td>";
			@out_nts = reverse @out_nts;
			foreach $out_nt (@out_nts){
				print HTML_FILE "<a href='$working_dir/batch_results/$out_nt'>$out_nt</a><br>";
			}
			print HTML_FILE "</td></tr>\n";
		}
	}
	
	print HTML_FILE "\t</table>\n";
	print HTML_FILE "</div></body></html>\n";
	close(HTML_FILE);
}


####################################################
#              Printing routines                   #
####################################################

####################################################
#              Print style file                    #
####################################################
sub print_style_file {
	open(CSS_FILE,">$html_dir/style.css");
	print CSS_FILE <<CSS;
#links {
	width: 11em;
	position: fixed;
	top: 5em;
}
#main {
	width: 45em;
	position: absolute;
	left: 13em;
	text-align: center;
}
#help_main {
	width: 31em;
	position: absolute;
	left: 20em;
	text-align: center;
}
table {
	padding-top: 0.5em;
	padding-bottom: 0.5em;
	margin: auto;
}
td {
	vertical-align: top;
	padding-left: 5px;
	padding-right: 5px;
}
a {
	text-decoration: none;
	color: #556f9f;
}
a:hover {
	text-decoration: underline;
}
ul {
	margin: 0px;
	margin-left: 1em;
	padding: 0px;
}
li {
	list-style-type: none;
}
p {
	text-align: justify;
}
CSS
	close(CSS_FILE);
}


####################################################
#              Print batch details.                #
####################################################
sub print_request {
	open(HTML_FILE, ">$html_dir/request.html");
	#Head
	print HTML_FILE "<html>\n";
	print HTML_FILE "<head>\n";
	#print HTML_FILE "\t<title>CalcHEP Batch Request Details</title>\n";
	print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
	print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
	#Body
	print HTML_FILE "<body>\n";
	############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
	
	print HTML_FILE "<div id='main'>\n";
	#print HTML_FILE "\t<h1>Batch Request Details</h1>\n";
	print HTML_FILE "\t<table>\n";
	print HTML_FILE "\t\t<tr><td>\n";
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='2'>Model</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>Model:</td><td>$model_name</td></tr>\n";
	#print HTML_FILE "\t\t\t<tr><td>Changed:</td><td>$model_changed</td></tr>\n";
	#print HTML_FILE "\t\t\t<tr></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>Gauge:</td><td>$gauge</td></tr>\n";
	print HTML_FILE "\t\t</table>\n";
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th>Processes</th></tr>\n";
	foreach $process (@processes){
		print HTML_FILE "\t\t\t<tr><td>$process</td></tr>\n";
	};
	foreach $decay (@decays){
		print HTML_FILE "\t\t\t<tr><td>$decay</td></tr>\n";
	};
	print HTML_FILE "\t\t</table>\n";
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th>Alias</th></tr>\n";
	foreach $parton (@partons){
		print HTML_FILE "\t\t\t<tr><td>$parton</td></tr>\n";
	};
	print HTML_FILE "\t\t</table>\n";
	print HTML_FILE "\t\t</td><td>\n";
	
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='2'>Parameters</th></tr>\n";
	for (my $j=0;$j<=$#vars_names;$j++){
		print HTML_FILE "\t\t\t<tr><td>$vars_names[$j]:</td><td>$vars_values[$j]</td></tr>\n";
	}
	print HTML_FILE "\t\t</table>\n";
	print HTML_FILE "\t\t</td></tr><tr><td>\n";
	
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='2'>PDFs</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>pdf<sub>1</sub>:</td><td>$pdf1</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>pdf<sub>2</sub>:</td><td>$pdf2</td></tr>\n";
	print HTML_FILE "\t\t</table>\n";
	print HTML_FILE "\t\t</td><td>\n";
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='2'>Momenta</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>p<sub>1</sub>=</td><td>$p1</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>p<sub>2</sub>=</td><td>$p2</td></tr>\n";
	print HTML_FILE "\t\t</table>\n";
	print HTML_FILE "\t\t</td></tr><tr><td>\n";
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='3'>Cuts</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><th>Param</th><th>Min</th><th>Max</th></tr>\n";
	for (my $j=0;$j<=$#cut_param;$j++){
		print HTML_FILE "\t\t\t<tr><td>$cut_param[$j]</td><td>$cut_min[$j]</td><td>$cut_max[$j]</td></tr>\n";
	}
	print HTML_FILE "\t\t</table>\n";
	
	print HTML_FILE "\t\t</td><td>\n";
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='4'>Regularizations</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><th>Mom</th><th>Mass</th><th>Width</th><th>Power</th></tr>\n";
	for (my $j=0;$j<=$#reg_mom;$j++){
		print HTML_FILE "\t\t\t<tr><td>$reg_mom[$j]</td><td>$reg_mass[$j]</td><td>$reg_width[$j]</td><td>$reg_pow[$j]</td></tr>\n";
	}
	print HTML_FILE "\t\t</table>\n";
	
	print HTML_FILE "\t\t</td></tr><tr><td>\n";
	
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='4'>Scans</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><td colspan='4'>N events (per step): $n_events</td</tr>\n";
	print HTML_FILE "\t\t\t<tr><th>Param</th><th>Begin</th><th>Step</th><th>N</th></tr>\n";
	for (my $j=0;$j<=$#run_param;$j++){
		print HTML_FILE "\t\t\t<tr><td>$run_param[$j]</td><td>$run_begin[$j]</td><td>$run_step[$j]</td><td>$run_n[$j]</td></tr>\n";
	}
	print HTML_FILE "\t\t</table>\n";
	
	print HTML_FILE "\t\t</td><td>\n";
	
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='2'>Parallelization Details</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>Parallelization:</td><td>$par_meth</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>Que:</td><td>$que</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>Walltime:</td><td>${walltime}hrs</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>Memory:</td><td>${memory}gb</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>email:</td><td>$email</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>Max cpus:</td><td>$max_cpus</td></tr>\n";
	print HTML_FILE "\t\t</table>\n";

	print HTML_FILE "\t\t</td></tr><tr><td>\n";

	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='2'>Vegas</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>n_Sess1</td><td>$nSess1</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>n_Calls1</td><td>$nCalls1</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>n_Sess2</td><td>$nSess2</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>n_Calls2</td><td>$nCalls2</td></tr>\n";
	print HTML_FILE "\t\t</table>\n";
	
	print HTML_FILE "\t\t</td><td>\n";
	
	print HTML_FILE "\t\t<table>\n";
	print HTML_FILE "\t\t\t<tr><th colspan='2'>Event Generator</th></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>sub-cubes</td><td>$subCubes</td></tr>\n";
	#print HTML_FILE "\t\t\t<tr><td>random search</td><td>$randSearch</td></tr>\n";
	#print HTML_FILE "\t\t\t<tr><td>simplex search</td><td>$simpSearch</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>max*N</td><td>$maxN</td></tr>\n";
	print HTML_FILE "\t\t\t<tr><td>find new MAX</td><td>$findNewMax</td></tr>\n";
	print HTML_FILE "\t\t</table>\n";
	
	
	print HTML_FILE "\t\t</td></tr>\n";
	print HTML_FILE "\t</table>\n";
	
	print HTML_FILE "</div>\n";
	print HTML_FILE "</body>\n";
	print HTML_FILE "</html>\n";
	close(HTML_FILE);
}

####################################################
#      Print run details for event file.           #
#      Plain format was removed as of 0.63.        #
####################################################
sub print_run_details {
	open(TXT_FILE, ">$working_dir/batch_results/tmp/run_details.txt");
	print TXT_FILE	"\n";
	print TXT_FILE "<calchep-batch>\n";
        print TXT_FILE "<![CDATA[\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Model Info                 #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "Model:     $model_name\n";
	print TXT_FILE "#$model_url\n";
	print TXT_FILE "Gauge:     $gauge\n\n";
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Processes                  #\n";
	print TXT_FILE "#########################################\n";
	foreach $process (@processes){
		print TXT_FILE "Process   :    $process\n";
	};
	foreach $decay (@decays){
		print TXT_FILE "Decay     :     $decay\n";
	};
	for (my $j=0;$j<=$#removes;$j++){
		print TXT_FILE "Remove    :".($removesNumber[$j]+1).": $removes[$j]\n";
	}
	for (my $j=0;$j<=$#removesD;$j++){
		print TXT_FILE "Remove    :".($removesDNumber[$j]+1).": $removesD[$j]\n";
	}
	foreach $parton (@partons){
		print TXT_FILE "Alias :    $parton\n";
	};
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            PDF's                      #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "pdf1 :       $pdf1\n";
	print TXT_FILE "pdf2 :       $pdf2\n\n";
	if($pdf1  =~ /[Ii][Ss][Rr].*[Bb]eam/ || $pdf2  =~ /[Ii][Ss][Rr].*[Bb]eam/){
		print TXT_FILE	"Bunch x+y sizes (nm) : $bunch_size\n";
		print TXT_FILE "Bunch length (mm)    : $bunch_length\n";
		print TXT_FILE "Number of particles  : $bunch_number\n#\n";
	}
	elsif($pdf1 =~ /[Ee]quiv[^:]*[Pp]hoton/ || $pdf2 =~ /[Ee]quiv[^:]*[Pp]hoton/){
		print TXT_FILE "Photon particle           : $photon_particle\n";
		print TXT_FILE "|Q|max                    : ,$photon_Qmax\n";
	}
	elsif($pdf1 =~ /[Pp]roton[^:]*[Pp]hoton/ || $pdf2 =~ /[Pp]roton[^:]*[Pp]hoton/){
		print TXT_FILE "Incoming particle mass    : $photon_incoming_particle_mass\n";
		print TXT_FILE "Incoming particle charge  : $photon_incoming_particle_charge\n";
		print TXT_FILE "|Q^2|max                  : $photon_Q2max\n";
		print TXT_FILE "Pt cut of outgoing proton :  $photon_proton_ptCut\n";
	}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Momenta                    #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "p1 :         $p1def\n";
	print TXT_FILE "p2 :         $p2def\n\n";
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Parameters                 #\n";
	print TXT_FILE "#########################################\n";
	for (my $j=0;$j<=$#vars_names;$j++){
		print TXT_FILE "Parameter:   $vars_names[$j]=$vars_values[$j]\n";
	}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            QCD running info           #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "parton dist. alpha : $alphaPDF\n";
	print TXT_FILE "alpha(MZ)          : $alphaMZ\n";
	print TXT_FILE "alpha nf           : $alphaNF\n";
	print TXT_FILE "alpha order        : $alphaOrder\n";
	print TXT_FILE "mb(mb)             : $alphaMbMb\n";
	print TXT_FILE "Mtop(pole)         : $alphaMtp\n";
	for (my $j=0;$j<=$#alphaFact1Scale;$j++){
		print TXT_FILE "alpha Fact 1 Q :".($alphaFact1Number[$j]+1).": $alphaFact1Scale[$j]\n";
	}
	for (my $j=0;$j<=$#alphaFact2Scale;$j++){
		print TXT_FILE "alpha Fact 2 Q :".($alphaFact2Number[$j]+1).": $alphaFact2Scale[$j]\n";
	}
	for (my $j=0;$j<=$#alphaRenScale;$j++){
		print TXT_FILE "alpha Ren Q :".($alphaRenNumber[$j]+1).": $alphaRenScale[$j]\n";
	}
	for (my $j=0;$j<=$#alphaShowScale;$j++){
		print TXT_FILE "alpha Show Q :".($alphaShowNumber[$j]+1).": $alphaShowScale[$j]\n";
	}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Breit-Wigner               #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "Breit Wigner range : $BWrange\n";
	if($TchannelWidths==1){print TXT_FILE "T-channel widths   : ON\n";}
	else{print TXT_FILE "T-channel widths   : OFF\n";}
	if($GItchannel==1){print TXT_FILE "GI in T-channel    : ON\n";}
	else{print TXT_FILE "GI in T-channel    : OFF\n";}
	if($GIschannel==1){print TXT_FILE "GI in S-channel    : ON\n";}
	else{print TXT_FILE "GI in S-channel    : OFF\n";}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Cuts                       #\n";
	print TXT_FILE "#########################################\n";
	for (my $j=0;$j<=$#cut_param;$j++){
		print TXT_FILE "Cut parameter :".($cut_Number[$j]+1).": $cut_param[$j]\n";
		print TXT_FILE "Cut invert    :".($cut_Number[$j]+1).": $cut_invert[$j]\n";
		print TXT_FILE "Cut min       :".($cut_Number[$j]+1).": $cut_min[$j]\n";
		print TXT_FILE "Cut max       :".($cut_Number[$j]+1).": $cut_max[$j]\n";
	}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Kinematics                 #\n";
	print TXT_FILE "#########################################\n";
	for (my $j=0;$j<=$#kinematics;$j++){
		print TXT_FILE "Kinematics :".($kin_Number[$j]+1).": $kinematics[$j]\n";
	}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Regularization             #\n";
	print TXT_FILE "#########################################\n";
	for (my $j=0;$j<=$#reg_mom;$j++){
		print TXT_FILE "Regularization momentum :".($reg_Number[$j]+1).": $reg_mom[$j]\n";
		print TXT_FILE "Regularization mass     :".($reg_Number[$j]+1).": $reg_mass[$j]\n";
		print TXT_FILE "Regularization width    :".($reg_Number[$j]+1).": $reg_width[$j]\n";
		print TXT_FILE "Regularization power    :".($reg_Number[$j]+1).": $reg_pow[$j]\n";
	}
	for (my $j=0;$j<=$#decay_reg_mom;$j++){
		print TXT_FILE "Decay Regularization momentum :".($decay_reg_Number[$j]+1).": $decay_reg_mom[$j]\n";
		print TXT_FILE "Decay Regularization mass     :".($decay_reg_Number[$j]+1).": $decay_reg_mass[$j]\n";
		print TXT_FILE "Decay Regularization width    :".($decay_reg_Number[$j]+1).": $decay_reg_width[$j]\n";
		print TXT_FILE "Decay Regularization power    :".($decay_reg_Number[$j]+1).": $decay_reg_pow[$j]\n";
	}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Distributions              #\n";
	print TXT_FILE "#########################################\n";
	for (my $j=0;$j<=$#dist_param;$j++){
		print TXT_FILE "Dist parameter          : $dist_param[$j]\n";
		print TXT_FILE "Dist min                : $dist_min[$j]\n";
		print TXT_FILE "Dist max                : $dist_max[$j]\n";
		print TXT_FILE "Dist n bins             : $dist_n_bins[$j]\n";
		print TXT_FILE "Dist title              : $dist_title[$j]\n";
		print TXT_FILE "Dist x-title            : $dist_x_title[$j]\n\n";

	}
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Events Generation          #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "Number of events (per run step): $n_events\n";
	print TXT_FILE "Max lumi [1/fb]                : $max_lumi\n";
	print TXT_FILE "Filename                       : $_[0]\n";
	#print TXT_FILE "File format                    : $fileFormat\n";
	print TXT_FILE "Cleanup                        : $cleanup\n";
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Parallelization info       #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "Parallelization method : $par_meth\n";
	print TXT_FILE "Que                    : $que\n";
	print TXT_FILE "Walltime               : $walltime\n";
	print TXT_FILE "Memory                 : $memory\n";
	print TXT_FILE "email                  : $email\n";
	print TXT_FILE "Max number of cpus     : $max_cpus\n";
	print TXT_FILE "sleep time             : $sleep_time\n";
	print TXT_FILE "nice level             : $nice_level\n";
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#            Vegas                      #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "nSess_1  : $nSess1\n";
	print TXT_FILE	"nCalls_1 : $nCalls1\n";
	print TXT_FILE "nSess_2  : $nSess2\n";
	print TXT_FILE	"nCalls_2 : $nCalls2\n";
	print TXT_FILE "\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "#           Event Generator             #\n";
	print TXT_FILE "#########################################\n";
	print TXT_FILE "sub-cubes      : $subCubes\n";
	#print TXT_FILE	"random search  : $randSearch\n";
	#print TXT_FILE "simplex search : $simpSearch\n";
	print TXT_FILE "MAX*N          : $maxN\n";
	print TXT_FILE "find new MAX   : $findNewMax\n"; 
	print TXT_FILE "\n";
        print TXT_FILE "]]>\n";
	print TXT_FILE "</calchep-batch>\n";
	close(TXT_FILE);
}


####################################################
#                 Print index                      #
####################################################
sub print_index {
  open(TXT_FILE,  ">$html_dir/index.txt");
  open(HTML_FILE, ">$html_dir/index.html");
  ############################
  #        Header            #
  ############################
  print TXT_FILE "\n\tCalcHEP Batch Details\n\n";
  print HTML_FILE "<html>\n";
  print HTML_FILE "<head>\n";
  print HTML_FILE "\t<title>CalcHEP Batch Details</title>\n";
  if (!($_[0]==1.5 or $_[0]==3)){
    print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
  }
  print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
  print HTML_FILE "</head>\n";
   ############################
   #        Body              #
   ############################
   print HTML_FILE "<body>\n";
   ############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
   
	print HTML_FILE "<div id='main'>\n";
	print HTML_FILE "<h1>CalcHEP Batch Details</h1>\n";
	print HTML_FILE "<h2>$model_name</h2>\n";
	if    ($_[0]==-1){
		print HTML_FILE "<h3>Processing Batch File</h3>\n";
		print TXT_FILE "\tProcessing Batch File\n\n";
	}
	elsif ($_[0]==0){
		print HTML_FILE "<h3>Generating Symbolic Code</h3>\n";
		print TXT_FILE "\tGenerating Symbolic Code\n\n";
	}
	elsif ($_[0]==1){
		print HTML_FILE "<h3>Calculating Cross Sections</h3>\n";
		print TXT_FILE "\tCalculating Cross Sections\n\n";
	}
	elsif ($_[0]==1.5){
		print HTML_FILE "<h3>Done!</h3>\n";
		print TXT_FILE "\tDone!\n\n";
	}
	elsif ($_[0]==2){
		print HTML_FILE "<h3>Generating Events</h3>\n";
		print TXT_FILE "\tGenerating Events\n\n";
	}
	elsif ($_[0]==3){
		print HTML_FILE "<h3>Done!</h3>\n";
		print TXT_FILE "\tDone!\n\n";
	}
	print HTML_FILE "<table>\n";
	print HTML_FILE "\t<tr><th></th><th>Finished</th><th>Time(hr)</th></tr>\n";
	print TXT_FILE "\t\tFinished\tTime(hr)\n";
	if ($_[0]==0){
		print HTML_FILE "\t<tr><td><a href='symbolic.html'>Symbolic</a></td>";
		print TXT_FILE "Symbolic\t";
		if ($#all_subprocesses<0){
			print HTML_FILE "<td></td>";
			print TXT_FILE "\t\t\t";
		}
		else {
			print HTML_FILE "<td>".
				($#all_subprocesses+1-num_not_in_lib())."/".($#all_subprocesses+1)."</td>";
			print TXT_FILE 
				($#all_subprocesses+1-num_not_in_lib())."/".($#all_subprocesses+1)."\t\t";
		}
		if ($symb_begin_time>0){
			printf HTML_FILE "<td>%.2f</td></tr>\n",(time()-$symb_begin_time)/3600;
			printf TXT_FILE "%.2f\n",(time()-$symb_begin_time)/3600;
		}
		else {print HTML_FILE "\n";}
	}
	elsif($_[0]>0){
		printf HTML_FILE "\t<tr><td><a href='symbolic.html'>Symbolic</a></td><td>%i/%i</td><td>%.2f</td></tr>\n",$#all_subprocesses+1,$#all_subprocesses+1,($symb_end_time-$symb_begin_time)/3600;
		printf TXT_FILE "Symbolic\t%i/%i\t\t%.2f\n",
			$#all_subprocesses+1,$#all_subprocesses+1,($symb_end_time-$symb_begin_time)/3600;
	}
	if ($_[0]==1){
		print HTML_FILE "\t<tr><td><a href='numerical.html'>&sigma;</a></td>";
		print TXT_FILE "sigma\t\t";
		if ($#step<0){
			print HTML_FILE "<td>$runs_finished/1</a></td>";
			print TXT_FILE "$runs_finished/1\t\t";
		}
		else {
			printf HTML_FILE "<td>$runs_finished/%i</td>",$#step+1;
			printf TXT_FILE "$runs_finished/%i\t\t",$#step+1;
		}
		if ($cs_begin_time>0){
			printf HTML_FILE "<td>%.2f</td></tr>\n",(time()-$cs_begin_time)/3600;
			printf TXT_FILE "%.2f\n",(time()-$cs_begin_time)/3600;
		}
		else {
			print HTML_FILE "<td></td></tr>\n";
			print TXT_FILE "\n";
		}
	}
	elsif ($_[0]>1){
		print HTML_FILE "\t<tr><td><a href='numerical.html'>&sigma;</a></td>";
		print TXT_FILE "sigma\t\t";
		if ($#step<0){
			print HTML_FILE "<td>1/1</td>";
			print TXT_FILE "1/1\t\t";
		}
		else {
			printf HTML_FILE "<td>%i/%i</td>",$#step+1,$#step+1;
			printf TXT_FILE "%i/%i\t\t",$#step+1,$#step+1;
		}
		printf HTML_FILE "<td>%.2f</td></tr>\n",($cs_end_time-$cs_begin_time)/3600;
		printf TXT_FILE "%.2f\n",($cs_end_time-$cs_begin_time)/3600;
	}
	if ($_[0]==2){
		print HTML_FILE "\t<tr><td><a href='numerical.html'>Events</a></td>";
		print TXT_FILE "Events\t\t";
		if ($#step<0){
			print HTML_FILE "<td>$runs_finished/1</td>";
			print TXT_FILE "$runs_finished/1\t\t";
		}
		else {
			printf HTML_FILE "<td>$runs_finished/%i</td>",$#step+1;
			printf TXT_FILE "$runs_finished/%i\t\t",$#step+1;
		}
		if ($events_begin_time>0){
			printf HTML_FILE "<td>%.2f</td>",(time()-$events_begin_time)/3600;
			printf TXT_FILE "%.2f\n",(time()-$events_begin_time)/3600;
		}
		else {print HTML_FILE "<td></td></tr>\n";}
	}
	elsif ($_[0]>2){
		print HTML_FILE "\t<tr><td><a href='numerical.html'>Events</a></td>";
		print TXT_FILE "Events\t\t";
		if ($#step<0){
			print HTML_FILE "<td>1/1</td>";
			print TXT_FILE "1/1\t\t";
		}
		else {
			printf HTML_FILE "<td>%i/%i</td>",$#step+1,$#step+1;
			printf TXT_FILE "%i/%i\t\t",$#step+1,$#step+1;
		}
		printf HTML_FILE "<td>%.2f</td></tr>\n",($events_end_time-$events_begin_time)/3600;
		printf TXT_FILE "%.2f\n",($events_end_time-$events_begin_time)/3600;
	}
	print HTML_FILE "</table>\n";
	print TXT_FILE "\n";

	print HTML_FILE "</div>\n";
	print HTML_FILE "</body>\n";
	print HTML_FILE "</html>\n";
	close(HTML_FILE);
	close(TXT_FILE);
}

####################################################
#            Print Process Library                 #
####################################################
sub print_init_model_library {
	open(LIB_FILE, ">$working_dir/Processes/models.txt");
	print LIB_FILE "################################\n";
	print LIB_FILE "#        Models Library        #\n";
	print LIB_FILE "#    Automatically generated   #\n";
	print LIB_FILE "#     Do not edit this file    #\n";
	print LIB_FILE "################################\n";
	close(LIB_FILE);
}
sub print_init_library {
	open(LIB_FILE, ">$working_dir/Processes/$model_dir/processes.txt");
	print LIB_FILE "################################\n";
	print LIB_FILE "#       Processes Library      #\n";
	print LIB_FILE "#    Automatically generated   #\n";
	print LIB_FILE "#     Do not edit this file    #\n";
	print LIB_FILE "################################\n";
	close(LIB_FILE);
}
sub print_lib_index {
	open(LIB_FILE, ">>$working_dir/Processes/models.txt");
	print LIB_FILE "$_[0] : $_[1]\n";
	close(LIB_FILE);
	
	open (HTML_FILE, ">$html_dir/library.html");
	print HTML_FILE "<html>\n";
	print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Process Library Index</title>\n";
   print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
   print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   print HTML_FILE "<body>\n";
   ############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
	
   print HTML_FILE "<div id='main'>\n";
   print HTML_FILE "\t<h1>Process Library Index</h1>\n";
   print HTML_FILE "\t<table>\n";
   print HTML_FILE "\t\t<tr><th>Model</th><th colspan='2'>Gauges</th></tr>\n";
   for (my $j=0;$j<=$#mod_dirs;$j++){
   	$model=$mod_names[$j];
   	$dir=$mod_dirs[$j];
   	print HTML_FILE "\t\t<tr><td>$model</td>";
   	@ggs = `ls $working_dir/Processes/$dir`;
   	if ($ggs[0] =~ /[Ff]eynman/ && $#ggs>0){
   		print HTML_FILE "<td><a href='$dir/Feynman/library.html'>Feynman</a></td><td><a href='$dir/Unitary/library.html'>Unitary</a></td></tr>\n";
   	}
   	elsif ($ggs[0] =~ /[Ff]eynman/){
   		print HTML_FILE "<td><a href='$dir/Feynman/library.html'>Feynman</a></td></tr>\n";
   	}
   	elsif ($ggs[0] =~ /[Uunitary]/){
   		print HTML_FILE "<td></td><td><a href='$dir/Unitary/library.html'>Unitary</a></td</tr>\n";
   	}
   }
   print HTML_FILE "\t</table>\n";
   print HTML_FILE "</div></body>\n";
   close(HTML_FILE);
}
sub print_library {
	open(LIB_FILE, ">>$working_dir/Processes/$model_dir/processes.txt");
	print LIB_FILE "$_[0] : $_[1] : $_[2]\n";
	close(LIB_FILE);
	
	#Create library directory if necessary
	$model_dir_tmp="m$model_num";
	if (!(-d "html/$model_dir_tmp")){system("mkdir html/$model_dir_tmp");}
	if (!(-d "html/$model_dir")){system("mkdir html/$model_dir");}
	
	#Write library.html
	open(HTML_FILE, ">$html_dir/$model_dir/library.html");
	print HTML_FILE "<html>\n";
   print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Process Library</title>\n";
   print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
   print HTML_FILE "\t <link rel='stylesheet' href='../../style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   print HTML_FILE "<body>\n";
   ############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='../../index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='../../request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='../../symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='../../numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='../../events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='../../library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='../../help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
	
   print HTML_FILE "<div id='main'>\n";
   print HTML_FILE "\t<h1>CalcHEP Process Library</h1>\n";
   print HTML_FILE "\t<h2>$model_name</h2>\n";
   print HTML_FILE "\t<h3>$gauge gauge</h3>\n";
   print HTML_FILE "\t<table>\n";
   print HTML_FILE "\t\t<tr><th>Directory</th><th>Process</th><th>Removes</th></tr>\n";
   
	for (my $j=0;$j<=$#lib_dirs;$j++){
		print HTML_FILE "\t\t<tr><td>$lib_dirs[$j]</td><td>$lib_procs[$j]</td><td>$lib_removes[$j]</td></tr>\n";
	}
	
	print HTML_FILE "\t</table>\n";
	print HTML_FILE "</div></body></html>\n";
	close(HTML_FILE);
}


####################################################
#                 Print symbolic                   #
####################################################
sub print_symbolic {
	open(HTML_FILE, ">$html_dir/symbolic.html");
	open(TXT_FILE, ">$html_dir/symbolic.txt");
	############################
	#        Header            #
	############################
	print TXT_FILE "\tCalcHEP Symbolic Details\n\n";
   print HTML_FILE "<html>\n";
   print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Symbolic Details</title>\n";
   print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
   print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   ############################
   #        Body              #
   ############################
   print HTML_FILE "<body>\n";
   ############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
   
	print HTML_FILE "<div id='main'>\n";
	print HTML_FILE "<h1>Symbolic Sessions</h1>\n";
	print HTML_FILE "<h2>$model_name</h2>\n";

	############################
   #        Processes         #
   ############################
	print HTML_FILE "\t<table>\n";
	print HTML_FILE "\t\t<tr><th>Processes</th><th>Removes</th><th>Lib</th>";
	print TXT_FILE "Processes                Removes                  Lib  ";
	if ($_[0]>=0){
		print HTML_FILE "<th>PID</th><th>Time(hr)</th>";
		print TXT_FILE "PID       Time";
	}
	print HTML_FILE "</tr>\n";
	print TXT_FILE "\n";
	for (my $j=0;$j<=$#all_subprocesses;$j++){
		print HTML_FILE "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/job.out'>$all_subprocesses[$j]</a></td>";
		print HTML_FILE "<td>$all_subremoves[$j]</td>";
		printf TXT_FILE "%-25s",$all_subprocesses[$j];
		printf TXT_FILE "%-25s",$all_subremoves[$j];
		if ($all_subproc_in_lib[$j] == 1){
			print HTML_FILE "<td>&#10003;</td>";
			print TXT_FILE "x    ";
		}
		else {
			print HTML_FILE "<td></td>";
			print TXT_FILE "     ";
		}
		if ($pids[$j] != 0){
			print HTML_FILE "<td>$pids[$j]</td>";
			printf TXT_FILE "%-10d",$pids[$j];
		}
		else {
			print HTML_FILE "<td></td>";
			print TXT_FILE "          ";
		}
		if ($end_times[$j]>$begin_times[$j]){
			$time = ($end_times[$j] - $begin_times[$j])/3600;
			printf HTML_FILE "<td>%.2f</td>",$time;
			printf TXT_FILE "%.2f",$time;
		}
		elsif ($begin_times[$j]>0){
			$time = (time() - $begin_times[$j])/3600;
			printf HTML_FILE "<td>%.2f</td>",$time;
			printf TXT_FILE "%.2f",$time;
		}
		else {print HTML_FILE "<td></td>";}
		print HTML_FILE "</tr>\n";
		print TXT_FILE "\n";
	}
	#Now for the widths
	print HTML_FILE "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$widths_dir/job.out'>Widths</a></td><td></td>";
	printf TXT_FILE "%-25s%-25s","Widths","";
	if ($widths_in_lib == 1){
		print HTML_FILE "<td>&#10003;</td>";
		print TXT_FILE "x    ";
	}
	else {
		print HTML_FILE "<td></td>";
		print TXT_FILE "     ";
	}
	if ($widths_pid != 0){
		print HTML_FILE "<td>$widths_pid</td>";
		printf TXT_FILE "%-10d",$widths_pid;
	}
	else {
		print HTML_FILE "<td></td>";
		print TXT_FILE "          ";
	}
	if ($widths_end_times>$widths_begin_time){
		$time = ($widths_end_time - $widths_begin_time)/3600;
		printf HTML_FILE "<td>%.2f</td>",$time;
		printf TXT_FILE "%.2f",$time;
	}
	elsif ($widths_begin_time>0){
		$time = (time() - $widths_begin_time)/3600;
		printf HTML_FILE "<td>%.2f</td>",$time;
		printf TXT_FILE "%.2f",$time;
	}
	else {print HTML_FILE "<td></td>";}
	print HTML_FILE "</tr>\n";
	print TXT_FILE "\n";
	
	print HTML_FILE "\t</table>\n";




   ############################
   #        Done              #
   ############################
	print HTML_FILE "</div>\n";
   print HTML_FILE "</body>\n";
   print HTML_FILE "</html>\n";
   print TXT_FILE "\n";
	close(HTML_FILE);
	close(TXT_FILE);
};


####################################################
#                 Print numerical                  #
####################################################
sub print_numerical {
	open(HTML_FILE, ">$html_dir/numerical.html");
	open(TXT_FILE, ">$html_dir/numerical.txt");
	############################
	#        Header            #
	############################
	print TXT_FILE "\tCalcHEP Numerical Details\n\n";
	print HTML_FILE "<html>\n";
   print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Numerical Details</title>\n";	
	if (!($_[0]==0.5 or $_[0]==2)){
	  print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
	}
   print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   ############################
   #        Body              #
   ############################
   print HTML_FILE "<body>\n";
   ############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
   
	print HTML_FILE "<div id='main'>\n";
	print HTML_FILE "<h1>Numerical Sessions</h1>\n";
	print HTML_FILE "<h2>$model_name</h2>\n";
	if($_[0]==0){
		print HTML_FILE "<h3>Calculating Cross Sections</h3>\n";
		print TXT_FILE "\tCalculating Cross Sections\n\n";
	}
	elsif($_[0]==0.5){
		print HTML_FILE "<h3>Done!</h3>\n";
		print TXT_FILE "\tDone!\n\n";
	}
	elsif($_[0]==1){
		print HTML_FILE "<h3>Generating Events</h3>\n";
		print TXT_FILE "\tGenerating Events\n\n";
	}
	elsif($_[0]==2){
		print HTML_FILE "<h3>Done!</h3>\n";
		print TXT_FILE "\tDone!\n\n";
	}

   ############################
   #        Processes         #
   ############################
	print HTML_FILE "\t<table>\n";
	print HTML_FILE "\t\t<tr><th>Scans</th><th>&sigma; (fb)</th><th>Running</th><th>Finished</th><th>Time (hr)</th><th>N events</th></tr>\n";
	print TXT_FILE "Scans               sigma (fb)     Running   Finished   Time (hr)   N events\n";
	
	my $tot_time=0;
	if($#step<0){
		my $total_time=0;
		my $running=0;
		my $finished=0;
		my $nevents_total=0;
		my $error="";
		my $cs_total=0;
		my $unc_total=0;
		my $num_subs=$#all_subprocesses;
		if ($_[0]==0){$num_subs=$#all_subprocesses;}
		elsif ($_[0]>0.5){$num_subs=$#all_subprocesses+1;}
		for (my $j=0;$j<=$#subprocesses;$j++){
			$nevents_total += $nevents[$j];
			$cs_total += $cs[$j];
			$unc_total += ($cs[$j]*$unc[$j])*($cs[$j]*$unc[$j]);
		}
		if($#decay_subprocesses<0){$final_cs[0]=$cs_total;}
		for (my $j=0;$j<=$num_subs;$j++){
			if ($begin_times[$j]>0&&$end_times[$j]>$begin_times[$j]){
				my $time = ($end_times[$j] - $begin_times[$j])/3600;
				$total_time += $time;
				$finished++;
			}
			elsif ($end_times[$j] eq "Error"){
				$error="Error";
			}
			elsif ($begin_times[$j]>0){
				my $time = (time() - $begin_times[$j])/3600;
				$total_time += $time;
				$running++;
			}
			
		}
		#Now for the widths
		if ($widths_begin_time>0&&$widths_end_time>$widths_begin_time){
			my $time = ($widths_end_time - $widths_begin_time)/3600;
			$total_time += $time;
			$finished++;
		}
		elsif ($widths_end_time eq "Error"){
			$error="Error";
		}
		elsif ($widths_begin_time>0){
			my $time = (time() - $widths_begin_time)/3600;
			$total_time += $time;
			$running++;
		}
		$tot_time=$total_time;
		my $line;
		if($#decay_subprocesses<0&&$_[0]<1){$line = sprintf("\t\t<tr><td><a href='runs/single.html'>Single</a></td><td>%.5g</td><td>%i/%i</td><td>%i/%i</td><td>%.2f</td><td></td>",
			1000*$final_cs[0],$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
		elsif($_[0]<1){$line = sprintf("\t\t<tr><td><a href='runs/single.html'>Single</a></td><td></td><td>%i/%i</td><td>%i/%i</td><td>%.2f</td><td></td>",
			$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
		else{$line = sprintf("\t\t<tr><td><a href='runs/single.html'>Single</a></td><td>%.5g</td><td>%i/%i</td><td>%i/%i</td><td>%.2f</td><td><a href='$working_dir/batch_results/$event_filenames[0].gz'>%i</a></td>",
			1000*$final_cs[0],$running,$num_subs+1,$finished,$num_subs+1,$total_time,$nevents_final[0]);}
		$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|g;
		if ($error eq "Error"){print HTML_FILE "$line<td>Error</td></tr>\n";}
		else {print HTML_FILE "$line<td></td></tr>\n";}
		if($#decay_subprocesses<0&&$_[0]<1){$line = sprintf("Single              %-15.4e%3i/%-6i%3i/%-7i%-12.2f",
			1000*$final_cs[0],$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
		elsif($_[0]<1){$line = sprintf("Single                             %3i/%-6i%3i/%-7i%-12.2f",
			$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
		else{$line = sprintf("Single              %-15.4e%3i/%-6i%3i/%-7i%-12.2f%i",
			1000*$final_cs[0],$running,$num_subs+1,$finished,$num_subs+1,$total_time,$nevents_final[0]);}
		if ($error eq "Error"){print TXT_FILE "$line\tError\n";}
		else {print TXT_FILE "$line\n";}
		
	}
	elsif($#step>=0) {
		for (my $k=0;$k<=$#step;$k++){
			my @step_tmp = @{$step[$k]};
			my $line = "";
			my $run_html_file = "";
			for (my $l=0;$l<=$#run_param;$l++){
				$line = sprintf("%s%s=%s ",$line, $run_param[$l], 
					$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
				$run_html_file = sprintf("%s%s%s",$run_html_file, $run_param[$l], 
					$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			}
			my $run_html_name=$run_html_file;
			$run_html_file=$run_html_file.".html";
			my $total_time=0;
			my $running=0;
			my $finished=0;
			my $error="";
			my $cs_total=0;
			my $nevents_total=0;
			my $num_subs=$#all_subprocesses;
			if ($_[0]==0){$num_subs=$#all_subprocesses;}
			elsif ($_[0]>0.5){$num_subs=$#all_subprocesses+1;}
			for (my $j=0;$j<=$#subprocesses;$j++){
				$nevents_total += $nevents[$j][$k];
				$cs_total += $cs[$j][$k];
			}
			if($#decay_subprocesses<0){$final_cs[$k]=$cs_total;}
			for (my $j=0;$j<=$num_subs;$j++){
				if ($begin_times[$j][$k]>0&&$end_times[$j][$k]>$begin_times[$j][$k]){
					$time = ($end_times[$j][$k] - $begin_times[$j][$k])/3600;
					$total_time += $time;
					$finished++;
				}
				elsif ($end_times[$j][$k] eq "Error"){
					$error="Error";
				}
				elsif ($begin_times[$j][$k]>0){
					$time = ( time() - $begin_times[$j][$k] )/3600;
					$total_time += $time;
					$running++;
				}
				
			}
			#Now for the widths
			if ($widths_begin_times[$k]>0&&$widths_end_times[$k]>$widths_begin_times[$k]){
				$time = ($widths_end_times[$k] - $widths_begin_times[$k])/3600;
				$total_time += $time;
				$finished++;
			}
			elsif ($widths_end_times[$k] eq "Error"){
				$error="Error";
			}
			elsif ($widths_begin_times[$k]>0){
				$time = ( time() - $widths_begin_times[$k] )/3600;
				$total_time += $time;
				$running++;
			}
			$tot_time = $tot_time + $total_time;
			if($#decay_subprocesses<0&&$_[0]<1){$line = sprintf("\t\t<tr><td><a href='runs/%s'>%s</a></td><td>%.5g</td><td>%i/%i</td><td>%i/%i</td><td>%.2f</td><td></td>",
				$run_html_file,$line,1000*$final_cs[$k],$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
			if($_[0]<1){$line = sprintf("\t\t<tr><td><a href='runs/%s'>%s</a></td><td></td><td>%i/%i</td><td>%i/%i</td><td>%.2f</td><td></td>",
				$run_html_file,$line,$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
			else{$line = sprintf("\t\t<tr><td><a href='runs/%s'>%s</a></td><td>%.5g</td><td>%i/%i</td><td>%i/%i</td><td>%.2f</td><td><a href='$working_dir/batch_results/$event_filenames[$k].gz'>%i</a></td>",
				$run_html_file,$line,1000*$final_cs[$k],$running,$num_subs+1,$finished,$num_subs+1,$total_time,$nevents_final[$k]);}
			$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|g;
			if ($error eq "Error"){print HTML_FILE "$line<td>Error</td></tr>\n";}
			else {print HTML_FILE "$line<td></td></tr>\n";}
			if($#decay_subprocesses<0&&$_[0]<1){$line = sprintf("%-20s%-15.4e%3i/%-6i%3i/%-7i%-12.2f",
				$run_html_name,1000*$final_cs[$k],$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
			elsif($_[0]<1){$line = sprintf("%-20s               %3i/%-6i%3i/%-7i%-12.2f",
				$run_html_name,$running,$num_subs+1,$finished,$num_subs+1,$total_time);}
			else{$line = sprintf("%-20s%-15.4e%3i/%-6i%3i/%-7i%-12.2f%i",
				$run_html_name,1000*$final_cs[$k],$running,$num_subs+1,$finished,$num_subs+1,$total_time,$nevents_final[$k]);}
			if ($error eq "Error"){print TXT_FILE "$line\tError\n";}
			else {print TXT_FILE "$line\n";}
		}
	}	
	my $line = sprintf("\t\t<tr><td></td><td></td><td></td><td></td><td>%.2f</td></tr>\n",$tot_time);
	print HTML_FILE $line;
	$line = sprintf("                                                        %.2f\n",$tot_time);
	print TXT_FILE "$line\n";
	print HTML_FILE "\t</table>\n";

	#Display plot
	print HTML_FILE "\t<img src='../batch_results/$fileName-cs.jpg'><br/><br/><br/>\n";
	print HTML_FILE "\t<p>Remember to clear your web browser cache if the plots are not updating properly.  Also, remember to refresh your browser if you started a new run.</p><br/>\n";


   ############################
   #        Done              #
   ############################
	print HTML_FILE "</div>\n";
   print HTML_FILE "</body>\n";
   print HTML_FILE "</html>\n";
	close(HTML_FILE);
	close(TXT_FILE);
	
	
	
	
	####################################################
	#        Print single numerical                    #
	####################################################
	if($#step<0){
		open(HTML_FILE, ">$html_dir/runs/single.html");
		open(TXT_FILE, ">$html_dir/runs/single.txt");
		############################
		#        Header            #
		############################
		print TXT_FILE "\tCalcHEP Numerical Details\n\n";
		print HTML_FILE "<html>\n";
   	print HTML_FILE "<head>\n";
   	print HTML_FILE "\t<title>CalcHEP Numerical Details</title>\n";
		if (!($_[0]==0.5 or $_[0]==2)){
		  print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
		}
   	print HTML_FILE "\t<link rel='stylesheet' href='../style.css' type='text/css'></link>\n";
		print HTML_FILE "</head>\n";
   	############################
   	#        Body              #
   	############################
   	print HTML_FILE "<body>\n";
   	############################
   	#        Links             #
   	############################
   	print HTML_FILE "\n\n<div id='links'>\n";
   	print HTML_FILE "\t<ul>\n";
   	print HTML_FILE "\t\t<li><a href='../index.html'>Home</a></li>\n";
   	#print HTML_FILE "\t\t<li><a href='../request.html'>Batch Request</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../symbolic.html'>Symbolic Results</a></li>\n";
	print HTML_FILE "\t\t<li><a href='../numerical.html'>Numerical Results</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../events.html'>Events Library</a></li>\n";
		print HTML_FILE "\t\t<li><a href='../library.html'>Process Library</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../help/index.html'>Help</a></li>\n";
   	print HTML_FILE "\t\t<br>\n";
		print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
		print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   	print HTML_FILE "\t</ul>\n";
   	print HTML_FILE "</div>\n\n\n";
   
		print HTML_FILE "<div id='main'>\n";
		print HTML_FILE "<h1>Numerical Sessions</h1>\n";
		print HTML_FILE "<h2>$model_name</h2>\n";
		if($_[0]==0){
			print HTML_FILE "<h3>Calculating Cross Sections</h3>\n";
			print TXT_FILE "\tCalculating Cross Sections\n\n";
		}
		elsif($_[0]==0.5){
			print HTML_FILE "<h3>Done!</h3>\n";
			print TXT_FILE "\tDone!\n\n";
		}

		elsif($_[0]==1){
			print HTML_FILE "<h3>Generating Events</h3>\n";
			print TXT_FILE "\tGenerating Events\n\n";
		}
		elsif($_[0]==2){
			print HTML_FILE "<h3>Done!</h3>\n";
			print TXT_FILE "\tDone!\n\n";
		}

		############################
	   #        Processes         #
   	############################
		print HTML_FILE "\t<table>\n";
		if($_[0]<1){
			print HTML_FILE "\t\t<tr><th>Processes</th><th>&sigma; (fb)</th><th>&Delta;&sigma; (%)</th><th>PID</th><th>Time (hr)</th><th></th><th colspan='2'>Details</th></tr>\n";
			print TXT_FILE "Processes                sigma (fb)     unc (%)   PID       Time (hr)\n";
		}
		else {
			print HTML_FILE "\t\t<tr><th>Processes</th><th>&sigma; (fb)</th><th>&Delta;&sigma; (%)</th><th>PID</th><th>Time (hr)</th><th>N events</th><th colspan='2'>Details</th></tr>\n";
			print TXT_FILE "Processes                sigma (fb)     unc (%)   PID       Time (hr)      N events\n";
		}
		my $time = 0;
		my $total_time=0;
		my $cs_total=0;
		my $unc_total=0;
		my $nevents_total=0;
		my $nevents_finished_total=0;
		my $error = "";
		my $num_subs=$#all_subprocesses;
		if ($_[0]==0){$num_subs=$#all_subprocesses;}
		elsif ($_[0]>0.5){$num_subs=$#all_subprocesses;}
		for(my $j=0;$j<=$#subprocesses;$j++){
			$nevents_total += $nevents[$j];
			$nevents_finished_total += $nevents_finished[$j];
			$cs_total += $cs[$j];
			$unc_total += ($cs[$j]*$unc[$j])*($cs[$j]*$unc[$j]);
		}
		for(my $j=0;$j<=$#subprocesses;$j++){
			$time = 0;
			if ($begin_times[$j]>0&&$end_times[$j]>$begin_times[$j]){
				$time = ($end_times[$j] - $begin_times[$j])/3600;
				$total_time += $time;
			}
			elsif ($end_times[$j] eq "Error"){
				$error="Error";
			}
			elsif ($begin_times[$j]>0){
				$time = (time() - $begin_times[$j])/3600;
				$total_time += $time;
			}
			if ($_[0]<1){
				my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/cs.o'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/session.dat'>session.dat</a></td></tr>\n",
					$all_subprocesses[$j],1000*$cs[$j],$unc[$j],$pids[$j],$time;
				$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
				print HTML_FILE $line;
				printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f\n",
					$all_subprocesses[$j],1000*$cs[$j],$unc[$j],$pids[$j],$time;
			}
			else {
				my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/job.out'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/events_1.txt'>%i/%i</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/session.dat'>session.dat</a></td></tr>\n",
					$all_subprocesses[$j],1000*$cs[$j],$unc[$j],$pids[$j],$time,$nevents_finished[$j],$nevents[$j];
				$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
				print HTML_FILE $line;
				printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f%i/%i\n",
					$all_subprocesses[$j],1000*$cs[$j],$unc[$j],$pids[$j],$time,$nevents_finished[$j],$nevents[$j];
			}		
		}
		my $line="";
		if($cs_total>0) {$unc_total = sqrt($unc_total)/$cs_total;}
		else {$unc_total=0;} 
		if($_[0]<1) {$line = sprintf("\t\t<tr><td>Total</td><td>%.5g</td><td>%.2g</td><td></td><td>%.2f</td><td></td></tr>\n",1000*$cs_total,$unc_total,$total_time);}
		else {$line = sprintf("\t\t<tr><td>Total</td><td>%.5g</td><td>%.2g</td><td></td><td></td></tr>\n",1000*$cs_total,$unc_total);}
		$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
		print HTML_FILE $line;
		if($_[0]<1){$line = sprintf("Total                    %-15.4e%-10.2e                    %-15.2f\n\n",	1000*$cs_total,$unc_total,$total_time);}
		else {$line = sprintf("Total                    %-15.4e%-10.2e\n\n", 1000*$cs_total,$unc_total);}
		print TXT_FILE $line;
		
		
		#Now for the decays
		print HTML_FILE "\t\t<tr><td><br></td></tr>\n";
		if($_[0]<1){
		print HTML_FILE "\t\t<tr><th>Decays</th><th>&Gamma; (GeV)</th><th>&Delta;&Gamma; (%)</th><th>PID</th><th>Time (hr)</th><th></th><th colspan='2'>Details</th></tr>\n";
		print TXT_FILE "Decays                   width (GeV)    unc (%)   PID       Time (hr)\n";
		}
		else{
		print HTML_FILE "\t\t<tr><th>Decays</th><th>&Gamma; (GeV)</th><th>&Delta;&Gamma; (%)</th><th>PID</th><th>Time (hr)</th><th>N events</th><th colspan='2'>Details</th></tr>\n";
		print TXT_FILE "Decays                   width (GeV)    unc (%)   PID       Time (hr)      N events\n";
		}
		for(my $j=$#subprocesses+1;$j<=$num_subs;$j++){
		  $time = 0;
		  if ($begin_times[$j]>0&&$end_times[$j]>$begin_times[$j]){
		    $time = ($end_times[$j] - $begin_times[$j])/3600;
		    $total_time += $time;
		  }
		  elsif ($end_times[$j] eq "Error"){
		    $error="Error";
		  }
		  elsif ($begin_times[$j]>0){
		    $time = (time() - $begin_times[$j])/3600;
		    $total_time += $time;
		  }
		  if($_[0]<1){
		    my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/job.out'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/session.dat'>session.dat</a></td></tr>\n",
		      $all_subprocesses[$j],$cs[$j],$unc[$j],$pids[$j],$time;
		    $line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
		    print HTML_FILE $line;
		    printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f\n",
		      $all_subprocesses[$j],$cs[$j],$unc[$j],$pids[$j],$time;
		  }
		  else{
		    my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/job.out'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/events_1.txt'>%i/%i</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/single/session.dat'>session.dat</a></td></tr>\n",
		      $all_subprocesses[$j],$cs[$j],$unc[$j],$pids[$j],$time,$nevents_finished[$j],$nevents[$j];
		    $line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
		    print HTML_FILE $line;
		    printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f%i/%i\n",
		      $all_subprocesses[$j],$cs[$j],$unc[$j],$pids[$j],$time,$nevents_finished[$j],$nevents[$j];
		  }
		}
		
		if($_[0]>0.5){
			#Now for the widths
			print HTML_FILE "\t\t<tr><td><br></td></tr>\n";
			print HTML_FILE "\t\t<tr><th>Widths</th><th></th><th></th><th>PID</th><th>Time (hr)</th><th></th><th colspan='2'>Details</th></tr>\n";
			print TXT_FILE "\nWidths                                            PID       Time (hr)\n";
			$time = 0;
			if ($widths_begin_time>0&&$widths_end_time>$widths_begin_time){
				$time = ($widths_end_time - $widths_begin_time)/3600;
				$total_time += $time;
			}
			elsif ($widths_end_time eq "Error"){
				$error="Error";
			}
			elsif ($widths_begin_time>0){
				$time = (time() - $widths_begin_time)/3600;
				$total_time += $time;
			}
			
			my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$widths_dir/single/decaySLHA_1.txt'>Widths</a></td><td></td><td></td><td>%i</td><td>%.2f</td><td></td><td></td><td><a href='$working_dir/Processes/$model_dir/$widths_dir/single/session.dat'>session.dat</a></td></tr>\n",
				$widths_pid,$time;
			$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
			print HTML_FILE $line;
			printf TXT_FILE "%-40s          %-10i%-15.2f\n",
				"Widths",$widths_pid,$time;
		
			#Totals
			print HTML_FILE "\t\t<tr><td><br></td></tr>\n";
			my $line = sprintf("\t\t<tr><td>Total</td><td>%.5g</td><td></td><td></td><td>%.2f</td><td><a href='$working_dir/batch_results/$event_filenames[0].gz'>%i/%i</a></td></tr>\n",1000*$final_cs[0],$total_time,$nevents_final[0],$n_events);
			$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
			print HTML_FILE $line;
			$line = sprintf("\nTotal                    %-15.4e                    %-15.2f%i/%i\n\n",1000*$final_cs[0], $total_time,$nevents_final[0],$n_events);
			print TXT_FILE $line;
		}
		print HTML_FILE "\t</table>\n\n";
		
		#Display plots
		print HTML_FILE "\t<h2>Distributions</h2>\n";
		@tmp_plot_filenames = @{$plot_filenames[0]};
		foreach my $filename (@tmp_plot_filenames){
			print HTML_FILE "\t<img src='../../batch_results/$filename'><br>\n";
		}
		print HTML_FILE "\t<p>Remember to clear your web browser cache if the plots are not updating properly.  Also, remember to refresh your browser if you started a new run.</p>\n";

	   ############################
	   #        Done              #
	   ############################
		print HTML_FILE "</div>\n";
	   print HTML_FILE "</body>\n";
	   print HTML_FILE "</html>\n";
		close(HTML_FILE);
		close(TXT_FILE);
	}
	####################################################
	#        Print run numerical                       #
	####################################################
	else {for (my $k=0;$k<=$#step;$k++){
		my @step_tmp = @{$step[$k]};
		my $line = "";
		my $run_html_file = "";
		my $subdir_name = "";
		for (my $l=0;$l<=$#run_param;$l++){
			$line = sprintf("%s%s=%s ",$line, $run_param[$l], 
				$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			$run_html_file = sprintf("%s%s%s",$run_html_file, $run_param[$l], 
				$run_begin[$l]+$run_step[$l]*$step_tmp[$l]);
			$subdir_name = $run_html_file;
		}
		open(TXT_FILE, ">$html_dir/runs/$run_html_file.txt");
		$run_html_file=$run_html_file.".html";
		open(HTML_FILE, ">$html_dir/runs/$run_html_file");
		############################
		#        Header            #
		############################
		print TXT_FILE "\tCalcHEP Numerical Details\n\n";
		print HTML_FILE "<html>\n";
   	print HTML_FILE "<head>\n";
   	print HTML_FILE "\t<title>CalcHEP Numerical Details</title>\n";
		if (!($_[0]==0.5 or $_[0]==2)){
		  print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
		}
   	print HTML_FILE "\t<link rel='stylesheet' href='../style.css' type='text/css'></link>\n";
		print HTML_FILE "</head>\n";
   	############################
   	#        Body              #
   	############################
   	print HTML_FILE "<body>\n";
   	############################
   	#        Links             #
   	############################
   	print HTML_FILE "\n\n<div id='links'>\n";
   	print HTML_FILE "\t<ul>\n";
   	print HTML_FILE "\t\t<li><a href='../index.html'>Home</a></li>\n";
   	#print HTML_FILE "\t\t<li><a href='../request.html'>Batch Request</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../symbolic.html'>Symbolic Results</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../numerical.html'>Numerical Results</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../events.html'>Events Library</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../library.html'>Process Library</a></li>\n";
   	print HTML_FILE "\t\t<li><a href='../help/index.html'>Help</a></li>\n";
   	print HTML_FILE "\t\t<br>\n";
		print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
		print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   	print HTML_FILE "\t</ul>\n";
   	print HTML_FILE "</div>\n\n\n";
   
		print HTML_FILE "<div id='main'>\n";
		print HTML_FILE "<h1>Numerical Sessions</h1>\n";
		print HTML_FILE "<h2>$model_name</h2>\n";
		if($_[0]==0){
			print HTML_FILE "<h3>Calculating Cross Sections</h3>\n";
			print TXT_FILE "\tCalculating Cross Sections\n\n";
		}
		elsif($_[0]==0.5){
			print HTML_FILE "<h3>Done!</h3>\n";
			print TXT_FILE "\tDone!\n\n";
		}
		elsif($_[0]==1){
			print HTML_FILE "<h3>Generating Events</h3>\n";
			print TXT_FILE "\tGenerating Events\n\n";
		}
		elsif($_[0]==2){
			print HTML_FILE "<h3>Done!</h3>\n";
			print TXT_FILE "\tDone!\n\n";
		}

		############################
	   #        Processes         #
   	############################
		print HTML_FILE "\t<table>\n";
		if($_[0]<1){
			print HTML_FILE "\t\t<tr><th>Processes</th><th>&sigma; (fb)</th><th>&Delta;&sigma; (%)</th><th>PID</th><th>Time (hr)</th><th></th><th colspan='2'>Details</th></tr>\n";
			print TXT_FILE "Processes                sigma (fb)     unc (%)   PID       Time (hr)\n";
		}
		else {
			print HTML_FILE "\t\t<tr><th>Processes</th><th>&sigma; (fb)</th><th>&Delta;&sigma; (%)</th><th>PID</th><th>Time (hr)</th><th>N events</th><th colspan='2'>Details</th></tr>\n";
			print TXT_FILE "Processes                sigma (fb)     unc (%)   PID       Time (hr)      N events\n";
		}
		my $time = 0;
		my $total_time=0;
		my $cs_total=0;
		my $unc_total=0;
		my $nevents_total=0;
		my $nevents_finished_total=0;
		my $error = "";
		my $num_subs=$#all_subprocesses;
		if ($_[0]==0){$num_subs=$#all_subprocesses;}
		elsif ($_[0]>0.5){$num_subs=$#all_subprocesses;}
		for(my $j=0;$j<=$#subprocesses;$j++){
			$nevents_total += $nevents[$j][$k];
			$nevents_finished_total += $nevents_finished[$j][$k];
			$cs_total += $cs[$j][$k];
			$unc_total += ($cs[$j][$k]*$unc[$j][$k])*($cs[$j][$k]*$unc[$j][$k]);
		}
		for(my $j=0;$j<=$#subprocesses;$j++){
			$time = 0;
			if ($begin_times[$j][$k]>0&&$end_times[$j][$k]>$begin_times[$j][$k]){
				$time = ($end_times[$j][$k] - $begin_times[$j][$k])/3600;
				$total_time += $time;
			}
			elsif ($end_times[$j][$k] eq "Error"){
				$error="Error";
			}
			elsif ($begin_times[$j][$k]>0){
				$time = (time() - $begin_times[$j][$k])/3600;
				$total_time += $time;
			}
			if ($_[0]<1){
				my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/cs.o'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/session.dat'>session.dat</a></td></tr>\n",
					$all_subprocesses[$j],1000*$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time;
				$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
				print HTML_FILE $line;
				printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f\n",
					$all_subprocesses[$j],1000*$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time;
			}
			else {
				my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/job.out'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/events_1.txt'>%i/%i</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/session.dat'>session.dat</a></td></tr>\n",
					$all_subprocesses[$j],1000*$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time,$nevents_finished[$j][$k],$nevents[$j][$k];
				$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
				print HTML_FILE $line;
				printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f%i/%i\n",
					$all_subprocesses[$j],1000*$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time,$nevents_finished[$j][$k],$nevents[$j][$k];
			}
			
		}
		my $line="";
		if($cs_total>0) {$unc_total = sqrt($unc_total)/$cs_total;}
		else {$unc_total=0;}
		if($_[0]<1) {$line = sprintf("\t\t<tr><td>Total</td><td>%.5g</td><td>%.2g</td><td></td><td>%.2f</td><td></td></tr>\n",1000*$cs_total,$unc_total,$total_time);}
		else {$line = sprintf("\t\t<tr><td>Total</td><td>%.5g</td><td>%.2g</td><td></td><td></td></tr>\n",1000*$cs_total,$unc_total);}
		$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
		print HTML_FILE $line;
		if($_[0]<1){$line = sprintf("Total                    %-15.4e%-10.2e                    %-15.2f\n\n",	1000*$cs_total,$unc_total,$total_time);}
		else {$line = sprintf("Total                    %-15.4e%-10.2e\n\n", 1000*$cs_total,$unc_total,$total_time);}
		print TXT_FILE $line;
		
		
		#Now for the decays
		print HTML_FILE "\t\t<tr><td><br></td></tr>\n";
		if($_[0]<1){
		  print HTML_FILE "\t\t<tr><th>Decays</th><th>&Gamma; (GeV)</th><th>&Delta;&Gamma; (%)</th><th>PID</th><th>Time (hr)</th><th></th><th colspan='2'>Details</th></tr>\n";
		  print TXT_FILE "Decays                   width (GeV)    unc (%)   PID       Time (hr)\n";
		}
		else{
		  print HTML_FILE "\t\t<tr><th>Decays</th><th>&Gamma; (GeV)</th><th>&Delta;&Gamma; (%)</th><th>PID</th><th>Time (hr)</th><th>N events</th><th colspan='2'>Details</th></tr>\n";
		  print TXT_FILE "Decays                   width (GeV)    unc (%)   PID       Time (hr)      N events\n";
		}
		for(my $j=$#subprocesses+1;$j<=$num_subs;$j++){
		  $time = 0;
		  if ($begin_times[$j][$k]>0&&$end_times[$j][$k]>$begin_times[$j][$k]){
		    $time = ($end_times[$j][$k] - $begin_times[$j][$k])/3600;
		    $total_time += $time;
		  }
		  elsif ($end_times[$j][$k] eq "Error"){
		    $error="Error";
		  }
		  elsif ($begin_times[$j][$k]>0){
		    $time = (time() - $begin_times[$j][$k])/3600;
		    $total_time += $time;
		  }
		  if($_[0]<1){
		    my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/job.out'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/session.dat'>session.dat</a></td></tr>\n",
		      $all_subprocesses[$j],$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time;
		    $line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
		    print HTML_FILE $line;
		    printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f\n",
		      $all_subprocesses[$j],$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time;
		  }
		  else{
		    my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/job.out'>%s</a></td><td>%.5g</td><td>%.2g</td><td>%i</td><td>%.2f</td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/events_1.txt'>%i/%i</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/prt_1'>prt_1</a></td><td><a href='$working_dir/Processes/$model_dir/$all_subproc_dir[$j]/$subdir_name/session.dat'>session.dat</a></td></tr>\n",
		      $all_subprocesses[$j],$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time,$nevents_finished[$j][$k],$nevents[$j][$k];
		    $line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
		    print HTML_FILE $line;
		    printf TXT_FILE "%-25s%-15.4e%-10.2e%-10i%-15.2f%i/%i\n",
		      $all_subprocesses[$j],$cs[$j][$k],$unc[$j][$k],$pids[$j][$k],$time,$nevents_finished[$j][$k],$nevents[$j][$k];
		  }
		  
		}
			
		if($_[0]>0.5){
			#Now for the widths
			print HTML_FILE "\t\t<tr><td><br></td></tr>\n";
			print HTML_FILE "\t\t<tr><th>Widths</th><th></th><th></th><th>PID</th><th>Time (hr)</th><th></th><th colspan='2'>Details</th></tr>\n";
			print TXT_FILE "\nWidths                                            PID       Time (hr)\n";
			$time = 0;
			if ($widths_begin_times[$k]>0&&$widths_end_times[$k]>$widths_begin_times[$k]){
				$time = ($widths_end_times[$k] - $widths_begin_times[$k])/3600;
				$total_time += $time;
			}
			elsif ($widths_end_times[$k] eq "Error"){
				$error="Error";
			}
			elsif ($widths_begin_times[$k]>0){
				$time = (time() - $widths_begin_times[$k])/3600;
				$total_time += $time;
			}
			my $line = sprintf "\t\t<tr><td><a href='$working_dir/Processes/$model_dir/$widths_dir/$subdir_name/decaySLHA_1.txt'>Widths</a></td><td></td><td></td><td>%i</td><td>%.2f</td><td></td><td></td><td><a href='$working_dir/Processes/$model_dir/$widths_dir/$subdir_name/session.dat'>session.dat</a></td></tr>\n",
				$widths_pids[$k],$time;
			$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
			print HTML_FILE $line;
			printf TXT_FILE "%-25s                         %-10i%-15.2f\n",
				"Widths",$widths_pids[$k],$time;
			
		
			#Totals
			print HTML_FILE "\t\t<tr><td><br></td></tr>\n";
			my $line = sprintf("\t\t<tr><td>Total</td><td>%.5g</td><td></td><td></td><td>%.2f</td><td><a href='$working_dir/batch_results/$event_filenames[$k].gz'>%i/%i</a></td></tr>\n",1000*$final_cs[$k],$total_time,$nevents_final[$k],$n_events);
			$line =~ s|e([\+\-][0-9]+)| x10<sup>$1<\/sup>|;
			print HTML_FILE $line;
			$line = sprintf("\n%-25s%-15.4e                    %-15.2f%i/%i\n\n","Total",1000*$final_cs[$k], $total_time,$nevents_final[$k],$n_events);
			print TXT_FILE $line;
		}		
		
		
		print HTML_FILE "\t</table>\n";


		#Display plots
		print HTML_FILE "\t<h2>Distributions</h2>\n";
		@tmp_plot_filenames = @{$plot_filenames[$k]};
		foreach my $filename (@tmp_plot_filenames){
			print HTML_FILE "\t<img src='../../batch_results/$filename'><br>\n";
		}
		print HTML_FILE "\t<p>Remember to clear your web browser cache if the plots are not updating properly.  Also, remember to refresh your browser if you started a new run.</p>\n";

		
	   ############################
	   #        Done              #
	   ############################
		print HTML_FILE "</div>\n";
	   print HTML_FILE "</body>\n";
	   print HTML_FILE "</html>\n";
		close(HTML_FILE);
		close(TXT_FILE);
	}}
};




####################################################
#            Print particle not found              #
####################################################
sub print_particle_not_found {
	open(HTML_FILE, ">$html_dir/index.html");
	print HTML_FILE "<html>\n";
   print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Batch Details</title>\n";
   print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
    print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   print HTML_FILE "<body>\n";
	############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
	
	print HTML_FILE "<div id='main'>\n";
  	print HTML_FILE "<h1>Particle Not Found</h1>\n";
   print HTML_FILE "<h2>Particle '$_[0]' was not found in '$model_name' model.</h2>\n";
   print HTML_FILE "<p>Please check the batch file and make sure it is correct.</p>\n";
	print HTML_FILE "</div>\n";
	print HTML_FILE "</body></html>\n";
	close(HTML_FILE);
};

####################################################
#                 Print No Batch File              #
####################################################
sub print_no_batch_file {
	open(HTML_FILE, ">$html_dir/index.html");
	print HTML_FILE "<html>\n";
   print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Batch Details</title>\n";
   print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
    print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   print HTML_FILE "<body>\n";
	############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
	print HTML_FILE <<END_HTML;
	<div id='help_main'>
	<h1>Missing Batch File</h1>
	<p>
		Batch file '$batch_file_name' could not be found.  Please refer to the <a href='help/index.html'>help section</a>`.
	</p>
	</div>
	</body></html>
END_HTML
	
	print "\n\nMissing Batch File\n\n";
	print "\tBatch file '$batch_file_name' could not be found.\n";
   print "\tPlease refer to the html help files found in:\n";
   print "\tfile://${working_dir}/html/help/index.html\n\n";
};


####################################################
#                 Print Model Changed              #
####################################################
sub print_model_changed {
	open(HTML_FILE, ">$html_dir/index.html");
	print HTML_FILE "<html>\n";
   print HTML_FILE "<head>\n";
   print HTML_FILE "\t<title>CalcHEP Batch Details</title>\n";
   print HTML_FILE "\t<meta http-equiv='refresh' content='$sleep_time'>\n";
    print HTML_FILE "\t <link rel='stylesheet' href='style.css' type='text/css'></link>\n";
	print HTML_FILE "</head>\n";
   print HTML_FILE "<body>\n";
	############################
   #        Links             #
   ############################
   print HTML_FILE "\n\n<div id='links'>\n";
   print HTML_FILE "\t<ul>\n";
   print HTML_FILE "\t\t<li><a href='index.html'>Home</a></li>\n";
   #print HTML_FILE "\t\t<li><a href='request.html'>Batch Request</a></li>\n";
   print HTML_FILE "\t\t<li><a href='symbolic.html'>Symbolic Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='numerical.html'>Numerical Results</a></li>\n";
   print HTML_FILE "\t\t<li><a href='events.html'>Events Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='library.html'>Process Library</a></li>\n";
   print HTML_FILE "\t\t<li><a href='help/index.html'>Help</a></li>\n";
   print HTML_FILE "\t\t<br>\n";
	print HTML_FILE "\t\t<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>\n";
	print HTML_FILE "\t\t<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>\n";
   print HTML_FILE "\t</ul>\n";
   print HTML_FILE "</div>\n\n\n";
	
	print HTML_FILE "<div id='help_main'>\n";
   print HTML_FILE "<h1>Model Changed</h1>\n";
   print HTML_FILE "<h2>Model changed was set to true</h2>\n";
   print HTML_FILE "<p>If the model was changed, the process library has to be deleted and redone.</p>\n";
   print HTML_FILE "<p>If the only changes to the model were changes in the numerical values of the ".
   	"variables, this does not require the process library to be deleted and redone.  If this is the ".
   	"only change, you can set 'Model changed' to 'No' or 'False' and rerun this program.</p>\n";
   print HTML_FILE "<p>If, on the other hand, changes were made to particles, constraints or vertices, the process library for this model must be deleted and redone.  To do this, delete the directory</p><center>$working_dir/Processes/$model_dir/.</center><p>After deleting this directory, set 'Model changed' to 'No' or 'False' and rerun this program.</p>\n";
   print HTML_FILE "</div>\n";
	print HTML_FILE "</body></html>\n";
	close(HTML_FILE);
	
	
	print "\n\nModel Changed\n\n";
	print "\tModel changed was set to true in the batch file.\n";
	print "\tIf the model was changed, the process library\n";
	print "\t\thas to be deleted and redone.\n";
	print "\tIf the only changes to the model were changes\n";
	print "\t\tin the numerical values of the variables,\n";
	print "\t\tthis does not require the process library to\n";
	print "\t\tbe deleted and redone.  If this is the only change,\n";
	print "\t\tyou can set 'Model changed' to 'No' or 'False'\n";
	print "\t\tand rerun this program.\n";
	print "\tIf, on the other hand, changes were made to particles,\n";
	print "\t\tconstraints or vertices, the process library for\n";
	print "\t\tthis model must be deleted and redone.  To do this,\n";
	print "\t\tdelete the directory:\n";
	print "\t\t$working_dir/Processes/$model_dir/\n";
	print "\t\tAfter deleting this directory, set 'Model changed'\n";
	print "\t\tto 'No' or 'False' and rerun this program.\n\n";
   print "\tPlease refer to the html help files found in:\n";
   print "\tfile://${working_dir}/html/help/index.html\n\n";
};




####################################################
#                 Print Help                       #
####################################################
sub print_help_batch_links {
	open(HTML_FILE, ">$_[0]");
	print HTML_FILE <<ENDHTML;
<html>
<head>
	<title>CalcHEP Batch Help</title>
	<link rel='stylesheet' href='../style.css' type='text/css'></link>
</head>
<body>
	<div id='links'>
		<ul>
			<li><a href='../index.html'>Home</a></li>
			<li><a href='../symbolic.html'>Symbolic Results</a></li>
			<li><a href='../numerical.html'>Numerical Results</a></li>
			<li><a href='../events.html'>Events Library</a></li>
			<li><a href='../library.html'>Process Library</a></li>
			<li><a href='index.html'>Help</a>
				<ul>
					<li><a href='batch_file.html'>Batch File</a><ul>
						<li><a href='comment.html'>Comments</a></li>
						<li><a href='model.html'>Model</a></li>
						<li><a href='process.html'>Process</a></li>
						<li><a href='pdf.html'>PDF</a></li>
						<li><a href='momentum.html'>Momentum</a></li>
						<li><a href='parameters.html'>Parameters</a></li>
						<li><a href='runs.html'>Scans</a></li>
						<li><a href='qcd.html'>QCD</a></li>
                                                <li><a href='BW.html'>BW</a></li>
						<li><a href='cuts.html'>Cuts</a></li>
						<li><a href='kinematics.html'>Kinematics</a></li>
						<li><a href='regularization.html'>Regularization</a></li>
						<li><a href='distributions.html'>Distribution</a></li>
						<li><a href='events.html'>Events</a></li>
						<li><a href='parallelization.html'>Parallelization</a></lii>
						<li><a href='vegas.html'>Vegas</a></li>
						<li><a href='generator.html'>Generator</a></li>
						<li><a href='example1.html'>Example 1</a></li>
						<li><a href='example2.html'>Example 2</a></li>
						<li><a href='example3.html'>Example 3</a></li>
					</ul></li>
					<li><a href='process_library.html'>Process Library</a></li>
					<li><a href='event_library.html'>Event Library</a></li>
				</ul>
			</li>
			<br>
			<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>
			<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>
		</ul>
	</div>
ENDHTML
	close(HTML_FILE);
}
sub print_help {
	print_help_index();
	print_help_batch_file();
	print_help_comments();
	print_help_model();
	print_help_process();
	print_help_pdf();
	print_help_momentum();
	print_help_parameters();
	print_help_runs();
	print_help_qcd();
	print_help_BW();
	print_help_cuts();
	print_help_kinematics();
	print_help_regularization();
	print_help_distributions();
	print_help_events();
	print_help_parallelization();
	print_help_vegas();
	print_help_generator();
	print_help_example1();
	print_help_example2();
	print_help_example3();
	print_help_process_library();
	print_help_event_library();
}

sub print_help_index {
	open(HTML_FILE, ">$html_dir/help/index.html");
	print HTML_FILE <<ENDHTML;
<html>
<head>
	<title>CalcHEP Batch Help</title>
	<link rel='stylesheet' href='../style.css' type='text/css'></link>
</head>
<body>
	<div id='links'>
		<ul>
			<li><a href='../index.html'>Home</a></li>
			<li><a href='../symbolic.html'>Symbolic Results</a></li>
			<li><a href='../numerical.html'>Numerical Results</a></li>
			<li><a href='../events.html'>Events Library</a></li>
			<li><a href='../library.html'>Process Library</a></li>
			<li><a href='index.html'>Help</a>
				<ul>
					<li><a href='batch_file.html'>Batch File</a></li>
					<li><a href='process_library.html'>Process Library</a></li>
					<li><a href='event_library.html'>Event Library</a></li>
				</ul>
			</li>
			<br>
			<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>
			<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>
		</ul>
	</div>	
	<div id='help_main'>
		<h1>Help</h1>
		<h3>Running</h3>
		<p>
			The batch script can be run in two ways.  It can be run directly from the run_batch perl script located in the bin directory as in
			<table>
				<tr><td>bin/./run_batch batch_file</td></tr>
			</table>
			where batch_file is the file that contains the instructions for the batch script.  If this method is used, the environment variable \$CALCHEP must first be set which refers to the CalcHEP main directory.  The batch script can also be invoked with the calchep_batch shell script in the users directory as in
			<table>
				<tr><td>./calchep_batch batch_file</td></tr>
			</table>
			where, again, batch_file is the file that contains the instructions for the batch script.  The default calchep_batch shell script automatically sets the \$CALCHEP environment variable and then invokes run_batch from the bin directory.  As the batch script runs, it continuously updates these html files with the current progress of the batch.  The frequency of the updates can be set in the batch file with the key phrase <a href='parallelization.html'>"sleep time"</a>.
		</p>
		<h3>Help Topics</h3>
		<p>
			Please choose the help topic from the menu on the left.
		</p>
                <h3>Warning</h3>
                <p>Please, please, please check the prt_1 files to make sure that the parameters, cuts, scales, etc. are exactly the way you intended.</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}

sub print_help_batch_file {
	print_help_batch_links("$html_dir/help/batch_file.html");
	open(HTML_FILE, ">>$html_dir/help/batch_file.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Batch File Help</h1>
		<p>
			This script is designed to be used in batch mode.  All the information about the batch is included by the user in a batch file.  The batch file can be named anything the user likes and is specified as the first argument of the batch script.  Most of the information available in CalcHEP is available in the batch file.  We describe each section of the batch file in these help files.  You can access each one by clicking on the links to the left.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_comments {
	print_help_batch_links("$html_dir/help/comment.html");
	open(HTML_FILE, ">>$html_dir/help/comment.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Comment Help</h1>
		<p>
			Any line beginning with a # is ignored by run_batch.  The # has to be at the very beginning of the line.  Some examples are:<br>
		<table>
			<tr><td># This is ignored.</td></tr>
			<tr><td>#Model:         Standard Model	   This is ignored.</td></tr>
			<tr><td>Model:     #   Standard Model(CKM=1)    This is not ignored.</td></tr>
		</table>
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}

sub print_help_model {
	print_help_batch_links("$html_dir/help/model.html");
	open(HTML_FILE, ">>$html_dir/help/model.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Model Help</h1>
		<h3>Model</h3>
		<p>
			The first section of the batch file should contain the specification of the model.  This is done by model name and should match exactly the name in the CalcHEP model list.  So, if you want to scan the \"Standard Model(CKM=1)\", you would specify this with the batch file line:<br>
			<table>
				<tr><td>Model</td><td>:</td><td>Standard Model(CKM=1)</td></tr>
			</table>
			There is no default for this line.  It must be included.
			<h3>Gauge</h3>
                </p>
		<p>
		The gauge of the calculation should also be specified in this section.  Choices are Feynman and unitary gauge.  CalcHEP is much better suited to calculation in Feynman gauge, but there may be times that unitary gauge is useful.  This can be specified using the keyword \"Gauge\" as in:<br>
			<table>
				<tr><td>Gauge</td><td>:</td><td>unitary</td></tr>
			</table>
			The default is Feynman.
		</p>
                <h3>Virtual W/Z Decays</h3>
               <p>
               CalcHEP allows decays of particle such as the Higgs to decay via off-shell W and Z bosons.  This behavior can be controled by the key phrase "Virtual W/Z decays" as in:
               <table>
                       <tr><td>Virtual W/Z decays : Off</td></tr>
               </table>
               The default is "On".
               </p>
                <h3>SLHA Widths</h3>
               <p>
               CalcHEP allows the use of SLHA widths to be used.  It can be turned off, and CalcHEP will use its built-in width calculator instead, as in:
               <table>
                       <tr><td>SLHA Widths : Off</td></tr>
               </table>
               The default is "On".
               </p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_process {
	print_help_batch_links("$html_dir/help/process.html");
	open(HTML_FILE, ">>$html_dir/help/process.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Process Help</h1>
		<h3>Process</h3>
		<p>
			Processes are specified using the \"Process\" keyword and standard CalcHEP notation as in:<br>
			<table>
				<tr><td>Process</td><td>:</td><td>p,p->j,l,l</td></tr>
			</table>
			Multiple processes can also be specified as in:<br>
			<table>
				<tr><td>Process</td><td>:</td><td>p,p->E,ne</td></tr>
				<tr><td>Process</td><td>:</td><td>p,p->M,nm</td></tr>
			</table>
			As many processes as desired can be specified.  When more than one process is specified, the processes are numbered by the order in which they are specified in the batch file.  So, in this example, p,p->E,ne is process 1 and p,p->M,nm is process 2.  This numbering can be useful when specifying <a href='qcd.html'>QCD scale</a>, <a href='cuts.html'>cuts</a>, <a href='kinematics.html'>kinematics</a>, <a href='regularization.html'>regularization</a> and <a href='distributions.html'>distributions</a> allowing these to be specified separately for each process.  There is no default for this keyword.  It must be specified.
		</p>
                <p>
                       If initial particles are polarized (and the particles are massless), the user can include the \"%\" symbol as in a gui session.  So, polarized e<sup>+</sup>, e<sup>-</sup> collisions can be specified as:<br>
			<table>
				<tr><td>Process</td><td>:</td><td>e%,E%->A,A</td></tr>
			</table>
                       In this case, the user can can take advantage of the keywords \"Polarization1\" and \"Polarization2\" to set the <a href='pdf.html'>polarizations</a>.  The values should be the same as used in the gui.  The default is no polarization.
                </p>
		<h3>Decay</h3>
		<p>
			Decays are specified using the \"Decay\" keyword and are also in standard CalcHEP notation as in:<br>
			<table>
				<tr><td>Decay</td><td>:</td><td>W->l,nu</td></tr>
			</table>
			Again, multiple decays can be specified as in:<br>
			<table>
				<tr><td>Decay</td><td>:</td><td>W->l,nu</td></tr>
				<tr><td>Decay</td><td>:</td><td>Z->l,l</td></tr>
			</table>
			The default is to not have any decays.  <a href='cuts.html'>Cuts</a> and <a href='distributions.html'>distributions</a> do not apply to decays, however, <a href='kinematics.html'>kinematics</a>, and <a href='regularization.html'>regularization</a> do.
		</p>
		<h3>Alias</h3>
		<p>
			It is sometimes convenient to specify groups of particles as in the particles that compose the proton or all the leptons.  This can be done with the keyword \"Alias\" as in:<br>
			<table>
				<tr><td>Alias</td><td>:</td><td>p=u,d,U,D,G</td></tr>
				<tr><td>Alias</td><td>:</td><td>l=e,E,m,M</td></tr>
				<tr><td>Alias</td><td>:</td><td>nu=ne,Ne,nm,Nm</td></tr>
				<tr><td>Alias</td><td>:</td><td>W=W+,W-</td></tr>
			</table>
			As many composite particles as necessary can be specified.  These definitions can be used in <a href='cuts.html'>cuts</a> and <a href='distributions.html'>distributions</a> as well as in the processes and decays.  The default is not to have any composite definitions.
			
		</p>
		<h3>Remove</h3>
		<p>
			It is sometimes necessary to remove particles from internal lines of the diagrams. This can be done with the keyword \"Remove\" as in:<br>
			<table>
				<tr><td>Remove</td><td>:</td><td>W+>2,Z</td></tr>
			</table>
			The notation is the same as in the graphical interface and is used in the symbolic session of productions processes directly without any modifications.  For decays, the keyword is \"Remove Decay\" as in:<br>
                        <table>
				<tr><td>Remove Decay</td><td>:</td><td>Z,H</td></tr>
			</table>
                        Aliases can not be used in Remove statements.  We would like to stress that the user should use these keywords with great care as violation of gauge invariance could occur ruining important cancellations between diagrams.
			
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_pdf {
	print_help_batch_links("$html_dir/help/pdf.html");
	open(HTML_FILE, ">>$html_dir/help/pdf.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>PDF Help</h1>
		<h3>PDF</h3>
		<p>
			The PDF of a proton or antiproton can be specified with the \"pdf1\" and \"pdf2\" kewords which correspond to the pdfs of the first and second incoming particles respectively.  Choices for these keywords are:<br>
			<table>
				<tr><td>cteq6l (anti-proton)    </td></tr>
		   	<tr><td>cteq6l (proton)         </td></tr>
    			<tr><td>mrst2002lo (anti-proton)</td></tr>
    			<tr><td>mrst2002lo (proton)     </td></tr>
    			<tr><td>cteq6m (anti-proton)    </td></tr>
    			<tr><td>cteq6m (proton)         </td></tr>
    			<tr><td>cteq5m (anti-proton)    </td></tr>
    			<tr><td>cteq5m (proton)         </td></tr>
    			<tr><td>mrst2002nlo (anti-proton)</td></tr>
    			<tr><td>mrst2002nlo (proton)    </td></tr>
    			<tr><td>None                    </td></tr>
    		</table>
    		An example for the LHC is:<br>
    		<table>
    			<tr><td>pdf1</td><td>:</td><td>cteq6l (proton)</td></tr>
    			<tr><td>pdf2</td><td>:</td><td>cteq6l (proton)</td></tr>
    		</table>
    		The default is none.  These keywords can also be used for electron positron colliders.  For this process the available pdfs are:<br>
    		<table>
    			<tr><td>ISR                     </td></tr>
    			<tr><td>ISR & Beamstrahlung     </td></tr>
    			<tr><td>Equiv. Photon           </td></tr>
    			<tr><td>Laser photons           </td></tr>
    			<tr><td>None                    </td></tr>
    		</table>
    		The following proton electron collider pdf is also available:<br>
    		<table>
    			<tr><td>Proton Photon           </td></tr>
    		</table>
    		All of these pdfs must be typed exactly or copied into the batch file.  
		</p>
		<h3>Bunch Specification</h3>
		<p>
			If \"ISR & Beam\" is chosen, then the following beam parameters may be specified:<br>
    		<table>
    			<tr><td>Bunch x+y sizes (nm)</td><td>:</td><td>550</td></tr>
    			<tr><td>Bunch length (mm)</td><td>:</td><td>0.45</td></tr>
				<tr><td>Number of particles</td><td>:</td><td>2.1E+10</td></tr>
			</table>
    		The default values are the default values in CalcHEP and correspond roughly with the ILC.
    	</p>
		<h3>Equiv. Photon</h3>
		<p>
			If \"Equiv. Photon\" is chosen for the pdf, then the following parameters may be specified:<br>
			<table>
				<tr><td>Photon particle</td><td>:</td><td>e^-</td></tr>
				<tr><td>|Q|max</td><td>:</td><td>150</td></tr>
			</table>
			Choices for the \"Photon particle\" keyphrase are mu^-, e^-, e^+, mu^+.  The default is e^+.  The default for the keyword \"|Q|max\" is the same as in CalcHEP.
		</p>
		<h3>Proton Photon</h3>
		<p>
			If \"Proton Photon\" is chosen then the following may be specified:<br>
			<table>
				<tr><td>Incoming particle mass</td><td>:</td><td>0.937</td></tr>
				<tr><td>Incoming particle charge</td><td>:</td><td>-1</td></tr>
				<tr><td>|Q^2|max</td><td>:</td><td>2.1</td></tr>
				<tr><td>Pt cut of outgoing proton</td><td>:</td><td>0.11</td></tr>
			</table>
			The defaults are the same as in CalcHEP.
		</p>
		<h3>Polarizations</h3>
		<p>
			If the initial particles are to be polarized and the process was specified using the \"%\" symbol as described in <a href='process.html'>Processes</a>, then the polarization of the beams can be specified using the \"Polarization1\" and \"Polarization2\" keywords as in:<br>
			<table>
				<tr><td>Polarization1</td><td>:</td><td>0.5</td></tr>
				<tr><td>Polarization2</td><td>:</td><td>-0.5</td></tr>
			</table>
			The allowed values and defaults are the same as in CalcHEP.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_momentum {
	print_help_batch_links("$html_dir/help/momentum.html");
	open(HTML_FILE, ">>$html_dir/help/momentum.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Momentum Help</h1>
		<h3>Momentum</h3>
		<p>
			The momentum of the incoming states can be specified with the keywords \"p1\" and \"p2\" and are in GeV as in:<br>
			<table>
				<tr><td>p1</td><td>:</td><td>7000</td></tr>
				<tr><td>p2</td><td>:</td><td>7000</td></tr>
			</table>
			These are the default values for the momenta.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_parameters {
	print_help_batch_links("$html_dir/help/parameters.html");
	open(HTML_FILE, ">>$html_dir/help/parameters.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Parameter Help</h1>
		<h3>Parameter</h3>
		<p>
			The parameters of the model are taken from the varsN.mdl file in the models directory.  Other parameter values can be used if specified using the \"Parameter\" keyword.  Here is an example:<br>
			<table>
				<tr><td>Parameter</td><td>:</td><td>EE=0.31</td></tr>
				<tr><td>Parameter</td><td>:</td><td>SW=0.481</td></tr>
				<tr><td>Parameter</td><td>:</td><td>MZ=91.1884</td></tr>
				<tr><td>Parameter</td><td>:</td><td>wW=2.08895</td></tr>
			</table>
			Any parameters not specified using this keyword in the batch file will be taken from the varsN.mdl file in the models directory.  This gives a convenient way of changing the default values of the parameters.  Simply open CalcHEP in symbolic mode, choose to edit the model and change the values of the indepenedent parameters.  These new values will then become the default values used by this batch program.  There is no need to redo the process library.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_runs {
	print_help_batch_links("$html_dir/help/runs.html");
	open(HTML_FILE, ">>$html_dir/help/runs.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Scan Help</h1>
		<h3>Scans</h3>
		<p>
			In some models it is useful to scan over a parameter such as the mass of one of the new particles.  For example, if there is a new W' gauge boson, it may be desireable to generate events and/or distributions for a range of masses for the W'.  This can be done with the \"Scan parameter\", \"Scan begin\", \"Scan step size\" and \"Scan n steps\" keyphrases.  Here is an example:<br>
			<table>
				<tr><td>Scan parameter</td><td>:</td><td>MWP</td></tr>
				<tr><td>Scan begin</td><td>:</td><td>400</td></tr>
				<tr><td>Scan step size</td><td>:</td><td>50</td></tr>
				<tr><td>Scan n steps</td><td>:</td><td>17</td></tr>
			</table>
			This will generate the events and/or distributions for the model with the mass of the W' set to 400GeV, 450GeV, 500GeV,...1200GeV.  As many scans as desired can be specified (including zero).  For each scan, all four keyphrases have to be specified.  Furthermore, if there is more than one scan, all four keyphrases have to be specified together.  Here is an example with two scans:<br>
			<table>
				<tr><td>Sccan parameter</td><td>:</td><td>MWP</td></tr>
				<tr><td>Scan begin</td><td>:</td><td>400</td></tr>
				<tr><td>Scan step size</td><td>:</td><td>50</td></tr>
				<tr><td>Scan n steps</td><td>:</td><td>17</td></tr>
				<tr><td></td></tr>
				<tr><td>Scan parameter</td><td>:</td><td>MF</td></tr>
				<tr><td>Scan begin</td><td>:</td><td>2000</td></tr>
				<tr><td>Scan step size</td><td>:</td><td>200</td></tr>
				<tr><td>Scan n steps</td><td>:</td><td>11</td></tr>
			</table>
			This example will scan over both parameters MWP and MF.

		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}



sub print_help_qcd {
	print_help_batch_links("$html_dir/help/qcd.html");
	open(HTML_FILE, ">>$html_dir/help/qcd.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>QCD Help</h1>
		<h3>QCD</h3>
		<p>
			The parameters of the QCD menu of the numerical session can be specified as in the following example:<br>
			<table>
				<tr><td>parton dist. alpha</td><td>:</td><td>ON</td></tr>
				<tr><td>alpha(MZ)</td><td>:</td><td>0.118</td></tr>
				<tr><td>alpha nf</td><td>:</td><td>5</td></tr>
				<tr><td>alpha order</td><td>:</td><td>NLO</td></tr>
				<tr><td>mb(mb)</td><td>:</td><td>4</td></tr>
				<tr><td>Mtop(pole)</td><td>:</td><td>174</td></tr>
				<tr><td>alpha Q</td><td>:</td><td>M45</td></tr>
			</table>
			The default values are the ones in CalcHEP itself.  Not all the keywords have to be included in the batch file.  It is sufficient to include the ones that need to be changed.  For example, if only the QCD scale needs to be changed, it can be specified as:<br>
			<table>
				<tr><td>alpha Q</td><td>:</td><td>Mt/2</td></tr>
			</table>
			The QCD scale can be specified in terms of the invariant mass of certain final state particles as in \"Mij\" which means that the QCD scale is taken to be the invariant mass of particles i and j.  Or, it can be specified as a formula in terms of the parameters of the model as in \"Mt/2\" which means half of the top quark mass.  When specifying the scale in terms of the invariant mass of final state particles, the numbers are taken from the way the processes are entered with the \"Process\" keyword.  So, if the process is specified as \"p,p->j,l,n\", \"M45\" means the invariant mass of the lepton and neutrino (l,n).  The batch script will take care of renumbering if the subprocesses have the final state particles in a different order.  It is also sometimes useful to use a different scale for different processes.  For example, suppose the two processes \"p,p->j,l,n\" and \"p,p->j,j,l,n\" are specified in the batch file, the scales could be specified as in this example:<br>
			<table>
				<tr><td>alpha Q</td><td>:1:</td><td>M45</td></tr>
				<tr><td>alpha Q</td><td>:2:</td><td>M56</td></tr>
			</table>
			The number between the :: specifies which process to apply this scale and corresponds to the order in which the user specified the processes.  If more than one process is specified, but the same non default scale is desired for all of them, this can be specified as in:<br>
			<table>
				<tr><td>alpha Q</td><td>:</td><td>Mt/2</td></tr>
			</table>
			This specification will apply the same scale \"Mt/2\" to all processes.
		</p>
                <p>
                        The key phrase "alpha Q" will apply the same scale to the couplings and to the parton distribution functions.  If, however, the user would like to apply different scales to the couplings and the parton distribution functions, he or she should use the key phrases "alpha Fact Q" for the parton distribution functions and "alpha Ren Q" for the renormalization scale for the couplings.  For example,
                        <table>
				<tr><td>alpha Fact Q</td><td>:</td><td>Mt/2</td></tr>
				<tr><td>alpha Ren Q</td><td>:</td><td>MZ</td></tr>
			</table>
                        which specifies that the parton distribution scale should be half the top quark mass and the renormalization scale should be the Z boson mass.  Individual processes can be given different factorization and renormalization scales using the :N: notation (where N is the process).  The default is "M12".  If "alpha Q" is used in the batch file, it takes precedence over "alpha Fact Q" and "alpha Ren Q".  Either "alpha Q" should be used or "alpha Fact Q" and "alpha Ren Q", but not both.
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_BW {
	print_help_batch_links("$html_dir/help/BW.html");
	open(HTML_FILE, ">>$html_dir/help/BW.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>BW Help</h1>
		<h3>Gauge Invariance</h3>
		<p>
			The parameters of the Breit-Wigner menu of the numerical session can be specified as in the following example:<br>
			<table>
				<tr><td>Breit Wigner range</td><td>:</td><td>3.5</td></tr>
				<tr><td>T-channel widths</td><td>:</td><td>ON</td></tr>
				<tr><td>GI in T-channel</td><td>:</td><td>ON</td></tr>
				<tr><td>GI in S-channel</td><td>:</td><td>ON</td></tr>
			</table>
			The default values are 2.7, OFF, OFF and OFF respectively.
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}




sub print_help_cuts {
	print_help_batch_links("$html_dir/help/cuts.html");
	open(HTML_FILE, ">>$html_dir/help/cuts.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Cuts Help</h1>
		<h3>Cut</h3>
		<p>
			Cuts are specified with the keywords \"Cut parameter\", \"Cut invert\", \"Cut min\" and \"Cut max\" and use standard CalcHEP notation, except for \"Cut invert\" which can be either \"True\" or \"False\".  These cuts are only applied to the production processes.  They are not applied to the products of the decays.  Here is an example:<br>
			<table>
				<tr><td>Cut parameter</td><td>:</td><td>T(le)</td></tr>
				<tr><td>Cut invert</td><td>:</td><td>False</td></tr>
				<tr><td>Cut min</td><td>:</td><td>20</td></tr>
				<tr><td>Cut max</td><td>:</td><td></td></tr>
			</table>
			For each cut, all four keyphrases have to be present.  As many cuts as desired can be included.  Including \"Cut min\" or \"Cut max\" but leaving the value blank will leave the value blank in the CalcHEP table.  If the cut should only be applied to a certain process, then the colon can be changed to :n: where n is the process.  So, for example, we could do:<br>
			<table>
				<tr><td>Cut parameter</td><td>:</td><td>T(l)</td></tr>
				<tr><td>Cut invert</td><td>:</td><td>True</td></tr>
				<tr><td>Cut min</td><td>:</td><td></td></tr>
				<tr><td>Cut max</td><td>:</td><td>20</td></tr>
				<tr><td></td></tr>
				<tr><td>Cut parameter</td><td>:</td><td>T(j)</td></tr>
				<tr><td>Cut invert</td><td>:</td><td>False</td></tr>
				<tr><td>Cut min</td><td>:</td><td>20</td></tr>
				<tr><td>Cut max</td><td>:</td><td></td></tr>
				<tr><td></td></tr>
				<tr><td>Cut parameter</td><td>:2:</td><td>J(j,j)</td></tr>
				<tr><td>Cut invert</td><td>:2:</td><td>False</td></tr>
				<tr><td>Cut min</td><td>:2:</td><td>0.4</td></tr>
				<tr><td>Cut max</td><td>:2:</td><td></td></tr>
				</table>
			This set of cuts will apply a p<sub>T</sub> cut to leptons and jets in all processes but a jet cone angle cut only to process 2.  The numbering of the processes corresponds to the order in which the processes are entered in the batch file.  Alias particle names can be used as long as they are defined by the keyword \"Alias\" in the process section.  Note that both of the transverse mass cuts apply a p<sub>T</sub>>20GeV cut in this example.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}



sub print_help_kinematics {
	print_help_batch_links("$html_dir/help/kinematics.html");
	open(HTML_FILE, ">>$html_dir/help/kinematics.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Kinematics Help</h1>
		<h3>Kinematics</h3>
		<p>
			As the number of final state particles increases, it can be very helpful to specify the \"kinematics\" which helps CalcHEP in the numerical integration stage.  This is done in exactly the same notation as in CalcHEP.  The numbering corresponds to the order the particles are entered in the process in the batch file.  Here is an example:<br>
			<table>
				<tr><td>Kinematics</td><td>:</td><td>12 -> 34 , 56</td></tr>
				<tr><td>Kinematics</td><td>:</td><td>34 -> 3 , 4</td></tr>
				<tr><td>Kinematics</td><td>:</td><td>56 -> 5 , 6</td></tr>
			</table>
			If multiple processes are specified, using a single colon as in the previous example will apply the kinematics to all processes.  If different kinematics is desired for each process, then the :n: notation can be used as in:<br>
			<table>
				<tr><td>Kinematics</td><td>:1:</td><td>12 -> 34 , 56</td></tr>
				<tr><td>Kinematics</td><td>:1:</td><td>34 -> 3 , 4</td></tr>
				<tr><td>Kinematics</td><td>:1:</td><td>56 -> 5 , 6</td></tr>
				<tr><td></td></tr>
				<tr><td>Kinematics</td><td>:2:</td><td>12 -> 3 , 456</td></tr>
				<tr><td>Kinematics</td><td>:2:</td><td>456 -> 45 , 6</td></tr>
				<tr><td>Kinematics</td><td>:2:</td><td>45 -> 4 , 5</td></tr>
			</table>
			where n corresponds with the process number as entered in the batch file.
		</p>
                <p>
                        For decays, add "Decay" to the beginning of the key phrases.
                </p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}



sub print_help_regularization {
	print_help_batch_links("$html_dir/help/regularization.html");
	open(HTML_FILE, ">>$html_dir/help/regularization.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Regularization Help</h1>
		<h3>Regularization</h3>
		<p>
			When a narrow resonance is present in the signal, it is a good idea to specify the \"regularization\".  This is done with the same notation as in CalcHEP.  Here is an example:<br>
			<table>
				<tr><td>Regularization momentum</td><td>:</td><td>34</td></tr>
				<tr><td>Regularization mass</td><td>:</td><td>MW</td></tr>
				<tr><td>Regularization width</td><td>:</td><td>wW</td></tr>
				<tr><td>Regularization power</td><td>:</td><td>2</td></tr>
			</table>
			Regularization for as many resonances can be specified as desired.  Furthermore, different resonances can be specified for each process using the :n: notation as in:<br>
			
			<table>
				<tr><td>Regularization momentum</td><td>:1:</td><td>34</td></tr>
				<tr><td>Regularization mass</td><td>:1:</td><td>MW</td></tr>
				<tr><td>Regularization width</td><td>:1:</td><td>wW</td></tr>
				<tr><td>Regularization power</td><td>:1:</td><td>2</td></tr>
				<tr><td></td></tr>
				<tr><td>Regularization momentum</td><td>:2:</td><td>45</td></tr>
				<tr><td>Regularization mass</td><td>:2:</td><td>MZ</td></tr>
				<tr><td>Regularization width</td><td>:2:</td><td>wZ</td></tr>
				<tr><td>Regularization power</td><td>:2:</td><td>2</td></tr>
			</table>
		</p>
                <p>
                        For decays, add "Decay" to the beginning of the key phrases.
                </p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_distributions {
	print_help_batch_links("$html_dir/help/distributions.html");
	open(HTML_FILE, ">>$html_dir/help/distributions.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Distribution Help</h1>
		<h3>Distributions</h3>
		<p>
			The ability to do distributions is still somewhat experimental so they should be checked carefully.  Distributions are only applied to the production process.  The decays are ignored.  Standard CalcHEP notation is used for the distribution parameter.  Here is an example:<br>
			<table>
				<tr><td>Dist parameter</td><td>:</td><td>M(e,E)</td></tr>
				<tr><td>Dist min</td><td>:</td><td>0</td></tr>
				<tr><td>Dist max</td><td>:</td><td>200</td></tr>
				<tr><td>Dist n bins</td><td>:</td><td>100</td></tr>
				<tr><td>Dist title</td><td>:</td><td>p,p->l,l</td></tr>
				<tr><td>Dist x-title</td><td>:</td><td>M(l,l) (GeV)</td></tr>
			</table>
			The value for the keyphrase \"Dist n bins\" has to be one of:<br>
			<table>
				<tr><td>300</td><td>150</td><td>100</td><td>75</td><td>60</td><td>50</td></tr>
				<tr><td>30</td><td>25</td><td>20</td><td>15</td><td>12</td><td>10</td></tr>
				<tr><td>6</td><td>5</td><td>4</td><td>3</td><td>2</td></tr>
			</table>
			These are the values allowed by the CalcHEP histogram routines.  The values given for the titles have to be pure text.  No special characters are currently allowed.  Gnuplot must be installed for plots to be produced on the fly and included in the html progress reports.  More than one distribution can be specified, however each distribution must be unambiguous and apply in exactly one way for each subprocess.  Also, distributions will work even if no events are requested.
		</p>
		<h3>Possible Issues</h3>
		<p>
		For this to work, the distributions have to be unambiguous and apply to all subprocesses the same way.  For example, if a process is p,p->l,l,l and the distribution M(l,l) is given, then this routine will not know which two leptons to apply the distribution to and the results are unpredictable.  If the process is p,p->l,l where l=e,E,m,M and the distribution M(e,E) is desired, this distribution will only apply to some of the subprocesses and give unpredictable results.  Make sure your distribution is unambiguous and applies in exactly one way to each subprocess.  If this is done, it should work.  Nevertheless, check each distribution carefully to make sure it is being done correctly.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}



sub print_help_events {
	print_help_batch_links("$html_dir/help/events.html");
	open(HTML_FILE, ">>$html_dir/help/events.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Events Help</h1>
		<h3>Number of events</h3>
		<p>
			The number of events is specified with the keyphrase \"Number of events\".  This specifies the number of events to produce after all subprocesses are combined and decayed.  If a run over a parameter is specified, this keyphrase determines the number of events to produce for each value of the run parameter.  The number of events requested can be zero.  In this case, the cross sections are determined and the distributions generated but no events are produced.  Here is an example:<br>
			<table>
				<tr><td>Number of events</td><td>:</td><td>1000</td></tr>
			</table>
		</p>
		<h3>Filename</h3>
		<p>
			The name of the file can be specified using the \"Filename\" keyword.  If specified, all the files will begin with this name.  Here is an example:<br>
			<table>
				<tr><td>Filename</td><td>:</td><td>pp-ll</td></tr>
			</table>
		</p>
		<h3>NTuple</h3>
		<p>
			If nt_maker has been installed in the bin directory, PAW ntuples can be made on the fly by setting \"NTuple\" to True as in:<br>
			<table>
				<tr><td>NTuple</td><td>:</td><td>True</td></tr>
			</table>
			The default is False.
		</p>
		<h3>Cleanup</h3>
		<p>
			If this is set to true, the individual event files are removed after the final event file is created.  This is useful for saving space on the hard drive.  It is True by default.  Here is an example:<br>
			<table>
				<tr><td>Cleanup</td><td>:</td><td>False</td></tr>
			</table>
		</p>
		<h3>Reuse Session</h3>
		<p>
			If this is set to true, the previous session is reused instead of starting from scratch.  This is useful when a long job has been run but the statistics are still not as good as desired.  If this is set to true, the batch program will start from where it left off in the previous calculation.  Two things are very important to remember.  This only works if Cleanup was set to False in the previous run and no parameters,cuts,regularization, etc are changed between the previous run and this one.  It is False by default.  Here is an example:<br>
			<table>
				<tr><td>Cleanup</td><td>:</td><td>False</td></tr>
				<tr><td>Reuse Session</td><td>:</td><td>True</td></tr>
			</table>
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}



sub print_help_parallelization {
	print_help_batch_links("$html_dir/help/parallelization.html");
	open(HTML_FILE, ">>$html_dir/help/parallelization.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Parallelization Help</h1>
		<h3>Parallelization Method</h3>
		<p>
			The parallelization mode is set using the keyphrase \"Parallelization method\" and can be either \"local\", \"pbs\" or \"lsf\".  In local mode, the jobs run on the local computer while in pbs mode, the jobs are run on a pbs cluster.  If run from a pbs or lsf cluster, the terminal should be on the computer with the pbs or lsf queue.  Here is an example of setting the batch to run in pbs mode:<br>
			<table>
				<tr><td>Parallelization mode</td><td>:</td><td>pbs</td></tr>
			</table>
			Local mode is the default.
		</p>
		<h3>PBS</h3>
		<p>
		If run in pbs mode, there are several options that may be necessary for the pbs cluster.  All of them can be left blank in which case they will not be given to the pbs cluster.  Here is an example of the options available:<br>
		<table>
			<tr><td>Que</td><td>:</td><td>brody</td></tr>
			<tr><td>Walltime</td><td>:</td><td>1.5</td></tr>
			<tr><td>Memory</td><td>:</td><td>1</td></tr>
			<tr><td>email</td><td>:</td><td>name\@address</td></tr>
		</table>
		The que specifies which pbs que to  submit the jobs to.  Walltime specifies the maximum time (in hours) the job can run for.  If this time is exceeded, the jobs are killed by the pbs cluster.  Memory specifies the maximum amount of memory (in G) that the jobs can use.  If this memory is exceeded by a job, the pbs cluster will kill the job.  email specifies which email to send a message to if the job terminates prematurely.  The default for all of these is whatever is the default on the pbs cluster.
		</p>
		<h3>LSF</h3>
		<p>
		If run in lsf mode, there are several options that may be necessary for the lsf cluster.  All of them can be left blank in which case they will not be given to the lsf cluster.  Here is an example of the options available:<br>
		<table>
			<tr><td>Que</td><td>:</td><td>brody</td></tr>
			<tr><td>Walltime</td><td>:</td><td>1.5</td></tr>
			<tr><td>Memory</td><td>:</td><td>1</td></tr>
			<tr><td>email</td><td>:</td><td>name\@address</td></tr>
                        <tr><td>Project</td><td>:</td><td>project_name</td></tr>
		</table>
		The que specifies which lsf que to  submit the jobs to.  Walltime specifies the maximum time (in hours) the job can run for.  If this time is exceeded, the jobs are killed by the lsf cluster.  Memory specifies the maximum amount of memory (in G) that the jobs can use.  If this memory is exceeded by a job, the lsf cluster will kill the job.  email specifies which email to send any messages t.  The default for all of these is whatever is the default on the lsf cluster.
		</p>
		<h3>Sleep Time</h3>
		<p>
		Sleep time specifies the amount of time (in seconds) the batch script waits before checking which jobs are done and updating the html progress reports.  If a very short test run is being done, then this should be low (say a few seconds).  However, if the job is very large and will take severl hours or days, this should be set very high (say minutes or tens of minutes).  This will reduce the amount of cpu time the batch program uses.  Here is an example setting the sleep time to 1 minute:<br>
		<table>
			<tr><td>sleep time</td><td>:</td><td>60</td></tr>
		</table>
		The default is 3 seconds.
		</p>
		<h3>Nice Level</h3>
		<p>
			When jobs are run on the local computer, this specifies what nice level the jobs should be run at.  If other users are using the same computer, this allows the job to be put into the background and run at lower priority so as not to disturb the other users.  This should be between 0 and 19 where 19 is the lowest priority and the nicest.  Typically, it should be run at level 19 unless the user is sure it will not disturb anyone.  The nice level should be set both for a local computer and for a pbs batch run.  The reason is that some jobs are run on the pbs queue computer even on the pbs cluster.  Here is an example:<br>
			<table>
				<tr><td>Nice level</td><td>:</td><td>19</td></tr>
			</table>
			Level 19 is the default.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}


sub print_help_vegas {
	print_help_batch_links("$html_dir/help/vegas.html");
	open(HTML_FILE, ">>$html_dir/help/vegas.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Vegas Help</h1>
		<h3>Vegas</h3>
		<p>
			The number of vegas calls can be controlled with the keywords \"nSess_1\", \"nCalls_1\", \"nSess_2\" and \"nCalls_2\".  The values are the same as in CalcHEP.  Here is an example:<br>
			<table>
				<tr><td>nSess_1</td><td>:</td><td>5</td></tr>
				<tr><td>nCalls_1</td><td>:</td><td>100000</td></tr>
				<tr><td>nSess_2</td><td>:</td><td>5</td></tr>
				<tr><td>nCalls_2</td><td>:</td><td>100000</td></tr>
			</table>
			The defaults are the same as in CalcHEP.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}



sub print_help_generator {
	print_help_batch_links("$html_dir/help/generator.html");
	open(HTML_FILE, ">>$html_dir/help/generator.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Generator Help</h1>
		<p>
			The following parameters of the event generation can be modified:<br>
			<table>
				<tr><td>sub-cubes</td><td>:</td><td>1000</td></tr>
				<tr><td>random search</td><td>:</td><td>100</td></tr>
				<tr><td>simplex search</td><td>:</td><td>50</td></tr>
				<tr><td>MAX*N</td><td>:</td><td>2</td></tr>
				<tr><td>find new MAX</td><td>:</td><td>100</td></tr>
			</table>
			The defaults are the CalcHEP defaults.
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}




sub print_help_example1 {
	print_help_batch_links("$html_dir/help/example1.html");
	open(HTML_FILE, ">>$html_dir/help/example1.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Example 1</h1>
		<p>
			This example generates 1000 events (for each MWP) of the process p,p->W,Z->l,l,l,n.
			<table>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Model Info                     </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Model</td><td>:</td><td>3-Site</td></tr>
				<tr><td>Gauge</td><td>:</td><td>Feynman</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Process Info                   </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Process</td><td>:</td><td>p,p->W,Z</td></tr>
				<tr><td>Decay</td><td>:</td><td>W->l,n</td></tr>
				<tr><td>Decay</td><td>:</td><td>Z->l,l</td></tr>
				<tr><td>Alias</td><td>:</td><td>p=u1,U1,d1,D1,G</td></tr>
				<tr><td>Alias</td><td>:</td><td>W=W+,W-</td></tr>
				<tr><td>Alias</td><td>:</td><td>l=e1,E1,e2,E2</td></tr>
				<tr><td>Alias</td><td>:</td><td>n=n1,N1,n2,N2</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  PDF Info                       </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>pdf1</td><td>:</td><td>cteq6l (proton)</td></tr>
				<tr><td>pdf2</td><td>:</td><td>cteq6l (proton)</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Momentum Info                  </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>p1</td><td>:</td><td>7000</td></tr>
				<tr><td>p2</td><td>:</td><td>7000</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Parameter Info                 </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Parameter</td><td>:</td><td>MF=4000</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Scan Info                       </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Scan parameter</td><td>:</td><td>MWP</td></tr>
				<tr><td>Scan begin</td><td>:</td><td>400</td></tr>
				<tr><td>Scan step size</td><td>:</td><td>50</td></tr>
				<tr><td>Scan n steps</td><td>:</td><td>17</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Event Info                     </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Number of events</td><td>:</td><td>1000</td></tr>
				<tr><td>Filename</td><td>:</td><td>pp-WZ-llln</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Parallelization Info           </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Parallelization method</td><td>:</td><td>local</td></tr>
				<tr><td>Max number of cpus</td><td>:</td><td>2</td></tr>
				<tr><td>sleep time</td><td>:</td><td>3</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Vegas Info                     </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>nSess_1</td><td>:</td><td>5</td></tr>
				<tr><td>nCalls_1</td><td>:</td><td>100000</td></tr>
				<tr><td>nSess_2</td><td>:</td><td>5</td></tr>
				<tr><td>nCalls_2</td><td>:</td><td>100000</td></tr>
			</table>

			
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}

sub print_help_example2 {
	print_help_batch_links("$html_dir/help/example2.html");
	open(HTML_FILE, ">>$html_dir/help/example2.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Example 2</h1>
		<p>
			This example gives the invariant mass distribution for the two leptons in the final state of p,p->l,l.
			<table>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Model Info                     </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Model</td><td>:</td><td>3-Site</td></tr>
				<tr><td>Gauge</td><td>:</td><td>Feynman</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Process Info                   </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Process</td><td>:</td><td>p,p->l,l</td></tr>
				<tr><td>Alias</td><td>:</td><td>p=u1,U1,d1,D1,G</td></tr>
				<tr><td>Alias</td><td>:</td><td>l=e1,E1,e2,E2</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  PDF Info                       </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>pdf1</td><td>:</td><td>cteq6l (proton)</td></tr>
				<tr><td>pdf2</td><td>:</td><td>cteq6l (proton)</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Momentum Info                  </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>p1</td><td>:</td><td>7000</td></tr>
				<tr><td>p2</td><td>:</td><td>7000</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Parameter Info                 </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Parameter</td><td>:</td><td>MF=4000</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Scan Info                       </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Scan parameter</td><td>:</td><td>MWP</td></tr>
				<tr><td>Scan begin</td><td>:</td><td>400</td></tr>
				<tr><td>Scan step size</td><td>:</td><td>50</td></tr>
				<tr><td>Scan n steps</td><td>:</td><td>17</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Cut Info                       </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Cut parameter</td><td>:</td><td>T(l)</td></tr>
				<tr><td>Cut min</td><td>:</td><td>20</td></tr>
				<tr><td>Cut max</td><td>:</td><td></td></tr>
				<tr><td></td></tr>
				<tr><td>Cut parameter</td><td>:</td><td>N(l)</td></tr>
				<tr><td>Cut min</td><td>:</td><td>0.4</td></tr>
				<tr><td>Cut max</td><td>:</td><td></td></tr>
				<tr><td></td></tr>
				<tr><td>Cut parameter</td><td>:</td><td>J(l,l)</td></tr>
				<tr><td>Cut min</td><td>:</td><td>0.2</td></tr>
				<tr><td>Cut max</td><td>:</td><td></td></tr>
				<tr><td></td></tr>
				<tr><td>Cut parameter</td><td>:</td><td>M(l,l)</td></tr>
				<tr><td>Cut min</td><td>:</td><td>MWP-100</td></tr>
				<tr><td>Cut max</td><td>:</td><td>MWP+100</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Distribution Info              </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Dist parameter</td><td>:</td><td>M(l,l)</td></tr>
				<tr><td>Dist min</td><td>:</td><td>MWP-100</td></tr>
				<tr><td>Dist max</td><td>:</td><td>MWP+100</td></tr>
				<tr><td>Dist n bins</td><td>:</td><td>100</td></tr>
				<tr><td>Dist title</td><td>:</td><td>p,p->l,l</td></tr>
				<tr><td>Dist x-title</td><td>:</td><td>M(l,l) (GeV)</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Parallelization Info           </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>Parallelization method</td><td>:</td><td>local</td></tr>
				<tr><td>Max number of cpus</td><td>:</td><td>2</td></tr>
				<tr><td>sleep time</td><td>:</td><td>3</td></tr>
				<tr><td></td></tr>
				<tr><td colspan="3">##################################</td>
				<tr><td colspan="3">#  Vegas Info                     </td>
				<tr><td colspan="3">##################################</td>
				<tr><td>nSess_1</td><td>:</td><td>5</td></tr>
				<tr><td>nCalls_1</td><td>:</td><td>100000</td></tr>
				<tr><td>nSess_2</td><td>:</td><td>5</td></tr>
				<tr><td>nCalls_2</td><td>:</td><td>100000</td></tr>
			</table>

		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}

sub print_help_example3 {
	print_help_batch_links("$html_dir/help/example3.html");
	open(HTML_FILE, ">>$html_dir/help/example3.html");
	print HTML_FILE <<ENDHTML;
	<div id='help_main'>
		<h1>Example 3</h1>
		<p>
			
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}





sub print_help_process_library {
	open(HTML_FILE, ">$html_dir/help/process_library.html");
	print HTML_FILE <<ENDHTML;
<html>
<head>
	<title>CalcHEP Batch Help</title>
	<link rel='stylesheet' href='../style.css' type='text/css'></link>
</head>
<body>
	<div id='links'>
		<ul>
			<li><a href='../index.html'>Home</a></li>
			<li><a href='../symbolic.html'>Symbolic Results</a></li>
			<li><a href='../numerical.html'>Numerical Results</a></li>
			<li><a href='../events.html'>Events Library</a></li>
			<li><a href='../library.html'>Process Library</a></li>
			<li><a href='index.html'>Help</a>
				<ul>
					<li><a href='batch_file.html'>Batch File</a></li>
					<li><a href='process_library.html'>Process Library</a></li>
					<li><a href='event_library.html'>Event Library</a></li>
				</ul>
			</li>
			<br>
			<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>
			<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>
		</ul>
	</div>	
	<div id='help_main'>
		<h1>Process Library Help</h1>
		<p>
			After the numerical code is generated for a process, it is stored in the \"Process Library\".  If the same process is used later, it is first looked for in the process library.  If it is there, the symbolic session is skipped and it is used again in the numerical stage.  This can save significant time.  
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}

sub print_help_event_library {
	open(HTML_FILE, ">$html_dir/help/event_library.html");
	print HTML_FILE <<ENDHTML;
<html>
<head>
	<title>CalcHEP Batch Help</title>
	<link rel='stylesheet' href='../style.css' type='text/css'></link>
</head>
<body>
	<div id='links'>
		<ul>
			<li><a href='../index.html'>Home</a></li>
			<li><a href='../symbolic.html'>Symbolic Results</a></li>
			<li><a href='../numerical.html'>Numerical Results</a></li>
			<li><a href='../events.html'>Events Library</a></li>
			<li><a href='../library.html'>Process Library</a></li>
			<li><a href='index.html'>Help</a>
				<ul>
					<li><a href='batch_file.html'>Batch File</a></li>
					<li><a href='process_library.html'>Process Library</a></li>
					<li><a href='event_library.html'>Event Library</a></li>
				</ul>
			</li>
			<br>
			<li>Thank you for using <a href='http://theory.sinp.msu.ru/~pukhov/calchep.html'>CalcHEP</a>!</li>
			<li>Please cite <a href='http://inspirehep.net/record/1123804'>arXiv:1207.6082</a></li>
		</ul>
	</div>	
	<div id='help_main'>
		<h1>Event Library Help</h1>
		<p>
			After the events and/or distributions are generated, they are stored in the batch_results directory.  The prefix of the files is the name specified in the batch file plus either "-single" if no runs were specified or a string specifying the run parameter values if one or more runs are specified.  We will assume this is filename in the following.  If events are requested, they will be stored in the files<br>
			<table>
				<tr><td>filename.lhe</td></tr>
				<tr><td>filename.nt</td></tr>
			</table>
			where filename.lhe is the event file in Les Houches format and filename.nt is in PAW ntuple format.  The ntuple file is only created if the keyword "NTuple" is set to true and nt_maker is present in the bin directory.  If distributions are requested, they will be  stored in the files<br>
			<table>
				<tr><td>filename.distr</td></tr>
				<tr><td>filename_1.jpg</td></tr>
				<tr><td>filename_2.jpg</td></tr>
				<tr><td>...</td></tr>
			</table>
			  where filename.distr is the raw distribution data and can be read by "show_distr" in the bin directory.  The distributions generated on the fly by the batch script are stored in the files ending in ".jpg".
		</p>
	</div>
</body>
</html>
ENDHTML
	close(HTML_FILE);
}



