<?php
##Title:                index.php
##Author:               Rich Stolz
##Last Updated:         $Id: index.php,v 1.8 2009/05/29 20:32:29 rstolz Exp $ 
##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

##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
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['requpseq'])) {
   if ($_POST['requpseq'] == 1) {
   $requpseq = 1;}
   }
else{$requpseq = 0;}



#SEQ menu vars
if ($_POST['requpseq'] == 1) {
   $requpseq = 1; }
else{ $requpseq = 0; }

if (isset($seqform)) {}
else {$seqform = 0;}
if (isset($_POST['K'])){$K = $_POST['K'];} 
else {$K = "$usrbin/DAT/K/fl.dat";}
if (isset($_POST['linker'])){$linker = $_POST['linker'];} 
else {$linker ="0";}
if (isset($_POST['nss'])){$nss = $_POST['nss'];} 
else {$nss ="";}
if (isset($_POST['percentnucleo'])){$percentnucleo = $_POST['percentnucleo'];} 
else {$percentnucleo ="80";}
if (isset($_POST['seqin'])){$seqin = $_POST['seqin'];} 
if (isset($_POST['X'])){$X = $_POST['X'];} 
else {$X = "0";}
if (isset($_POST['X0'])){$X0 = $_POST['X0'];} 
else {$X0 ="0";}


########################################################################################
########################################################################################

########################################################################################
########################################################################################
##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, $errors, $K, $linker, $MMTV, $nuclength, $nss, $nssarr, $numnuc, $percentnucleo, $reqtypenss, $requpseq, $seqscanfile, $seqinlength,  $sesspath, $seqin, $SID, $validseq, $X, $X0;

$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 (1 == $requpseq ) {
       uploader();
       $fh0 = fopen($uploadfile, 'r');
       $seqin = fread($fh0, filesize($uploadfile));
       fclose($fh0);
      }
  if (1 == $reqtypenss) {
	$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
       $nssarr = split("[\n\r\t ,]+", trim($nss));
       $numnuc = count($nssarr);
       $nss = implode("\n", $nssarr);
       	   $confin = "$linker\n$X\n$sesspath$SID/seqin.txt\n$nss\n-1\n$sesspath$SID/icm.par";
       }
   elseif (0 == $reqtypenss) {
$seqinlength = (strlen(trim(chunk_split(strtoupper(preg_replace('/[^A,T,G,C]/i','', $seqin)), 1, "\n")))+1)/2;
	$numnuc = floor($percentnucleo*$seqinlength/($nuclength+$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 ($percentnucleo < 1 ) {
        $numnuc = floor($percentnucleo*$seqinlength/($nuclength+$linker));
        }
	elseif ($percentnucleo < 0 ) {
        $numnuc = floor($numnuc) + 2 ;
	}
	elseif ($percentnucleo > 1 ) {
	$numnuc = $percentnucleo;
	}
$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 (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.";
        $validseq = FALSE;}
	##otherwise make $validseq true as to use in determining if form should 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);

  	##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 350Kb
  $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)) {
        ##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 the file with another name and try again.";
      }
  } else {
     echo "Error: Only files under 1Gb 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, $percentnucleo, $seqinlength, $sesspath, $SID, $validnss, $X;
	##verify entry contains only  numerical entries
	if (preg_match('/[^0-9,\s]/i', $_POST['nss']) == TRUE)
	{
	$nsscond1 = FALSE;
	$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);
	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'] = "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) {
	  $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 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.";
            $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 
<<<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
 </body>
</html>
HTMLEND;
}


##This function makes the Go/Reset buttons
function button ($type, $value, $onclick, $style){
echo <<<BUTTON
<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, $nssintype_1, $reqtypenss, $requestnss, $requestnss0, $requpseq, $seqin, $SID, $webdirSeq, $X;


if (isset($seqin)){}
else {$seqin = "$directions";}

##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
echo <<<OPTGROUP
    <optgroup label="$selectname parameter">

OPTGROUP;
  foreach( $files AS $name ) {
    echo "     <option value=\"$outdir$name\">" . substr($name,0,20) . "</option> \n";}
echo <<<OPTGROUP
    </optgroup>
OPTGROUP;
}



##Determine if directions or the user's sequence should be printed in the textbox


##This function prints the text boxes
function textbox($name, $rows, $cols, $input) {
$textboxstyle = <<<STYLE
font-weight: bold; font-size:14px;font-family:Times New Roman background:#ffffe0; color:#000000; padding-left: 6px; padding-right: 6px; border: 10px  #FFFFFF;
STYLE;
echo <<<TEXTBOX

<TEXTAREA name=$name rows=$rows cols=$cols style=$textboxstyle>$input</TEXTAREA>
TEXTBOX;
}

##This function makes the Skip buttons
function requestbutton ($requpseq_val, $reqtypenss_val, $buttonname, $preface, $postscript) {
global $seqin, $X;
echo <<<REQBUT
$preface
<FORM action="$_SERVER[PHP_SELF]"  method="post" >
  <input type="hidden" name="requpseq" value= $requpseq_val>
  <input type="hidden" name="reqtypenss"  value= $reqtypenss_val>
  <input type="submit"value="$buttonname"
    style="height:15px; width:40px; color:FF9900;
    font-weight: bold; font-size:10px; font-family:Times New Roman;">
</p>
</FORM>

$postscript
REQBUT;
}


##Begin printing form
htmlbegin( "", "$cssbishop");
echo <<<FORM1

 <body>
  <h2 align="center">
    <font style="font-weight: bold;" size="+1">
    <span style="color:FF9900;">
FORM1;
errors();
echo <<<FORM2

    </span>
    <span class="style1">
