#!/usr/bin/perl

BEGIN {
    push @INC, ('/usr/local/share/perl/5.10.1','/home/adnetec/perl5/lib/perl5');

    use DateTime;
    use CGI qw/:standard :html3/;
    $q = new CGI;
    $id = $q->param('id');
    $nameString = $q->param('h');
    $bredir = $q->param('redir');
    $host = $q->remote_host();

## Check load of machine before running the script
##
    my $thisLoad = get_load_average();
    my $dt = DateTime->now;
    if ( $thisLoad >= 50 ) {
	$code = 400;
	print "content-type: text/html \n\n";
	print '<p class="Cell4Font">The machine is having a high load ['.$thisLoad.']. Please try again later.</p>';

	open(LOG,">>au.log");
	print LOG join '',$dt->mdy,' ',$dt->hms,' h: ',$host,' id:',$id,' l: ',$thisLoad," [high load refused]\n";
	close(LOG);
	exit(0);
    }

    sub get_load_average {
	open(LOAD, "/proc/loadavg") or die "Unable to get server load \n";
	my $load_avg = <LOAD>;
	close LOAD;
	my ( $one_min_avg ) = split /\s/, $load_avg;
	return $one_min_avg;
    }


}


use CGI qw/:standard :html3/;

use DBI;
use ReDIF::init;
use Math::Round;

use ReDIF::Parser qw( &redif_open_file
                      &redif_open_dir
                      &redif_get_next_template
                      &redif_open_dir_recursive
                      );

ReDIF::Parser::set_parser_options( x_attributes => 1, utf8_output => 1 );

messages();

my $user = "adnetec";

$js_general = '/home/adnetec/cgi-bin/general.js';
open(FORM,"<$js_general") or die "$! $js_general";
while (<FORM>) {
    $TmpJSGeneral .= $_;
}

$template = '/home/adnetec/cgi-bin/newtemplate.cit';
$template = '/home/adnetec/cgi-bin/bootTemplate.cit';
open(FORM,"<$template") or die "$! $template";
while (<FORM>) {
    $TmpTemplate .= $_;
}
$TmpTemplate =~ s/\{JAVASCRIPT\}/$TmpJSGeneral/;

my $q = new CGI;
my $id = $q->param('id');
my $nameString = $q->param('h');
my $bredir = $q->param('redir');
my $host = $q->remote_host();

#binmode(STDOUT, ':utf8' );
my $today = &parse_date;


$bredir = 'yes' unless $bredir eq 'no';
$bredir = 'yes';


#$id="psh93";
#$id="pzy2";
#$id="pdo31";
#$id="pfe17";
#$id="pgr70";
#$id="pgo256";
#$id="pvi116";
#$id="pzi32";
#$id="per17";
#$id="pda10";
#$id="psa510";
#$id="pga43";

my $minyear = 2000;
my $maxyear = 2019;

$TmpTemplate =~ s/10pt/8pt/g;

if ($nameString =~ /^p\w+\d+$/) {
    my $URL = "http://citec.repec.org/$nameString";

    print "Status: 302 Moved\nLocation: $URL\n\n";

##    open(LOG,">>au.log");
##    print LOG "$today h: $host id: $id ns: $nameString [redirect 1]\n";
##    close(LOG);

    exit(0);

}

if ( $id =~ /^p\w+\d+$/ and $bredir eq "yes") {
    $id =~ m/^p(\w)/;
    my $thisFile = "/home/adnetec/public_html/p/$1/$id.html";
    if (-e $thisFile) {
	my $URL = "https://citec.repec.org/p/$1/$id.html";
	print "Status: 302 Moved\nLocation: $URL\n\n";
##	open(LOG,">>au.log");
##	print LOG "$today h: $host id: $id ns: $nameString [redirect 2]\n";
##	close(LOG);

	exit(0);
    }
}

$error = 2;


open(LOG,">>au.log");
print LOG "$today h: $host id: $id ns: $nameString\n";
close(LOG);

print "content-type: text/html \n\n";

