#!/usr/bin/perl -I /raid/GSCAN/ -I  /raid/GSCAN/ERNESTO/biomart06/biomart-perl/lib
#use Devel::Profiler;
use strict;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use CGI qw/:standard *table p img td Tr /;
use Data::Dumper;

use POSIX;

use lib "perlScripts"; # ADDED TJ
require "qtlGraph.pl";
require "qtlDB.pl";
require "qtlUCSC.pl";
require "qtlOptions.pl";
require "qtlJS.pl";
require "qtlpage.elements.pl";
require "qtlView.pl";
require "qtlLogin.pl";
require "qtlInclude.pl";

open(TMP66, ">/tmp/debug.txt");
my $fh = select(TMP66);
$| = 1;
select($fh);

my $options = DefaultOptions();
my $include = Includes();

if ( $options->{"image.format"} eq "SVG" ) {
  use GD::SVG;
}
else {
  use GD;
}


SetFonts( $options );
WriteHTML( $include, $options );


sub WriteHTML {

  my ( $include, $options ) = @_;

  my $query = new CGI;
  my $build_id = "build";
  my $from_id = "from";
  my $to_id = "to";
  my $tview_id ="trait loci";
  my $qtltable_id = "trait loci table";
  my $gview_id = "genome";
  my $go_id = "region";
  my $trait_id ="viewtraits";
  my $gogene_id = "go to gene";
  my $gosnp_id = "go to SNP";
  my $chr_id = "chromosome";
  my $scroll_id = "scroll";
  my $zoom_id = "zoom";
  my $gscan_id = "gscan";
  my $coord_id = "coord";
  my $state_id = "state";
  my $gene_id = "gene_symbol";
  my $snp_id = "snp";
  my $label_id = "subscanlabels";
  my $vista_id = "vista";
  my $pop_id = "population";
  my $text_id = "view as text";
  my $ucsc_id = "enable_ucsc";
  my $multi_id = "separate_subscans";

  my $build = $query->param($build_id);
 
  ### ADDED TJ ####
  #Get the build from the database, if the default.build is in the database, use the default  
  if(! $build){
    $build=checkDefaultValue("genome_build", $build, "default.build");
  }
  #################

  $build = $options->{"default.build"} if ( ! $build );
  $options->{"default.build"} = $build;
  

  #if build chosen is 34 then use qtlGenes.pl (script which does not use the BioMart Perl API). But if build chosen is 36 then use qtlGenes_wAPI.pl (which uses the BioMart API).
  if ($build==34) {
      require "qtlGenes.pl";
  } else {
      require "qtlGenes_wAPI.pl";
  }
  my @chr = param($chr_id);
  my $chr = $chr[0];
  my $from = param($from_id);
  $from = int(1.0e6 * $from ) if ( $from =~ /\./ );
  my $to = param($to_id);
  $to = int(1.0e6 * $to ) if ( $to =~ /\./ );
  my $traitview = param($trait_id);
  my $tview = param($tview_id);
  my $qtlview = param($qtltable_id);
  my $gview = param($gview_id);
  my $go = param($go_id);
  my $go_gene = param($gogene_id);
  my $oldstate = param($state_id);
  my @qtl = param($gscan_id);
  my $qtl = join(",",@qtl);
  @qtl = split(/,/,$qtl);
  my $gene = param($gene_id);
  my $go_snp = param($gosnp_id);
  my $snp = param($snp_id);
  my @selected_labels = param($label_id);
  my $coord = param($coord_id);
  my $zoom = param($zoom_id);
  my $scroll = param($scroll_id );
  my $view_as_text = param($text_id);
  my $enable_ucsc = param($ucsc_id);
  my $multi = param($multi_id) ? param($multi_id) : $options->{'draw.separate.subscans'};
  $options->{'draw.separate.subscans'} = $multi;


  ###
  ## Public / private control
  my $vista = param($vista_id);
  if ($vista !~ /\w+/){
  	my @split = /\//, $0;
	$vista = pop @split;
  }
  ##
  my $population = param($pop_id);
  
  ##### ADDED TJ ##########
  if(! $population){
    $population=checkDefaultValue("population", $population, "default.population");
  }
  #########################

  $population = $options->{"default.population"} if ( ! $population );

  my $chrMax = 1;
  
  my $viewdata = "";
  my $state = "region";
  my ( $id, $chrom, $start, $end );
  if ( $go   ) {
    $state = "region";
    my $lengths = GetChromExtents( $build, $options, $options->{dbh} );
    if ( $lengths && $lengths->{$chr} > 0 ) {
      $chrMax = $lengths->{$chr};
    }
    else {
      $chrMax = 2.0e8;
    }
    # $chrMax = getChromosomeLengthFromUCSC($build,$chr,$options);
    if ($to !~ /\d+/){
      $to = $chrMax;
    }
    elsif ($to > $chrMax) {
      $to = $chrMax;
    }
    if ($from !~ /\d+/){
      $from = 1;
    }
  }
  elsif ( $tview ) {
    $state = "traits";
  }
  elsif ( $qtlview ) {
    $state = "qtltable";
  }
  elsif ( $gview ) {
    $state = "genome";
  }
  elsif ( $go_gene ) {
    if ( $gene ){
      my $geneinfo = multiFind( $build, $gene,$options ) ;
#      print TMP66 "geneinfo $gene $geneinfo @$geneinfo\n";
      if ( $geneinfo) {
	( $id, $chrom, $start, $end ) = @$geneinfo;
	if ( $start > $end ) {
	  my $tmp = $start; $start = $end; $end = $tmp;
	}
#	print TMP66 "id $id, $chrom, $start, $end\n";
	$gene = $id;
	$chrom =~ s/chr//;
	$from = $start-$options->{"gene.window"};
	$from = 1 if ( $from < 1 );
	$to = $end+$options->{"gene.window"};
	$chr = $chrom; 
	$state = "region";
      }
      else {
	$gene = "NOT FOUND";
      }
    }
  }
  elsif ( $go_snp ) {
    if ( $snp ){
      my $snpinfo = GetMarkerMapping( $build, $build, [$snp], $options->{dbh}) ;
      if ( $#$snpinfo >= 0 ) {
	my ( $id, $build, $chrom, $pos, $strand, $cm ) = @{$snpinfo->[0]};
	$chrom =~ s/chr//;
	$from = $pos-$options->{"gene.window"};
	$from = 1 if ( $from < 1 );
	$to = $pos+$options->{"gene.window"};
	$chr = $chrom; 
	$state = "region";
	$viewdata .= p(join( " ", @{$snpinfo->[0]} ));
      }
      else {
	$snp = "NOT FOUND";
      }
    }
  }

  if ( $oldstate eq "genome" && $oldstate ne $state ) {
    $from = undef;
    $to = undef;
    param($from_id,undef);
    param($to_id,undef);
  }
  
  if ( $from > $to ) {
    my $tmp = $from; $from = $to; $to = $tmp;
  }

  param($state_id, $state);
  param($build_id,$build);

  param($gscan_id,@qtl);
  param($chr_id,$chr);
  param($trait_id,$traitview);
  param($gene_id,$gene);
  param($snp_id,$snp);
  param($vista_id,$vista);
  param($pop_id,$population);
  param($multi_id,$multi);

  my $labels = join( ",", @selected_labels );
  @selected_labels = split(/,/,$labels);
  if ( $#selected_labels < 0 ) {
    @selected_labels = @{$options->{'selected.labels'}};
  }
  param($label_id,@selected_labels);


  if ( $to && $from ) {
    $to = int($to);
    $from = int($from);
    $coord = int(($to+$from)/2) if ( ! $coord );
    $zoom = 1 if ( ! $zoom );
    $scroll = 0 if ( ! $scroll );
    ( $from, $to ) = ScrollZoom( $from, $coord, $to, $zoom, $scroll ) if ( ! $go_gene );
  }

  print TMP66 "options $options colours $options->{colours}\n";
  my $html2;
  if ( $state eq "region" ) {
    my $tmpviewdata;
    ( $tmpviewdata, $from, $to ) = RegionView( $build, $population, $qtl, $chr, $from, $to, $traitview, $view_as_text, $enable_ucsc, $labels, $options, [$gene] );
    param($from_id,$from);
    param($to_id,$to);
	param('chrmax',$chrMax),
    $viewdata .= $tmpviewdata;
  }
  elsif ( $state eq "traits" ) {
    $viewdata .= TraitLociView( $build, $population, 1,  $options );
  }
  elsif ( $state eq "qtltable" ) {
    $viewdata .= TraitLociTableView( $build, $population, $qtl, $options );
  }
  else {
     $viewdata .= WholeGenomeView( $build, $population, $qtl, $view_as_text, $labels, $options );
  }
  my $len = length($viewdata);
  print TMP66 "PRINTING DUMPER 2\n"; 
  print TMP66 Dumper($viewdata);
  print TMP66 "After DUMPER 2\n";
  $html2 =    start_form(-name=>"viewer") . hidden(-name=>$vista_id, -value=>$vista) . locator( $build_id, $build, $pop_id, $population, $chr_id, $from_id, $to_id, $gscan_id, $tview_id, $qtltable_id, $go_id, $gview_id, $gogene_id, $gene_id, $gosnp_id, $snp_id, $state_id, $state, $from, $to,$trait_id, $traitview,  $label_id, \@selected_labels, $text_id, $view_as_text, $ucsc_id, $enable_ucsc, $multi_id, $multi, $options,$chrMax ) .   end_form() .  hr() . $viewdata . end_table() . end_html() ;

  print  header(), start_html({-title=>"GScanViewer", -ALINK=>"orange", -bgcolor=> "#FFFFFF", -style=>{'src'=>$options->{css}}, -script=>js() });
  print start_table( -CELLSPACING=>"0", -CELLPADDING=>"0", -BORDER=>"0", -WIDTH=>'100%') . Tr(td( $include->{margin}), td({ -bgcolor=> 'white',  -align=>'left'},  $include->{header})).end_table(). start_table( -CELLSPACING=>"0", -CELLPADDING=>"0", -BORDER=>"0", -WIDTH=>'100%')  .Tr(td(  h1('Genome Scan Viewer') .hr() . $html2));
  param($zoom_id,0);
  param($scroll_id,0);

}