Interactive Chromatin Folding
    </span>
  </h2>
  <table align="center" width="600" border="6">
FORM2;

if ($reqtypenss == 1 ) {
requestbutton("$requpseq", "0", "E_Use", "", ""); 
}
if ($reqtypenss == 0) {
requestbutton("$requpseq", "1", "E_Skip", "", "");
}
if ($requpseq == 0) {
requestbutton("1", "$reqtypenss", "S_Skip", "", "");
}
if ($requpseq == 1) {
requestbutton("0", "$reqtypenss", "S_Use", "", "");
}
echo <<<FORM2
    <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">
      <input type="hidden" name= "reqtypenss" value= "$reqtypenss">
<td>
      <fieldset>
       <legend> Sequence Options: </legend>
</br>
FORM2;
if ($requpseq == 0) {
      textbox("seqin", "20", "50", $seqin);
echo <<<FORM2
<br>
<br>
    <span style="color:FF9900;">Try one of our samples here:&nbsp;</span>
<br>
     <select name="seqmenu" onchange="window.open(this.options[this.selectedIndex].value,'_blank');">
FORM2;
     menu($dirSeq, $webdirSeq, ".txt", "Seq");
echo "</select>";
}
if ($requpseq == 1) {


echo <<<SEQUPLOAD

Choose a DNA sequence to upload:
<br>
  <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>
<br>
SEQUPLOAD;
} 
echo <<<FORM2
</td>
</fieldset>
FORM2;
echo "<td>";
if ($reqtypenss == 0){
echo "</br>
<span class=\"style2\">
<br>
     <fieldset>
      <legend> Energy Options: </legend>
<br>
    <span class=\"style2\">
E<sub><em>nuc</em></sub> = &frac12 K(X - X<sub>0</sub>)<sup>2</sup>
</p>";
##K value menu
echo "K = <select name=\"K\" $option \'>";
menu($dirK, $dirK, ".dat", "K");
echo "</select> </p>";
##X value menu
echo "X = <select name=\"X\" $option \'>";
menu($dirX, $dirX, ".par", "X");
echo "</select> </p>";  
##X0 value menu
echo "X<sub>0</sub> = <select name=\"X0\" $option \'>";
menu($dirX0, $dirX0, ".par", "X0");
echo <<<FORM3
</select> 
<p>
    </span>
   </fieldset>
<br>
    <span class = "style2">
   <fieldset>
    <legend>Placement Options:</legend>
<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>
Occupancy:
FORM3;
textbox("percentnucleo", "1", "3", ".70");

echo <<<FORM
</p>
Linker Length: 
FORM;
textbox("linker", "1", "3", "30");
echo <<<FORM3
</fieldset>
</span>
</p>
FORM3;
}
else { 
echo <<<XMENU
<fieldset>
 <legend>Placement Options</legend>
<span class = "style2">
X = <select name="X" $option \'>
XMENU;
menu($dirX, $dirX, ".par", "X");
echo " </select>
<br>";
echo <<<FORM
<br>
Linker Length:
FORM;
textbox("linker", "1", "3", "30");
echo <<<FORM
<p>
Positions:<br>
FORM;
textbox("nss", "5", "30", "Replace text with Nucleosome Start Sites");
echo <<<FORM
</span>
<p>
FORM;
}
echo <<<FORM
<p>
</td>
</fieldset>
</table>
<p align="center">
FORM;
button("submit", "Go", " ", $buttonstyle1);
button("button", "Reset", "ONCLICK=\"window.location.href='$_SERVER[PHP_SELF]'\" $buttonstyle1 ");
echo <<<FORM6
</p>
</FORM>

</align>
</P> 
</P>
</span>
FORM6;
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);
}




################################################################################################################################################################################
function conditionsmet(){
print_output();
jmol_html("eq.out.xyz", "betaform.html");
jmol_html("icm.xyz", "chromatin.html");
}


################################################################################################################################################################################

##CALL FUNCTIONS AS NEEDED
counter();
if (isset($_POST['stage']) && ('process' == $_POST['stage'])) { 
 if (empty($errors)) {
makeconfin();
     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 ; $usrbin/nss.awk  E.out  $nuclength > E.dat");
exec("cd $sesspath$SID ; $usrbin/make-xyz-from-par.tcsh $numnuc ");
exec("awk < $sesspath$SID/icm.dat '{ print $1, $3 }' > $sesspath$SID/icmgraph.dat");
passthru("cd $sesspath$SID ; $usrbin/makepng.tcsh");
print_output();
jmol_html("eq.out.xyz", "betaform.html");
jmol_html("icm.xyz", "chromatin.html");
}
}
        else  { print_form(); }
 }
     elseif ($reqtypenss == 0){
	if (empty($errors))  {
	exec("cd $sesspath$SID ; cat $sesspath$SID/confin.txt | $usrbin/icm");
	exec("cd $sesspath$SID ; $usrbin/make-xyz-from-par.tcsh $numnuc ");
	exec("awk < $sesspath$SID/E.dat '{ print $1, $3 }' > $sesspath$SID/icmgraph.dat");
	exec("gracebat -par $sesspath$SID/E.dat autoscale y -hardcopy -hdevice PNG -printfile $sesspath$SID/E.png -fixed 400 320 -nxy $sesspath$SID/E.dat");
	exec("cd $sesspath$SID ; $usrbin/makepng.tcsh");
	conditionsmet();
jmol_html("eq.out.xyz", "betaform.html");
jmol_html("icm.xyz", "chromatin.html");
}
        elseif (FALSE == empty($errors))  {print_form();}
     }
}
else {print_form();}
}
else {print_form();}
?>
