#!/usr/local/bin/perl

#display_map.pl  
###############

require "../bin/geneloc/variables";
require "sub_set_range.pl";
require "sub_cyto_bands.pl";
require "../bin/geneloc/sub_db.pl";
require "sub_math.pl";
require "sub_print_html_top.pl";
use GL;
use DBI;
use DBD::mysql;
use CGI qw(:standard);
#my $db_name = $ARGV[0];
$| = 1;  #show results on the Web output as they come out

#colors in display
my $db_name = "geneloc_display_" . $DISPLAY_VERSION;
my $gl_db = "geneloc_". $DATA_VERSION;
my $dbh = SET_DBH($db_name, $PWORD);
my $dbh2 = SET_DBH($gl_db, $PWORD);
$page_bg_color =           "\"#FFFFFF\"";         #bg means background
$table_headings_bg_color = "\"#1E88C1\"";
$in_contig_bg_color =      "\"#CCFFFF\"";
$orphan_mkr_bg_color =     "\"#FFFFDC\"";
$titles_font_color =       "\"#990033\"";
$labels_font_color =       "\"#1E88C1\"";
$yellow_font_color =        "\"orange\"";

$this_script = "display_map.pl";
$this_url = "$URL_CGI_SCRIPTS/$this_script";
$homepage_url = "/geneloc";
$search_homepage_url =
                 "$URL_CGI_SCRIPTS/search_map.pl";
$mkr_cards_url = 
             "$URL_CGI_SCRIPTS/marker_cards.pl";
$exon_struct_url = "$URL_CGI_SCRIPTS/exon_struct.pl";
my $ve_url = "https://ve.genecards.org/gene-set-analysis";

#display a sample output with preset parameters, if that's what was asked

if (param("sample") eq "on") { 
    my %params = &create_sample_parameters;
}else{
    my $query = new CGI;
    my @names = $query->param;
    foreach $name (@names) {
	if ($name eq "classes") {
		my @classes = param("$name");
		@{$params{$name}} = @classes;
	} else {
		$params{$name} = param("$name");
	}
    }
}

sub create_sample_parameters {

    %params = ( "chr_nr" => 19,
              "range_type" => "Mb_range",
              "min_Mb" => 22,
              "max_Mb" => 23.5,
              "plus_minus_Mb" => 23.5,
              "match" => "exact",
	   #   "size" => "on",
	      "range" => "on",
              "genes" => "on",
       #       "est_clusters" => "on",
              "enhancers" => "on",
              "rh_mkrs" => "on",
              "est_mkrs" => "on",
              "polymorh_mkrs" => "on",
              "sts_mkrs" => "on",
              "d_numbers" => "on",
              #"types" => "on"
	      );
   return %params;
}

#normal query with user's parameters

$chr_nr = $params{"chr_nr"};
if ($chr_nr =~ /^0/) {
	$chr_nr =~ s/^0//;
}
$chromosome_length = &find_chr_length_new ($chr_nr);  #will get chr length in bp
$chr_nr="null" unless $chr_nr;
$max_Mb_range_to_show = 10 * 1000000;
#$reperform_search_link = "[<a href=\"$search_homepage_url\">Reperform Search</a>]";

#Get user's query from the server (the sub is in "cgi-lib.pl").

if ($params{"range"}) {
   $params{"start"} = "on";
   $params{"end"} = "on";
}
if ($params{"match"} eq "exact") {  #this means that default is overlap
  $exact = 1;
} else {
  $exact = 0;
}
if ($params{"range_type"} eq "gh_id") {
	$params{"entity"} = "enhancer";
}
#Initialize output html file.

  print "Content-type: text/html\n\n";
  print "<html><HEAD><TITLE>GeneLoc Integrated Map for Chromosome $chr_nr: Search Results</TITLE>";
  print "<link rel=\"stylesheet\" type=\"text/css\" href=\"../$CURRENT/defaultTheme.css\">";
  print "<link rel=\"stylesheet\" type=\"text/css\" href=\"/$CURRENT/geneloc.css?id=v43\">";
#  print "</HEAD>\n"; #<html> was missing!
#  print "<BODY BGCOLOR=$page_bg_color LINK=\"#003366\">\n";
#  print "<script src=\"../$CURRENT/jquery.js\"></script>\n";
#  print "<script src=\"../$CURRENT/geneloc.js\"></script>\n"; 
#  print "<script src=\"../$CURRENT/jquery.fixedheadertable.js\"></script>\n";
#print html top

print_html_top ();

#Decide which range to show in browser