$error = 2 if $host =~ /60\.248/;
$error = 1 if $host =~ /^37\.49\.230\.105/;
$error = 2 if $host =~ /180\.76\./;
$error = 2 if $host =~ /^118\./;
$error = 2 if $host =~ /76\.174\.184/;
$error = 2 if $host =~ /162\.252\.87/;
$error = 2 if $host =~ /104\.245\.101\.73/;
$error = 2 if $host =~ /201\.234\.181\.230/;
$error = 2 if $host =~ /^2607:5300:60:6fc6::/;

$error = 2 if $host =~ /193\.70\.8\.217/;
$error = 2 if $host =~ /163\.172\./;
$error = 2 if $host =~ /^64\.62\.252\./;

$error = 0 if $host =~ /2001:720:1014:50::a:d/;
$error = 0 if $host =~ /141.237.205.197/;
$error = 0 if $host =~ /185.11.153.229/;


#$error=2;
if ($error == 2) {
    $code = 400;

	$string = join '','
<p class="Cell4Font">This form allows you to add a new citation to our database.</p>
<p class="Cell4Font">Error: Too much requests ',$code,' ',$host,'</p>
<p class="Cell4Font">There have been too much request submited from your machine. This usualy means that a robot is working with this form, and robots are not permited to issue request. If this is not the case for you, please contact barrueco at uv.es to reset the request counter for your machine. He apologizes for the inconveniences caused.</p>
<p class="principal">Please contact barrueco at uv.es for more details</p>';

    open(LOG,">>au.log");
    print LOG "$host($IPs{$host}) $date error $referer\n";
close(LOG);

    writeOut($string);

    exit(0);
}

#exit(0);





require "/home/adnetec/RePEc/zzz/conf/citec.conf";
require '/home/adnetec/RePEc/remo/cpd/conf/relatedworks.dat';

$dbh = DBI->connect("DBI:mysql:citec;host=localhost;port=3307;mysql_read_default_file=/home/adnetec/.my.cnf", $user, $password)
    or print $q->p({-class=>'header'},"Error $DBI::err - $DBI::errstr ...\n");
$dbh->do("use citec2");

if  ($nameString) {
    doSearchAuthor($nameString);
}


write_error($messages{1},1) if ! $id;
write_error($messages{2},1) unless $id =~ /^p\w+\d+$/;

$sn = $dbh->prepare("select autorid,id from AUTOR where id = ?");
$smyworks = $dbh->prepare("select distinct t1.docid from PUBLICA as t1, AUTOR as t2 where t1.autorid = t2.autorid and id = ?");
$sth = $dbh->prepare("select distinct t1.year,t1.titulo,t2.nombre from DOCUMENTO as t1, FUENTE as t2, ESPUBLICADO as t3 where t1.docid = t3.docid and t2.scodigo = t3.scodigo and t1.docid = ? limit 1");
$sci = $dbh->prepare("select cita from CITA where escitado = ?");
$sye = $dbh->prepare("select year from DOCUMENTO where docid = ?");
$sturl = $dbh->prepare("select url from DIRECCIONES where docid = ?");
$ath = $dbh->prepare("select distinct t1.id,t1.Fname,t1.Sname from AUTOR as t1, PUBLICA as t2 where t1.autorid = t2.autorid and t2.docid = ?");
$sty = $dbh->prepare("select sameAs from RELATIONS where docid = ? and sameAstype = ?");

## Checks that the handle exists
$mdata = $sn->execute($id);
$id =~ /^p(\w)/;
#$sourceFile = '/opt/snefru/home/adrepec/ftp/opt/ReDIF/RePEc/per/pers/'.$1.'/'.$id.'.rdf';
$sourceFile = '/mnt/tebuk/home/adrepec/ftp/opt/ReDIF/RePEc/per/pers/'.$1.'/'.$id.'.rdf';

write_error($messages{3},1) if ($mdata != 1 or ! -e $sourceFile);

$mworks = $smyworks->execute($id);

#print "mworks $mworks<p>";

while ( @myworks = $smyworks->fetchrow_array ) { push @myWorks, $myworks[0]; }

