
<?php

include("variables.php");

########################################################################################
########################################################################################
##Define variables

##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.  T
##define array $errors
if (isset($errors)) {}
else {$errors = array();}

##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);}


#NSS menu vars - these variables are used for the functionality of selecting the nucleosome start sites.
if (isset($_POST['reqtypenss'])) {
   if ($_POST['reqtypenss'] == 1) {
       $reqtypenss = 1;}
} else {$reqtypenss = 0;}

if (isset($_POST['seqform'])) {
   if ($_POST['seqform'] == 1) {
       $seqform = 1;}
} else {$seqform = 0;}

### $nssintype_1 = "";

if (isset($_POST['K'])){$K = $_POST['K'];} 
else {$K = "0";}

if (isset($_POST['X'])){$X = $_POST['X'];} 
else {$X = "0";}

if (isset($_POST['X0'])){$X0 = $_POST['X0'];} 
else {$X0 ="0";}

if (isset($_POST['linker'])){$linker = $_POST['linker'];} 
else {$linker ="0";}

if (isset($_POST['nss'])){$nss = $_POST['nss'];} 
else {$nss ="";}

if (isset($_POST['numnuc'])){$numnuc = $_POST['numnuc']*1.0;} 
else {$numnuc ="0";}

if (isset($_POST['seqin'])){$seqin = $_POST['seqin'];} 




################################################################################################################################################################################


#SEQ menu vars
if (isset($_POST['requpseq'])) {
   if ($_POST['requpseq'] == 1) {
   $requpseq = 1;
   }
elseif($_POST['requpseq'] == 0){
   $requpseq = 0;
   }
}

########################################################################################
##########################################################################################Define Functions


################################################################################################################################################################################
##This function simply 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 SIDmTen controls how many full session directories are kept and how many are archived
$SIDmTen = $SID - 10;
$dir = "$sesspath/$SIDmTen";
$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 makeconfig() as to verify that all characters are valid. 
##  This was done in this manner as to allow makeconfig work with both form data and uploaded data.



########################################################################################
function makeconfig() {
global $confin, $directions, $errors, $K, $linker, $MMTV, $nuclength, $nss, $nssarr, $numnuc,$reqtypenss, $requpseq, $seqscanfile, $seqinlength,  $sesspath, $seqin, $SID, $validseq, $X, $X0;

## This function writes the sequence file and confirms that all user input data is valid, 
## then writes the confin file
## make global variables


$seqinfile = "$sesspath$SID/seqin.txt";
$uploadfile = "$sesspath/$SID/uploaded.txt";

#Read nuclength from $X file
$fh = fopen($X, 'r');
$nuclength = fread($fh, 5);
fclose($fh);

$subseq = substr($seqin, 0, 15);
$subdirections = substr($directions, 0, 15);
if ($subseq == $subdirections){
$seqin = $MMTV;}

  if ($requpseq == 1 ) {
       uploader();
       $fh0 = fopen($uploadfile, 'r');
       $seqin = fread($fh0, filesize($uploadfile));
       fclose($fh0);
  }
  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'] = "ERROR:your sequence must have only: a, t, g, c, \n A, T, G, C \n or spaces.";
        $validseq = FALSE;
   ##otherwise make $validseq true so form can be reprinted
  } else {$validseq = TRUE;}
  $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);

  if ($reqtypenss == 1) {
       $eqconfin = "$X0\n$sesspath$SID/seqin.txt\n$sesspath$SID/eq.out.par\n";
       $fn = "$sesspath/$SID/eq.conf.in";
       $fp = fopen($fn, 'w+');
         fwrite($fp, $eqconfin );
       fclose($fp);
       $seqscandat = "$X0\n$X\n$K\n$sesspath$SID/seqin.txt\n$sesspath$SID/E.out";
       $seqscanfile = "$sesspath$SID/seqscan.txt";
       $fp = fopen($seqscanfile, 'w+');
   	 fwrite($fp, $seqscandat );
       fclose($fp);
       #calc numnuc
       ##trim whitespaces 
       $nssarr = split("[\n\r\t ,]+", trim($nss));
       $numnuc = count($nssarr);
       $nss = implode("\n", $nssarr);                                      
       $confin = "$X0\n$X\n$sesspath$SID/seqin.txt\n$nss\n-$numnuc\n$sesspath$SID/wdna.par\n";
       }
 elseif($reqtypenss == 0) {
  ##CAUTION
  ##adding text to the string $confinE seems to affect the fortran code
  ### changing the helical parameters, energy values and so forth.
##    numnuc 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 ($numnuc < 0 ) {
      $numnuc = floor($numnuc) + 2 ;
    } elseif ($numnuc < 1 ) {
      $numnuc = floor($numnuc*$seqinlength*1.0/($nuclength+$linker));
    }
   $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";
  }

  #write confin
  $fp = fopen("$sesspath$SID/confin.txt", 'w+');
        fwrite($fp, $confin );
   fclose($fp);

}

