#!/usr/local/bin/perl

###############################################################################
# Program     : ShowMSRunSummary
# Author      : Eric Deutsch <edeutsch@systemsbiology.org>
# $Id: ShowMSRunSummary 3243 2005-03-21 09:02:00Z edeutsch $
#
# Description : This CGI program displays a summary of an MSrun
#
# SBEAMS is Copyright (C) 2000-2005 Institute for Systems Biology
# This program is governed by the terms of the GNU General Public License (GPL)
# version 2 as published by the Free Software Foundation.  It is provided
# WITHOUT ANY WARRANTY.  See the full description of GPL terms in the
# LICENSE file distributed with this software.
#
###############################################################################


###############################################################################
# Set up all needed modules and objects
###############################################################################
use strict;
use Getopt::Long;
use FindBin;

use lib "$FindBin::Bin/../../lib/perl";
use vars qw ($sbeams $sbeamsMOD $q $current_contact_id $current_username
             $PROG_NAME $USAGE %OPTIONS $QUIET $VERBOSE $DEBUG $DATABASE
             $TABLE_NAME $PROGRAM_FILE_NAME $CATEGORY $DB_TABLE_NAME
             @MENU_OPTIONS);

use SBEAMS::Connection qw($q);
use SBEAMS::Connection::Settings;
use SBEAMS::Connection::Tables;

use SBEAMS::Proteomics;
use SBEAMS::Proteomics::Settings;
use SBEAMS::Proteomics::Tables;

$sbeams = new SBEAMS::Connection;
$sbeamsMOD = new SBEAMS::Proteomics;
$sbeamsMOD->setSBEAMS($sbeams);
$sbeams->setSBEAMS_SUBDIR($SBEAMS_SUBDIR);


#use CGI;
#$q = new CGI;


###############################################################################
# Set program name and usage banner for command like use
###############################################################################
$PROG_NAME = $FindBin::Script;
$USAGE = <<EOU;
Usage: $PROG_NAME [OPTIONS] key=value kay=value ...
Options:
  --verbose n         Set verbosity level.  default is 0
  --quiet             Set flag to print nothing at all except errors
  --debug n           Set debug flag

 e.g.:  $PROG_NAME [OPTIONS] [keyword=value],...

EOU

#### Process options
unless (GetOptions(\%OPTIONS,"verbose:s","quiet","debug:s")) {
  print "$USAGE";
  exit;
}

$VERBOSE = $OPTIONS{"verbose"} || 0;
$QUIET = $OPTIONS{"quiet"} || 0;
$DEBUG = $OPTIONS{"debug"} || 0;
if ($DEBUG) {
  print "Options settings:\n";
  print "  VERBOSE = $VERBOSE\n";
  print "  QUIET = $QUIET\n";
  print "  DEBUG = $DEBUG\n";
}


###############################################################################
# Set Global Variables and execute main()
###############################################################################
main();
exit(0);


###############################################################################
# Main Program:
#
# Call $sbeams->Authenticate() and exit if it fails or continue if it works.
###############################################################################
sub main {

  #### Do the SBEAMS authentication and exit if a username is not returned
  exit unless ($current_username = $sbeams->Authenticate(
    permitted_work_groups_ref=>['Proteomics_user','Proteomics_admin',
      'Proteomics_readonly'],
    #connect_read_only=>1,
    #allow_anonymous_access=>1,
  ));


  #### Read in the default input parameters
  my %parameters;
  my $n_params_found = $sbeams->parse_input_parameters(
    q=>$q,parameters_ref=>\%parameters);
  #$sbeams->printDebuggingInfo($q);


  #### Process generic "state" parameters before we start
  $sbeams->processStandardParameters(parameters_ref=>\%parameters);


  #### Decide what action to take based on information so far
  if ($parameters{action} eq "???") {
    # Some action
  } else {
    $sbeamsMOD->display_page_header();
    handle_request(ref_parameters=>\%parameters);
    $sbeamsMOD->display_page_footer();
  }


} # end main


