#!perl
package GeneInfoUserPage_base;
use strict;
use DBI;
use CGI qw/:all/;
use CGI::Carp qw(fatalsToBrowser);

use lib "/usr/local/dicty/www_dictybase/db/lib/dictyBase/Objects";
use GeneInfo;
use Reference;
use Locus;
use Feature;
use ConfigURLdictyBase;
use ConfigPathdictyBase;

use lib "/usr/local/dicty/www_dictybase/db/lib/common";
use Login qw (ConnectToDatabase);
use TextUtil qw (DeleteUnwantedChar);

use lib "/usr/local/dicty/www_dictybase/db/lib/dictyBase";
use dictyBaseObject;
use dictyBaseCentralMod qw(:formatPage :navigateInfo);

#######################################################################
#################### global variables #################################
#######################################################################

our $maxDisplayNo = 30;
our $dbh;
our $dblink;
our $configUrl;
our $configPath;
our $downloadfile;
our $downloadUrl;

#######################################################################
sub new {      ############ constructor ###############################
#######################################################################

        my ($type, %args) = @_;

        my $self = {};
        bless $self, $type;

              $self->{'_database'} = $args{'database'};
        $self->{'_help'}     = defined($args{'help'}) ?
                               $args{'help'} : "Gene_Info.html";
        $self->{'_locus'}     = $args{'locus'};
            return $self;
}

sub help { $_[0]->{_help} }
sub database { $_[0]->{_database} }
sub title { $_[0]->{_title} }
sub locus { $_[0]->{_locus} }

######################################################################
sub DESTROY {   ############ destructor ##############################
######################################################################
            if (defined $dbh) {
                $dbh->disconnect;
            }
}

######################################################################
sub start{
######################################################################

            my ($self) = @_;
        $configPath = ConfigPathdictyBase->new;
        $configUrl = ConfigURLdictyBase->new;
        $dblink = $configUrl->dblink($self->database);
        $self->setDownloadfile;
        my $locus = $self->{'_locus'};
        &DeleteUnwantedChar(\$locus);
        $self->{'_locus'} = $locus;
        if (!$self->locus) {
            if((!param('topic')) && (!param('date'))) {
                $self->{'_title'} = "Gene Info Search";
                $self->printEntryForm;
            }
            elsif (param('date')) {
                $dbh = &ConnectToDatabase($self->database);
                $self->displayAllRefsThisDate;
            }
            else {
                $dbh = &ConnectToDatabase($self->database);
                $self->displayAllRefs4topics;
            }
            exit;
        }
        if ($self->locus =~ /\*/ || $self->locus =~ /\%/) {
            $dbh = &ConnectToDatabase($self->database);
            my @loci = $self->getGeneList;
            if (@loci > 1) {
                $self->displayGeneList(@loci);
                exit;
            }
            elsif (!@loci) {
                $self->err_report("The locus/feature you entered is not found in database. Please correct it and try again.");
                exit;
            }
            else {
                $self->{'_locus'} = $loci[0];
            }
        }
        elsif (!param('topic')) {
            my $dictyBase = dictyBaseObject->new(database=>$self->database,
                                     query=>$self->locus);
            if ($dictyBase->isMultiple) {
                $dbh = &ConnectToDatabase($self->database);
                my @loci = $self->getGeneList;
                if (@loci == 1) {
                    $self->{'_locus'} = $loci[0];
                }
                else {
                    $self->displayGeneList(@loci);
                    exit;
                }
            }
            elsif ($dictyBase->locusName) {
                $self->{'_locus'} = $dictyBase->locusName;
            }
            elsif ($dictyBase->featureName) {
                $self->{'_locus'} = $dictyBase->featureName;
            }
            else {
                $self->err_report("The locus/feature you entered is not found in database. Please correct it and try again.");
                exit;
            }
        }
        $dbh = &ConnectToDatabase($self->database);
        $self->{'_title'} = $self->locus." Literature Guide";
        my $giObject = GeneInfo->new(dbh=>$dbh,
                                     locus=>$self->locus);
        if (param('topic')) {
            $self->displayRef4topic($giObject);
        }
        #elsif (param('date')) {
            #$self->displayAllRefsThisDate($giObject);
        #}
        elsif (param('type')) {
            $self->displayLoci($giObject);
        }
        else {
            $self->displaySummary($giObject);
        }
        exit;

}

#######################################################################
sub printEntryForm {
#######################################################################
        my ($self) = shift;

        &printStartPage($self->database, $self->title, $self->help);
        print center(table({-border=>3,
                        -cellpadding=>4,
                        -cellspacing=>4},

                       Tr({-align=>'LEFT'},
                          [
                           td({-bgcolor=>"#b7d8e4",
                               -width=>350},
                              table({-border=>0},
                                    Tr({align=>'LEFT'},
                                       [
                                        td(start_form,
                                           "Enter locus name : ").
                                        td(textfield(-name=>'locus',
                                                     -size=>'15')),
                                        td("&nbsp;").td(submit, reset, end_form)
                                        ]))
                              )
                           ])));

        &printEndPage;
}

########################################################################
sub displaySummary {
########################################################################
    my ($self, $giObject) = @_;
    &printStartPage($self->database, $self->title, $self->help);
    print table({-border=>'0',
                 -width=>'100%'},
Tr(td{-width=>'100%',
                       -colspan=>'2',
                       -valign=>'top'},
                       font({-size=>'+1'},
                       ("This page displays all the papers associated with ".$self->locus." in dictyBase, along with all the literature topics those papers address.  Click on a topic on the left to see the papers that address it."))).
Tr(td{-width=>'100%',
                       -colspan=>'2',
                       -valign=>'top'},
                ("&nbsp;")).
                Tr(td({-width=>'30%',
                       -bgcolor=>'#d8d8d8',
                       -valign=>'top'},
                      $self->topicsSection($giObject)).
                   td({-width=>'70%',
                       -valign=>'top'},
                      table({-width=>'100%',
                             -border=>'0'},

                            Tr(td(h4(a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=".$self->locus},$self->locus).
                                          " Literature Curation Summary"))).
                            Tr(td($self->summary($giObject)))
                      )
                   )
                )
         );

    &printEndPage;
}