%point = (                                #define pointers to subroutines
   "specify_band"    => \&specify_band,
   "Mb_range"        => \&Mb_range,
   "between_markers" => \&between_markers,
   "within_marker"   => \&within_marker,
   "covered_by_marker" => \&covered_by_marker,
   "gh_id" => \&gh_id, #when called from genecards. 
   "gc_id" => \&gc_id, #when called from genecards. 
                       #gc_id and contig (for potential 
                       #future use) are specified
   "within_id" => \&within_id   #used when this cgi-script is called from aliases.pl
                                #in this case specified are: 
                                #around_id, around_marker, chr_nr, mid_bp
);

$operate_range_type = $params{"range_type"};

$sub_ref = $point{$operate_range_type};      #decide which subroutine to operate
&{$sub_ref}($dbh, $dbh2);                                 #operate the relevant subroutine

#Note from 16.8.2000

#The program gets range in Mb (if "Mb_range" or "within_id" or "specify_band")
#but from then on it works with base pairs, namely, the variables $wlfm, $wrfm
#are from now on in base pairs

#if this is a continue page (i.e. original query contained a too big range)

$continue_message = "";
if ($params{"continue_from"}) {
   $continue_message = " (continued) ";
   $wlfm = $params{"continue_from"};
}

#if user asked for a too big range - notify and show only beginning of range

$add_msg = "";
if ($wrfm-$wlfm > $max_Mb_range_to_show) {
   $new_wrfm = $wlfm + $max_Mb_range_to_show;
   $new_wrfm = sprintf($new_wrfm);
   %continue_args = %params;
   $continue_args{"continue_from"} = $new_wrfm;

   # convert hash to argument list
   @arg_list = ();
   while (($arg_key, $arg_value) = each (%continue_args)) {
      push (@arg_list, $arg_key . "=" . $arg_value);
   } 
   $new_arg_list = join ("&", @arg_list);

   $add_msg = "This page shows genomic objects between $wlfm - $new_wrfm bp
          [<a href=\"display_map.pl?$new_arg_list\">Next page - view further
          </a>]<p>\n";
   $wrfm = $new_wrfm;
}
  if ($params{"plus_minus_Mb"}) { 
	$plus_minus = $params{"plus_minus_Mb"};
  }
  if ($params{"min_Mb"}) {
	$loc_mb = $params{"min_Mb"};
  } else {
	$loc_mb = "null";
  }
  if ($params{"around_marker"}) {
	 $string = $params{"around_marker"};
  } else {
	$string = "null";
  }
  my ($entity, $coords, $show_genes, $show_ests, $show_markers, $show_enhancers, $gene, $enh);
  $entity = $params{"entity"};
  if ($entity eq "gene") {
        $gene = "checked";
  } elsif ($entity eq "enhancer") {
        $enh = "checked";
  }

#  if ($operate_range_type eq "within_id") {
#	$aliases = "checked";
#  }
  if ($operate_range_type eq "Mb_range") {
	$coords = "checked";
  }
  my @classes = @{$params{"classes"}}; 
  foreach (@classes) {
	if ($_ eq "gene") {
		$params{"genes"} = "on";
	} elsif ($_ eq "est") {
		$params{"est_clusters"} = "on";
	} elsif ($_ eq "enhancer") {
		$params{"enhancers"} = "on";
	} elsif ($_ eq "marker") {
		$params{"rh_mkrs"} = "on";
		$params{"est_mkrs"} = "on";
		$params{"polymorh_mkrs"} = "on";
		$params{"sts_mkrs"} = "on";
		$params{"sts_unknown_type"} = "on";
		$params{"d_numbers"} = "on";
		$params{"types"} = "on";
	}
  }
  if ($params{"genes"}) {
	$show_genes = 1;
  } else {
	$show_genes = "null";
  }
  if ($params{"enhancers"}) {
        $show_enhancers = 1;
  } else {
        $show_enhancers = "null";
  }
  if ($params{"est_clusters"}) {
        $show_ests = 1;
  } else {
        $show_ests = "null";
  }
  if ($params{"rh_mkrs"} || $params{"est_mkrs"} || $params{"polymorh_mkrs"} || $params{"sts_mkrs"} || $params{"sts_unknown_type"}) {
        $show_markers = 1;
  } else {
        $show_markers = "null";
  }

  my $search = "<div style=\"margin-left:15px;float:left;\"><B>Display genomic neighborhood for:</B><br /><br /><div style=\"float:left;\"><input type=\"radio\" id=\"genename\" name=\"search_type\" value=\"gene\"$gene onChange=\"searchType()\">gene</div><div style=\"float:left;\"><input type=\"radio\" id=\"enhname\" name=\"search_type\" value=\"enh\"$enh onChange=\"searchType()\">enhancer</div><div style=\"float:left;\"><input type=\"radio\" id=\"coord\" name=\"search_type\" value=\"coordinates\"$coords onChange=\"searchType()\">genomic coordinates </div><div style=\"margin-top:10px;margin-left:5px;\"><div id=\"gene_text\"></div><div id=\"enh_text\"></div><div id=\"coord_text\"></div></div></div><script type=\"text/javascript\"> searchType(\"$chr_nr\",$loc_mb,$plus_minus,\"$string\",$show_genes,$show_ests,$show_markers,$show_enhancers);</script>";
  print $search;

