#!/usr/bin/perl

use LWP::Simple;
require "config.pl";
open LOG, ">>$LogFile";
if(!$ARGV[0]){
	print "syntax get_daily.pl yyyy/mm/dd\n";
	exit;
}
my $date = $ARGV[0];
my $utils = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils";

my $db     = "Pubmed";
my $query  = "(\"$date\"[EDat]%20:%20\"$date\"[EDat])+AND+hasabstract[text]";
my $report = "MEDLINE";

my $esearch = "$utils/esearch.fcgi?db=$db&retmax=1&usehistory=y&term=$query";
my $esearch_result = get($esearch);

$esearch_result =~ m|<Count>(\d+)</Count>.*<QueryKey>(\d+)</QueryKey>.*<WebEnv>(\S+)</WebEnv>|s;

my $Count    = $1;
my $QueryKey = $2;
my $WebEnv   = $3;

print LOG "Count = $Count; QueryKey = $QueryKey;\n";
if(!$Count){ # In case of no new record
	close LOG;
	exit;
}
my $retstart;
my $retmax = $Count;

my $efetch = "$utils/efetch.fcgi?rettype=$report&retmode=text&retstart=$retstart&retmax=$retmax&db=$db&query_key=$QueryKey&WebEnv=$WebEnv";
my $efetch_result = get($efetch);
$date =~ tr/\///d;
open OUT, ">temp/$date.txt";
print OUT "$efetch_result\n";
close OUT;
close LOG;
exit;
