package SinglePageFormat;

##########################################################
#                                                        #
# dictyBase Extension of SinglePageFormat                #
#                                                        #
##########################################################

use SinglePageFormat_base;
use Go_locus_goev;
use GO_ANNOTATION_WITH_FROM;
BEGIN { %SinglePageFormat:: = %SinglePageFormat_base:: }

#
# this function is kind of redundant (see geneInfoUserPage)
#  consider writing geneinfo function that would be used
#  by both geneifnoUserpage and singlepage
#
########################################################################
sub references4topic {
########################################################################
#for literature section

    my ($self, $giObject, $topic) = @_;

    #get all papers associated with this gene/feature;
    my $sthCurated = $dbh->prepare("
          SELECT * FROM (
                SELECT unique GI.reference_no, R.citation, R.year,
                       R.pubmed, J.abbreviation
                FROM   CGM_DDB.locus_gene_info GI, CGM_DDB.reference R,
                       CGM_DDB.journal J
                WHERE  GI.locus_no = ?
                AND    GI.reference_no = R.reference_no
                AND    R.journal_no = J.journal_no(+)
                AND    upper(GI.literature_topic) != 'NOT YET CURATED'
                UNION
                SELECT unique GI.reference_no, R.citation, R.year,
                       R.pubmed, J.abbreviation
                FROM   CGM_DDB.feat_gene_info GI, CGM_DDB.reference R,
                       CGM_DDB.journal J
                WHERE  GI.feature_no = ?
                AND    GI.reference_no = R.reference_no
                AND    R.journal_no = J.journal_no(+)
                AND    upper(GI.literature_topic) != 'NOT YET CURATED'
          )
          ORDER BY year
            ");

     my $sthNotCurated = $dbh->prepare("
          SELECT * FROM (
                SELECT unique GI.reference_no, R.citation, R.year,
                       R.pubmed, J.abbreviation
                FROM   CGM_DDB.locus_gene_info GI, CGM_DDB.reference R,
                       CGM_DDB.journal J
                WHERE  GI.locus_no = ?
                AND    GI.reference_no = R.reference_no
                AND    R.journal_no = J.journal_no(+)
                AND    upper(GI.literature_topic) = 'NOT YET CURATED'
                UNION
                SELECT unique GI.reference_no, R.citation, R.year,
                       R.pubmed, J.abbreviation
                FROM   CGM_DDB.feat_gene_info GI, CGM_DDB.reference R,
                       CGM_DDB.journal J
                WHERE  GI.feature_no = ?
                AND    GI.reference_no = R.reference_no
                AND    R.journal_no = J.journal_no(+)
                AND    upper(GI.literature_topic) = 'NOT YET CURATED'
          )
          ORDER BY year
            ");

    my $arrayRef;

    if ($topic =~ /^curated/) {
        $sthCurated->execute($self->locusNo, $self->featNo);
        $arrayRef = $sthCurated->fetchall_arrayref();
        $sthCurated->finish;
    }
    else {
        $sthNotCurated->execute($self->locusNo, $self->featNo);
        $arrayRef = $sthNotCurated->fetchall_arrayref();
        $sthNotCurated->finish;
    }

    my @refs = reverse(@$arrayRef);
    my $count = @refs;

    my $returnList;

    my ($locusNm4RefNoHashRef, $featNm4RefNoHashRef, $url4RefNoHashRef);
    my ($relatedRefInfo4RefNoHashRef, $webSupplementUrl4RefNOHashRef);

=comment
    if (!$self->locusNm && @refs > 100) {
        $locusNm4RefNoHashRef = $giObject->getLocusNm4RefNoHashRef;
        $featNm4RefNoHashRef = $giObject->getFeatNm4RefNoHashRef;
        $url4RefNoHashRef = $giObject->getUrl4RefNoHashRef;
        $relatedRefInfo4RefNoHashRef
            = $giObject->getRelatedRefInfo4RefNoHashRef;
        $webSupplementUrl4RefNOHashRef
            = $giObject->getWebSupplementUrl4RefNoHashRef;
    }
=cut

    foreach my $rowRef (@refs) {
        my ($refNo, $ORIcitation, $year, $pubmed, $journal) = @$rowRef;
        my ($refObject, $topList);
        if ($refNo) {
            $refObject = Reference->new(dbh=>$dbh, reference_no=>$refNo);
        }
        my ($citation, $locusList, $featureList);
        if (!$self->locusNm && @refs > 100) {
            my $urls = $$url4RefNoHashRef{$refNo};
            my $relatedRefInfo = $$relatedRefInfo4RefNoHashRef{$refNo};
            my $webSuppUrl = $$webSupplementUrl4RefNOHashRef{$refNo};
            $citation = $self->citation2($refNo, $ORIcitation, $pubmed,
                                         $journal, $urls,
                                         $relatedRefInfo, $webSuppUrl);
            $locusList = $$locusNm4RefNoHashRef{$refNo};
            $featureList = $$featNm4RefNoHashRef{$refNo};
        }
        else {
            $citation = $self->citation($refObject, $topic);
            foreach my $rowRef (@{$refObject->locusArrayRef}) {

                my ($locusNm) = @$rowRef;
                $locusList .= $locusNm."\t";
            }
            $locusList =~ s/\t$//;
            foreach my $rowRef (@{$refObject->featureArrayRef}) {
                my ($featNm) = @$rowRef;
                $featureList .= $featNm."\t";
            }
            $featureList =~ s/\t$//;
        }

        my $thisgene = $self->locusNm || $self->featNm;
        my $linkTopic;
        if ($topic =~ /^curated/) {
            my %foundtopic;
#            my $linkTopic;
            foreach my $rowRef (@{$refObject->locusTopicArrayRef}) {
                my ($onetopic, $thislocus) = @$rowRef;
                $foundtopic{$onetopic} = 1 if ($thislocus eq $self->locusNm);
            }
            foreach my $rowRef (@{$refObject->featureTopicArrayRef}) {
                my ($onetopic, $thisfeatNm) = @$rowRef;
                $foundtopic{$onetopic} = 1 if ($thisfeatNm eq $self->featNm);
            }

            foreach my $key (keys %foundtopic) {
                $linkTopic = $key;
                $linkTopic =~ s/ /+/;
                $topList .= font({-size=>'-1'}, a({-href=>$configUrl->dictyBaseCGIRoot."$db/reference/geneinfo.pl?locus=$thisgene&topic=$linkTopic", -target=>'infowin'},$key)) . br;
            }
        }
        else {
            $linkTopic = $topic;
            $linkTopic =~ s/ /+/;
            $topList = font({size=>'-1'}, a({-href=>$configUrl->dictyBaseCGIRoot."$db/reference/geneinfo.pl?locus=$thisgene&topic=$linkTopic", -target=>'infowin'}, "Not Yet Curated"));
        }

        my $loci;
#        if ($locusList && $featureList) {
#            $loci = $locusList."\t".$featureList;
#        }
#        elsif ($locusList) { $loci = $locusList; }
     if ($locusList) { $loci = $locusList; }
        elsif ($featureList) { $loci = $featureList; }
        $loci =~ s/^\t//;
        $loci =~ s/\t$//;
        my @loci = split(/\t/, $loci);

        my $listLoci;

        my $i;
        foreach my $locus (@loci) {
            if ( $self->locusNm && $self->locusNm =~ /^$locus$/i) {
                next;
            }
            $i++;
            if ($i > 15) { last; }
            if ($i == 15) {
                $listLoci .= " |".a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/reference/reference.pl?refNo=$refNo#summary", -target=>'infowin'}, font({-color=>'red'}, "MORE"));
            }
            else {
                $listLoci .= " |".a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=$locus", -target=>'infowin'}, $locus);
            }
        }
        $listLoci =~ s/^\|//;
        if (!$listLoci) { $listLoci = br; }

        $returnList .= Tr(td({-width=>"25%", -bgcolor=>"#b7d8e4",
                                  -valign=>"top"},
                                 $topList).
                              td({-width=>"50%",
                                  -valign=>"top"},
                                 $citation).
                              td({-width=>"25%",
                                  -valign=>"top"},
                                 $listLoci));
    }

    return ($returnList, $count);
}

#
#  changed next button hash to fit our layout
#
########################################################################
sub getIDs {
########################################################################

    my ($self) = @_;

    my $search = $self->query;

    my $searchType = $self->queryType;

    #parameter 'dictyBaseid' only accept dictyBaseid. parameter 'locus' cannot accept dictyBaseid
    my $object;

    if ($searchType eq 'dictyBaseid') {
        $object = dictyBaseObject->new(database=>$self->database, dictyBaseid=>$search);
    }
    elsif (($searchType eq 'locus') && ($search =~/^[SsLl]\d{7}/)) {

        my $mssg = "Your search for \'".font({-color=>'red'},$self->query)."\' d
id not return any hits. Please modify your query and try again!";

        $self->SearchForm($mssg);
    }
    else {
        $object = dictyBaseObject->new(database=>$self->database, query=>$search);
    }

    if ($object->isMultiple){
        $self->err_report("Multiple results found\n");
        $self->DESTROY;
    }

    %nextButton = ( 'names' => 'go', 'go' => 'paragraph',
                    'paragraph' => 'phenotype', 'phenotype' => 'proteininfo',
                     'proteininfo' => 'notes',
                    'notes' => 'seq',
                    'seq'=> 'literature'
                  );

    %helpURL = ( 'names' => $self->help . "#names_identifiers",
                 'go' => $helpBase . "GO.html",
                 'paragraph' => $helpBase . "Locus.html#summary",
                 'phenotype' => $self->help . "#phenotypes",
                 'homologs' => $self->help . "#homologs",
                 'proteininfo' => $helpBase . "protein_page.html",
                 'pdb' => $helpBase . "PDB_Homolog.html",
                 'motifs'=> $helpBase . "Protein_Motifs.html",
                 'exp' =>  $helpBase . "expression.html",
                 'notes' => $helpBase . "locusHistory.html",
                 'seq' => $self->help . "#Retrieval",
                 'map' => $self->help . "#map",
                 'interactions' => $self->help . "#interactions_help",
                 'literature' => $helpBase . "Literature_Topics.html"
               );

    $self->{'_featNm'} = $object->featureName;
    $self->{'_locusNm'} = $object->locusName;
    $self->{'_dictyBaseid'} = $object->primarydictyBaseID;
    $self->{'_featureType'} = $object->featureType;
    $self->{'_alias'} = $object->alias;
    $self->{'_locusNo'} = $object->locusNo;
    $self->{'_featureNo'} = $object->featureNo;

    return;
}


#
# take out unimplemented features
#
# this function is kind of redundant (see ProteinPage.pm)
#  consider writing protien function that would be used
#  by both proteinpage and singlepage
#
#
########################################################################
sub proteinInfo {
########################################################################
    my ($self, $dictyBase) = @_;

    my $rows = $self->titleRow("Physical Properties and Transcript Information", "proteininfo", ": predicted from sequence", '2');

    if (!$dictyBase->protInfo) {
        $rows .= Tr(td({-colspan=>'2'}, "No protein information available."));
        return table({-width=>"100%", -cellpadding=>"0", -cellspacing=>"1",
                      -border=>"1"}, $rows);
    }

    #get protein data from DB
    my $sth = $dbh->prepare ("
        SELECT p.molecular_weight, p.pi, p.protein_length,
               p.n_term_seq, p.c_term_seq, p.codon_bias,
               p.cai, p.fop_score, p.gravy_score, p.aromaticity_score
        FROM CGM_DDB.feature f, CGM_DDB.protein_info p
        WHERE f.feature_name = ? and
              f.feature_no = p.feature_no
    ");
    $sth->execute($self->featNm);
    my @data = $sth->fetchrow;
    $sth->finish;

    #trim codonW results
    for (my $i=5; $i<10; $i++) {
        $data[$i] = sprintf("%.3f", $data[$i]);
    }

    #put ',' in long integer
    my $mw = $self->formatNumber($data[0]);
    my $prlen = $self->formatNumber($data[2]);
    my $aaUrl = $configUrl->dictyBaseCGIRoot."$db/protein/aa.pl?locus=".$self->locusNm."&feat=".$self->featNm;

    my $secStrbaseURL = $configUrl->dictyBaseCGIRoot."$db/protein/secStructure?Feat=".$self->featNm."&Locus=".$self->proteinNm;
    my $heli = $secStrbaseURL."&Type=HW";
    my $pepplot = $secStrbaseURL."&Type=PP";
    my $pepStr = $secStrbaseURL."&Type=PS";

    $rows .= Tr(
                td({-align=>'left', -valign=>'top', -rowspan=>'10'},
                   table({-border=>2, -width=>325, -cellpadding=>3, -cellspacing=>0},
                      Tr({-bgcolor=>"a4abc2"},
                         td({-align=>'center', -colspan=>2},
                            b('Protein Sequence Calculations').
                            br.
                            font({-size=>"-1"}, 'from Predicted Full length Translation')
                         )
                      ),

                      Tr({-align=>'center'},
                         th({-bgcolor=>'#d8d8d8'}, 'N-term'),
                         td($data[3])
                      ),

                      Tr({-align=>'center'},
                         th({-bgcolor=>'#d8d8d8'}, 'C-term'),
                         td($data[4])
                      ),

                      Tr({-align=>'center'},
                         th({-bgcolor=>'#d8d8d8'}, 'Length(aa)'),
                         td($prlen)
                      ),

                      Tr({-align=>'center'},
                         th({-bgcolor=>'#d8d8d8'}, 'MW(Da)'),
                         td($mw)
                      ),

#                        Tr({-align=>'center'},
#                           th({-bgcolor=>'#d8d8d8'}, 'pI'),
#                           td($data[1])
#                        ),

                     Tr({-align=>'center'},
                        th({-colspan=>2}, a({-href=>"javascript:newwindow()"},'Amino Acid Composition (full length)'))
                     )
#,
#
#                        Tr({-align=>'center'},
#                           td({-colspan=>2}, b("GCG tools: ") . a({-href=>$pepplot}, "PepPlot"). ", " . a({-href=>$heli}, "Helical Wheel") . ", " . a({-href=>$pepStr}, "PepStruct"))
#                        )
                    ), p, #table contain the seq calculation table

#                    table({-border=>2, -width=>325, -cellpadding=>3, -cellspacing=>0},
#                                Tr({-bgcolor=>"a4abc2"},
#                                   td({-align=>'center', -colspan=>2},
#                                b('Transcript Translation Calculations')
#                          )
#                        ),
#
#                        Tr({-align=>'right'},
#                                    th({-bgcolor=>'#d8d8d8'}, 'Codon Bias'),
#                           td($data[5]."&nbsp"."&nbsp")
#                        ),
#
#                        Tr({-align=>'right'},
#                           th({-bgcolor=>'#d8d8d8'}, 'Codon Adaptation Index'),
#                           td($data[6]."&nbsp"."&nbsp")
#                        ),
#
#                        Tr({-align=>'right'},
#                           th({-bgcolor=>'#d8d8d8'}, 'Frequency of Optimal Codons'),
#                           td($data[7]."&nbsp"."&nbsp")
#                        ),
#
#                        Tr({-align=>'right'},
#                           th({-bgcolor=>'#d8d8d8'}, 'Hydropathicity of Protein'),
#                           td($data[8]."&nbsp"."&nbsp")
#                        ),
#
#                        Tr({-align=>'right'},
#                           th({-bgcolor=>'#d8d8d8'}, 'Aromaticity Score'),
#                           td($data[9]."&nbsp"."&nbsp")
#                        )
#                   )
              ), #td
                td(
                    pre($self->DomainDisplaySeq)
                )
            );

    return table({-width=>"100%", -cellpadding=>"0", -cellspacing=>"1",
                      -border=>"1"}, $rows);
}
########################################################################
sub titleRow {
########################################################################
    my ($self, $title, $anchor, $subtitle, $col) = @_;
    my $makeTitle = font({-size=>"+2", -color=>"white"},
                         a({-name=>$anchor}, $title));
    if ($subtitle) {
        $makeTitle .= font({-color=>"white"}, $subtitle);
    }

    $col = '6' if (!$col);

    my $helplink = $helpURL{$anchor} || $self->help;

    my $row = td({-align=>"left", -width=>"70%"}, $makeTitle
              ) . "\n" .
              td({-align=>"center", -width=>"10%"},
              a({-href=>"#top"}, "[TOP]")
              ) . "\n";

    if ($nextButton{$anchor}) {
        $row .= td({-align=>"center", -width=>"10%"},
              a({ -href=>"#" . $nextButton{$anchor} }, "[NEXT]")
              ) . "\n";
    }
    else {
        $row .= td({-align=>"center", -width=>"10%"},
                    "&nbsp") . "\n";
    }
    $row .= td({-align=>"right", -width=>"10%"},
              a({-href=>$helplink}, img({-alt=>"Help",-border=>"0",
                 -align=>"right", -valign=>"middle", -src=>$helpButton}))
            ) . "\n";

    return Tr(
              th({-colspan=>"$col", -align=>"left", -width=>"100%"},
              table({-width=>"100%", -cellpadding=>"0", -cellspacing=>"0",
                  -border=>"0"},
                    Tr($row))));
}
########################################################################
sub contentBlock {
########################################################################

    my ($self, $dictyBase, $locus_url) = @_;

    my $content = h2(a({-name=>"top"}, "Contents"));

    my $positionalInfo = $dictyBase->positionalInfo;
#
#
#sub orfMap         { $_[0]->{'ORFMap'}        }
#
#sub miniORFMap     { $_[0]->{'miniORFMap'}    }

    my $orfMapUrl = $dictyBase->orfMap;
    my $miniMapUrl = $dictyBase->miniORFMap;

    my $mappingData = $dictyBase->mappingData;

    my $list = td(
          table({-width=>'100%', -border=>0, -cellspsacing=>6},
           Tr(
            td(li(a({-href=>"#names"}, "Names and Identifiers"))),
            td(li(a({-href=>"#go"},"GO Annotations")))
           ) . "\n",
           Tr(
            td(li(a({-href=>"#paragraph"}, "Summary Paragraph"))),
            td(li(a({-href=>"#phenotype"}, "Phenotypes")))
           ) . "\n",
#           Tr(
#            td(li(a({-href=>"#homologs"}, "Homologs"))),
#            td(li(a({-href=>"#proteininfo"}, "Protein Info") . " (physical properties, transcript info)"))
#           ) . "\n",
#           Tr(
#            td(li(a({-href=>"#pdb"}, "PDB Homologs") . " (protein structure info)")),
#            td(li(a({-href=>"#motifs"}, "Motifs")))
#           ) . "\n",
#           Tr(
#            td(li(a({-href=>"#exp"}, "Genome-wide Expression") . br . "(and other large-scale analyses)")),
#            td(li(a({-href=>"#notes"}, "Locus History") . " (misc. notes)"))
#           ) . "\n",
#           Tr(
#            td(li(a({-href=>"#seq"}, "Sequence Retrieval and Analysis"))),
#            td(li(a({-href=>"#map"}, "Map and Table Displays")))
#           ) . "\n",
#           Tr(
#            td(li(a({-href=>"#interactions"}, "Interactions"))),
#            td(li(a({-href=>"#commanno"}, "Community Annotation")))
#           ) . "\n",
           Tr(
            td(li(a({-href=>"#literature"}, "Literature Guide")))
           )
          )
                  );

    my ($geneticPositionBlock, $blockCont);
    if ($positionalInfo) {
        $blockCont .= a({-href=>$orfMapUrl}, img({-alt=>"ORFMAP",-border=>"1", -src=>$miniMapUrl})) . br . br . $positionalInfo;
    }
    if ($mappingData) {
        $blockCont .= br. a({-href=>$mappingData}, "Genetic Map Data");
    }

    $geneticPositionBlock = td($blockCont);

    $content .=
      ul(
       table({-width=>'100%'},
        Tr($list, $geneticPositionBlock
        )
       )
      );

    $content .= h2(a({-href=>$locus_url}, "dictyBase Locus Page"));

    return blockquote($content);
}
#
# changed name to just show locus name instead of locusname/featurename
# took out a bunch of stuff we don't do yet
#######################################################################
sub SinglePage {
#######################################################################
    my ($self) = @_;

    $self->getIDs;


    if ((!$self->featNm) && (!$self->locusNm)) {
        $self->err_report("No LOCUS and Feature Name: Invalid entry!\n");
    }
    elsif (!$self->dictyBaseid) {
        $self->err_report("No dictyBaseID!\n");
    }

    my $dictyBase;

    $dictyBase = dictyBaseObject->new(dictyBaseid=>$self->dictyBaseid,
                          database=>$self->{'_database'});

    #to be able to retrieve candida homolog URL
    $dictyBase->_initURLs;

    $showNm = $self->locusNm;
    if (!$self->locusNm) {
        $showNm = $self->featNm;
    }

    $self->{'_showNm'} = $showNm;

    my $title = "$showNm Single Page Format";
    my $Locus = $self->locusNm || $self->featNm;
    my $locus_url = $configUrl->dictyBaseCGIRoot ."gene_page.pl?dictybaseid=".$self->dictyBaseid;
    my $startMssg = "This page provides a single page alternative format to the ". a({-href=>$locus_url}, "dictyBase Locus Page") . ". Note that all of the information provided here is also available on the dictyBase locus page, either directly or a single click away. ";

    my $aaUrl = $configUrl->dictyBaseCGIRoot."$db/protein/aa.pl?locus=".$self->locusNm."&feat=".$self->featNm;

    # Here's the javascript code that we include in the document.
    my $javascript =  "
      <SCRIPT language=\"JavaScript\">
      <!--
         if (document.layers)
            isNS = true
         else
            isNS = false
         if (document.all)
            isIE = true
         else
            isIE = false
         if (isNS)
            var gBorder = 20; //Minimum image border to avoid scrollbars in NS
         else
            var gBorder = 55; //Minimum image border to avoid scrollbars in IE

         function newwindow() {
            window.open('$aaUrl','Composition','toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=no,resizable=yes,width=200,height=680,screenX=0,screenY=40,top=40,left=450');
         }

         function switchAddress(list ){
            location.href = list.options[list.selectedIndex].value;
         }
      //-->
      </SCRIPT> "
    ;

    &printStartPage($self->database, $title, $self->help);

    print $javascript;

    print p, font({-size=>'+1'}, $startMssg), p;
    print $self->contentBlock($dictyBase, $locus_url), p;
    print $self->namesIdentifiers($dictyBase), p;
    print $self->goAnnotations, p;
    print $self->summaryParagraph($dictyBase), p;
    print $self->phenotypesAlleles($dictyBase), p;
#    print $self->homologs($dictyBase), p;
    print $self->proteinInfo($dictyBase), p;
#    print $self->pdbStructure($dictyBase), p;
#    print $self->motifs($dictyBase), p;
#    print $self->genomeWideAnalysis($dictyBase), p;
    print $self->locusHistory, p;
    print $self->sequenceRetrieve($dictyBase), p;
#    print $self->maptableDisplay, p;
#    print $self->interactions($dictyBase), p;
#    print $self->communityAnnotation, p;
    print $self->literatureGuide, p;

    &printEndPage;

    $self->DESTROY;
}



#
#  took out gcg format for all sequences, took out a few types of seq that we don't keep
#  took out some analyses that we don't have.
#
########################################################################
sub sequenceRetrieve {
########################################################################
    my ($self, $dictyBase) = @_;
    my $rows = $self->titleRow("Sequence Retrieval and Analysis", "seq", "", '2');

    if (!$self->featNo) {
        $rows .= Tr(td("No sequence data available."));
        return table({-width=>"100%", -cellpadding=>"0", -cellspacing=>"1",
                      -border=>"1"}, $rows);
    }

    $rows .= Tr(th({-align => 'left', -width => '10%'}, "Sequence Retreival"),
                td({-align => 'left', -width => '90%'}, br.$dictyBase->write_sequence_retreival_selector)
               ) . "\n";

    $rows .= Tr(th({-align=>'left', -width=>'10%'}, "Analysis options" ),
                td({-align=>'left', -width=>'90%'}, br.$dictyBase->write_analysis_selector)
               ) . "\n";


#    my @otherDBseq = $self->getAssociatedSeq;
#    unshift(@otherDBseq, th({-align=>'left', -bgcolor=>"#a4abc2", -colspan=>'2'}, "Sequence from other databases"));
#
    return table({-width=>"100%", -cellpadding=>"0", -cellspacing=>"1",
                      -border=>"1"}, $rows);
#.
#           table({-width=>"100%", -cellpadding=>"0", -cellspacing=>"1",
#                      -border=>"1"}, Tr([@otherDBseq]));
}


########################################################################
sub getGoAnnotationRow {
########################################################################
    my ($self) = @_;
    my ($type, $No, $tabNm, $goArrayRef);
    my $locusObj = Locus->new(dbh=>$dbh,
                              locus_name=>$self->locusNm) if ($self->locusNm);
    if (!$locusObj) {
        my $featObj = Feature->new(dbh=>$dbh,
                                   feature_name=>$self->featNm);
        if (!$featObj) {
            $self->err_report("The feature/locus you entered (".font({-color=>'red'}, $self->locusNm).") is not found in database. Please correct it and try again.");
        }
        else {
            $type = "Feature";
            $No = $featObj->feature_no;
            $tabNm = "GO_FEAT_GOEV";
            $goArrayRef = $featObj->goInfoArrayRef;
        }
    }
    else {
        $type = "Locus";
        $No = $locusObj->locus_no;
        $tabNm = "GO_LOCUS_GOEV";
        $goArrayRef = $locusObj->goInfoArrayRef;
    }
    if (!$$goArrayRef[0]) {
        return;
    }

    my (%desc4code, %goEvCodeNo);
    Go->GetGoEvidenceInfo(dbh=>$dbh,
                          goEvidenceDesc4CodeRef=>\%desc4code,
                          goEvidenceNoRef=>\%goEvCodeNo);

    my ($functionRows, $processRows, $componentRows);
    my $functionBgcolor= "#FFFFFF";
    my $processBgcolor= "#FFFFFF";
    my $componentBgcolor= "#FFFFFF";

    foreach my $rowRef (@$goArrayRef) {

        my ($goid, $goTerm, $goAspect, $goDefinition) = @$rowRef;

        my $citationEtcArrayRef = Go->GetReferenceInfo(dbh=>$dbh,
                                                       goid=>$goid,
                                                       type=>$type,
                                                       No=>$No);
        my $bgcolor;
        if ($goAspect =~ /^F/i ) {  $bgcolor = $functionBgcolor; }
        elsif ($goAspect =~ /^P/i ) {  $bgcolor = $processBgcolor; }
        elsif ($goAspect =~ /^C/i ) {  $bgcolor = $componentBgcolor; }

        my ($rowspan, $isNotRowspan);
        foreach my $refRow (@$citationEtcArrayRef) {
            my ($citation, $refNo, $isNot, $dateCreated, $goevCodeList)
                = split(/::/, $refRow);
            if ($isNot =~ /^Y/i) { $isNotRowspan++; }
            else { $rowspan++; }
        }

        my $row = td({-width=>'15%',
                      -bgcolor=>"$bgcolor",
                      -align=>'center',
                      -valign=>'middle',
                      -rowspan=>$rowspan},
                     a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/GO/go.pl?goid=$goid"}, $goTerm));
        my $isNot = a({-href=>$configUrl->dictyBaseHelp."GO.html#not"},
                      b(i("NOT")));
        if ($goAspect =~ /^F/i) { $isNot .= " a "; }
        elsif ($goAspect =~ /^P/i) { $isNot .= " involved in "; }
        else { $isNot .= " part of "; }
        my $notRow = td({-width=>'15%',
                         -bgcolor=>"$bgcolor",
                         -align=>'center',
                         -valign=>'middle',
                         -rowspan=>$isNotRowspan},
                         $isNot.a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/GO/go.pl?goid=$goid"}, $goTerm));
        my $notRows;
        foreach my $refRow (@$citationEtcArrayRef) {

            my ($citation, $refNo, $isNot, $dateCreated, $goevCodeList)
                = split(/::/, $refRow);

            $refNo =~ s/[^0-9]//g;

            #### $goevCodeList = goevCodes delimited by '|'
            my @evCode = split(/\|/, $goevCodeList);
            my $codeList;
            foreach my $evCode (@evCode) {
                my $desc = $self->uppercaseWords($desc4code{$evCode});
                $desc = "\u$desc";
                my $prikey = $goid."::".$No."::".$goEvCodeNo{$evCode}."::".$isNot;

###### Code added by Sohel Merchant to display the with from field ################
                 my $with;


                my $go_loc_goev = Go_locus_goev->new(dbh=>$dbh,
                             goid=>$goid,
                             locus_no=>$No,
                             go_evidence_no=>$goEvCodeNo{$evCode},
                             is_not=>$isNot);
                my $with_from_id = $go_loc_goev->with_from;
                if($with_from_id)
                {

                    my $go_anno_with_from = GO_ANNOTATION_WITH_FROM->new(dbh=>$dbh, id=>$with_from_id);
                    my $source = $go_anno_with_from->external_db;
                    my $ext_id = $go_anno_with_from->external_id;
                    # if($source =~ /|/ && $ext_db =~ /|/)
#                     {
#                     }else
#                     {
                         if($goEvCodeNo{$evCode} == 10)
                         {
                              $with = " ".$source.": ";
                         }else
                         {
                              $with = " with ".$source.": ";
                         }
                         if ($source =~ /DDB/i)
                         {
                              my $dictyBaseidObj = dictyBaseid->new(dbh=>$dbh,
                                                  dictyBaseid=>$ext_id);
                              my $showNm;
                              if ($dictyBaseidObj && $dictyBaseidObj->locus_name)
                              {
                                   $showNm = $dictyBaseidObj->locus_name;
                              }

                              if ($showNm) {
                                   $with .= a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=$showNm"}, $showNm);
                              }
                         }elsif($source =~ /GO/i)
                         {
                              $with .= a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/GO/go.pl?goid=$ext_id"}, $ext_id);

                         }elsif($source =~ /SPTR/i or $source =~ /UniProt/i)
                         {

                              $with .= a({-href=>"http://www.pir.uniprot.org/cgi-bin/upEntry?id=$ext_id"}, $ext_id);
                         }elsif($source =~ /SGD/i)
                         {

                              $with .= a({-href=>"http://db.yeastgenome.org/cgi-bin/gene_page.pl?sgdid=$ext_id"}, $ext_id);
                         }elsif($source =~ /MGI/i)
                         {
                              $with .= a({-href=>"http://www.informatics.jax.org/searches/accession_report.cgi?id=$ext_id"}, $ext_id);
                         }elsif($source =~ /TIGR_CMR/i)
                         {
                              $with .= a({-href=>"http://www.tigr.org/tigr-scripts/CMR2/GenePage.spl?locus=$ext_id"}, $ext_id);

                         }elsif($source =~ /WB/i)
                         {
                              $with .= a({-href=>"http://www.wormbase.org/db/gene/gene?name=$ext_id"}, $ext_id);

                         }elsif($source =~ /InterPro/i)
                         {
                              $with .= a({-href=>"http://www.ebi.ac.uk/interpro/IEntry?ac=$ext_id"}, $ext_id);
                         }else
                         {
                              $with .= $ext_id;
                         }


                    #}



                }

#####Code ends here ###############################################################################


                my $externalIdArrayRef = Go->GetExternalIdSourceInfo(dbh=>$dbh,
                                                   tab_name=>$tabNm,
                                                   primary_key=>$prikey);


                if (@$externalIdArrayRef) {
                    $with = " with ";
                }

                my $preSource;
                foreach my $rowRef (@$externalIdArrayRef) {
                    my ($externalId, $source) = @$rowRef;
                    if ($preSource && $preSource ne $source) {
                        $with .= " and ".$source.": ";
                    }
                    elsif ($preSource ne $source) {
                        $with .= $source.": ";
                    }
                    else {
                        $with .= ", ";
                    }
                    if ($source =~ /dictyBase/i) {
                        my $dictyBaseidObj = dictyBaseid->new(dbh=>$dbh,
                                                  dictyBaseid=>$externalId);
                        my $showNm;
                        if ($dictyBaseidObj && $dictyBaseidObj->locus_name) {
                            $showNm = $dictyBaseidObj->locus_name;
                        }
                        elsif ($dictyBaseidObj) {
                            $showNm = $dictyBaseidObj->feature_name;
                        }
                        if ($showNm) {
                            $with .= a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=$showNm"}, $showNm);
                        }
                    }
                    else {
                        $with .= $externalId;
                    }
                    $preSource = $source;
                }

                $codeList .= li($evCode." : ".a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/GO/goEvidence.pl#$evCode"}, $desc).$with);
            }


            ####
            ### add with here
            ####


            $codeList .= "<br><font size=1><b>Last updated on $dateCreated</b></font>";

            my $refObj = Reference->new(dbh=>$dbh,
                                        reference_no=>$refNo);
            if (!$refObj) {
                next;
            }

            my $formatedCitation = $refObj->formatedCitation;

            my $cells = td({-width=>'55%',
                              -align=>'left',
                              -valign=>'top'},
                             $formatedCitation).
                          td({-width=>'30%',
                              -align=>'left',
                              -valign=>'top'},
                             $codeList);
            if ($isNot =~ /^Y/i) {
                      $notRow .= $cells;
                $notRows .= Tr({-bgcolor=>"$bgcolor"}, $notRow);
                undef $notRow;
            }
            else {
                $row .= $cells;
                if ($goAspect =~ /^F/i) {
                    $functionRows .= Tr({-bgcolor=>"$bgcolor"}, $row);
                }
                elsif ($goAspect =~ /^P/i) {
                    $processRows .= Tr({-bgcolor=>"$bgcolor"}, $row);
                }
                elsif ($goAspect =~ /^C/i) {
                    $componentRows .= Tr({-bgcolor=>"$bgcolor"}, $row);
                }
                undef $row;
            }
        }
        if ($notRows) {
            if ($goAspect =~ /^F/i) {
                $functionRows .= $notRows;
            }
            elsif ($goAspect =~ /^P/i) {
                $processRows .= $notRows;
            }
            elsif ($goAspect =~ /^C/i) {
                $componentRows .= $notRows;
            }
        }

        if ($goAspect =~ /^F/i ) {
            $functionBgcolor = $self->setBgcolor($bgcolor);
        }
        elsif ($goAspect =~ /^P/i ) {
            $processBgcolor = $self->setBgcolor($bgcolor);
        }
        elsif ($goAspect =~ /^C/i ) {
            $componentBgcolor = $self->setBgcolor($bgcolor);
        }
    }
    if (!$functionRows && !$processRows && !$componentRows) {
        &err_report("No go annotation found for feature/locus = '" . $self->locusNm . "'.");
    }



    return ($functionRows, $processRows, $componentRows);
}






########################################################################
1;
########################################################################