########################################################################
sub displayAllRefs4topics {
########################################################################
    my ($self) = @_;
    $self->{'_title'} = "References Associated with Literature Topic(s): ";

    my $giObject = GeneInfo->new(dbh=>$dbh);

    my $topicRefs = $self->references4topic($giObject);

    my $navigationBar = $self->displayNavigationBar;

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

    print table({-width=>'100%',
                 -border=>'0'},
                Tr(td(&ResultNumber(totalHit=>$self->{'_end'},
                                    showNum=>$maxDisplayNo,
                                    beg=>param('beg')))).
                # Tr(td($navigationBar)).
                Tr(td(
                      table({-align=>'center',
                             -border=>'0',
                             -cellpadding=>'3',
                             -cellspacing=>'3',
                             -width=>'100%'},
                            Tr(th({-align=>'left',
                                   -bgcolor=>'#a4abc2'},
                                  "Reference").
                               th({-align=>'left',
                                   -bgcolor=>'#a4abc2'},
                                  "Genes Addressed")).
                            $topicRefs
                       ))).
                Tr(td($navigationBar))
         ) ;
}

########################################################################
sub displayRef4topic {
########################################################################
    my ($self, $giObject) = @_;
    &printStartPage($self->database, $self->title, $self->help);
    my $topic;
    if (param('topic') =~ /^curated/i) {
        $topic = "Curated References";
    }
    elsif (param('topic') =~ /^not yet curated/i) {
        $topic = "References Not Yet Curated";
    }
    else { $topic = param('topic'); }
    my $topicRefs = $self->references4topic($giObject);
    my $navigationBar = $self->displayNavigationBar;
    print "<a name='top'>";
    print table({-border=>'0',
                 -width=>'100%'},
                Tr(td({-width=>'30%',
                       -bgcolor=>'#d8d8d8',
                       -valign=>'top'},
                      $self->topicsSection($giObject)).
                   td({-width=>'70%',
                       -valign=>'top'},
                      table({-width=>'100%',
                             -border=>'0'},
                            $self->locusInfo.
                            Tr(td(h3(font({-color=>'red'},
                                          $self->locus).
                                  " - $topic"))).
                            Tr(td(&ResultNumber(totalHit=>$self->{'_end'},
                                                showNum=>$maxDisplayNo,
                                                beg=>param('beg')))).
                            # Tr(td($navigationBar)).
                            Tr(td(
                                  table({-align=>'center',
                                         -border=>'0',
                                         -cellpadding=>'3',
                                         -cellspacing=>'3',
                                         -width=>'100%'},
                                        Tr(th({-align=>'left',
                                               -bgcolor=>'#a4abc2'},
                                              "Reference").
                                           th({-align=>'left',
                                               -bgcolor=>'#a4abc2'},
                                              "Other Genes Addressed")).
                                        $topicRefs
                                  )
                            )).
                            Tr(td($navigationBar))
                      )
                   )
                )
         );
    print "<a name='bot'>";
    &printEndPage;
}

########################################################################
sub displayGeneList {
########################################################################
    my ($self, @loci) = @_;
    &printStartPage($self->database, $self->title, $self->help);
    my $num = @loci;
    print center(b("There are ".font({-color=>'red'}, $num)." loci found for locus name like ".font({-color=>'red'}, $self->locus)." in database")),p;
    my $return;
    foreach my $locus (@loci) {
        $return .= li(a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=$locus"},
                     $locus));
    }
    print ul($return),p;

    &printEndPage;
}

########################################################################
sub displayLoci {
########################################################################
    my ($self, $giObject) = @_;
    &printStartPage($self->database, $self->title, $self->help);
    my $geneNum = $giObject->geneNum;
    print table({-align=>'center',
                 -valign=>'top',
                 -cellpadding=>'4'},
                 Tr(td({-bgcolor=>"#b7d8e4"},
                               a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus},
                                 $self->locus." Literature Topics")).
                    td({-bgcolor=>"#b7d8e4"},
                               a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=".$self->locus},
                               $self->locus." Locus Info"))));

    print table({-align=>'center',
                 -valign=>'top'},
                 Tr(td(h2(font({-color=>'red'}, $geneNum)." other genes are mentioned in papers curated for ".$self->locus))));

    my $arrayRef4locus = $giObject->locusList;
    my $arrayRef4feat = $giObject->featureList;
    push (@$arrayRef4locus, @$arrayRef4feat);
    my $tableList;
    my (@rows, @tables, @tableLabels, %geneLabel);
    my ($geneNo, $i, $colNum, $begGene, $preGene);
    my ($labelBeg, $labelEnd, $label);
    foreach my $rowRef (@$arrayRef4locus) {
            my ($gene) = @$rowRef;
            if (uc($gene) eq uc($self->locus)) { next; }
            $i++;
            $geneNo++;
            $geneLabel{$geneNo} = $gene;
            if ($i > 20) {
                $colNum++;
                unshift(@rows, td("${begGene}-${preGene}"));
                $tableList .= td(table({-align=>'center',
                                        -valign=>'top',
                                        -cellspacing=>'3',
                                        -cellpadding=>'3',
                                        -border=>'1'},
                                       Tr({-align=>'center'},\@rows)));

                undef @rows;
                $i = 1;
                $begGene = $gene;
            }
            if ($colNum == 5) {
                $labelBeg = $geneNo - 100;
                $labelEnd = $geneNo - 1;
                $label = "${labelBeg}-$labelEnd";
                push(@tableLabels, "${label}($geneLabel{$labelBeg}-$geneLabel{$labelEnd})");
                my $table= table({-align=>'center',
                                  -valign=>'top'},
                                 Tr(th({-colspan=>'5',
                                        -bgcolor=>"#a4abc2",
                                        -align=>'center'},
                                       font({-size=>'+1'}, $label))).
                                 Tr($tableList));
                push(@tables, $table);
                undef $tableList;
                undef $colNum;
            }
            if ($i == 1) {
                $begGene = $gene;
            }
            push(@rows, td(a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=$gene", -target=>'infowin'},$gene)));
            $preGene = $gene;
    }
    unshift(@rows, td("${begGene}-${preGene}"));
    $tableList .= td({-align=>'center',
                      -valign=>'top'},
                     table({-align=>'center',
                            -valign=>'top',
                            -cellspacing=>'3',
                            -cellpadding=>'3',
                            -border=>'1'},
                           Tr({-align=>'center'},\@rows)));

    my $labelBeg = $labelEnd + 1;
    my $label = "${labelBeg}-$geneNo";
    push(@tableLabels, "${label}($geneLabel{$labelBeg}-$geneLabel{$geneNo})");
    my $table= table({-align=>'center',
                      -valign=>'top'},
                     Tr(th({-colspan=>'5',
                            -bgcolor=>"#a4abc2",
                            -align=>'center'},
                           font({-size=>'+1'}, $label))).
                     Tr($tableList));
    push(@tables, $table);
    my $popup = table({-align=>'center'},
                      Tr(td(b(font({-size=>'+1'}, "Jump to: "))).
                         td(start_form).
                         td(popup_menu(-name=>'jumpItem',
                                       -"values"=>\@tableLabels,
                                       -onchange=>'jump(this)')).
                         td(end_form)));
    for(my $i = 0; $i <= @tables; $i++) {
        print "<a name='$tableLabels[$i]'>";
        if ($geneNum > 100) {
            print $popup;
        }
        print $tables[$i];
    }

    my $maxCuratedDate = $giObject->maxCuratedDate;
    my $maxPubmedSearchDate = $giObject->maxPubmedSearchDate;

    print br.br.table({-align=>'center'},
                      Tr(td(b("Date of last curation:")).
                         td($maxCuratedDate).
                         td(b("Date of last PubMed Search:")).
                         td($maxPubmedSearchDate)
                         ));

   &printEndPage;
}

########################################################################
sub locusInfo {
########################################################################
    my ($self) = @_;
    return Tr(td(table({-align=>'right',
                          -border=>'0',
                          -cellpadding=>'4'},
                         Tr(td({-bgcolor=>'#b7d8e4',
                                -align=>'right'},
                               a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=".$self->locus},
                                $self->locus." Locus Info")))
                         )));

}