#compose web page headings

  my $page_headings = "";
  #my $download_link = "<a href=\"$URL_STATIC_HTML_PAGES/$CURRENT/genehancer.xlsx\" download><b>Download</a> GeneHancer data dump</b>"; #download moved to GeneCards
  #$page_headings .= "<H2>&nbsp;&nbsp;<FONT COLOR=$titles_font_color>Chromosome $chr_nr</FONT></H2>\n";

  #$page_headings .= "<H3><div style=\"float:left;text-align:left;\">&nbsp;&nbsp;&nbsp;<FONT COLOR=$titles_font_color>$msg" . $continue_message . "</FONT></div><div style=\"float:right;text-align:left;width:50%;\">$download_link</div></H3>\n";

  if ($msg =~ /Error:/i) {
    $msg =~ s/Error:<br>/error:<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/; # improve the formatting of the error message
    $msg = "$GENELOC_UNDER_CONSTR_ERR_PREFIX $msg </i> $GENELOC_UNDER_CONSTR_ERR_SUFFIX";
  } else {
    $msg = "&nbsp;&nbsp;&nbsp;$msg";
  }
  $page_headings .= "<H4><div style=\"float:left;text-align:left;\"><FONT COLOR=red>$msg</FONT>" . "$continue_message" . "</H4>\n";
  if ($msg =~ /Error:/i || $msg =~ /not in the GeneLoc map./) {
     print $page_headings;
     #print "</BODY>";
     #print "</HTML>";
     print_footer();
     exit;
  }
if ($add_msg) {
    $page_headings .= "&nbsp;&nbsp;&nbsp;$add_msg";
}
  #if ($explanation) {
  #   $page_headings .=  "&nbsp;&nbsp;&nbsp;Explanation:<BR>$explanation<P>";
  #}

#  $page_headings .=  "&nbsp;&nbsp;&nbsp;&nbsp;[ <a href=\"$homepage_url\"> GeneLoc Home Page</a> ]\n";
         
#  $page_headings .=  "<p>\n";

#compose marker types legend (if necessary)

my $legend_table = "<BR>";

if ($params{"types"}) {

   my $tlines = "";
   if ($params{"rh_mkrs"}) {
      $tlines .= "<TR><TD><FONT SIZE=-1 COLOR=$labels_font_color>RHmkr</FONT></TD><TD>STSs mapped on RH map</TD></TR>\n";
   }
   if ($params{"est_mkrs"}) {
      $tlines .= "<TR><TD><FONT SIZE=-1 COLOR=$labels_font_color>cDNA&nbsp;</FONT></TD><TD>STSs derived from cDNA</TD></TR>\n";
   }
   if ($params{"polymorh_mkrs"}) {
      $tlines .= "<TR><TD><FONT SIZE=-1 COLOR=$labels_font_color>Polym</FONT></TD><TD>Polymorphic markers</TD></TR>\n";
   }
   if ($params{"sts_mkrs"}) {
      $tlines .= "<TR><TD><FONT SIZE=-1 COLOR=$labels_font_color>onYAC</FONT></TD><TD>STSs mapped on YAC contigs</TD></TR>\n";
   }
   

   if ($tlines) {
      $legend_table =  "<TABLE BORDER style='margin-right:25px;'>\n" .
                          "<TR BGCOLOR=$table_headings_bg_color>\n" .
                          "<TD COLSPAN=2><center><FONT COLOR=\"white\">Marker types:</FONT></TD><center></TR>\n" .
                          $tlines . 
                          "</TABLE>\n";
   }
}

#print headings and legend_table
print "<div style=\"position:relative;top:5px;float:right;\">$legend_table</div>";
print "<TABLE WIDTH=\"100%\">\n",

      "<TR>\n",
      "   <TD ALIGN=\"LEFT\">\n",
          $page_headings, "\n", 
      #"   </TD>\n",
       