redif_open_file ( $sourceFile );
while ($T = eval {redif_get_next_template} ) {
    $author= $T->{'name-full'}[0];

### Reads the data about production
    foreach $type ( qw(article paper book chapter) ) {
	$typekey = "author-$type";
	foreach $ah (@{ $T->{$typekey} }) {
##	    print "$author $type $ah<p>";
	    $DATA{$ah}{type} = $typekey;
	    $DATA{$ah}{type} =~ s/author/redif/;
	    $DATA{$ah}{done} = 1;

##	    push @{ $THIS{$type} }, getmydata($ah,$type,1);
	}
    }

### Process production taking care of diff versions
#    print "TEsting ...<p>";
    foreach $ah (sort keys %DATA) {
	my @toProcess;
	next unless $DATA{$ah}{done} == 1;

	$n++;
#	print "<p>$n $ah is $DATA{$ah}{type} and $DATA{$ah}{done}<br>\n";
	push @toProcess,$ah;
	$nty = $sty->execute($ah,$DATA{$ah}{type});
	if ($nty >= 1) {
	    while ( @related = $sty->fetchrow_array ) {
		$DATA{$related[0]}{done} = 2;
###		print " UNO: $ah is the same than $related[0]<br> \n";
		push @toProcess,$related[0];
	    }
	} else {
###	    print " DOS: $ah $DATA{$ah}{type}<br>\n";
	}
	my $type = $DATA{$ah}{type};
	$type =~ s/redif/author/;
	push @{ $THIS{$type} }, getmydata(@toProcess,$type,1);
##	print join '',"<p>*******<br>",getmydata(@toProcess,$type,1),"<br>*****<p>";
    }

#    exit(0);


    my $nhindex = &h_index();
    ($ncoauthors,$scoauthors) = &co_authors();

    write_error($messages{5},1) if $nTotalCitations == 0;

    $outString .= '<p class="authorHeader">'.$author.'<hr style="height:3px;background-color:#3E576F;color:#3E576F"/></p>';

    $outString .= '<table width="100%" border="0" style="margin-bottom:25px"><tr><td width="400px" class="headerNumbers"  valign="top"><p class="tSection">Affiliation: </p>';
    $outString .= '<p>';

    my $nele=0;
    for $ele (@{ $T->{workplace} }) {
	last if $nele >=4;
	$nele++;
	if ($ele->{institution}[0] =~ /repec:edi:(.*)/i ) {
##    if ( $T->{workplace}[0]{institution}[0] =~ /repec:edi:(.*)/i  ) {
	    $insFile = '/mnt/tebuk/home/adrepec/ftp/opt/ReDIF/RePEc/edi/inst/'.$1.'.rdf';
##	$outString .=  "<p>KKK: $insFile</p>\n";
	    redif_open_file ( $insFile );
	    while ($I = eval {redif_get_next_template} ) {
		$outString .= '<span class="enumerate"> '.$I->{primary}[0]{name}[0].' ';
		$outString .= "(".$ele->{share}[0]."% share)" if $ele->{share}[0];
		$outString .= "</span><br/>\n";
#####		$outString .=  "<p> and: ".$I->{secondary}[0]{name}[0].' <br/> '.$I->{secondary}[0]{location}[0]."</p>\n" if $I->{secondary}[0]{name}[0];
	    }
	}
    }
    $outString .= "</p>\n";

    $outString .= '<p class="tSection">Co-Authors ('.$ncoauthors.'): </p>'.$scoauthors;
    $outString .= "<p class=\"MainCell\">Authors registered in RePEc who have co-authored more than one work in the last five years with $author. </p>";
    $outString .= '<p>[<a href="http://econpapers.repec.org/RAS/'.$id.'.htm">More details</a> in EconPapers]</p>';
    $outString .= '<div class="dialnet-autor" data-code="'.$id.'" data-source="RPE"></div>';

    $outString .= '</td><td width="50%" class="headerNumbers" valign="top">';
    $outString .= '<p class="tSection">Citation Profile:</p>';
    $outString .= '<p>';
    foreach $stype ( qw(article paper book chapter) ) {
	$CITYPE{$stype} = 0 if ! $CITYPE{$stype};
	$outString .= '<a href="#'.$stype.'">'.ucfirst($stype)."s</a>: ".$nTotal{$stype}." ($CITYPE{$stype} citations)<br/>\n" if $nTotal{$stype} > 0;
    }
    $outString .= '</p>';

    foreach $rr (sort keys %CIT) {
	next if $rr == 0000;
	next if $rr < $minyear;
	next if $rr > $maxyear;
	$ncityears++;
    }

    $average = nearest(.01,($nTotalCitas / $ncityears));
    $p_s_c = nearest(.01,(($nTotalSelftCitas * 100) / $nTotalCitas));

    $outString .= "<p>Total times cited: $nTotalCitas<br/>Total self citations: $nTotalSelftCitas ($p_s_c \%)<br/>Average times cited by year:  $average ($ncityears years)<br/>";
    $outString .= "h-index: $nhindex<br/></p><p></p>";
    $outString .= join '','Permalink for this report: <br/><a href="http://citec.repec.org/',$id,'">http://citec.repec.org/',$id,'</a><br/>';
    $outString.= '</td></tr></table>';
}
#   print  "(1) $outString <p>";

    $outString .= join '','<p><b>Citation report created: ',$today,' &nbsp;&nbsp;&nbsp;<a href="/cgi-bin/au.pl?id=',$id,'&redir=no">Refresh data now</a></b></p><p><b>Note:</b> Citations are only consolidated across paper versions,  not across document types. <br/>This may result in a higger h-index than in IDEAS rankings<br/>';
    $outString .= "<p>Missing citations? Add them with our <a href=\"/cgi-bin/ui.pl\">user input service</a><br/>";
    $outString .= "Incorrect content? <a href=\"mailto:barrueco\@uv.es\">Let us know</a></p>";