########################################################################
sub topicsSection {
########################################################################
    my ($self, $giObject) = @_;
    return table({-width=>'100%',
                  -cellpadding=>'0',
                  -cellspacing=>'0'},
                 Tr(td({-bgcolor=>'#d8d8d8',
                        -align=>'left',
                        -valign=>'center'},
                       h4(a({-href=>$configUrl->dictyBaseCGIRoot."gene_page.pl?gene_name=".$self->locus}, $self->locus).
                          font({-color=>'black'}, " LITERATURE TOPICS".br."(formerly Gene Info)")
                       ))).
                 $self->geneticsCellBiol($giObject).
                 $self->nucleicAcidInfo($giObject).
                 $self->proteinInfo($giObject).
                 $self->relatedGenesProteins($giObject).
                 $self->researchAids($giObject).
                 $self->curatedLiterature($giObject).
                 $self->additionalInfo($giObject)
            );



}

########################################################################
sub geneticsCellBiol {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasCellularLocation,
                                         "Cellular Location");
    $returnTopics .= $self->topicEntry($giObject->hasCellCyclePhaseInvolved,
                                       "Cell Cycle Phase Involved");
    $returnTopics .= $self->topicEntry($giObject->hasFunctionProcess,
                                       "Function/Process");
    $returnTopics .= $self->topicEntry($giObject->hasGeneticInteractions,
                                       "Genetic Interactions");
    $returnTopics .= $self->topicEntry($giObject->hasMutantsPhenotypes,
                                       "Mutants/Phenotypes");
    $returnTopics .= $self->topicEntry($giObject->hasRegulationOf,
                                       "Regulation of");
    $returnTopics .= $self->topicEntry($giObject->hasRegulatoryRole,
                                       "Regulatory Role");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Genetics/Cell Biology"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub nucleicAcidInfo {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasDnaRnaSequenceFeatures,
                                         "DNA/RNA Sequence Features");
    $returnTopics .= $self->topicEntry($giObject->hasMapping,
                                       "Mapping");
    $returnTopics .= $self->topicEntry($giObject->hasRnaLevelsAndProcessing,
                                       "RNA Levels and Processing");
    $returnTopics .= $self->topicEntry($giObject->hasTranscription,
                                       "Transcription");
    $returnTopics .= $self->topicEntry($giObject->hasTranslationalRegulation,
                                       "Translational Regulation");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Nucleic Acid Information"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub proteinInfo {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics =
        $self->topicEntry($giObject->hasProteinNucleicAcidInteractions,
                          "Protein-Nucleic Acid Interactions");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasProteinPhysicalProperties,
                        "Protein Physical Properties");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasProteinProcessingRegulation,
                        "Protein Processing/Regulation");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasProteinProteinInteractions,
                        "Protein-protein Interactions");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasProteinNucleicAcidStructure,
                        "Protein/Nucleic Acid Structure");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasSubstratesLigandsCofactors,
                        "Substrates/Ligands/Cofactors");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasProteinSequenceFeatures,
                        "Protein Sequence Features");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Protein Information"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub relatedGenesProteins {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasDiseaseGeneRelated,
                                         "Disease Gene Related");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasNonFungalRelatedGenesProteins,
                        "Non-Fungal Related Genes/Proteins");
    $returnTopics .= $self->topicEntry(
                        $giObject->hasFungalRelatedGenesProteins,
                        "Fungal Related Genes/Proteins");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Related Genes/Proteins"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub researchAids {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasAlias,
                                          "Alias");
    $returnTopics .= $self->topicEntry($giObject->hasOtherFeatures,
                                           "Other Features");
    $returnTopics .= $self->topicEntry($giObject->hasStrainsConstructs,
                                           "Strains/Constructs");
    $returnTopics .= $self->topicEntry($giObject->hasTechniquesAndReagents,
                                           "Techniques and Reagents");
    $returnTopics .= $self->topicEntry($giObject->hasGenomeWideAnalysis,
                                           "Genome-wide Analysis");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Research Aids"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub curatedLiterature {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasSelectedReview,
                                          "Selected Review");
    $returnTopics .= $self->topicEntry($giObject->hasReviews,
                                           "Reviews");
    $returnTopics .= $self->topicEntry($giObject->hasCurated,
                           "List of all Curated References", "curated");
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Curated Literature"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub additionalInfo {
########################################################################
    my ($self, $giObject) = @_;
    my $returnTopics = $self->topicEntry($giObject->hasNotYetCurated,
                                         "References Not Yet Curated",
                                         "not yet curated");
    $returnTopics .= $self->topicEntry($giObject->hasArchivedLiterature,
                                       "Archived Literature");
    $returnTopics .= $self->topicEntry(1, "Literature Curation Summary");
    $returnTopics .= $self->geneSummaryParagraph($giObject);
    $returnTopics .= $self->pubmedSearch;
    if ($returnTopics) {
        $returnTopics = Tr(td({-bgcolor=>"#a4abc2"},
                           b("Additional Information"))).ul($returnTopics);
    }
    return $returnTopics;
}

