<?php
##Title:                index.php
##Author:               Rich Stolz
##Last Updated:         $Id: index.php,v 1.12 2009/06/30 15:56:00 rstolz Exp rstolz $ 
##Site:                 dna.ccs.tulane.edu



include("variables.php");
##This is a fully marked-up copy of this file.  Please see ______________ for a non-markedup version of the file.
########################################################################################
########################################################################################
##Define variables

if (isset($_POST['seqin'])){$seqin = $_POST['seqin'];}
##Static variables (paths and large text blocks) are in the file variables.php. Because of the "if(isset($variable))" statement the variables below can NOT be included in the variables.php file.  Only static variables are included in this file.
##define array $errors

##This function intializes all of the variables in the array $variables
function initializevar ($var){
global $var;
if (isset($var)){} 
else {$var ="";}
}

foreach($variables AS $var ) {
initializevar($var);}

#SEQ menu vars
if (isset($seqform)) {}
else {$seqform = 0;}
if (isset($_POST['nss'])){$nss = $_POST['nss'];} 
else {$nss ="";}


########################################################################################
########################################################################################

########################################################################################
########################################################################################
##This function prints the errors from each of the functions
function errors() {
global $errors;
if (empty($errors)) {}
else {$trimmederrors = trim($errors);
  foreach ($errors as $key => $val) {
 	echo $val."</p>";}}
}

########################################################################################
########################################################################################
function counter() {
##This function opperates the counter and cleans-up the sessions directory
global $SID, $count, $sesspath;
if ($SID == 0){
  ##Take the hits from the file $count
  $hits = file($count);
    ##Increment it by one
    $hits[0] ++;
  ##write the new number to the file $count
  $fp = fopen($count , "w");
          fputs($fp , "$hits[0]");
        fclose($fp);
$SID = $hits[0];
##Make directory for the new session
mkdir("$sesspath$SID", 0777);
}
##The variable SIDarch controls how many full session directories are kept and how many are archived
$SIDarch = $SID - 10;
$dir = "$sesspath/$SIDarch";
$directory = escapeshellarg($dir);
exec("rm -rf $directory");
}

########################################################################################
########################################################################################
##This function creates a temporary file with an unverified sequence in it.  This file is then used by makeconfin() as to verify that all characters are valid.  This was done in this manner as to allow makeconfin work with both form data and uploaded data.