sub ScrollZoom {
  my ( $from, $coord, $to, $zoom, $scroll ) = @_;

  my $width;

  $coord = int(($from+$to)/2) if ( ! defined($coord));

  if ( $scroll == 0.0 ) { #zoom 
    $width = int(($to-$from+1)/(2*$zoom))+1;
    $from = $coord - $width + 1;
    $to = $coord + $width - 1;
    $width = ($to-$from+1);
  }
  elsif ( $scroll < 0 ) { #scroll left
    $width = int($to-$from+1);
    $to += int($scroll*$width);
    $from = $to-$width;
  }
  elsif ( $scroll > 0 ) { #scroll right
    $width = int($to-$from+1);
    $from += int($scroll*$width);
    $to  = $from+$width;
  }
  if ( $from < 1 ) {
    $from = 1;
    $to = $from+$width-1;
  }
  return ( int($from),int($to) );
}

# SUB ADDED TJ #
sub checkDefaultValue{ 
  my ($table, $value, $defaultValue)=@_ ;
  my $cat=gscan_catalogue($options->{dbh}, $table);
    my $rows=$#{$cat};
    $value=$cat->[0][0];
    for(my $i=0; $i< $#{$cat}+1; $i++){
      if(defined $cat->[$i][0]){
	if($cat->[$i][0] =~ /($options->{$defaultValue})/){
	  $value=$1;
	  $i=$#{$cat}+1;
	}
      }
    }
return $value;
}

#		
sub GetChromExtents {
  my ($build, $options) = @_;
  my $dbh = gscandb_connect( DBOptions() );
  my $lengths = undef;
  if ( $dbh ) {
    my ( $build_id,$truebuild,$truebuild_id) = true_genome_build( $dbh, $build );
    
    $lengths = chromosome_lengths($dbh, $build);
#    if ( !defined($lengths)) {
#      my @tab;
#      foreach my $chr ( theChromosomes()) {
#	$lengths->{$chr} = getChromosomeLengthFromUCSC( $build, $chr, $options );
#	push @tab, [ $chr, $build, $lengths->{$chr} ];
#      }
#      TableUpload( $dbh, \@tab, "chromosome", "update" );
#    }
    return $lengths;
  }
}