###############################################################################
# Handle Request
###############################################################################
sub handle_request {
  my %args = @_;


  #### Process the arguments list
  my $ref_parameters = $args{'ref_parameters'}
    || die "ref_parameters not passed";
  my %parameters = %{$ref_parameters};


  #### Define some generic varibles
  my ($i,$element,$key,$value,$line,$result,$sql);


  $sbeams->printUserContext();


  #### verify that needed parameters were passed
  unless ($parameters{fraction_id}) {
    print "ERROR: not all needed parameters were passed.  This should never ".
      "happen!  Please report this error.<BR>\n";
    return;
  }


  #### Find the corresponding information for this fraction_id
  $sql = qq~
	SELECT fraction_tag,data_location,SB.search_batch_id,
               search_batch_subdir
	  FROM $TBPR_FRACTION F
	 INNER JOIN $TBPR_SEARCH_BATCH SB
               ON ( F.experiment_id = SB.experiment_id )
	 WHERE fraction_id IN ($parameters{fraction_id})
  ~;

  my @fractions = $sbeams->selectSeveralColumns($sql);
  unless (@fractions) {
    print "ERROR: Unable to find any fractions for fraction_id".
      " = '$parameters{fraction_id}'.  This really should never ".
      "happen!  Please report the problem.<BR>\n";
    return;
  }


  #### Provide links to the plots
  foreach my $fraction_ref ( @fractions ) {
    $key = $fraction_ref->[0];
    $value = $fraction_ref->[1];
    my $search_batch_id = $fraction_ref->[2];
    my $search_batch_subdir = $fraction_ref->[3];
    #printf("%22s = %s<BR>\n",$key,$value);
    print "<H3>Fraction: $key ($search_batch_subdir)</H3>\n";

    my $filename = "$value/$key.summary.html";
    unless ($filename =~ /^\//) {
      $filename = $RAW_DATA_DIR{Proteomics}."/$filename";
    }

    #print("filename = $filename<BR>\n");
    if ( -e $filename ) {
      print qq~
        Images are available for this MS Run:
	<UL>
	  <LI><A HREF="$CGI_BASE_DIR/Proteomics/GetImage?fraction_id=$parameters{fraction_id}&image_type=MSrun&search_batch_id=$search_batch_id">Standard image with (1,1) in lower left</A>
	  <LI><A HREF="$CGI_BASE_DIR/Proteomics/GetImage?fraction_id=$parameters{fraction_id}&image_type=MSrun_vflip&search_batch_id=$search_batch_id">Flipped image with (1,1) in upper left corner</A> (Use this for ImageJ)
	 </UL>
        In these image, the column number is the same as the scan number of
	MS spectrum.  MS/MS spectra are removed and replaced with an
        interpolation between neighboring MS spectra.  However, overlaid on
	these interpolations are colored pixels at the location of an actual
	MS/MS spectrum (column is scan number, row is m/z).  You can find the
	colored pixels in the table below and click to see the SEQUEST
	search results.
        <BR><BR>
	The following is a listing of all MS/MS spectra that were attempted,
        labeled with their result:
        <UL>
	<LI><font color=red>BadSpec: MS/MS was attempted but spectrum was bad</font>
	<LI><font color=blue>PoorHit: SEQUEST attempted to identify this spectrum but the results did not get a high Probability</font>
	<LI><font color=orange>HighProb: SEQUEST identified the spectrum with a Probability &gt; 0.7</font>
      </UL>Click on "SBEAMS" to see the SEQUEST search results<BR><BR>
      ~;

      open(INFILE,"$filename");
      while (<INFILE>) {
        print $_;
      }
    } else {
      print "[SUMMARY NOT AVAILABLE FOR THIS DATASET]<BR>\n";
    }
  }



} # end handle_request