## EMPEZAMOS LA PRODUCCION:
## Lee variables para grafico citas
for ( $n = $maxyear - 15 ; $n <= $maxyear ; $n++) {
    $stringYears .= "$n,";
    $CIT{$n} = 0 if ! $CIT{$n};
    $stringCitations .= "$CIT{$n},";
}
$stringYears =~ s/\,$//;
$stringCitations =~ s/\,$//;


#$outString .=  "<p>min: $minyear, max: $maxyear</p>";

$outString .= '<div id="container" style="width: 603px; margin-left: 0px; float: left; height: 400px"></div><p/>';
$outString .= '<div id="chart1" style="width: 600px; margin-bottom: 40px; margin-left: 0px; float: left; height: 400px"></div><p/>';

## EMPIEZA TABLA PRODUCCION MOSTRAR
###$outString .= '<div style="position:relative; margin-left: 17px; float: left">
###<p><b>Scientific production by document type in the las 15 years:</b></p>';
###$outString .=  '<table border="1" withd="80%"  class="DataTableBorder">';
###$outString .=  "<thead> <tr><th> </th>";
###for ( $n = $maxyear - 15 ; $n <= $maxyear ; $n++) {
###    $outString .=  '<th  class="descripCell">'.$n."</th>\n";
###}
###$outString .=  "</tr></thead>";
###foreach $type ( sort keys %YEARS ) {
###   $outString .=  '<tbody><tr><th  class="descripCell">'.$type.'</th>';
###    for ( $n = $maxyear - 15; $n <= $maxyear ; $n++) {
###	$YEARS{$type}{$n} = 0 if ! $YEARS{$type}{$n};
###	$outString .=  '<td class="dataCell2">'.$YEARS{$type}{$n}."</td>";
###    }
###    $outString .=  "</tr></tbody>";
###}
###$outString .=  "</table></div>";
## ACABA TABLA PRODUCCION MOSTRAR