#      "   <TD ALIGN=\"RIGHT\">\n",
#          $legend_table,
#      "   </TD>\n",
      "</TR>\n",
      "</TABLE>\n",
      "<br />\n";

#############  rewrite ->

#Set key for reading data from source table (put here variable names from the html page)

#possible arguments in query:
#     "loc", "start", "end", "size",
#     "genes", "est_clusters",
#     "d_numbers",
#     "rh_mkrs", "est_mkrs", "polymorh_mkrs", "sts_mkrs",
#     "cyto_genes"

@table_key = ("loc", "start", "end", "size", "genes","enhancers",
              "est_clusters", "d_numbers", "rh_mkrs", "est_mkrs",
              "polymorh_mkrs", "sts_mkrs", "cyto_genes");
$border = 3;   #index of last "location" column

#Take into consideration which data the user wants to see in the results.

#Create an array of numbers which are the indexes of the columns
#that the user wants to see.

undef(@columns);
for $i (0 .. $#table_key)  {
   push (@columns, $i) if ($params{"$table_key[$i]"});
}

#give error message in case user did not specify any data to retrieve

unless (@columns) {
   print "<b>Error:<br>You did not specify which data you would like to retrieve.<b><p>\n";
              #$reperform_search_link\n";
   #print "</BODY>";
   #print "</HTML>";
print_footer();
   exit;
}

##############  <- rewrite

#Write a message of "histaygut" about the map locations

$histaygut = "The locations in this table are only approximate, as they are derived by
integrating data from various mapping and sequencing resources.  Currently, a gene or EST cluster may appear multiple times if it
includes several markers that were mapped to different positions.";


   
#   print "<P>\n";

#Write a "wait for results" message.

#   print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Please wait for results...<P>\n";

#Write table in the output and terminate it.
   #print "<div style='width:1270px;margin-left:15px;margin-right:15px;'><TABLE BORDER style=\"width:1270px;\">";
   #print "<div style='width:1270px;margin-left:15px;margin-right:15px;'><TABLE BORDER style=\"width:1270px;border-spacing:5;\" class='fixedHeaderTable'>";
   &get_hand_data;                        #!!!!!!!!!!!!!!!!!!!!!
   print "</tbody></TABLE></div></section>";
   print "<script type=\"text/javascript\"> searchType(\"$chr_nr\",$loc_mb,$plus_minus,\"$string\",$show_genes,$show_ests,$show_markers,$show_enhancers);</script>";
   #print "</BODY>";
   #print "</HTML>";
print_footer();
##########################################################################################

sub numerically { $a <=> $b; }

##########################################################################################

