<?php
//*******************//
//*****MAIN CODE*****//
//*******************//
//************get parameters*************
// test drive
//print_r(compare_bed_files(225, 226, 20));

function compare_bed_files($bedfile_id1, $bedfile_id2, $bp_overlap) {
    require_once 'compare.functions.php';
    require_once 'const.inc.php';
    require_once 'util.function.php';
    require_once 'db.function.php';
    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'WELCHgrape55';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
    $dbname = 'dasr';
    mysql_select_db($dbname);
    $overlaps = $bp_overlap;
    if($overlaps < 1) {
        $overlaps = 1;
    }
	
    //print "Overlaps Cutoff: $overlaps bps<br/>";
    #################### Output data from Mysql into text files #########################
    $q1 = "select filetype, name from bedfile where bedfile_id = $bedfile_id1";
    $q2 = "select filetype, name from bedfile where bedfile_id = $bedfile_id2";
    $row = mysql_fetch_row(mysql_query($q1));
    $table1 = $row[0];
    $name1 = $row[1];
    //$filename1 = $row[1];   // need table1 name
    $row = mysql_fetch_row(mysql_query($q2));
    $table2 = $row[0];
    $name2 = $row[1];
    //$filename2 = $row[1];   // need table2 name
    //print "Compared Files: (1)$filename1  (2)$filename2<br/>";
    if(!$table1 || !$table2) {
        die("Invalid bedfile ID specified for compare().\n");
    }

    $temp = FILE_REPOSITORY_PATH . "/" . uniqid();
    mkdir($temp);
    // mysql user must have write perms
    chmod($temp, 0777);
    $filename1 = uniqid();
    $filename2 = uniqid();

    $db = getDB();
    if($table1 == 'rawbed') {
        //copy($db->getOne("select filepath from rawbed where bedfile_id = ?", $bedfile_id1), "$temp/$filename1");
        $basefile = $db->getOne("select filepath from rawbed where bedfile_id = ?", $bedfile_id1);
        `cut -f1-6 $basefile > $temp/$filename1`;
    } else {
        //$table1 = "${table1}_real";
        $q3 = "select chrom,chromstart,chromend,name,score,strand from $table1 where bedfile_id = $bedfile_id1 order by chrom,chromstart into outfile '$temp/$filename1'";
        //$q3 = "select chrom,chromstart,chromend,name,score,strand from ${table1}_real where bedfile_id = 1 order by chrom,chromstart into outfile '$temp/$filename1'";
        mysql_query($q3) or die ("Error q3: $q3\n");
    }

    if($table2 == 'rawbed') {
        //$table2 = "${table2}_real";
        //copy($db->getOne("select filepath from rawbed where bedfile_id = ?", $bedfile_id2), "$temp/$filename2");
        $basefile = $db->getOne("select filepath from rawbed where bedfile_id = ?", $bedfile_id2);
        `cut -f1-6 $basefile > $temp/$filename2`;
    } else {
        $q4 = "select chrom,chromstart,chromend,name,score,strand from $table2 where bedfile_id = $bedfile_id2 order by chrom,chromstart into outfile '$temp/$filename2'";
        //$q4 = "select chrom,chromstart,chromend,name,score,strand from ${table2}_real where bedfile_id = 2 order by chrom,chromstart into outfile '$temp/$filename2'";
        mysql_query($q4) or die ("Error q4: $q4\n");
        // prepend header onto file?
    }

    #################### Run bedtool #########################
    //$temp = "temp/result.bed";
    $resultfile = uniqid();
    //$action = "/var/www/DASR_2011/BEDTools-Version-2.11.2/bin/intersectBed -wao -a $temp/$filename1 -b $temp/$filename2 > $temp/$resultfile";  // original overlapped file
    $action = "/var/www/DASR_2011/BEDTools-Version-2.11.2/bin/intersectBed -wao -a $temp/$filename2 -b $temp/$filename1 > $temp/$resultfile";  // original overlapped file
    system($action); // call BEDTools

    ############### Get cutoff processed file(combined columns)################
    $random_number = genRandomString();
    //print "<br/><b>Please Keep Your Retrieval ID: $random_number<b><br/>";
    $new_file = "$temp/". uniqid() ."_combinedcolumns.txt";                              //combined columns
    overlaps_cut($new_file, "$temp/$resultfile", $overlaps);

    ###############overlap_bedfile(overlap interval)################
    $new_file1 = "$temp/". uniqid() . "_overlapbedfile.txt";                      // overlap_bedfile
    $fh = fopen($new_file, "r") or exit("Unable to open $new_file!");            // read from an original overlapped file, $temp
    $fh1 = fopen($new_file1, "w") or exit("Unable to write $new_file1!");		   // write into a new overlapped file
    while(!feof($fh)) {
	$line = fgets($fh);
	$chr  = explode("\t", $line);
	for($i = 1; $i <= sizeof($chr) - 1; $i++) {
            if($chr[$i] == $chr[0]) {
                $i += 1;
                $low = max($chr[$i], $chr[1]);       // low boundary of the overlap interval
                $high = min($chr[$i + 1], $chr[2]);	   // high boundary of the overlap interval
                fwrite($fh1, "$chr[0]\t$low\t$high\n");
            }
	}
    }
    fclose($fh);
    fclose($fh1);
    //system("chmod a+x 777 $new_file");
    //system("chmod a+x 777 $new_file1");


	##################ADDED BY G.Bonilla 06/13/2012 #################
	################## insert results of overlap into summarybed table #############
/*
	$err = '';
    if(trim(`/usr/bin/wc -l $new_file1`) > RAWBED_THRESHOLD) {
        #$db->query("insert into rawbed (bedfile_id, filepath) values (?,?)", array($bedfile_id1, $new_file1));
        #$filetype = 'rawbed';
    } else {
        require_once 'load_bed.function.php';
        $err = load_bed($bedfile_id1, $new_file1);
        if(!$err) {
            unlink($new_file1);  // save space
            $filetype = 'summarybed';
        } else {
            $db->query("update bedfile set descr = ? where bedfile_id = ?", array($err, $bedfile_id1));
            #$db->query("insert into rawbed (bedfile_id, filepath) values (?,?)", array($bedfile_id1, $new_file1));
            #$filetype = 'rawbed';
        }
    }
*/	################----- end of added by G.B.------------------################################


    #################### Plot Graphics #######################
    $chromosome = chromosome_count($new_file);
    $fmt_xaxis = join("|",array_keys($chromosome));
    $fmt_yaxis = join(",",array_values($chromosome));
    //cht (chart type), chd (data), and chs (chart size)
    //print max(array_values($chromosome));
    $chart1 = "https://chart.googleapis.com/chart?".
    "cht=bvs".
    "&chxt=x,y,y".
    "&chm=N,000000,0,-1,11".
    "&chxl=
	0:|$fmt_xaxis|
	2:|Overlap|counts|".
	"&chxp=2,100,90".
	"&chxs=2,0000FFFF".
    "&chd=t:$fmt_yaxis".
    "&chxr=1,0,".max(array_values($chromosome)).
    "&chds=0,".max(array_values($chromosome)).
    "&chbh=25,10,4".
    "&chs=1000x200";
    //print $chart1;
    //print "</br>Figure 1: Overlap-counts distribute on all Chromosome.</br>";

    $file1_percentage = get_percentage_array(chromosome_count($new_file), chromosome_count("$temp/$filename1"));
    $file2_percentage = get_percentage_array(chromosome_count($new_file), chromosome_count("$temp/$filename2"));
    $fmt_xaxis = join("|", array_keys($file1_percentage));
    $fmt_yaxis_1 = join(",", array_values($file1_percentage));
    $fmt_yaxis_2 = join(",", array_values($file2_percentage));
    $chart2 = "https://chart.googleapis.com/chart?".
    "cht=lc".
    "&chxt=x,y,y".
    "&chco=4D89F9,C6D9FD,".
    "&chd=t:$fmt_yaxis_1|$fmt_yaxis_2".
    "&chm=N,FF0000,0,-1,11,1.0|N,0000FF,1,-1,11,-1.0".
    "&chdl=$name1|$name2".       //fixme: use original names here, not temp names
    "&chco=FF0000,0000FF".
    "&chxl=
	0:|$fmt_xaxis|
	2:|Overlap|Per-Read|".
	"&chxp=2,100,90".
	"&chxs=2,0000FFFF".
    //"&chxr=1,0,".max(array_values($file1_percentage)).
    //"&chds=0,".max(array_values($file1_percentage)).
    "&chxr=1,0,".max(max(array_values($file1_percentage)),max(array_values($file2_percentage))).
    "&chds=0,".max(max(array_values($file1_percentage)),max(array_values($file2_percentage))).
    "&chbh=25,15,4".
    "&chs=1000x200";
    //print $chart2;
    //print "</br>Figure 2: Overlaps-Per-Read(OPR) for  $filename1  and  $filename2.</br>";
    //print "</br>Intuitively, a higher  OPR curve indicates that two samples overlaps better.</br>";
	
	################# Statistics 
	
    #################### Remove the unnecessary files #######################
    //system("rm $temp/$resultfile $temp/$filename2 $temp/$filename1");
    //rrmdir($temp);

    #####################		Download	    	   #######################
    //print "</br><a href='download.php?download_file=$new_file' class='Body-C4'>Format1-Combined Colummns:Download HERE</a>";
    //print "</br><a href='download.php?download_file=$new_file1' class='Body-C4'>Format2-OverlapBedfile:Download HERE</a>";

    ###########################     Output Return      #######################
    //$path = $_SERVER['DOCUMENT_ROOT']."/DASR_2011/DASR_compare/";


	#################### Statistics On a genome basis #######################
	$total_overlaps = array_sum(array_values($chromosome)); 
	$total_file1_percentage = round($total_overlaps/array_sum(array_values(chromosome_count("$temp/$filename1"))),4);
	$total_file2_percentage = round($total_overlaps/array_sum(array_values(chromosome_count("$temp/$filename2"))),4);

	$total_statistics = 
	array(
	"Overlap_chr"=>$chromosome,     		// type :array
	"Overlap_total"=>$total_overlaps,		// type :int
	"OPR_file1"=>$file1_percentage,			// type :array
	"OPR_file2"=>$file2_percentage,			// type :array
	"OPR_total_file1"=>$total_file1_percentage,  //type :float
	"OPR_total_file2"=>$total_file2_percentage	 //type :float
	);
    	return array("overlap_bedfile" => $new_file1,
        	"overlap_combined_columns" => $new_file,
	       	"overlaps_chart1" => $chart1,
	       	"overlaps_chart2" => $chart2,
	       	"temp" => $temp,
                "total_statistics" => $total_statistics
        );
}

######################     small functions      #########################
function genRandomString() {
    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = NULL;
    for($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
    }
    return $string;
}

function overlaps_cut($new_file, $temp, $overlaps) {
    $fh = fopen($temp, "r") or exit("Unable to open $temp!");             // read from an original overlapped file, $temp
    $fh1 = fopen($new_file, "w") or exit("Unable to write $new_file!");    // write into a new overlapped file
    while(!feof($fh)) {
        $line = fgets($fh);
        $chr  = explode("\t",$line);
        if((int)$chr[sizeof($chr) - 1] >= $overlaps) {                     // according to some criteria
           //print "</br>$chr  $overlaps</br>";
           fwrite($fh1,$line);
        }
    }
    fclose($fh);
    fclose($fh1);
}

?>
