<p class="Body-P"><span class="Body-C5"><a href = "DASR_count.html">Return</a></span></p>

<?php

$bedfile_id  = $_POST["file"];
$chr = $_POST["chr"];
$start=(int)$_POST["startpos"];
$end=(int)$_POST["endpos"];
$action=$_POST["action"];


if ($start>$end)
{die("chromosome start position is greater than end position!");}

$con = mysql_connect("localhost","root2","SMUCKrasp23");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }  
  
mysql_select_db("dasr", $con)
or die ("could not select database!");

if ($chr=="All chromosomes" and !$start and !$end)
$query = "";

if (!$start and !$end and $chr != "All chromosomes")
$query = "WHERE chrom = '$chr'";

if ($start or $end)
$query= "WHERE chrom = '$chr' AND chromstart> $start  AND chromend< $end;";

if ($bedfile_id)
$query = "WHERE  bedfile_id=$bedfile_id and chrom = '$chr';";

if ($bedfile_id and $chr == "All chromosomes" )
$query = "WHERE bedfile_id=$bedfile_id;";






if ($action=="Count Reads"){

$result = mysql_query("Select count(*) from summarybed $query;");

$row = mysql_fetch_row($result);
$table1 = $row[0];

print "The file you have chosen is: $bedfile_id<br/>";
print "Chromosome: $chr<br/>";
print "Position $start to $end <br/>";
print "Query result:  $table1<br/>";
#print "End of the if statement for  Count Reads";
}

if ($action=="View Reads across all chromosomes"){
$result = mysql_query("select chrom, count(*) From summarybed where bedfile_id = $bedfile_id Group by chrom order by chrom;");
//printing the table
echo "<table border='1'>";
echo "<table border='1'>
<tr>
<th>chrom</th>
<th>count(*)</th>
</tr>";

$count = array();
$chr   = array();
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['chrom'] . "</td>";
echo "<td>" . $row['count(*)'] . "</td>";
array_push($count,$row['count(*)']);
array_push($chr,$row['chrom']);
echo "</tr>";
}
echo "</table>";

//After printing the table, want to give the total number of reads
//Want to return the total count for the file (same as above)

$total_read = mysql_query("Select count(*) from summarybed WHERE bedfile_id=$bedfile_id;");
//Need to get the number from the resulting query
$row_total_read = mysql_fetch_row($total_read);
$total_read_number = $row_total_read[0];
print "Total number of reads for this BED file is: $total_read_number <br/>";

//Creating the pie chart
$count_str = join(",",array_values($count));
$chr_str = join("|",array_values($chr));

$color_inx1 = rand(0,2);
$color_inx2 = $color_inx1 +1;
$color_array = array("FF0000","0000FF","00FF00","BB0000");
//print (gettype($count_str));
$chart1 = "<img src = 'https://chart.googleapis.com/chart?
chs=300x225
&cht=p
&chd=t:$count_str
&chl=$chr_str
&chco=$color_array[$color_inx1],$color_array[$color_inx2]'
/>";
print $chart1;
}//end of the if statement
mysql_close($con);
exit;
?>  