$outString .= '<div style="position:relative; margin-left: 17px; float: left;width:100%">';
foreach $type ( qw(article paper book chapter) ) {
    $outString .= '<p class="productionHeader"><b><a name="'.$type.'">'.ucfirst($type)."s:</a></b></p>\n";
    $outString .= '<table width="90%" border="0" class="sortable" id="sortable_example">';
    $outString .=  "<thead> <tr><th  class='dataCellHeader'>Year</th><th  class='dataCellHeader'>Title</th><th  class='dataCellHeader'>Cited</th></tr></thead>";

   $typekey = "author-$type";
    foreach $ah (sort @{ $THIS{$typekey} }) {
	$outString .= "$ah\n";
    }
    $outString .= "</table>";
}
$outString .= "</div>";

## EMPIEZA TABLA PRODUCCION OCULTA
$outString .=  '<table style="visibility:hidden" id="datatable" border="1" withd="80%">';
$outString .=  "<thead> <tr><th> </th>";
foreach $type ( keys %YEARS ) {
    $outString .=  "<th>$type</th>\n";
}
$outString .=  "</tr></thead>";
for ( $n = $maxyear - 15 ; $n <= $maxyear ; $n++) {
    $outString .=  "<tbody><tr><th>$n</th>";
    foreach $type ( keys %YEARS ) {
	$YEARS{$type}{$n} = 0 if ! $YEARS{$type}{$n};
	$outString .=  "<td>$YEARS{$type}{$n}</td>";
    }
    $outString .=  "</tr></tbody>";
}
$outString .=  "</table>";
## ACABA TABLA PRODUCCION

$outString .= '<div style="position:relative; margin-left: 17px; float: left;width:100%">';
#$outString .= '<p class="productionHeader"><a name="coauthors"><b>Co-Authors</b></a></p>';
#$outString .= $scoauthors;
$outString .= "</div>";

my $refString = '&nbsp;&nbsp;&nbsp;<a href="/cgi-bin/au.pl?id='.$id.'&redir=no">Refresh data now</a>';
my $metadataString = '
<link rel="SCHEMA.dc" href="http://purl.org/dc/elements/1.1/">
<meta name="dc.title" content="Citations profile: '.$author.'">
<meta name="dc.author" content="Citations in Economics">
<meta name="dc.subject" content="Citations; Economics; Impact Factor; Rankings; Research Impact; Research Production; h-index">
<meta name="keywords" content="Citations; Economics; Impact Factor; Rankings; Research Impact; Research Production; h-index">
';

$TmpTemplate =~ s/\{Main\}/$outString/;
#$TmpTemplate =~ s/\{METADATA\}//;
$TmpTemplate =~ s/YEARS/$stringYears/;
$TmpTemplate =~ s/CITATIONDATA/$stringCitations/;
$TmpTemplate =~ s/\{doctitle\}/ Citation profile for $author/;
$TmpTemplate =~ s/ TODAY/ $today $refString/;
$TmpTemplate =~ s/\{METADATA\}/$metadataString/;
$TmpTemplate =~ s/\{SECTION\}/Search results/;
$TmpTemplate =~ s/\{TITLE\}/Search results/;

print $TmpTemplate;
exit(0);

sub co_authors {
    my $ncoauthors;
    my $scoauthors = '<ul>';
    foreach $mid (sort { @{$AUTW{$b}} <=> @{$AUTW{$a}} } keys %AUTW) {
	next if grep /$mid/, @myauthors;
	next if $id eq $mid;
	last if $#{ $AUTW{$mid} } <= 1;
	$ncoauthors++;
	$scoauthors .= join '','<li><b><a href="/',$mid,'">',$AUTN{$mid},'</a></b> (',$#{ $AUTW{$mid} }+1,') </li>';
    }
    $scoauthors .= '</ul>';
    ($ncoauthors,$scoauthors);
}