function makeconfin() {
#make global variables
global $confin, $directions,$dirK, $dirX, $dirX0, $errors, $K, $linker, $MMTV, $nuclength, $nss, $nssarr, $numnuc, $occupancy, $seqscanfile, $seqinlength,  $sesspath, $seqin, $SID, $validseq, $X, $X0;

$seqinfile = "$sesspath$SID/seqin.txt";
$uploadfile = "$sesspath/$SID/uploaded.txt";

##sequence options
if($_POST['sequence'] == "seq_type") {
if (isset($_POST['seqin'])) {$seqin = $_POST['seqin'];}
$subseq = substr($seqin, 0, 15);
$subdirections = substr($directions, 0, 15);
if (($subseq == $subdirections) || ($_POST['sequence'] == "seq_default")){
$seqin = $MMTV;}
else{$seqin = $_POST['seqin'];}}

if($_POST['sequence'] == "seq_default") {$seqin = $MMTV;}

if (($_POST['sequence'] == "seq_upload") && ($_FILES["uploadedfile"])) {
       uploader();
       $fh0 = fopen($uploadfile, 'r');
       $seqin = fread($fh0, filesize($uploadfile));
       fclose($fh0);
       }
##For all sequence options:
if (preg_match('/[^A,T,G,C,\s]/i', $seqin)) {
##if not A, T, G, C's add an error to the error array and re-print the form
$errors['seqin'] = "Please fix your sequence to have only a, t, g, c, \n A, T, G, and C characters with spaces.";}
$seq4prog = trim(chunk_split(strtoupper(preg_replace('/[^A,T,G,C]/i','', $seqin)), 1, "\n"));
$seqinlength = (strlen($seq4prog)+1)/2;
$fp = fopen($seqinfile, 'w+');
{
fwrite($fp, $seq4prog );
}
fclose($fp);

##energy options
if ($_POST['energy'] == "energy_simple"){
$K = "$dirK/MD-B.dat";
$X = "$dirX/01kx5.min.par";
$X0 = "$dirX0/MD-B.par";
$occupancy = .70;
$linker = 30;
}
if ($_POST['energy'] == "energy_default"){
if (isset($_POST['K_energy'])){$K = $_POST['K_energy'];} 
if (isset($_POST['X_energy'])){$X = $_POST['X_energy'];} 
if (isset($_POST['X0_energy'])){$X0 = $_POST['X0_energy'];} 
if (isset($_POST['occupancy_energy'])){$occupancy = $_POST['occupancy_energy'];}
if (isset($_POST['linker_energy'])){$linker = $_POST['linker_energy'];}
}
if (($_POST['energy'] == "energy_default") || ($_POST['energy'] == "energy_simple")){
$seqinlength = (strlen(trim(chunk_split(strtoupper(preg_replace('/[^A,T,G,C]/i','', $seqin)), 1, "\n")))+1)/2;

#Read nuclength from $X file
$fh = fopen($X, 'r');
$nuclength = fread($fh, 5);
fclose($fh);
##$numnuc = floor($occupancy*$seqinlength/($nuclength+$linker));
##echo "\$occupancy = $occupancy \$seqinlength = $seqinlength\$nuclength = $nuclength \$linker = $linker";
	##      Percent Occupancy  can be < 0 =>       a shift ; just report as negative number add 2 b/c icm program error
##                  >0 && < 1 => a percentage of max; must be converted to integer
##                  >= 1         a number of nucleosomes
        if ($occupancy < 1 ) {
        $numnuc = floor($occupancy*$seqinlength/($nuclength+$linker));
        }
	elseif ($occupancy < 0 ) {
        $numnuc = floor($numnuc) + 2 ;
	}
	elseif ($occupancy > 1 ) {
	$numnuc = $occupancy;
	}
$max = ($numnuc)*($nuclength+$linker);
if ((($numnuc)*($nuclength+$linker)) > $seqinlength) {
	$errors['2manynuc'] = "The sequence length specified is not  long enough to support this many nucleosomes.  Please reduce the occupancy or linker length.";
	}
	$confin = "$X0\n$X\n$K\n$sesspath$SID/seqin.txt\n$sesspath$SID/eq.out.par\n$sesspath$SID/E.dat\n$numnuc\n$linker\n";
}


if ($_POST['energy'] == "nss_type"){
if (isset($_POST['linker_nss'])){$linker = $_POST['linker_nss'];}
if (isset($_POST['X_nss'])){$X = $_POST['X_nss'];} 
if (isset($_POST['X0_nss'])){$X0 = $_POST['X0_nss'];}
if (isset($_POST['K_nss'])){$K = $_POST['K_nss'];}
$fh = fopen($X, 'r');
$nuclength = fread($fh, 5);
fclose($fh);
##TOM Why are we not asking the user to specify a XO value?
#$X0 = "$dirX0/MD-B.par";
##TOM Why are we not asking the user to specify a XO value?
#$K = "$dirK/MD-B.dat";
#calc $numnuc
$nssarr = split("[\n\r\t ,]+", trim($nss));
$numnuc = count($nssarr);
$nss = implode("\n", $nssarr);
if (!empty($nss)) {
$confin = "$X0\n$X\n$sesspath$SID/seqin.txt\n$nss\n-1\n$sesspath$SID/icm.par\n";
}
if (empty($nss)) {
$confin = "$X0\n$X\n$sesspath$SID/seqin.txt\n-1\n$sesspath$SID/icm.par\n";
}


$seqscandat = "$X0\n$X\n$K\n$sesspath$SID/seqin.txt\n$sesspath$SID/eq.out.par\n$sesspath$SID/E.dat\n0\n$seqinlength\n";

$seqscanfile = "$sesspath$SID/seqscan.txt";
$fp = fopen($seqscanfile, 'w+');
{ fwrite($fp, $seqscandat ); }
fclose($fp);
}

  	##write confin
	$fp = fopen("$sesspath$SID/confin.txt", 'w+');
	{ fwrite($fp, $confin ); }
	fclose($fp);

}