sub get_hand_data {
    
    #convert %in to an argument list (for heading links)
    
    $arg_list = &arg_list(\%params);
    
    #prepare a hash to hold arguments for ? link
    
    %qm_link_args = %params;
    $qm_link_args{"range_type"} = "covered_by_marker";
    
    my $show_mkrs = 1 if ($params{"rh_mkrs"} or $params{"est_mkrs"} or $params{"polymorh_mkrs"} or $params{"sts_mkrs"} or $params{"sts_unknown_type"});
    
    # write titles line 
    
    my $heads_line = "";
    my $nr_of_data_columns = 0; #will be used to determine colspan for the genonic_seq line
    
    # add posibility of midpoint, start, end, size when time comes:
    $heads_line .= "<th>#<div>#</div></th>\n"; 
    $heads_line .= "<th>Midpoint (bp)<div>Midpoint (bp)</div></th>\n"   if $params{"loc"};
    $heads_line .= "<th>Location<div>Location</div></th>\n"      if $params{"range"};
#    $heads_line .= "<th>End (bp)<div>End (bp)</div></th>\n"        if $params{"range"};
    $heads_line .= "<th>Size (bp)<div>Size (bp)</div></th>\n"       if $params{"size"};
    
    if ($params{"genes"}) {
	$heads_line .= "<th>Strand<div>Strand</div></th><th>Gene<div>Gene</div></th>\n";
	$nr_of_data_columns++;
    }
    
    if ($params{"enhancers"}) {
	$heads_line .= "<th>Enhancer ID<div>Enhancer ID</div></th>\n";
	$nr_of_data_columns++;
    }
    if ($params{"est_clusters"}) {
	$heads_line .= "<th>Unigene cluster<div>Unigene cluster</div></th>\n";
	$nr_of_data_columns++;
    }
    if ($params{"genes"}) {
	$heads_line .= "<th>Entrez Gene Id<div>Entrez Gene Id</div></th><th>Ensembl Id<div>Ensembl Id</div></th>\n";
	$nr_of_data_columns++;
    }
    if ($params{"genes"} || $params{"est_clusters"}) {
	$heads_line .= "<th>Description<div>Description</div></th>\n";
	$nr_of_data_columns++;
    }
    if ($show_mkrs) {
	$heads_line .= "<th>Genetic Marker<div>Genetic Marker</div></th>\n";
	$nr_of_data_columns++;
    }
    
    if ($show_mkrs and $params{"d_numbers"}) {
	$heads_line .=  "<th>Marker D-number<div>Marker D-number</div></th>\n";
	$nr_of_data_columns++;
    }
    
    if ($params{"types"}) {
	
	my $types_nr = 0;
	foreach $type ("rh_mkrs", "est_mkrs", "polymorh_mkrs", "sts_mkrs") {
	    $types_nr++ if $params{"$type"};
	}
	$heads_line .= "<th COLSPAN=$types_nr><center>Marker type</center><div>Marker type</div></th>\n" if $types_nr;
	$nr_of_data_columns += $types_nr;
    }
#    print "<thead ><TR BGCOLOR=$table_headings_bg_color class=\"header\">\n",
#    $heads_line,
#    "</TR></thead><tbody>\n";
    
    #write data lines
    
    my $time0 = time();
    
    #deal with the range query
    
    #this will be relevant when objects have range
    
    my $comparison_criterion;
    if ($exact) {  #match is "exact"
	$comparison_criterion = "start >= $wlfm and end <= $wrfm";
    } elsif ($params{"plus_minus_Mb"}) { #match is overlap and +/- is specified
        my $plus_minus_bp = $params{"plus_minus_Mb"} * 1000000;
        my $low = $wlfm - $plus_minus_bp/2; #param is whole interval, not 
	my $high = $wrfm + $plus_minus_bp/2; #flanking bases
	$comparison_criterion = "end >= $low and start <= $high"; 
    }else {   #match is "overlap"
	$comparison_criterion = "end >= $wlfm and start <= $wrfm"; 
    }
    
    #determine the criterion for sorting objects in the table output
    
    my $sort_criterion;   #this means that default is midpoint
    #if ($params{"sort_obj"} eq "start") { #param doesn't yet exist!
	$sort_criterion = "start";
    #} else {
#	$sort_criterion = "midpoint";
 #   }
    
    #query the map_display table of the database
    
    my $select =
	"select * from map_display
     where chromosome = '${chr_nr}'
     and ($comparison_criterion)
     order by $sort_criterion";
    
    
   # my $sth = $dbh->prepare($select) or
#	cgi_error ("can't prepare SQL query:<P>" . $dbh->errstr() );
 #   $sth->execute or cgi_error ("can't execute SQL query:<P>" . $sth->errstr() );
    my (@rows) = PARSE ($select, $dbh);
#	my $j = 0; 
 #   while (@row = $sth->fetchrow_array) {
    my (@symbols, @fields, @gh_ids, @all);
    foreach $row (@rows) {
	@fields = split (/;/, $row);
	if ($fields[7] =~ /^orgul/i) {
		push (@symbols, $fields[5]);
	}elsif ($fields[7]) {
		push (@symbols, $fields[7]);
	}
	push (@gh_ids, $fields[6]) if $fields[6];
    }
   my $symbols = join (",", @symbols);
   my $gh_ids = join (",", @gh_ids);
   my $all = $symbols . "," . $gh_ids;
   my $data = "$symbols";
   #$data = "$symbols,$gh_ids";
   my $data2 = "pow,biff,zot";
   #my $button = "<form action=\"$ve_url\" method=\"post\" target=\"_blank\" style=\"margin-left:15px;\"><input type=\"hidden\" name=\"symbols\" 
   #value=\"$data\"><input type=\"hidden\" name=\"genes\" value=\"\"> <input type=\"submit\" value=\"Export genes and enhancers to VarElect\"></form>";
   my $button = "<form id=\"genes_enh\" action=\"$ve_url\" onsubmit=\"return veList('$symbols','$gh_ids','$all')\" method=\"post\" target=\"_blank\" 
   style=\"margin-left:15px;\"><input type=\"checkbox\" name=\"genes\" id=\"genes\" value=\"\" checked>Genes<input type=\"checkbox\" 
   name=\"enhancers\" id=\"enhancers\" value=\"\"><input type=\"hidden\" id=\"symbols\" name=\"symbols\" value=\"\">Enhancers <input type=\"submit\" 
   value=\"Export to VarElect\"></form>";
   print "$button";
  print "<section class=\"\"><div class=\"container2\"><table>"; 

    print "<thead ><TR BGCOLOR=$table_headings_bg_color class=\"header\">\n",
    $heads_line,
    "</TR></thead><tbody>\n";

    foreach $row (@rows) {
	my $anchor_in = 0;
	my (
	    $id,
	    $midpoint,
	    $start,
	    $end,
	    $size,
	    $gc_id,
	    $gh_id,
	    $gene_name,
	    $est_cluster_id,
	    $est_acc,
	    $object_desc,
	    $mkr_name,
	    $mkr_D_nr,
	    $mkr_is_rh,
	    $mkr_is_cDNA,
	    $mkr_is_polym,
	    $mkr_is_onYAC,
	    $chromosome,
	    $contig,
	    $strand, 
	    $eg_id,
	    $ens_id
	    ) = split (/;/, $row);
#add new field for #desc (can be instead of est_cluster_name)
	if (($params{"range_type"} ne "specify_band" && $params{"range_type"} ne "Mb_range" && $params{"range_type"} ne "between_markers" && (($params{"around_id"} == $id && $id) || ($params{"around_id"} == $gh_id && $gh_id) || ($params{"around_id"} == $est_cluster_id && $est_cluster_id))) || (($params{"around_marker"}) && ($params{"around_marker"} =~ /^$mkr_name$/i ||$params{"around_marker"} =~ /^$gene_name$/i  ||$params{"around_marker"} =~ /^$gh_id$/i  ||$params{"around_marker"} =~ /^$est_acc$/i ))) {
	    $mark_line = "class=\"yellow\"";
	}else{
	    $mark_line = "";
	    #$anchor_line = "";
	}
	    $anchor_line = "<a class=\"anchor\" name=\"$id\"></a> <a  class=\"anchor\" name=\"$est_cluster_id\"></a> <a class=\"anchor\" name=\"$gene_name\"></a><a  class=\"anchor\" name=\"$gc_id\"></a><a  class=\"anchor\" name=\"$gh_id\"></a>";
	#if mkr is not any of rh, cDNA, polym, onYAC
	#set a variable $mkr_is_unknown_type
	$mkr_is_unknown_type = "";
	if ($mkr_name        and
	    !$mkr_is_rh    and
	    !$mkr_is_cDNA  and
	    !$mkr_is_polym and
	    !$mkr_is_onYAC      ) {
	    $mkr_is_unknown_type = "on";
	}
	
	
	#variables that will help us not to print line if it does
	#not contain anything that the user wanted to see
	
	my $exist_mkrs_fit_show = 1 if ($params{"rh_mkrs"}       and $mkr_is_rh    or
					$params{"est_mkrs"}      and $mkr_is_cDNA  or
					$params{"polymorh_mkrs"} and $mkr_is_polym or
					$params{"sts_mkrs"}      and $mkr_is_onYAC or
					$params{"sts_unknown_type"} and $mkr_is_unknown_type);
	
	my $objects_to_show = 1     if ($params{"genes"}         and $gc_id        or
	 				$params{"enhancers"}  and $gh_id	   or					$params{"est_clusters"}  and $est_cluster_id or
					$genomic_seq_id                        or
					$exist_mkrs_fit_show                      );
	
	#set $line_bg_color
	
	my $row_bg_color = "";
	
	if ($genomic_seq_id) {   #lines that defined contig boundaries
	    $row_bg_color = "BGCOLOR=$table_headings_bg_color";
	}
	
	if ($midloc_is_in_seq_region == 1) {  #lines of sequenced regions
	    $row_bg_color = "BGCOLOR=$in_contig_bg_color";
	}
	
	
	#construct the line to write (did not do it yet)
	
	my $data_line = "";
	#print the location if there are objects in the line that the user wanted to see
	#otherwise - jump to next line
	$j++ if $objects_to_show;
	my $line_num = "<span style=\"font-weight:bold;color:gray\">$j</span></td>";
	my $num_in = 0;
	if ($params{"loc"}) { 
	    if ($objects_to_show){
                $data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
		$data_line .= $line_num unless $num_in;
		$num_in = 1;
		$data_line .= "<td><B>$midpoint</B></TD>\n";
	    } else {
		next;
	    }
	}
	
	#range 
	my $link_name = "";
	if ($gc_id) {
		if ($gene_name =~ /ORGUL/) {
                        $link_name = $gc_id;
                } else {
			$link_name = $gene_name;
		}
	} elsif ($gh_id) {
		$link_name = $gh_id;
	} elsif ($mkr_name) {
		$link_name = $mkr_name;
		chomp $link_name;
	} 
	my $start_formatted = format_int_commas ($start);
        my $end_formatted = format_int_commas ($end);
	my $ent = "gene";
	if ($gh_id) {
		$ent = "enhancer";
	}
	if ($params{"range"}) {
	    if ($objects_to_show) {
		my $gl_link = "display_map.pl?" .
                           "range_type=within_id&" .
                           "chr_nr=$chr_nr&" .
                           "around_id=$id&" .
                           "around_marker=$link_name&" .
                           "start_bp=$start&" .
                           "end_bp=$end&" .
                           "plus_minus_Mb=$plus_minus&" .
                           "match=exact&" .
                           "range=on";
                           $gl_link .= "&genes=on" if $params{"genes"};
                           $gl_link .= "&est_clusters=on" if $params{"est_clusters"};
                           $gl_link .= "&enhancers=on" if $params{"enhancers"};
                           $gl_link .= "&d_numbers=on" if $params{"d_numbers"};
                           $gl_link .= "&types=on" if $params{"types"};
                           $gl_link .= "&polymorh_mkrs=on" if $params{"polymorh_mkrs"};
                           $gl_link .= "&sts_mkrs=on" if $params{"sts_mkrs"};
                           $gl_link .= "&est_mkrs=on" if $params{"est_mkrs"};
                           $gl_link .= "&rh_mkrs=on" if $params{"rh_mkrs"};
                           $gl_link .= "&sts_unknown_type=on" if $params{"sts_unknown_type"};
			   $gl_link .= "&entity=$ent";
                           $gl_link .= "#$id";
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<td nowrap><A HREF=\"$gl_link\" title=\"Show $link_name on the map for chromosome $chr_nr\">chr$chr_nr: $start_formatted-$end_formatted</a></TD>\n";
#		$data_line .= "<TD><B>$end</B></TD>\n";
	    } else {
		next;
	    }
	    
	}
	
	#size 
	
	if ($params{"size"}) {
	    
	    if ($objects_to_show) {
		#my $size = $end_loc - $start_loc;
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<B>$size</B></TD>\n";
	    } else {
		next;
	    }            
	    
	}
	
	
	#data lines
	
	if ($params{"genes"}) {
	    if ($strand) {
		$data_line .= "<TD align=center>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "$strand</TD>\n";
	    }else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	    if ($gc_id) {
		$gene_disp = "$gene_name ($gc_id)";
		if ($gene_name =~ /ORGUL/) {
			$gene_name = $gc_id;
			$gene_disp = $gene_name;
		}
		my $gene_link = "<A HREF=\"$URL_CARDDISP$gene_name\" title=\"See $gene_disp in GeneCards\" target=\"aaa\">$gene_name </A>";
		my $exon_link = "<br /><A target=\"aaa\" HREF=\"${exon_struct_url}?disp_name=$gene_name&chr_nr=$chr_nr\" title=\"See $gene_name exon structure\" style=\"display:block;font-size:14px;text-indent:-1em;padding-left:2em;\">Exon structure</A>";
		if ($gene_name eq $gc_id) {
			$exon_link = "";
		}
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "$gene_link$exon_link</TD>\n";
	    } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	}
	if ($params{"enhancers"}) {
	    if ($gh_id) {
		my $select = "select gene_sym from gh_best_gene where gh_id = \"$gh_id\"";
		my @gene_rows = PARSE ($select, $dbh);
		my $best_gene = $gene_rows[0];
		my $rc = $dbh->disconnect;
		my $gh_link = "<A HREF=\"$URL_CARDDISP$best_gene&keywords=$gh_id&prefilter=genomic_location#genomic_location\" target=\"aaa\" title=\"See enhancer details in $best_gene, the highest scoring associated GeneCards gene\">$gh_id </A>";
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "$gh_link</TD>\n";
	    } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	}
	my %acc;
	my @cluster_links;
	my @desc_links;
	my $cluster_link_concat;
	my $desc_link_concat;
	if ($params{"est_clusters"}) {
	    if ($est_cluster_id) {
		my @accs = split (/, /, $est_acc);
		my @descs = split (/\|/, $object_desc);
		my $i;
		for ($i = 0; $i <= $#accs; $i++) { 
		    $acc{$descs[$i]} = $accs[$i];
		}
		foreach $i (@accs) {
		    my ($org, $number) = split (/\./, $i);
		    my $cluster_link = "<A HREF=\"$URL_UNIGENE$number\" target=\"aaa\">$i</A>";
		    push (@cluster_links, $cluster_link);
		}
		$cluster_link_concat = join ("; ", @cluster_links);
		
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "$cluster_link_concat</TD>\n";
	    } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	}
	if ($params{"genes"}) {
	    if ($eg_id) {
		$data_line .= "<td>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<a href=\"$URL_ENTREZGENE$eg_id\" target=\"aaa\">$eg_id</a></td>\n";
	    }else{
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	    if ($ens_id) {
		$data_line .= "<td>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<a href=\"$URL_ENSEMBL$ens_id\" target=\"aaa\">$ens_id</a></td>\n";
	    }else{
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	}

	if ($params{"genes"} || $params{"est_clusters"}) {
	    my @descs = split (/\|/, $object_desc);
	    my $desc_link;
	    foreach $i (@descs) {
		if ($i =~ /(est)/) { #est cluster--unigene link
		    my $hs_id = $acc{$i};
		    ($org, $number) = split (/\./, $hs_id);
		    $desc_link = "<A HREF=\"$URL_UNIGENE$number\" target=\"aaa\">$i</A>";
		}else{ #gene--genecards link
		    $desc_link = "<A HREF=\"$URL_CARDDISP$gene_name\" title=\"$gc_id\" target=\"aaa\">$i</A>";
		}
		push (@desc_links, $desc_link);
	    }
	    $desc_link_concat = join ("; ", @desc_links);
	    if ($desc_link_concat ) {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "$desc_link_concat</TD>\n";
	    } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	}
	if ($show_mkrs) {
	    if ($exist_mkrs_fit_show){   #if the marker on line fits the types the user wanted to see, print mkr name
		
		my $mkr_link = "<A HREF=\"${mkr_cards_url}?id=$id\" target=\"aaa\">$mkr_name</A>";
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "$mkr_link</TD>\n";
	    } else {                                 #if user does not want mkrs on map, print what's in data_line and go to next line
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	}
	if ($params{"d_numbers"}) {
	    if ($mkr_D_nr) {
		my $dnr_link = "<A HREF=\"${mkr_cards_url}?id=$id\" target=\"aaa\">$mkr_D_nr</A>";
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "$dnr_link</TD>\n";
	    } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
	    }
	}
	if ($params{"types"}) {
	    if ($params{"rh_mkrs"}) {
		if ($mkr_is_rh) {
		    $data_line .=  "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<FONT SIZE=-1 COLOR=$labels_font_color>$mkr_is_rh</FONT></TD>\n";
		} else {
		    $data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
		}
	    }
	    if ($params{"est_mkrs"}) {
		if ($mkr_is_cDNA) {
		    $data_line .=  "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<FONT SIZE=-1 COLOR=$labels_font_color>$mkr_is_cDNA</FONT></TD>\n";
            } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
            }
	    }
	    if ($params{"polymorh_mkrs"}) {
		if ($mkr_is_polym) {
		    $data_line .=  "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<FONT SIZE=-1 COLOR=$labels_font_color>$mkr_is_polym</FONT></TD>\n";
            } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
            }
	    }
	    if ($params{"sts_mkrs"}) {
            if ($mkr_is_onYAC) {
		$data_line .=  "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<FONT SIZE=-1 COLOR=$labels_font_color>$mkr_is_onYAC</FONT></TD>\n";
            } else {
		$data_line .= "<TD>";
		$data_line .= $anchor_line unless $anchor_in;
		$anchor_in = 1;
                $data_line .= $line_num unless $num_in;
                $num_in = 1;
		$data_line .= "<BR></TD>\n";
            }
	}
	}

	#print the entire line to HTML table
	print $err;
	print "<TR $mark_line>\n",
	$data_line,
    "</TR>\n";
	
    } #end of getting results from SQL query
    
    #if ($sth->err()) {
	#print "<tr><td>\n";
	#cgi_error ("problem in fetchrow_array<P>:" . $sth->errstr() );
	#print "</td></tr>\n";
    #}
    
    $dbh->disconnect
	or cgi_error ("failed to disconnect:<P>" . $dbh->errstr() );
    
    my $time1 = time();
    my $time = $time1 - $time0;
    
}

##########################################################################################
#sub to convert %in to an argument list

sub arg_list {
   local ($args_ref) = @_;
   local (%args) = %{$args_ref};
   local ($arg_list) = "";
   while (($arg_key, $arg_value) = each (%args)) {
      $arg_list .= "&" . $arg_key . "=" . $arg_value;
   }
return $arg_list;
}

##########################################################################################

sub cgi_error {

  my($string) = @_;
  print "\n<P><B><FONT SIZE =+1 COLOR=RED>Error:</FONT></B> $string<P>\n";
  
}