########################################################################################
function uploader() {
##make global variables
global $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 500Kb
  $filename = basename($_FILES['uploadedfile']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "txt") && ($_FILES["uploadedfile"]) && 
    ($_FILES["uploadedfile"]["size"] < 500000)) {
    //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)) {
        //move the uploaded file to uploads/
        if ((move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$newname))) {
	   $requpseq = 1;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploadedfile"]["name"]." already exists; please save the file with another name and try again.";
      }
  } else {
     echo "Error: Only .txt files under 500Kb are accepted for upload";
  }
  } else {
    echo "Error: 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, $seqinlength, $sesspath, $SID, $validnss, $X;
#$nss1 = explode("/n", $nss);
	##verify entry contains only  numerical entries
	if (preg_match('/[^0-9,\s]/i', $_POST['nss']) == TRUE){
	  $nsscond1 = FALSE;
	  $errors['nss'] = "ERROR: nucleosome start sites are numerical values separated  by spaces";
	}else{
	##open nucleosome files and  obtain the length of the nucleosome selected.
	$fh = fopen($X, 'r');
	$nuclength = fread($fh, 5);
	fclose($fh);
   if ($nss == ""){
     $nsscond2 = FALSE;
     $errors['nssempty'] = "If the energy function is to be bypassed at least one nucleosome start site must be specified.";}
   else {
	sort($nssarr, SORT_NUMERIC);
	##delete duplicate values
	$nss = array_unique($nssarr);
	$last = end($nss);
	$maxnss = $seqinlength - $nuclength;
	if ($last > $maxnss) {
	  if ($seqinlength < $nuclength) {
	  $nsscond3 = FALSE;
	  $errors['nssseq'] = "Each selected nucleosome is $nuclength" . "bp in length. \nPlease specify a sequence that is greater than $nuclength" . "bp long.";
          }
	  elseif ($seqinlength > $nuclength) {
	  $nsscond4 = FALSE;
	  $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 site 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.";
            $nsscond5 = FALSE;
	    }else $gtnuclength = true;
	}
	}}
if($nsscond1 = FALSE || $nsscond2 = FALSE || $nsscond3 = FALSE || $nsscond4 = FALSE || $nsscond5 = FALSE){$validnss = "";}
else{$validnss = 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 <<<HEAD
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
$script
$css
<title>Chromatin Folding</title>
</head>
  <body>
HEAD;
}

function htmlend(){
echo " 
    </body>
  </html>
";}

########################################################################################
########################################################################################
##This function prints the main form that the user uses to imput data.
function print_form($seqin, $K, $X, $X0){
global $directions, $dirK, $dirX, $dirX0, $dirSeq, $Energy, $errors, $nssintype_1, $reqtypenss, $requestnss,  $requpseq, $SID, $webdirSeq;

##This function makes the menus for K, X, XO and the sample sequences.
function menu($indir, $outdir, $ext, $selectname){
$files = array();
$handle = opendir($indir);
  while($filename = readdir($handle))
  {if ( substr( $filename, -4 ) == "$ext" ) {
        $files[] = $filename;}}
closedir($handle);
sort( $files );

// Output results
  foreach( $files AS $name ) {
    echo "<option value=\"$outdir$name\">" . substr($name,0,18) . "</option> \n";}
}

##This function makes the Go/Reset buttons
function goreset ($type, $value, $onclick){
echo <<<GORESET
<INPUT TYPE="$type" VALUE="$value" style="height:30px;width:65px;font-weight: bold; font-size:16px;font-family:'Times New Roman';" $onclick> 
GORESET;
}

##Determine if directions or the user's sequence should be printed in the textbox

if (isset($_POST['seqin'])) {$seqin = $_POST['seqin'];}
else {$seqin = "$directions";}


##Define whether or not the user will see the text box to insert NSS's, or if they will see a button requesting to the text box.  The function is similiar to the seqtype() function
##These are the var that prints the default button
$nssintype0 = '';
$requestnss0 = "<FORM action=\"$_SERVER[PHP_SELF]\" method=\"post\" ><input type=\"hidden\" name= \"reqtypenss\" value= \"1\"><input type=\"hidden\" name= \"requpseq\" value= \"$requpseq\"><INPUT TYPE=\"submit\" VALUE=\" Skip \"style=\"height:15px;width:50px; font-size:10px;font-family:'Times New Roman';\"></FORM></span>";

##These are the var for the the upload button
$nssintype1 = '
<input type="hidden" name= "reqtypenss" value= "1"><TEXTAREA name="nss" rows="7" cols="15" STYLE="background:#ffffe0; color:#000000;
font-family: arial; font-size:12px; padding-left: 6px; padding-right: 6px; border: 10px">
Directions: 
****************
1) Replace this text with indices of nucleosome start sites.
</TEXTAREA>';
$requestnss1 ='';

if ($reqtypenss == 1) {
 $requestnss = $requestnss1;
 $Energy = FALSE;
 if ($requpseq == 1) {
   $nssin_type = $nssintype1;
   $nssintype_1 = $nssintype1; }
 elseif ($requpseq == 0) {
   $nssin_type = "";
   $nssintype_1 = $nssintype1;
   $requestnss = $requestnss1;}}
elseif ($reqtypenss == 0) { 
 $nssin_type = $nssintype0;
 $requestnss = $requestnss0;
 $Energy = TRUE;}

##This function defines whether or not the user will see the button to browse their file system for a sequence file, or if they will see a button requesting to upload a file.

$seqintype0='';
$requestseq0 = "<span class=\"style2\"> <FORM action=\"$_SERVER[PHP_SELF]\"  onReset=\"return allowReset()\" method=\"post\" ><input type=\"hidden\" name= \"requpseq\" value= \"1\"><input type=\"hidden\" name= \"reqtypenss\" value= \"$reqtypenss\"><input type=\"hidden\" name= \"seqin\" value= \"\$seqin\"><INPUT TYPE=\"submit\" VALUE=\"Upload Sequence\" style=\"height:25px;width:150px;font-weight: bold; font-size:14px;font-family:'Times New Roman';\"></p></FORM>";
$seqform0 = "<TEXTAREA name=\"seqin\" rows=\"15\" cols=\"50\" STYLE=\"background:#ffffe0; color:#000000;
font-family: Arial; font-size:14px; padding-left: 6px; padding-right: 6px; border: 10px  #FFFFFF;\">
$seqin
</TEXTAREA></p>
</p>
</th>
</td>
<td>";

$seqintype1 = '
Choose a DNA sequence to upload: </p> </p>
<input name="MAX_FILE_SIZE" value="350000" type="hidden">
<input name="uploadedfile" type="file" style="height:25px;width:150px;font-weight: bold; font-size:14px;font-family:\'Times New Roman\'</p></FORM>";>
';
$requestseq1 = "";
$seqform1 = "";
if ($requpseq == 1) {
  $seqin_type = $seqintype1;
  $requestseq = $requestseq1;
  $seqform = $seqform1;}
elseif ($requpseq == 0) { 
  $seqin_type = $seqintype0;
  $requestseq = $requestseq0;
  $seqform = $seqform0;}
##Begin printing form
htmlbegin("", "");
echo <<<STYLEINFO
  <body>
   <style type="text/css">
     body { color: #EBF4E1; background: #00331A; }
	 <!--
.style1 {font-size: 18px;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
	color: #ebf4e1;}
.style2 {font-size: 14px;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
	color: #ebf4e1;}
-->
   </style>

   <h2 align="center">
     <font style="font-weight: bold;" size="+1"><span
      style="color: rgb(255, 0, 0);">
STYLEINFO;
errors();
echo <<<HEADERINFO
</p>
</p>
<span class="style1">
Interactive Chromatin Folding
<br>
(I see 'em.)
<br>
</span>
<span class= "style2">
</h2>

<table align="center" border="0">
<tr>
<td>
<th align="left" width=400>
<FORM enctype="multipart/form-data" action="$_SERVER[PHP_SELF]"  onReset="return allowReset()" method="post" >
<input type="hidden" name="stage" value="process">
<input type="hidden" name= "requpseq" value= "$requpseq">
$seqform
</p>
<h3 align="center">
HEADERINFO;
###$requestseq
##echo <<<SAMPLE
##<form id="seqmenu">
##  <div align="center">
##  <select name="seqmenu" onchange="window.open(this.options[this.selectedIndex].value,'_blank');">
##SAMPLE;
##menu($dirSeq, $webdirSeq, ".txt", "Seq");

##echo <<<SAMPLE
##<form id="seqmenu">
##  <select name="seqmenu" onchange="window.open(this.options[this.selectedIndex].value,'_blank');">
##SAMPLE;
##menu($dirSeq, $webdirSeq, ".txt", "Seq");

if ($Energy == TRUE){
echo "<span class=\"style2\"> Energy Options:
$requestnss <br>
<span class=\"style2\"> 
<p>
E<sub><em>nuc</em></sub> = &frac12 K(X - X<sub>0</sub>)<sup>2</sup>
<p> " ;
echo " <h6 align=\"left\"></span>  ";
##K value menu
echo "K = <select name=\"K\"  \'>";
menu($dirK, $dirK, ".dat", "K");
echo "</select> <p> <p>";
##X value menu
echo "X =  <select name=\"X\" \'>";
menu($dirX, $dirX, ".par", "X");
echo "</select> <p> <p>"; 
##X0 value menu
echo "X<sub>0</sub> =  <select name=\"X0\" \'>";
menu($dirX0, $dirX0, ".par", "X0");
echo "</select> <p> <p>"; 
echo "</h6>" ;
} 
else {
echo "<span class=\"style2\"> Conformation: <p>" ;
echo " <h6 align=\"left\"></span>  ";
##X value menu
echo "Nucleosomes =  <select name=\"X\"  \'>";
menu($dirX, $dirX, ".par", "X");
echo "</select> <p> <p>"; 
##X0 value menu
echo "Linker =  <select name=\"X0\" \'>";
menu($dirX0, $dirX0, ".par", "X0");
echo "</select> <p> <p>"; 
echo "</h6>" ;
}

if ($reqtypenss == 0){
echo <<<OCCUPANCY
<h4 align="center"></span>
<span class = "style2">Occupancy:</u>
          <p> 
<h6 align="left"></span>
Nucleosomes: <br>
number:<input type="text" name='numnuc' size="1" value="0.7" style=height:30px;width:50px;font-weight:
 bold; font-size:14px;font-family:\'Times New Roman\'>
<br>
n > 1 : number nucleosomes <br>
n < 1 : percentage of max  <br>
n = 0 : constant nucleosome spacing <br>
n < 0 : constant spacing + shift <br>
<br>
Linker: <br>
length:<input type="text" name='linker' size="1" value="30" style=height:30px;width:50px;font-weight:
bold; font-size:14px;font-family:\'Times New Roman\'>
<br>
</h6>
</h4>

</p></p> </p> </p> </p></p>
          <h5 align="center">
OCCUPANCY;
} elseif ( $reqtypenss == 1) {
echo <<<OCCUPANCY
<h4 align="center"></span>
<span class = "style2">Positions:</u>
<br>
$nssintype_1
<br>
OCCUPANCY;
}

goreset("submit", "Go", " ");
goreset("button", "Reset", "ONCLICK=\"window.location.href='$_SERVER[PHP_SELF]'\" ");

echo <<<ENDFORM
           </FORM>
          </h5>
         </td>
        </tr>
       </table>
     </P> 
 </P>
</span>
<span style="color: rgb(255, 153, 0);">Try one of our
samples here:&nbsp;</span>
$requestseq
ENDFORM;
htmlend();
}



########################################################################################
########################################################################################
##This function prints all output from the form.
function print_output() {
global  $betaformxyz, $chromatinxyz, $cssout, $jmolscript, $seqin, $SID, $webdir, $sesspath, $progDIR ;
htmlbegin($jmolscript, $cssout);
echo <<<END
<div style="text-align: left;" id="wrap">
<span style="color: rgb(255, 153, 0);"></span><span
 style="color: rgb(255, 153, 0);"></span>
<div id="main-content">
<div style="text-align: center;">
<span style="color: rgb(204, 228, 217);">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" target="_blank" href="$webdir$SID/wti.png">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: rgb(255, 153, 0);">
          &nbsp;Java may take a moment to load.
       </span><span style="color: rgb(255, 153, 0);"></span>
      </h2>
      <h2><span style="color: rgb(255, 153, 0);">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("http://dna.ccs.tulane.edu/wdna/jmol"); // REQUIRED
jmolApplet(150, value = "load $webdir/$SID/eq.out.xyz; spin on; script http://dna.ccs.tulane.edu/wdna/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/wdna.occ.xyz; spin on; script http://dna.ccs.tulane.edu/wdna/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 ;"> 
END;
passthru("cd $sesspath$SID ; $progDIR/xyz2dists ");
echo <<<END
</span></h2>
      <br style="color: rgb(255, 153, 0);">
      <div style="text-align: center;">
      <h2><span style="color: rgb(255, 153, 0);">
         Right Click Jmol image for options
         </span><br>
         <span style="color: rgb(255, 153, 0);"><br>
      </span><span style="color: rgb(255, 153, 0);">
     <a target="_blank" href="http://www.java.com/en/download/manual.jsp"
          style="color: rgb(255, 0, 0);">Download Java </a>
       <br>
      </span></h2>
      </div>
      <br>
      </td>
      <td></td>
    </tr>
    <tr>

     <td style="text-align: center;">
      <h2> <a rel="me" target="_blank" href="$webdir$SID/wsl.png">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">
        </a>
       </li>
      </ul>
     </div>
     </td>


     <td style="text-align: center;">
      <h2> <a rel="me" target="_blank" href="$webdir$SID/wro.png">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">
        </a>
       </li>
      </ul>
     </div>
     </td>
    
    </tr>
    <tr>

     <td style="text-align: center;">
      <h2> <a rel="me" target="_blank" href="$webdir$SID/wri.png">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">
        </a>
       </li>
      </ul>
     </div>
     </td>
 
     <td style="text-align: center;">
      <h2> <a rel="me" target="_blank" href="$webdir$SID/wtw.png">Twist</a></h2>
      <div id="main-content">
      <ul>
       <li>
        <a rel="me" target="_blank" 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>
</div>
</body>
</html>
END;
}

### TcB 5/5 cleaned up html manually from top to this point
###  NOTE  that only nss seems to work correctly at this point
################################################################################################################################################################################
function jmol_html($infile, $outfile) {
global $sesspath, $SID;
$string = 
<<<END
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <script src="http://dna.ccs.tulane.edu/wdna/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(" http://dna.ccs.tulane.edu/wdna/jmol"); // REQUIRED
jmolApplet(500, value = "load http://dna.ccs.tulane.edu/wdna/sessions/$SID/$infile; spin on; script http://dna.ccs.tulane.edu/wdna/prog/nuc-cores.txt;");
jmolBr(); // a button
jmolButton("reset", "Reset to original orientation");
            </script>
</body>
</html>
END;
$fn = "$sesspath$SID/$outfile";
$fp = fopen($fn, 'w+');
	{fwrite($fp, $string );}
       fclose($fp);
}




################################################################################################################################################################################
function conditionsmet(){
print_output();
jmol_html("eq.out.xyz", "betaform.html");
jmol_html("wdna.occ.xyz", "chromatin.html");
}


################################################################################################################################################################################

##CALL FUNCTIONS AS NEEDED
counter();
if (isset($_POST['stage']) && ('process' == $_POST['stage'])) { 
 if (empty($errors)) {
makeconfig();
     if ($reqtypenss == 1)      { 
pc_validate_nss();
 if (empty($errors)) {
        if(($validseq = TRUE) && ($validnss = TRUE)){
exec("cd $sesspath$SID ; cat $sesspath$SID/confin.txt | $usrbin/fold-conf");
exec("cd $sesspath$SID ;cat $seqscanfile | $usrbin/seq-scan");
exec("cd  $sesspath$SID ; cat $sesspath$SID/eq.conf.in | $usrbin/eq-conf");
exec("cd $sesspath$SID ; $progDIR/nss.awk  E.out  $nuclength > $sesspath$SID/wdna.dat");
exec("cd $sesspath$SID ; $progDIR/make-xyz-from-par.tcsh $numnuc ");
exec("awk < $sesspath$SID/wdna.dat '{ print $1, $3 }' > $sesspath$SID/wdnagraph.dat");
passthru("cd $sesspath$SID ; /home/www/htdocs/wdna/prog/makepng.tcsh");
print_output();
jmol_html("eq.out.xyz", "betaform.html");
jmol_html("wdna.occ.xyz", "chromatin.html");
}
}
        else  { print_form(); }
 }
     elseif ($reqtypenss == 0){
 if (empty($errors)) {
	if (TRUE == $validseq)  {
	exec("cd $sesspath$SID ; cat $sesspath$SID/confin.txt | $usrbin/icm");
	exec("cd $sesspath$SID ; $progDIR/make-xyz-from-par.tcsh $numnuc ");
	exec("awk '{print $1, $3}' $sesspath$SID/wdna.dat > $sesspath$SID/wdnagraph.dat");
	exec("gracebat  -autoscale y -hardcopy -hdevice PNG -printfile $sesspath$SID/E.png -fixed 400 320 -nxy $sesspath$SID/wdna.dat");
	exec("cd $sesspath$SID ; $progDIR/makepng.tcsh");
 if (empty($errors)) {
	conditionsmet();
	}}
  else  { print_form(); }
        }
        elseif (FALSE == $validseq)  {print_form();}
     }
}
else {print_form();}
}
else {print_form();}
?>