########################################################################################
########################################################################################
function uploader() {
##make global variables
global $errors, $SID, $sesspath;
##Сheck that we have a file
if((!empty($_FILES["uploadedfile"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  ##Check if the file is txt and it's size is less than 1Gb
  $filename = basename($_FILES['uploadedfile']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($_FILES["uploadedfile"]) && ($_FILES["uploadedfile"]["size"] < 10000000)) {
    ##Determine the path to which we want to save this file
      $newname = "$sesspath$SID/" . "uploaded.txt";
      ##Check if the file with the same name is already exists on the server
      if (!file_exists($newname)) {
	 $errors['upload_absent'] = "No file was specified for the upload.";
        ##move the uploaded file to uploads/
      }
  } else {
     $errors['upload_size'] =  "Only files under 1Gb are accepted for upload";
  }
} else {
 $errors['upload_failed'] = "No file uploaded";
}
}

########################################################################################
########################################################################################
## This function opens the nss file and confirms that all user input data is valid.
function pc_validate_nss() {
global  $errors, $linker, $nss, $nssarr, $nuclength, $numnuc, $occupancy, $seqinlength, $sesspath, $SID;
if (isset($_POST['X_nss'])){$X = $_POST['X_nss'];}
	##verify entry contains only  numerical entries
if ($nss == ""){
        $errors['nssempty'] = "If the energy function is to be bypassed at least
 one nucleosome start site must be specified.";}
	if (preg_match('/[^0-9,-\s]/i', $_POST['nss']) == TRUE) {
	$errors['nss'] = "Please fix your listing to have only nucleosome start sites \n (numerical entries only) separated  by spaces";
	}else{
	##opening file to be read as to obtain the length of the nucleosome selected.
	$fh = fopen($X, 'r');
	$nuclength = fread($fh, 5);
	fclose($fh);
	sort($nssarr, SORT_NUMERIC);
	##delete duplicate values
	$nss = array_unique($nssarr);
	$last = end($nss);
	$maxnss = $seqinlength - $nuclength;
if ($nss['0'] <= "0"){
        $errors['nsszero'] = "Nucleosome start sites must be numerical values greater or equal to '1'.";}
echo "\$maxnss = $maxnss \$seqinlength = $seqinlength \$nuclength = $nuclength";
	if ($last > $maxnss) {
	  if ($seqinlength < $nuclength) {
	  $errors['nssseq'] = "Using this X value, each nucleosome is $nuclength" . "bp in length. \nPlease specify a sequence that is greater than $nuclength" . "bp long.";
          }
	  elseif ($seqinlength > $nuclength) {
	  $errors['nssend'] = "You have requested a nucleosome start site that is less than \n $nuclength from the end of your sequence.  The last nucleosome start \n sites for this sequence must be less than $maxnss";
	  }
        }
	$zeros = range(1, $seqinlength);
	## from [0] to [n-1] in the array $nss subtract the value [i+1] from the value [i]
	$i=0;
	while($i < count($nss) -1) {
	  $diff = $nss[$i+1] - $nss[$i];
	  $i++;
	## if $diff is less than the $nuclength condition is false, otherwise condition is true
	    if ($diff < $nuclength ) {
	    $tooclose[] = $nss[$i-1]; 
	    $tooclose[] = $nss[$i];
	    $gtnuclength = false;
	    $tooclose = join(', ', array_unique($tooclose));
            $errors['nssclose'] = "Please fix your nucleosome start sites as to insure there \n are at least $nuclength bp between each nucleosome. The nucleosomes \n at: " . $tooclose . " are less than $nuclength bp apart.";
	    }else $gtnuclength = true;
	}
}
}

########################################################################################
########################################################################################
##These functions are used to begin/end *MOST* html files created by the program.  This is one area that could be cleaned up significantly and made more robust as to make the program run faster and smoother.
function htmlbegin($script, $css){
echo 
<<<HTMLBEGIN
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>Interactive Chromatin Folding</title>
  <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
  $script
  $css
 </head>
HTMLBEGIN;
}

function htmlend(){
echo  <<<HTMLEND
\n
 </body>
</html>
HTMLEND;
}


##This function makes the Go/Reset buttons
function button ($type, $value, $onclick, $style){
echo <<<BUTTON
\n<INPUT TYPE ="$type"
VALUE ="$value"
STYLE ="$style"
$onclick> 
BUTTON;
}


########################################################################################
########################################################################################
##This function prints the main form that the user uses to input data.
function print_form(){
global $basewebdir, $cssbishop, $directions, $dirK, $dirX, $dirX0, $dirSeq, $errors,  $seqin, $SID, $webdirSeq, $X;

include("popuptext.php");
if (isset($seqin)){}
else {$seqin = "$directions";}

##This function makes the menus for K, X, X0 and the sample sequences.
function menu($indir, $outdir, $ext, $selectname, $postvar, $option, $desc_on_off, $refs_on_off){
include("popuptext.php");
$files = array();
$handle = opendir($indir);
  while($filename = readdir($handle))
  {if ( substr( $filename, -4 ) == "$ext" ) {
        $files[] = $filename;}}
closedir($handle);
sort( $files );
if ($desc_on_off == 1){
$Q = "Q"."$postvar"."_popup_text";
popup("Q$postvar", $$Q, 0, 0);
}
if ($refs_on_off == 1){
$R = "R"."$postvar"."_popup_text";
popup("R$postvar", $$R, 0, 0);
}
## Output results
echo <<<OPTGROUP
    <select name="$postvar" $option>

    <optgroup label="$selectname">

OPTGROUP;

  foreach( $files AS $name )
  {
    echo "     <option value=\"$outdir$name\">" . substr($name,0,9) . "</option> \n";
  }
echo"    </optgroup>
	</select>";

if ($desc_on_off == 1){
echo <<<OPTGROUP
<div id="$postvar" onMouseOver="ShowPopupQ(this);" onMouseOut="HidePopupQ(this);">
<img alt="What is this?" src="images/questionmark.gif" />
</div>
OPTGROUP;
}

if ($refs_on_off == 1){
echo <<<OPTGROUP
<div id="$postvar" onMouseOver="ShowPopupR(this);" onMouseOut="HidePopupR(this);">
<img alt="References" src="images/ref.gif" />
</div>
OPTGROUP;
}

}

##This function prints the text boxes
function textbox($postvar, $rows, $cols, $input, $desc_on_off, $refs_on_off) {
include("popuptext.php");
if ($desc_on_off == 1){
$Q = "Q"."$postvar"."_popup_text";
popup("Q$postvar", $$Q, -800, 0);
}

if ($refs_on_off == 1){
   $R = "R"."$postvar"."_popup_text";
   popup("R$postvar", $$R, -800, 0);
}

echo <<<TEXTBOX
        <TEXTAREA name=$postvar rows=$rows cols=$cols>$input</TEXTAREA>
TEXTBOX;
if ($desc_on_off == 1){
echo <<<POPUP
<a id="$postvar" onMouseOver="ShowPopupQ(this);" onMouseOut="HidePopupQ(this);">
<img alt="What is this?" src="images/questionmark.gif" />
</a>
POPUP;
}

if ($refs_on_off == 1){
echo <<<POPUP
<a id="$postvar" onMouseOver="ShowPopupR(this);" onMouseOut="HidePopupR(this);">
<img alt="References" src="images/ref.gif" />
</a>
POPUP;
}
}
        
##This function prints the popup boxes
function popup($postvar, $text, $top, $left)
##  Must place text "<a id="hoverover" onMouseOver="ShowPopup(this);" onMouseOut="HidePopup();">" before hover region and "</a> after hover region.
{ echo <<<POPUP

      <div id="hoverpopup$postvar" style="visibility:hidden; position:absolute; top:$top; left:$left;">
       <!-- popup table -->
       <table border=8 bordercolor="#00331A" bgcolor="#EBF4E1">
        <tr>
         <td>
          <font color="#00331A" size="2px">
$text
          </font>
         </td>
        </tr>
       </table>
       <!-- popup table -->
      </div>

POPUP;
}


##Begin printing form
htmlbegin( "<script type=\"text/javascript\" src=\"http://dna.ccs.tulane.edu/icm/form.js\"></script>", "$cssbishop");
echo <<<FORM1

 <body>
  <h2 align="center">
    <span style="color:FF9900; font-weight:bold; size=+1">
FORM1;
errors();
echo <<<FORM2
<!-- print errors if there are any -->
    </span>
  </h2>
    <form  enctype="multipart/form-data" action="$_SERVER[PHP_SELF]"  onReset="return allowReset()" method="POST" >
  <!-- main table -->
  <table align=center width=100% border=6>
   <caption class="style1">Interactive Chromatin Folding</caption>
      <input type="hidden" name="stage" value="process" />
     <td width=50%>
       <!-- sequence options fieldset -->
       <fieldset>
        <legend class="style2"> Sequence Input Options: </legend>
</br>
       <!-- Sequence selection menu table -->
       <table>
        <tr>
            <td>
             <input type="radio" name="sequence" value="seq_default" id="seq_default" rel="default_seq" checked />
Default Sequence
            </td>
            <td>
             <input type="radio" name="sequence" value="seq_type" id="seq_type" rel="type_seq" />
Type Sequence
            </td>
            <td>
             <input type="radio" name="sequence" value="seq_upload" id="seq_upload"  rel="upload_seq" />
Upload Sequence
            </td>
        </tr>
       </table>
       <!-- Sequence selection menu table -->
       <!-- Sequence selection content table -->
       <table>
</br>
         <tr rel="default_seq">
          <td>
            <p  align="center">
The default sequence selection is the MMTV sequence (GENBANK V01175).
            </p>
</br>
</br>
          </td>
         </tr>
          <tr rel="type_seq">
            <td>
                <span class="accessibility">
If you would like to type your sequence, please insert your sequence here
                </span>
<p>
<p>
FORM2;
      textbox("seqin", "20", "35", $seqin, 0, 0);
echo <<<SAMPLESEQ
</br>
</br>
             <span style="color:FF9900;">
Try one of our samples here:
             </span>
</br>
SAMPLESEQ;
     menu($dirSeq, $webdirSeq, ".txt", "Sample Sequences", "seqmenu", "onchange=window.open(this.options[this.selectedIndex].value,'_blank');", 0, 1);
echo <<<FORM3
          </td>
         </tr>
         <tr rel="upload_seq">
          <td>
                 <span class="accessibility">
If you would like to upload  your sequence,choose a DNA sequence to upload:
                 </span>
             <input type="hidden" name="MAX_FILE_SIZE" value="350000" />
             <input type="file"  name="uploadedfile" style="height:25px;width:150px;font-weight: bold; font-size:14px;font-family:'Times New Roman'"/>
</br>
</br>
          </td>
         </tr>
        </table>
        <!-- Sequence selection content table -->
       </fieldset>
       <!-- sequence options fieldset -->
FORM3;
echo <<<FORM
            <td width=50%>
              <span class="style2">
      <!-- nucleosome placement options fieldset -->
      <fieldset>
        <legend class="style2"> Nucleosome Placement Options </legend>
       <!--energy selection table --> 
       <table>
         <tr>
 <td>
              <input type="radio" name="energy" value="energy_simple" rel="simple_energy" />
                        Use Default Parameters
          </td>

          <td>
              <input type="radio" name="energy" value="energy_default" rel="default_energy" checked />
                        Use Energy Calculations
          </td>
          <td>
              <input type="radio" name="energy" value="nss_type" rel="type_nss" />
                        Specify Nucleosome Placement
          </td>
         </tr>
       </table>
       <!--energy selection table --> 
       <!--energy content table --> 
       <table>
        <tr rel="simple_energy">
         <td>
The default energy selection will use default values for each of the parameters.  Click "Go" to fold the DNA using this selection.
</td>
</tr>
        <tr rel="default_energy">
         <td>
</br>
      <!-- energy options fieldset -->
      <fieldset>
            <legend>Energy Options</legend>
E<sub><em>nuc</em></sub> = &frac12 &sum(K(X - X<sub>0</sub>)<sup>2</sup>)
</p>
FORM;
echo "K = ";
##K value menu
menu($dirK, $dirK, ".dat", "Stiffness", "K_energy", "", 1, 1);
##X value menu
echo "\n</br>\n</br>\n X = "; 
menu($dirX, $dirX, ".par", "Nucleosomes", "X_energy", "",  1, 1);
##X0 value menu
echo "\n</br>\n</br>\nX<sub>0</sub> = ";
menu($dirX0, $dirX0, ".par", "Free", "X0_energy", "",  1, 1);
echo <<<FORM
      </fieldset>
      <!-- energy options fieldset -->
<p>
</br>
      <!-- placement options fieldset (energy)-->
      <fieldset>
        <legend>Placement Options:</legend>
Occupancy:
FORM;
textbox("occupancy_energy", "1", "3", ".70", 1, 0);
echo <<<FORM

</br>
</br>
FORM;
echo "Linker Length:";
textbox("linker_energy", "1", "3", "30", 1, 0);
echo <<<FORM
</br>
</br>
Temperature:
FORM;
textbox("temp", "1", "3", "298", 1, 0);
echo "Kelvin";
echo <<<FORM
        </td>
      </fieldset>
      <!-- placement options fieldset (energy)-->
      </tr>
      <tr rel="type_nss">
       <td>
</br>
      <!-- placement options fieldset (type nss) -->
      <fieldset>
         <legend>Placement Options</legend>
FORM;
echo "K = ";
##K value menu
menu($dirK, $dirK, ".dat", "Stiffness", "K_nss", "", 1, 1);
##X value menu
echo "\n</br>\n</br>\n X = "; 
menu($dirX, $dirX, ".par", "Nucleosomes", "X_nss", "",  1, 1);
##X0 value menu
echo "\n</br>\n</br>\nX<sub>0</sub> = ";
menu($dirX0, $dirX0, ".par", "Free", "X0_nss", "",  1, 1);
echo "</br>
</br>
 Linker Length:";
textbox("linker_nss", "1", "3", "30", "1", "1");
echo <<<FORM
<p>
FORM;
echo <<<FORM
Positions:</br>
FORM;
textbox("nss", "5", "18", "", "1", "0");

echo <<<FORM
</br>
      </fieldset>
      <!-- placement options fieldset (type nss) -->
       </table>
       <!--energy content table --> 
        </tr>
<p>
      </fieldset>
      <!-- nucleosome placement options fieldset -->
      </span>
  </td>
  </table>
  <!-- main table -->
<p align="center">
FORM;
button("submit", "Go", "", $buttonstyle1);
button("button", "Reset", "ONCLICK=\"window.location.href='$_SERVER[PHP_SELF]'\" $buttonstyle1 ");
echo <<<FORM
</p>
</form>
FORM;
htmlend();
}

########################################################################################
########################################################################################
##This function prints all output from the form.
function print_output() {
global $basewebdir, $betaformxyz, $chromatinxyz, $cssout, $jmolscript, $seqin, $SID, $webdir, $usrbin;
htmlbegin($jmolscript, $cssout);
echo <<<OUT1
<div style="text-align: left;" id="wrap">
<span style="color:FF9900;"></span><span
style="color:FF9900;"></span>
<div id="main-content">
<div style="text-align: center;"><a rel="me"
target="_blank" href="$webdir$SID/wsl.png"><span
style="color:CCE4D9;">Click
images for larger view</span></a></div>
<table style="width: 100%; text-align: left; margin-left: 0px; margin-right: auto;"
border="1" cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td style="text-align: center;">
<h2><a rel="me" target="_blank"
href="$webdir$SID/wsh.png">Shift</a></h2>
<div id="main-content">
<ul>
<li><a rel="me" target="_blank"
href="$webdir$SID/wsh.png"><img
style="border: 0px solid ;" src="$webdir$SID/thumb.wsh.png"
alt="Shift"></a></li>
</ul>
</div>
</td>
<td style="text-align: center;">
<h2><a rel="me" href="$webdir$SID/wti.png"
target="_blank">Tilt</a></h2>
<div id="main-content">
<ul>
<li><a rel="me" target="_blank"
href="$webdir$SID/wti.png"> <img
style="border: 0px solid ;" src="$webdir$SID/thumb.wti.png"
alt="Tilt"></a></li>
</ul>
</div>
</td>
<td colspan="1" rowspan="3">
<div style="text-align: center;">
<h2><span style="color:FF9900;">&nbsp;Java
may take a moment to
load.</span><span style="color:FF9900;"></span></h2>
<h2><span style="color:FF9900;">Please be patient.</span></h2>
</div>
<p style="text-align: center;"> <a
target="_blank" rel="me" href="$webdir$SID/EL.png">
<img alt="Nucleosome Footprint"
style="border: 0px solid ; width: 205px; height: 205px;"
src="$webdir$SID/E.png"></a></p>
<p align="center"><a target="_blank"
rel="me" href="$webdir$SID/EL.png">Click for a larger
view</a></p>
</br>
<h3 align="center"><a href="$webdir$SID/E.dat">Save
Energy data </a><a href="$webdir$SID/E-L.png"></br>
</a>
</h3>
      <table align="center" border="0">
        <tbody>
          <tr>
            <td>
            <h3 align="left"> Free DNA</br>
        <script>
jmolInitialize("$basewebdir/jmol"); // REQUIRED
jmolApplet(150, value = "load $webdir/$SID/eq.out.xyz; spin on; script $basewebdir/prog/nuc-cores.txt");
jmolBr(); // a button
jmolButton("reset", "Reset");
        </script>
            </h3>
            <h3 align="center">
            <form><a =""><input value="Larger Window" onclick="window.open('$webdir$SID/betaform.html','JmolBeta','width=525,height=600')" type="button"/></a></form>
            </h3>
            </td>
            <td>
            <h3 align="right"> Chromatin</br>
        <script>
jmolApplet(150, value = "load $webdir/$SID/icm.occ.xyz; spin on; script $basewebdir/prog/nuc-cores.txt");
jmolBr(); // a button
jmolButton("reset", "Reset");
        </script>
            </h3>
            <h3 align="center">
            <form><a =""><input
 value="Larger Window"
 onclick="window.open('$webdir$SID/chromatin.html','JmolChromatin','width=525,height=600')"
 type="button"/></a></form>
            </h3>
            </td>
          </tr>
        </tbody>
      </table>
</p> </br>
<h2><span style="color: #FFFFFF ;"> 
OUT1;
passthru("cd $sesspath$SID ; $usrbin/errorcheck");
echo <<<OUT2
</span></h2>
      <br style="color:FF9900;">
      <div style="text-align: center;">
      <h2><span style="color:FF9900;">Right
Click the Jmol image&nbsp;for
available options</span></br>
      <span style="color:FF9900;"></br>
      </span><span style="color:FF9900;"><a
 target="_blank"
 href="http://www.java.com/en/download/manual.jsp"
 style="color:FF9900;">Download Java here</a></br>
      </span></h2>
      </div>
      </br>
      </td>
      <td></td>
    </tr>
    <tr>
      <td style="text-align: center;">
      <h2><a href="$webdir$SID/wsl.png" rel="me"
 target="_blank">Slide</a></h2>
      <div id="main-content">
      <ul>
        <li><a rel="me" target="_blank"
 href="$webdir$SID/wsl.png"> <img
 style="border: 0px solid ;" src="$webdir$SID/thumb.wsl.png"
 alt="Slide"></br>
          </a></li>
      </ul>
      </div>
      </td>
      <td style="text-align: center;">
      <h2><a href="$webdir$SID/wro.png" rel="me"
 target="_blank">Roll</a></h2>
      <div id="main-content">
      <ul>
        <li><a rel="me" target="_blank"
 href="$webdir$SID/wro.png"><img
 style="border: 0px solid ;" src="$webdir$SID/thumb.wro.png"
 alt="Roll"></br>
          </a></li>
      </ul>
      </div>
      </td>
    </tr>
    <tr>
      <td style="text-align: center;">
      <h2><a href="$webdir$SID/wri.png" rel="me"
 target="_blank">Rise</a></h2>
      <div id="main-content">
      <ul>
        <li><a rel="me" target="_blank"
 href="$webdir$SID/wri.png"><img
 style="border: 0px solid ;" src="$webdir$SID/thumb.wri.png"
 alt="Rise"></br>
          </a></li>
      </ul>
      </div>
      </td>
      <td style="text-align: center;">
      <h2><a target="_blank" href="$webdir$SID/wtw.png"
 rel="me">Twist</a></h2>
      <div id="main-content">
      <ul>
        <li><a target="_blank" rel="me"
 href="$webdir$SID/wtw.png"><img
 style="border: 0px solid ;" src="$webdir$SID/thumb.wtw.png"
 alt="Twist"></a></li>
      </ul>
      </div>
      </td>
    </tr>
  </tbody>
</table>
</div>
<p align="center">
OUT2;
button("button", "Reset", "ONCLICK=\"window.location.href='$_SERVER[PHP_SELF]'\" $buttonstyle1 ");
echo <<<OUT2
</p>
</div>
</body>
</html>
OUT2;
}
################################################################################################################################################################################
function jmol_html($infile, $outfile) {
global $basewebdir, $sesspath, $SID, $webdir;
$string = 
<<<JMOL1
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <script src="$basewebdir/jmol/Jmol.js"
 type="text/javascript">
  </script>
  <meta content="text/html; charset=ISO-8859-1"
 http-equiv="content-type">
  <title>Bishop Lab -</title>
</head>
<body>
        <script>
jmolInitialize("$basewebdir/jmol"); // REQUIRED
jmolApplet(500, value = "load $webdir/$SID/$infile; spin on; script $basewebdir/prog/nuc-cores.txt");
jmolBr(); // a button
jmolButton("reset", "Reset to original orientation");
            </script>
</body>
</html>
JMOL1;
$fn = "$sesspath/$SID/$outfile";
$fp = fopen($fn, 'w+');
	{fwrite($fp, $string );}
       fclose($fp);
}




################################################################################################################################################################################

################################################################################################################################################################################

##CALL FUNCTIONS AS NEEDED
counter();
if (isset($_POST['stage']) && ('process' == $_POST['stage'])) { 
 if (empty($errors)) {
   makeconfin();
   if ($_POST['energy'] == "nss_type"){ pc_validate_nss(); }
   }
if (($_POST['energy'] == "energy_default") || ($_POST['energy'] == "energy_simple")){
if (empty($errors)) { exec("cd $sesspath$SID ; cat $sesspath$SID/confin.txt | $usrbin/icm");}
}
if ($_POST['energy'] == "energy_default"){ 
$temp = $_POST['temp'];
}
if ($_POST['energy'] == "nss_type"){
if (empty($errors)) { exec("cd $sesspath$SID ; cat $seqscanfile | $usrbin/icm");
if (!file_exists("$sesspath$SID/icm.par")) {$errors['icm.par'] = "icm.par  does not exist.";}
}
if (empty($errors)) { exec("cd $sesspath$SID ; cat $sesspath$SID/confin.txt | $usrbin/fold-conf" );}
if (empty($errors)) { exec("cd $sesspath$SID ; $usrbin/nss.awk  E.dat  $nuclength > icm.dat");
if (!file_exists("$sesspath$SID/icm.dat")) {$errors['icmdat'] = "icm.dat does not exist.";}                                                                
}
}
elseif (FALSE == empty($errors))  {print_form();}
if (empty($errors)) { exec("cd $sesspath$SID ;$usrbin/make-xyz-from-par.tcsh $numnuc $temp ");}
if (empty($errors)) {exec("cd $sesspath$SID ; $usrbin/makepng.tcsh");
if (!file_exists("$sesspath$SID/eq.out.xyz") && (filesize("$sesspath$SID/icm.xyz")<4000)) {$errors['eqout'] = "ICM web failed to make a model.  Please check your inputs and try again, or e-mail bishop@tulane.edu with subject: $SID error.";}
if (!file_exists("$sesspath$SID/icm.xyz") && (filesize("$sesspath$SID/icm.xyz")<4000)) {$errors['icm'] = "ICM web failed to make a model.  Please check your inputs and try again, or e-mail bishop@tulane.edu with subject: $SID error";}}
if (empty($errors)){ 
print_output();
jmol_html("eq.out.xyz", "betaform.html");
jmol_html("icm.occ.xyz", "chromatin.html");
}
if (!empty($errors))  {print_form();}
}
else  { print_form(); }
?>