sub doSearchAuthor {
    my $autString = join '','%',substr $_[0], 0, 10,'%';
    write_error($messages{4},1) if ($autString =~ m/[\|\@\#\\]/);

    $sau = $dbh->prepare("select autorid,id,Fname,Sname from AUTOR where Sname like ? and id is not null order by Sname");
    $mauthors = $sau->execute($autString);

    my $outString = 'Your search by authors with name: '.$autString.' produced the following results:<p><ul>';
    while ( @mauthors = $sau->fetchrow_array ) {
	$outString .= join '','<li> <a href="/'.$mauthors[1].'">'.$mauthors[3].', '.$mauthors[2].'</a><br/>';
    }
    $outString .= '</ul></p>';
    write_error($outString);
}

sub h_index {
    my $hindex;
    foreach $hcit ( sort { $HCIT{$b} <=> $HCIT{$a} } keys %HCIT) {
	$num++;
#        $hindex .= "<p> $num : doc: $hcit -> cit: $HCIT{$hcit}";
	$hindex = $num if $num <= $HCIT{$hcit};
#	$hindex .= "</p>";
    }
    $hindex;
}

sub write_error {

    if ($_[1]) {
	$string = '<p class="Cell2Font">Oops!! There was an error. </p>' ;
	$string .= '<p class="Cell2Font">'.$_[0].'<p>';
	$TmpTemplate =~ s/\{Main\}/$string/;
	$TmpTemplate =~ s/\{METADATA\}//;
	$TmpTemplate =~ s/ AUTHOR/ ERROR/;
	$TmpTemplate =~ s/\{doctitle\}//;
	$TmpTemplate =~ s/\{SECTION\}/Search results/;
	$TmpTemplate =~ s/\{TITLE\}/Search results/;
    } else {
	$string = $_[0];
	$TmpTemplate =~ s/\{Main\}/$string/;
	$TmpTemplate =~ s/\{METADATA\}//;
	$TmpTemplate =~ s/ AUTHOR/ /;
	$TmpTemplate =~ s/\{SECTION\}/Search results/;
	$TmpTemplate =~ s/\{TITLE\}/Search results/;
    }


    $TmpTemplate =~ s/ TODAY/ $today/;
    $TmpTemplate =~ s/<td width="100"/<td width="100" height="200"/;
    $TmpTemplate =~ s/\{doctitle\}//;

    print $TmpTemplate;
    exit(0);
}

sub messages {

    %messages = (
	'1','<p>A required person id is missing.</p>',
	'2','<p>Wrong person id format, please contact barrueco at uv.es for further information.</p>',
	'3','<p>The person id you have typed does not exist in our database.</p>',
	'4','<p>The string you have typed is not correct, please try again.</p>',
	'6','<p>The machine is having a high load. Please try again later.</p>',
	'5','<p>This author has no citations yet. You may use our <a href="http://citec.repec.org/cgi-bin/ui.pl">user submission form</a> to provide references citing him/her</p>',
	);
}


sub getmydata {
    my $ref;
    my $docid;
    my %lcites;
    my $ncites = 0;
    my $nworks = 1;
    my $ncontrol = pop(@_);
    my $type = pop(@_);
    $type =~ s/author\-//;
##    print "Type: $type, queda $#_ <br>";

## These two for each are done to eliminate duplicate citations, that is, a references which cites more than one work.
    foreach $docid ( @_ ) {
	$rc = $sci->execute($docid) or die "can't execute the query: $sth->errstr";
	while ( @cit = $sci->fetchrow_array ) {
	    $lcites{$cit[0]} = 1;
	}
    }

    foreach $docid (keys %lcites) {
	$ncites++;
	$ry = $sye->execute($docid) or die "can't execute the query: $sth->errstr";
	while ( @yea = $sye->fetchrow_array ) { $ncityear = $yea[0]; }
	$CIT{$ncityear}++;
	$CITYPE{$type}++;
	$nTotalCitas++;
	if (grep {$_ eq $docid} @myWorks) { $nTotalSelftCitas++; }
    }

    my 	$sameAs;
    my 	$sameAsCited;
    foreach $docid ( @_ ) {
	$rv = $sth->execute($docid) or die "can't execute the query: $sth->errstr";
	while ( @row = $sth->fetchrow_array ) {
	    $myear = $row[0];
###	    print "Year: $myear<br>";
	    my $thisurl;
	    $dourl = $sturl->execute($docid);
	    if ($dourl >= 1) {
		while ( @urls  = $sturl->fetchrow_array ) {
		    $thisurl = "http://ideas.repec.org/cgi-bin/get_doc.pl?url=$urls[0]\;urn=$docid";
		}
	    } else {
#	    $thisurl = "http://citec.repec.org/cgi-bin/get_data.pl?h=$CITES{$ref[2]}&o=all&f=short";
		undef $thisurl;
	    }

	    if ($nworks == 1) {
		$sameAs = $docid;
		$sameAsCited = $ncites;
		$ref .= '<tr><td class="dataCell2"><a name="'.$docid.'">'.$row[0].'</a></td><td class="dataCell2"><b>'.$row[1].'</b> In: '.$row[2].'.<br/>';
		$ref .= ' [<a href="'.$thisurl.'">Full Text</a>]' if $thisurl;
		$ref .= '[<a href="/'.$docid.'">Citation analysis</a>]</td><td class="dataCell3">'.$ncites.'</td></tr>';
		$YEARS{$type}{$row[0]}++;
		$HCIT{$docid} = $ncites;
		$nTotalDoc++;
		$nTotal{$type}++;
	    } else {
		$ref .= '<tr bgcolor="#D3D3D3"><td class="dataCell2"><a name="'.$docid.'">'.$row[0].'</a></td><td class="dataCell2"><i><b>'.$row[1].'</b>.('.$row[0].') In: '.$row[2].'.</i><br/>';
		$ref .= ' [<a href="'.$thisurl.'">Full Text</a>]' if $thisurl;
		$ref .= '[<a href="/'.$docid.'">Citation analysis</a>]<br/>This paper has another <a href="#'.$sameAs.'">version</a>. Agregated cites: '.$sameAsCited.'</td><td class="dataCell3"></td></tr>';
	    }

	    $minyear = $row[0] if $row[0] < $minyear and $row[0] != 0000;
	    $maxyear = $row[0] if $row[0] > $maxyear;
	    if ($myear >= $maxyear - 5) {
		$arv = $ath->execute($docid) or die "can't execute the query: $sth->errstr";
		while ( @arow = $ath->fetchrow_array ) {
		    next if $arow[0] eq $id;
		    if ($arow[0] =~ /^p/i and $ncontrol == 1) {
			$AUTN{$arow[0]} = "$arow[2], $arow[1]";
			push @{ $AUTW{$arow[0]} }, $docid;
			$nco{$arow[0]} = 1;
		    } elsif ($arow[0] =~ /^p/i and $ncontrol == 2) {
			push @myauthors, $arow[0];
		    }
		}
	    }
	}
	$nworks++;
    }

#    print "r: $row[0] t: $_[1] -> $YEARS{$row[0]}{$_[1]}<br>\n";

#    $DOCS{$_[1]}{$row[0]}++;

#    $ref = '<!-- '.$myear.'-->'.$ref;
    $nTotalCitations = $nTotalCitations + $ncites;
    $ref .= "</tr>";
    $ref;
}


sub parse_date {
    my $mytime = $_[0];

####    print "Mytime $mytime\n";

    if ( $_[0] =~ /^\d\d/ ) {
####	print "Defined $_[0]\n";
	( @now ) = localtime($_[0]);
####	print "-> @now <-\n";
    } else {
	( @now ) = localtime;
    }

    $now[5] = $now[5]+1900;
    $now[4] = $now[4]+1;

    for (0..4) { $now[$_] = join '','0',$now[$_] if $now[$_] < 10; }

    return join '',$now[5],'-',$now[4],'-',$now[3],' ',$now[2],':',$now[1],':',$now[0];

  }

sub writeOut {
    my $string = $_[0];

    if ($string =~ /^htt/) {
	print "Location: $string \n\n";
    } else {
	print "content-type: text/html \n\n";
	$TmpTemplate =~ s/\{Main\}/$string/;
	$TmpTemplate =~ s/\{doctitle\}/Add reference form/;
	$TmpTemplate =~ s/\{METADATA\}//;
	$TmpTemplate =~ s/\{JAVASCRIPT\}//;
	$TmpTemplate =~ s/\{SECTION\}/Search results/;
	$TmpTemplate =~ s/\{TITLE\}/Search results/;
	print $TmpTemplate;
    }
    exit(0);

}