########################################################################
sub topicEntry {
########################################################################
    my ($self, $foundTopic, $listTopic, $linkTopic) = @_;
    if (!$foundTopic) { return;}
    if (!$linkTopic) { $linkTopic = $listTopic; }
    my $locus = $self->locus;
    if (!param('topic') && $listTopic =~ /Literature Curation Summary/i) {
        return Tr(td(li(img({-border=>'0',
                             -src=>$configUrl->breadServerRoot.'images/right.gif'}).font({-color=>'red'},
                            "Literature Curation Summary"))));
    }
    elsif (param('topic') =~ /^$linkTopic/i) {
        $linkTopic =~ s/ /\+/g;
        return Tr(td(li(img({-border=>'0',
                             -src=>$configUrl->breadServerRoot.'images/right.gif'}).font({-color=>'red'},
                            "$listTopic"))));
    }
    else {
        $linkTopic =~ s/ /\+/g;
        if ($listTopic =~ /Literature Curation Summary/i) {
            return Tr(td(li(a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=$locus"}, $listTopic))));
        }
        else {
            return Tr(td(li(a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=$locus&topic=$linkTopic"}, "$listTopic"))));
        }
    }
}

########################################################################
sub summary {
########################################################################
    my ($self, $giObject) = @_;
    my $allRefs = $self->references4topic($giObject, "all");
    my $navigationBar = $self->displayNavigationBar;
    my $curatedRefNum = $giObject->curatedRefNum;
    my $notYetCuratedRefNum = $giObject->notYetCuratedRefNum;
    my $communityAnnotatedRefNum = $giObject->communityAnnotatedRefNum;

    my $communityAnnotationRefNumRow;

    if ($communityAnnotatedRefNum) {

        my $locusObj = Locus->new(dbh=>$dbh,
                                  locus_name=>$self->locus);

        my $dictyBaseid = $locusObj->dictyBaseid || $locusObj->dictyBaseidList;

        my $communityUrl = $configUrl->dictyBaseCGIRoot."$dblink/DisplayCommuAnno?dictyBaseid=$dictyBaseid";

        $communityAnnotationRefNumRow =
            Tr(td(a({-href=>$communityUrl,
                     -target=>'infowin'},
                    img({-src=>$configUrl->dictyBaseImages."star.gif",
                         -border=>0}))." ".
                  b("References selected for Community Annotation")));
    }

    if (!$curatedRefNum && !$notYetCuratedRefNum) {
        return b("No reference found for ".font({-color=>'red'}, $self->locus)." in database in this moment.");
    }
    return table({-width=>'100%',
                  -align=>'right',
                  -border=>'0'},
                 Tr(td(b("Curated References for ".
                         $self->locus.": ").
                       a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus.
                          "&topic=curated"},
                         $curatedRefNum))).
                 Tr(td(b("References Not Yet Curated: ").
                       a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus.
                          "&topic=not+yet+curated"}, $notYetCuratedRefNum))).
                 Tr(td($self->selectedReview($giObject))).
                 $communityAnnotationRefNumRow.
                 Tr(td(hr)).
## all refs here
                Tr(td(
                table({-width=>'100%',
                 -border=>'0'},
                Tr(td(&ResultNumber(totalHit=>$self->{'_end'},
                                    showNum=>$maxDisplayNo,
                                    beg=>param('beg')))).
                # Tr(td($navigationBar)).
                Tr(td(
                      table({-align=>'center',
                             -border=>'0',
                             -cellpadding=>'3',
                             -cellspacing=>'3',
                             -width=>'100%'},
                            Tr(th({-align=>'left',
                                   -bgcolor=>'#a4abc2'},
                                  "Reference").
                               th({-align=>'left',
                                   -bgcolor=>'#a4abc2'},
                                  "Genes Addressed")).
                            $allRefs
                       ))).
                Tr(td($navigationBar))
         ) ))
##########

           );
}

########################################################################
sub selectedReview {
########################################################################
    my ($self, $giObject) = @_;
    my $minCuratedDate = $giObject->minCuratedDate;
    my $maxCuratedDate = $giObject->maxCuratedDate;
    my $otherGeneNum = $giObject->geneNum;
    my $maxPubmedSearchDate = $giObject->maxPubmedSearchDate;
    if (!$giObject->hasSelectedReview) {
        return
               Tr(td(b("Number of Other Genes referred to in ".$self->locus." Literature: ").a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus."&type=other"}, $otherGeneNum))).
               #Tr(td("&nbsp;")).
               Tr(td(b("Date of last curation: ").$maxCuratedDate)).
               Tr(td(b("Date of last PubMed Search: ").$maxPubmedSearchDate));
    }
    my $arrayRef = $giObject->selectedReviewRef;
    my $rowRef = @$arrayRef[0];
    my ($refNo, $citation, $year) = @$rowRef;
    my ($citation, $refObject) = $self->citation($refNo);
#    my $note = " The literature for this gene has been reviewed in the reference(s) listed under Selected Review. Due to the extensive literature available for this gene, only references published since $minCuratedDate have been curated. Earlier references can be found under ".
#                a({-href=>url."?locus=".$self->locus."&topic=Archived+Literature", target=>'infowin'}, "Archive of older references").
#                    " and older reviews can be found under the ".
#                    a({-href=>url."?locus=".$self->locus."&topic=Reviews", target=>'infowin'}, "Reviews")." topic.";

    my $note = " Due to extensive literature available for this gene, not all references have been curated. dictyBase considers information published one year or more prior to the ".a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus."&topic=Reviews", target=>'infowin'}, "Selected Review")." to be covered by that review. Therefore, many references published before the review will not be curated to a specific Literature Topic. Instead, these papers will be listed in ".a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus."&topic=Archived+Literature", target=>'infowin'}, "Archived Literature.");

    my $return = #Tr(td(b(u("Selected Review:")))).
           #Tr(td(blockquote($citation))).
           Tr(td(blockquote(b("Note:").$note)));
    if ($otherGeneNum >= 1) {
        $return .= Tr(td(b("Number of Other Genes referred to in ".$self->locus." Literature: ").font({-color=>'red'}, a({-href=>"/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus."&type=other"},$otherGeneNum))));
    }
    $return .=  Tr(td(b("Date of last curation: ").$maxCuratedDate)).
           Tr(td(b("Date of last PubMed Search: ").$maxPubmedSearchDate));
    return $return;
}

########################################################################
sub references4topic {
########################################################################
    my ($self, $giObject, $all) = @_;

    my $arrayRef;
    if ($all) {
        $arrayRef = $giObject->topicInfo;
    }
    elsif (param('topic') =~ /\:/) {
        my @topic = split(/\:/, param('topic'));
        foreach my $topic (@topic) {
            $self->{'_title'} .= $topic.", ";
            if (!$arrayRef) {
                $arrayRef = $giObject->topicInfo($topic);
            }
            else {
                my $thisArrayRef =  $giObject->topicInfo($topic);
                push(@$arrayRef, @$thisArrayRef);
            }
        }
        $self->{'_title'} =~ s/, $//;
    }
    else {
        if (!$self->locus) {
            $self->{'_title'} .= param('topic');
        }
        $arrayRef = $giObject->topicInfo(param('topic'));
    }

    my $end = @$arrayRef;
    my (@refs, %tmp);
    if (param('sortedBy') =~ /citation/i) {
        foreach my $rowRef (@$arrayRef) {
            my ($refNo, $citation, $year, $pubmed, $journal) = @$rowRef;
            $tmp{$citation} = $refNo."\t".$year."\t".$pubmed."\t".$journal;
        }
        foreach my $citation (sort (keys %tmp) ) {
            my ($refNo, $year, $pubmed, $journal) =
                split(/\t/, $tmp{$citation});
            my @row = ($refNo, $citation, $year);
            my $rowRef = \@row;
            push(@refs, $rowRef);
        }
    }
    elsif (!$self->locus) {
        my @tmpRefs;
        foreach my $rowRef (@$arrayRef) {
            my ($refNo, $citation, $year, $pubmed, $journal) = @$rowRef;
            if ($tmp{$year}) { $tmp{$year} .= "::"; }
            $tmp{$year} .= $refNo."\t".$citation."\t".$pubmed."\t".$journal;
        }
        foreach my $year (sort{$a<=>$b} (keys %tmp) ) {
            my @entry = split(/::/, $tmp{$year});
            foreach my $entry (@entry) {
                my ($refNo, $citation, $pubmed, $journal) =
                    split(/\t/, $entry);
                my @row = ($refNo, $citation, $year, $pubmed, $journal);
                my $rowRef = \@row;
                push(@tmpRefs, $rowRef);
            }
        }
        @refs = reverse (@tmpRefs);
    }
    else {
        @refs = reverse (@$arrayRef);
    }

    my $returnList;
    my $bgcolor;
    my $beg = param('beg');
    if (!$beg) { $beg = 1; }
    my $matchYear;
    if (param('navigateList') =~ /^Year ([0-9]+)$/i) {
        $matchYear = $1;
    }
    if (!param('id')) {
        open(OUT, ">$downloadfile") ||
            die "Can't open '$downloadfile' for writing:$!\n";
        print OUT "Citation\tLoci\n\n";
    }
    my $searchFor = param('searchFor');
    my $filterBy = param('filterBy');
    my ($num, $skipRow, $stop, $matchNum);
    my @navigationList;
    my %year;

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

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

    my %foundRef;
    foreach my $rowRef (@refs) {
        my ($refNo, $ORIcitation, $year, $pubmed, $journal) = @$rowRef;
        if ($foundRef{$refNo}) {
            $end--;
            next;
        }
        $foundRef{$refNo}++;
        $year{$year}++;
        if ($matchYear && $matchYear < $year) {
            $skipRow++;
            next;
        }
        if ($filterBy) {
            if ($searchFor =~ /citation/i &&
                $ORIcitation !~ /$filterBy/i) {
                next;
            }
            elsif ($searchFor =~ /year/i &&
                   $year !~ /$filterBy/i) {
                next;
            }

        }
        my ($citation, $locusList, $featureList);
        if (!$self->locus && @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 {
            my $refObject;
            ($citation, $refObject) = $self->citation($refNo);
            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 $loci;
        if ($locusList && $featureList) {
            $loci = $locusList."\t".$featureList;
        }
        elsif ($locusList) { $loci = $locusList; }
        elsif ($featureList) { $loci = $featureList; }
        $loci =~ s/^\t//;
        $loci =~ s/\t$//;
        my @loci = split(/\t/, $loci);
        if (!param('id')) {
            print OUT "$ORIcitation\t@loci\n";
        }
        $num++;
        if ($num < $beg) { next; }
        if ($num >= $beg + $maxDisplayNo && !param('id')) {
            if (!$stop) { $stop = $num - 1; }
            next;
        }
        elsif ($num >= $beg + $maxDisplayNo && param('id')) {
            if (!$stop) {$stop = $num - 1;}
            next;
        }
        my $listLoci;
        my $i;
        foreach my $locus (@loci) {
            if ($self->locus && $self->locus =~ /^$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; }
        if (!$bgcolor) {
            $returnList .= Tr(td({-width=>"70%",
                                  -valign=>"top"},
                                 $citation).
                              td({-width=>"30%",
                                  -valign=>"top"},
                                 $listLoci));
            $bgcolor = "#d8d8d8";
        }
        else {
            $returnList .= Tr({-bgcolor=>"$bgcolor"},
                              td({-width=>"70%",
                                  -valign=>"top"},
                                 $citation).
                              td({-width=>"30%",
                                  -valign=>"top"},
                                 $listLoci));
            $bgcolor = "";
        }
        $matchNum++;
    }
    $self->{'_end'} = $end;
    if (!param('id')) { close(OUT); }
    foreach my $year (sort {$a<=>$b;} keys %year ) {
        push(@navigationList, "Year $year");
    }
    $self->{'_skipRow'} = $skipRow;
    $self->{'_stop'} = $stop;
    $self->{'_matchNum'} = $matchNum;
    $self->{'_navigationList'} = \@navigationList;
    return $returnList ;
}

########################################################################
sub citation {
########################################################################
    my ($self, $refNo) = @_;
    my $refObject = Reference->new(dbh=>$dbh,
                                   reference_no=>$refNo);
    my $citation;
    if (param('topic') =~ /not yet curated/i) {
        $citation = $refObject->formatedCitation4notYetTopic;
    }
    else {
        $citation = $refObject->formatedCitation;
    }
    return ($citation, $refObject);
}

########################################################################
sub citation2 {
########################################################################
    my ($self, $refNo, $citation, $pubmed, $journal, $urls,
        $relatedRefInfo, $webSuppUrl) = @_;
    $citation =~ s/^([^0-9]+\([0-9]{4}\))(.+)$/<b>$1<\/b>$2/;
    $citation =~ s/^([^0-9]+\([0-9]{4}\))$/<b>$1<\/b> personal communication/;
    $citation .= br;
    my $image = "dictyBaserefsml.gif";
    $citation .= a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/reference/reference.pl?refNo=$refNo",
                           -target=>'infowin'},
                          img({-src=>$configUrl->dictyBaseImages."$image",
                               -border=>'0',
                               -alt=>"dictyBase Papers Entry"}));
    if ($pubmed) {
        $citation .= "&nbsp;&nbsp;".a({-href=>$configUrl->ncbiUrlRoot."query.fcgi?cmd=Retrieve&db=PubMed&list_uids=${pubmed}&dopt=Abstract",
                      -target=>'infowin'},
                          img({-src=>$configUrl->dictyBaseImages."pubmedrefsml.gif",
                               -border=>'0',
                               -alt=>"Pubmed Entry"}))."&nbsp;&nbsp;";
    }
    if ($urls) {
        #KD: no longer using the specific gifs for specfic journals; just
        #    using one generic gif
        #my $journalGif = $journal;
        #$journalGif =~ s/ /\./g;
        #$journalGif .= ".gif";
        #if (! -e $configPath->gifDir."$journalGif") {
        #    $journalGif = "Generic.gif";
        #}
        my $journalGif = "full_text.gif";

        $citation .= a({-href=>"$urls",
                        -target=>'infowin'},
                       img({-src=>$configUrl->dictyBaseImages."$journalGif",
                            -border=>'0',
                            -alt=>"online article1"}))."&nbsp;&nbsp;";
    }
    if ($webSuppUrl) {
        $citation .= a({-href=>"$webSuppUrl",
                        -target=>'infowin'},
                       img({-src=>$configUrl->dictyBaseImages."webSupplement.gif",
                            -border=>'0',
                            -alt=>"Web Supplement"}));

    }
    if ($relatedRefInfo) {
        $citation .= a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/reference/reference.pl?refNo=".$refNo."&type=other",
                        -target=>'infowin'},
                       img({-src=>$configUrl->dictyBaseImages."C&E.gif",
                            -border=>'0',
                            -alt=>"dictyBase Curated Comments & Errata"}));

    }
    return $citation;
}

########################################################################
sub geneSummaryParagraph {
########################################################################
    my ($self, $giObject) = @_;
    my $found;
    my $locus = $self->locus;
    my $paragraphNo = $giObject->paragraphNo();

    if (defined $giObject->paragraphNo) {
        $found = 1;
    }
    else {
        undef $found;
    }

    if (!$found) { return; }
    return
           Tr(td(a({-href=>$configUrl->dictyBaseCGIRoot."$dblink/locus.pl?locusNo=".$giObject->locusNo."#summaryParagraph",
                        -target=>'infowin'},
                   $self->locus." Gene Summary Paragraph")));
}

########################################################################
sub pubmedSearch {
########################################################################
    my ($self) = @_;
    return Tr(td(a({-href=>$configUrl->ncbiUrlRoot."query.fcgi?cmd=search&db=PubMed&term=%28".$self->locus."%5bTEXT%3anoexp%5d%20AND%20Dictyostelium%20discoideum%5bALL%5d%29",
                    -target=>'infowin'},
                   "PubMed Search"))).
           Tr(td(a({-href=>$configUrl->ncbiUrlRoot."query.fcgi?cmd=search&db=PubMed&term=%28".$self->locus."%5bALL%5d%20AND%20Dictyostelium%20discoideum%5bALL%5d%29",
                    -target=>'infowin'},
                   "Expanded PubMed Search")));
}

########################################################################
sub displayNavigationBarNew {
########################################################################
    my ($self)= @_;
    my $end = $self->{'_end'};
    if ($end <= $maxDisplayNo) { return;}
    my $beg = param('beg');
    my $matchNum = $self->{'_matchNum'};
    my $stop = $self->{'_stop'};
    my $skipRow = $self->{'_skipRow'};
    if (!$stop) { $stop = $end;}
    if ($beg < $skipRow + 1) {
            $beg = $skipRow + 1;
    }
    if ($stop < $skipRow + 30) {
            $stop += $skipRow + 1;
    }
    my $navigationBar;

#    if (!$beg) { $beg = 1; }
#    my ($prevBeg, $nextBeg);
#    if ($end > $stop+1) {
#        $nextBeg = $stop-1;
#    }
#    if ($beg > 1) {
#        $prevBeg = $beg - 28;
#        if ($prevBeg < 1) { $prevBeg = 1;}
#    }
    my $id = param('id');
    if (!$id) { $id = $$; }
#    my $filterBy = param('filterBy');
#    my $sortedBy = param('sortedBy');
#    my $searchFor = param('searchFor');
#    my $navigationListRef = $self->{'_navigationList'};
#    my @listItem = @$navigationListRef;
#    my @sortColumn = ("Citation", "Year");
    my $topic = param('topic');
    $topic =~ s/ /\+/g;
    my $url = "/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus."&topic=$topic&id=$id";
#    my $nextPrevUrl = $url;
#    if ($filterBy) {
#        $filterBy =~ s/ /\+/g;
#        $searchFor =~ s/ /\+/g;
#        $nextPrevUrl .= "&searchFor=$searchFor&filterBy=$filterBy";
#    }
#    elsif ($sortedBy) {
#        $sortedBy =~ s/ /\+/g;
#        $nextPrevUrl .= "&sortedBy=$sortedBy";
#    }
#    $navigationBar =  &navigationBar(database=>$self->database,
#                                     url=>$url,
#                                     nextPrevUrl=>$nextPrevUrl,
#                                     beg=>$beg,
#                                     nextBeg=>$nextBeg,
#                                     prevBeg=>$prevBeg,
#                                     downloadfile=>"geneinfo.$id.xls",
#                                     navigateListRef=>\@listItem,
#                                     sortListRef=>\@sortColumn,
#                                     pos=>'top'), br;
#

    $navigationBar = &ResultPageList(url=>$url,
                                     totalHit=>$self->{'_end'},
                                     beg=>$beg,
                                     showNum=>$maxDisplayNo);

    return $navigationBar;
}


########################################################################
sub displayNavigationBar {
########################################################################
    my ($self)= @_;
    my $end = $self->{'_end'};
    if ($end <= $maxDisplayNo) { return;}
    my $beg = param('beg');
    my $matchNum = $self->{'_matchNum'};
    my $stop = $self->{'_stop'};
    my $skipRow = $self->{'_skipRow'};
    if (!$stop) { $stop = $end;}
    if ($beg < $skipRow + 1) {
            $beg = $skipRow + 1;
    }
    if ($stop < $skipRow + 30) {
            $stop += $skipRow + 1;
    }
    my $navigationBar;

    if (!$beg) { $beg = 1; }
    my ($prevBeg, $nextBeg);
    if ($end > $stop+1) {
        $nextBeg = $stop+1;
    }
    if ($beg > 1) {
        $prevBeg = $beg - $maxDisplayNo;
        if ($prevBeg < 1) { $prevBeg = 1;}
    }
    my $id = param('id');
    if (!$id) { $id = $$; }
    my $filterBy = param('filterBy');
    my $sortedBy = param('sortedBy');
    my $searchFor = param('searchFor');
    my $navigationListRef = $self->{'_navigationList'};
    my @listItem = @$navigationListRef;
    my @sortColumn = ("Citation", "Year");
    my $topic = param('topic');
    $topic =~ s/ /\+/g;
    my $url = "/db/cgi-bin/dictyBase/reference/geneinfo.pl?locus=".$self->locus."&topic=$topic&id=$id";
    if (param('date')) {
        $url .= "&date=1";
    }
    my $nextPrevUrl = $url;
    if ($filterBy) {
        $filterBy =~ s/ /\+/g;
        $searchFor =~ s/ /\+/g;
        $nextPrevUrl .= "&searchFor=$searchFor&filterBy=$filterBy";
    }
    elsif ($sortedBy) {
        $sortedBy =~ s/ /\+/g;
        $nextPrevUrl .= "&sortedBy=$sortedBy";
    }
    $navigationBar =  &ResultPageList(url=>$url,
                                     totalHit=>$self->{'_end'},
                                     beg=>$beg,
                                     showNum=>$maxDisplayNo).
                      &navigationBar(database=>$self->database,
                                     url=>$url,
                                     nextPrevUrl=>$nextPrevUrl,
                                     beg=>$beg,
                                     nextBeg=>$nextBeg,
                                     prevBeg=>$prevBeg,
                                     downloadfile=>"geneinfo.$id.xls",
                                     navigateListRef=>\@listItem,
                                     sortListRef=>\@sortColumn,
                                     pos=>'top'), br;

    return $navigationBar;
}

########################################################################
sub setDownloadfile {
########################################################################
    my ($self) = @_;
    if (!param('id')) {
        $downloadfile = $configPath->tmpDir."geneinfo.$$.xls";
        $downloadUrl = $configUrl->dictyBaseHtmlTmp."geneinfo.$$.xls";
    }
    else {
        $downloadfile = $configPath->tmpDir."geneinfo.".param('id').".xls";
        $downloadUrl = $configUrl->dictyBaseHtmlTmp."geneinfo.".param('id').".xls";
    }
}

########################################################################
sub getGeneList {
########################################################################
    my ($self) = @_;

    my $locus = $self->{'_locus'};
    $locus =~ s/\*/\%/g;

    my $locusArrayRef = Locus->GetLocusArrayRefBYname(dbh=>$dbh,
                                                      locus_name=>$locus);
    my @loci;
    foreach my $rowRef (@$locusArrayRef) {
        my ($locusNm) = @$rowRef;
        push(@loci, $locusNm);
    }
    my $featArrayRef = Feature->GetFeatureArrayRefBYname(dbh=>$dbh,
                                              feature_name=>$locus);
    foreach my $rowRef (@$featArrayRef) {
        my ($featNm) = @$rowRef;
        push(@loci, $featNm);
    }
    return @loci;
}

########################################################################
sub err_report {
########################################################################
    my ($self, $err) = @_;

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

    print b($err);

    &printEndPage;

#    $dbh->disconnect;
    exit;
}
########################################################################
sub displayAllRefsThisDate {
########################################################################
## display references published within a time frame.  KD
    my ($self) = @_;
    $self->{'_title'} = "References Added to dictyBase This Week";

    my $giObject = GeneInfo->new(dbh=>$dbh);

    my $dateRefs = $self->references4date($giObject);

    my $navigationBar = $self->displayNavigationBar;

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

    print table({-width=>'100%',
                 -border=>'0'},
                Tr(td($navigationBar)).
                Tr(td(
                      table({-align=>'center',
                             -border=>'0',
                             -cellpadding=>'3',
                             -cellspacing=>'3',
                             -width=>'100%'},
                            Tr(th({-align=>'left',
                                   -bgcolor=>'#a4abc2'},
                                  "Reference").
                               th({-align=>'left',
                                   -bgcolor=>'#a4abc2'},
                                  "Genes Addressed")).
                            $dateRefs
                       ))).
                Tr(td($navigationBar))
         ) ;
}
########################################################################
sub references4date {
########################################################################
    ## KD added to find references added in a range of dates
    my ($self, $giObject) = @_;
    my $arrayRef;
    $arrayRef = $giObject->dateInfo;
    my $end = @$arrayRef;


    ## code for navigation bar
    my (@refs, %tmp);
    if (param('sortedBy') =~ /citation/i) {
        foreach my $rowRef (@$arrayRef) {
            my ($refNo, $citation, $year, $pubmed, $journal) = @$rowRef;
            $tmp{$citation} = $refNo."\t".$year."\t".$pubmed."\t".$journal;
        }
        foreach my $citation (sort (keys %tmp) ) {
            my ($refNo, $year, $pubmed, $journal) =
                split(/\t/, $tmp{$citation});
            my @row = ($refNo, $citation, $year);
            my $rowRef = \@row;
            push(@refs, $rowRef);
        }
    }
    elsif (!$self->locus) {
        my @tmpRefs;
        foreach my $rowRef (@$arrayRef) {
            my ($refNo, $citation, $year, $pubmed, $journal) = @$rowRef;
            if ($tmp{$year}) { $tmp{$year} .= "::"; }
            $tmp{$year} .= $refNo."\t".$citation."\t".$pubmed."\t".$journal;
        }
        foreach my $year (sort{$a<=>$b} (keys %tmp) ) {
            my @entry = split(/::/, $tmp{$year});
            foreach my $entry (@entry) {
                my ($refNo, $citation, $pubmed, $journal) =
                    split(/\t/, $entry);
                my @row = ($refNo, $citation, $year, $pubmed, $journal);
                my $rowRef = \@row;
                push(@tmpRefs, $rowRef);
            }
        }
        @refs = reverse (@tmpRefs);
    }
    else {
        @refs = reverse (@$arrayRef);
    }

    my $returnList;
    my $bgcolor;
    my $beg = param('beg');
    if (!$beg) { $beg = 1; }
    my $matchYear;
    if (param('navigateList') =~ /^Year ([0-9]+)$/i) {
        $matchYear = $1;
    }
    if (!param('id')) {
        open(OUT, ">$downloadfile") ||
            die "Can't open '$downloadfile' for writing:$!\n";
        print OUT "Citation\tLoci\n\n";
    }
    my $searchFor = param('searchFor');
    my $filterBy = param('filterBy');
    my ($num, $skipRow, $stop, $matchNum);
    my @navigationList;
    my %year;

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

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

    my %foundRef;
    foreach my $rowRef (@refs) {
        my ($refNo, $ORIcitation, $year, $pubmed, $journal) = @$rowRef;
        if ($foundRef{$refNo}) {
            $end--;
            next;
        }
        $foundRef{$refNo}++;
        $year{$year}++;
        if ($matchYear && $matchYear < $year) {
            $skipRow++;
            next;
        }
        if ($filterBy) {
            if ($searchFor =~ /citation/i &&
                $ORIcitation !~ /$filterBy/i) {
                next;
            }
            elsif ($searchFor =~ /year/i &&
                   $year !~ /$filterBy/i) {
                next;
            }

        }
        my ($citation, $locusList, $featureList);
        if (!$self->locus && @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 {
            my $refObject;
            ($citation, $refObject) = $self->citation($refNo);
            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 $loci;
        if ($locusList && $featureList) {
            $loci = $locusList."\t".$featureList;
        }
        elsif ($locusList) { $loci = $locusList; }
        elsif ($featureList) { $loci = $featureList; }
        $loci =~ s/^\t//;
        $loci =~ s/\t$//;
        my @loci = split(/\t/, $loci);
        if (!param('id')) {
            print OUT "$ORIcitation\t@loci\n";
        }
        $num++;
        if ($num < $beg) { next; }
        if ($num >= $beg + $maxDisplayNo && !param('id')) {
            if (!$stop) { $stop = $num - 1; }
            next;
        }
        elsif ($num >= $beg + $maxDisplayNo && param('id')) {
            if (!$stop) {$stop = $num - 1;}
            next;
        }
        my $listLoci;
        my $i;
        foreach my $locus (@loci) {
            if ($self->locus && $self->locus =~ /^$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; }
        if (!$bgcolor) {
            $returnList .= Tr(td({-width=>"70%",
                                  -valign=>"top"},
                                 $citation).
                              td({-width=>"30%",
                                  -valign=>"top"},
                                 $listLoci));
            $bgcolor = "#d8d8d8";
        }
        else {
            $returnList .= Tr({-bgcolor=>"$bgcolor"},
                              td({-width=>"70%",
                                  -valign=>"top"},
                                 $citation).
                              td({-width=>"30%",
                                  -valign=>"top"},
                                 $listLoci));
            $bgcolor = "";
        }
        $matchNum++;
    }
    $self->{'_end'} = $end;
    if (!param('id')) { close(OUT); }
    foreach my $year (sort {$a<=>$b;} keys %year ) {
        push(@navigationList, "Year $year");
    }
    $self->{'_skipRow'} = $skipRow;
    $self->{'_stop'} = $stop;
    $self->{'_matchNum'} = $matchNum;
    $self->{'_navigationList'} = \@navigationList;
    return $returnList ;
}

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



