#!/usr/bin/env perl


=pod

=head1 NAME

addbibinfo - add information from public databases to a bib file

=head1 SYNOPSIS

addbibinfo  [-c I<config>] [-d]  [B<-e> 1|0] [B<-f>] [B<-o> I<output>] [-t all|mr|doi|zbl]  I<bib_file>

=head1 OPTIONS

=over 4

=item B<-c> I<config_file>

Configuration file.  If this file is absent, some defaults are used.
See below for its format.


=item B<-d>

Debug mode on

=item B<-e>

If 1 (default), add an empty field if the information cannot be found.  This
prevents repeated searches for the same entries if you add new entries
to the file.  Calling C<-e 0> suppresses this behavior.


=item B<-f>

Force search for information even if present in the file


=item B<-o> I<output>

Output file.  If this option is not used, the name for the 
output file is formed by adding C<_output> to the input file

=item B<-t>

Type of search:

=over 4

=item B<all>

Search for all information (default)

=item B<mr>

Search for MR numbers only

=item B<zbl>

Search for ZBL numbers only

=item B<doi>

Search for DOI numbers only

=back


=back

=head1 DESCRIPTION

The script reads a BibTeX file, parses it and tried to add from the
public databases the following information to each entry:

=over 4

=item *

doi number from http://www.crossref.org

=item *

MR number from https://mathscinet.ams.org/batchmrlookup

=item *

ZBL number from https://zbmath.org

=back


You can tell script to add only the databases you need using B<-t>
option with the list of reqiired databases.  If called as C<bibdoiadd>,
C<bibmradd>, or C<bibzbladd>, the script behaves as called with C<-t
doi>, C<-t mr>, or C<-t zbl> option correspondingly.

If a bibliographic entry already has the requested field (which could
be empty), the script does not search for it unless B<-f> option is
chosen.  If the script cannot find the information, it adds an empty
field to the entry unless C<-e 0> option is chosen.

The name of the output file is either set by the B<-o> option or 
is derived by adding the suffix C<_output> to the output file.

=head1 CONFIGURATION FILE 

The configuration file relates to the Crossref queries, and is mostly
self-explanatory: it has comments (starting with C<#>) and assginments
in the form

   $field = value ;

Crossref-related parameters in the hash C<%$crossrefparams>.  They are
C<$mode> (C<'free'> or C<'paid'>), C<$email> (for free users) and
C<$username> and C<$password> for paid members.

Field names can be rededined in this file, see L<FIELD NAMES> below.  


=head1 FIELD NAMES

The names of the fields by default are

=over 4

=item B<mr>

mrnumber

=item B<zbl>

zblnumber

=item B<doi>

doi

=back

You can rededine them in the config file redefining the hash
C<%{$fieldnames}>, for example

   $fieldnames->{mr} = {MR};

=head1 EXAMPLES

   addbibionfo -c addbibionfo.cfg -t 'mr doi' -o - citations.bib > result.bib
   addbibionfo  -o result.bib citations.bib 

=head1 AUTHOR

Boris Veytsman

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2026 Boris Veytsman

This is free software.  You may redistribute copies of it under the
terms of the GNU General Public License
L<http://www.gnu.org/licenses/gpl.html>.  There is NO WARRANTY, to the
extent permitted by law.


=cut

use strict;
$main::VERSION='1.0 2026/11/09';
BEGIN {
    # find files relative to our installed location within TeX Live
    chomp(my $TLMaster = `kpsewhich -var-value=TEXMFROOT`); # TL root
    if (length($TLMaster)) {
	unshift @INC, "$TLMaster/texmf-dist/scripts/bibtexperllibs";
    }
}

use Getopt::Std;
use File::Basename;
use IO::File;
use BibTeX::Parser;
use LWP::UserAgent;
use LaTeX::ToUnicode;
binmode(STDERR, ":encoding(UTF-8)");

my $USAGE= <<END;
USAGE: $0 [-c I<config>] [-d]  [B<-e> 1|0] [B<-f>] [B<-o> I<output>] [-t all|mr|doi|zbl] I<bib_file>\n

Version $main::VERSION

This is free software.  You may redistribute copies of it under the
terms of the GNU General Public License
http://www.gnu.org/licenses/gpl.html.  There is NO WARRANTY, to the
extent permitted by law.
END

our %opts;
getopts('c:de:fo:t:',\%opts) or die $USAGE;

################################################################
# Defaults and options
################################################################

our $fieldnames;

$fieldnames->{mr} = 'mrnumber';
$fieldnames->{zbl} = 'zblnumber';
$fieldnames->{doi} = 'doi';

our $crossrefparams;
$crossrefparams -> {mode}='free';
$crossrefparams -> {email}='user@doman.com';



if ($opts{c}) {
    if (-r $opts{c}) {
	#
	# Sometimes we might have legacy config files
	#
	our $mode;
	our $email;
	our $username;
	our $password;
	push @INC, ".";
	require $opts{c};
	if (length($mode)) {
	    $crossrefparams->{mode} = $mode;
	}
	if (length($email)) {
	    $crossrefparams->{email} = $email;
	}
	if (length($username)) {
	    $crossrefparams->{username} = $username;
	}
	if (length($password)) {
	    $crossrefparams->{password} = $password;
	}
	
    } else {
	die "Cannot read config file $opts{c}.\n\n$USAGE";
    }
}

my $inputfile = shift;

my $outputfile = $inputfile;

$outputfile =~ s/\.([^\.]*)$/_output.$1/;

my $input= IO::File->new($inputfile) or 
    die "Cannot find BibTeX file $inputfile\n$USAGE\n";
my $output = IO::File->new("> $outputfile") or 
    die "Cannot write to $outputfile\n$USAGE\n";


if (exists $opts{o}) {
    $outputfile = $opts{o};
}

my $DEBUG = 0;
if (exists $opts{d}) {
    $DEBUG = 1;
}

my $forceSearch=0;
if (exists $opts{f}) {
    $forceSearch = $opts{f};
}		
my $forceEmpty = 1;
if (exists $opts{e}) {
    $forceEmpty = $opts{e};
}		


# The hash of enabled search types.  Values are fieldnames and
# search classes
my $searchTypes={};

# Adding search types from the base name and options
my $scriptname = basename($0);
$scriptname =~ s/\..*$//;
if ($scriptname eq 'bibdoiadd') {
    $searchTypes -> {doi} -> {fieldname} = $fieldnames->{doi};
}
if ($scriptname eq 'bibmradd') {
    $searchTypes -> {mr} -> {fieldname} = $fieldnames->{mr};
}
if ($scriptname eq 'bibzbladd') {
    $searchTypes -> {zbl} -> {fieldname} = $fieldnames->{zbl};
}
if ($opts{t}) {
    my @types = split /\s+/, $opts{t};
    foreach my $type (@types) {
	if (exists $fieldnames->{$type}) {
	    $searchTypes->{$type}->{fieldname} = $fieldnames->{$type};
	} else {
	    print STDERR "Unknown search type $type.\n";
	    exit(-1);
	}
    }
}
# Default is to use all dbs
if (!%$searchTypes) {
    my @types = ('zbl', 'mr', 'doi');
    foreach my $type (@types) {
	if (exists $fieldnames->{$type}) {
	    $searchTypes->{$type}->{fieldname} = $fieldnames->{$type};
	}
    }
}

# Opening search objects
foreach my $type (keys %$searchTypes) {
    if ($type eq 'mr') {
	$searchTypes->{$type}->{search} = new
	    BibSearchMr($searchTypes->{$type}->{fieldname});
    }
    if ($type eq 'zbl') {
	$searchTypes->{$type}->{search} = new
	    BibSearchZbl($searchTypes->{$type}->{fieldname});
    }
    if ($type eq 'doi') {
	$searchTypes->{$type}->{search} = new
	    BibSearchDoi($searchTypes->{$type}->{fieldname},
	    $crossrefparams);
    }
}


if ($DEBUG) {
    foreach my $type (sort keys %$searchTypes) {
	print STDERR "Setup for ", $type, ":\n";
	print STDERR "  Field name: ", $searchTypes->
	{$type}->{search}->Get('fieldname'),
	    "\n";
	print STDERR "  Website: ", $searchTypes->
	{$type}->{search}->Get('website'),
	    "\n";
    }
}

# Creating user agent

my $ua = new LWP::UserAgent(
    ssl_opts => {
        verify_hostname => 0,
    }
    );


my $parser=new BibTeX::Parser($input);
# Now we read the file and process it
while (my $entry = $parser->next ) {
    if (!$entry->parse_ok()) {
	print STDERR "Cannot understand entry: ";
	$entry->print(*STDERR);
	print STDERR "Skipping this entry\n";
	next;
    }
    if ($DEBUG) {
	print STDERR "Working with ", $entry->key(), "\n";
    }
    foreach my $type (sort keys %$searchTypes) {
	$searchTypes-> {$type}->{search}->
	    AddField($entry, $ua, $forceSearch, $forceEmpty, $DEBUG);
    }
    print $output 
	$entry->to_string(), 
	 "\n\n";


}




#########################################################
# Generic search
##########################################################
{
    package BibSearch;
    use URI;
    sub new {
	my $class = shift;
	my $fieldname = shift;
	my $self;
	$self->{fieldname}=$fieldname;
	return bless $self, $class;
    }
    sub Get {
	my $self = shift;
	my $field = shift;
	return $self->{$field};
    }
    sub AddField {
	my $self=shift;
	my $entry=shift;
	my $ua = shift;
	my $forceSearch = shift;
	my $forceEmpty = shift;
	my $DEBUG=shift;
	my $fieldname = $self->Get('fieldname');
	if ($DEBUG) {
	    print STDERR "  Looking for ",
		$fieldname, "\n";
	}
	if ($entry->has($fieldname)) {
	    if ($forceSearch) {
		if ($DEBUG) {
		    print STDERR "  Entry already has ",
			$fieldname,
			". Overriding since -f is chosen.\n"
		}
	    } else {
		if ($DEBUG) {
		    print STDERR "  Entry already has ",
			$fieldname,
			". Skipping.\n"
		}
		return();
	    }
	}
	my $uri = new URI ($self->{website});	
	my $searchParams = $self -> GetSearchParams($entry);
	$uri -> query_form($searchParams);
	if ($DEBUG) {
	    print STDERR "  Query: $uri\n";
	}
	my $response = $ua->get($uri);
	if ($response->is_success) {
	    if ($DEBUG) {
		print STDERR
		    "  Response: ",
		    $response->decoded_content, "\n";
	    }
	    my $value = $self->
		ExtractValue($response->decoded_content);
	    if ($DEBUG) {
		print STDERR "  Extracted: $value\n";
	    }
	    if (!length($value) && !$forceEmpty) {
		return();
	    }
	    $entry->field($fieldname, $value);	    
	} else {
	    print STDERR "  BAD RESPONSE: ",
		$response->status_line, "\n"
	}
	
	return();
    }
	       
}

#############################################################
# Specific search classes.  Each must define the following
# procedures
#
# * new (fieldname) - set up
#############################################################
{
    package BibSearchMr;
    use parent -norequire, "BibSearch";
    sub new {
	my $class = shift;
	my $fieldname = shift;
	if (!$fieldname) {
	    $fieldname = 'mrnumber';
	}
	my $self = new BibSearch ($fieldname);
	$self->{website} = "https://mathscinet.ams.org/batchmrlookup";
	return bless $self, $class;
    }
    sub GetSearchParams {
	my $self = shift;
	my $entry = shift;
	my $searchParams;
	my @data;
	if ($entry->has('issn')) {
	    push @data, $entry->field('issn');
	} else {
	    push @data, "";
	}
	if ($entry->has('journal')) {
	    push @data, $entry->cleaned_field('journal');
	} else {
	    push @data, "";
	}
	if ($entry->has('author')) {
	    my @authors = $entry->cleaned_author();
	    my @lastnames;
	    foreach my $author (@authors) {
		push @lastnames, $author->last();
	    }
	    if (scalar @lastnames) {
		push @data, join(";", @lastnames);
	    } else {
		push @data, "";
	    }
	} else {
	    push @data, "";
	}
	if ($entry->has('volume')) {
	    push @data, $entry->cleaned_field('volume');
	} else {
	    push @data, "";
	}
	if ($entry->has('number')) {
	    push @data, $entry->cleaned_field('number');
	} else {
	    push @data, "";
	}
	if ($entry->has('pages')) {
	    my $page = $entry->cleaned_field('pages');
	    $page =~ s/-.*//;
	    $page =~ s/\+.*//;
	    push @data, $page;
	} else {
	    push @data, "";
	}
	if ($entry->has('year')) {
	    push @data, $entry->cleaned_field('year');
	} else {
	    push @data, "";
	}
	push @data, $entry->type();
	push @data, $entry->key();
	push @data, "";
	if ($entry->has('title')) {
	    my $title = $entry->cleaned_field('title');
	    $title =~ s/|/ /g;
	    push @data, $entry->cleaned_field('title');
	} else {
	    push @data, "";
	}        
	my $qdata = join("|", @data);

	$searchParams->{qdata}=$qdata;
	$searchParams->{api} = 'xref';

	return($searchParams);
    }
    sub ExtractValue {
	my $self = shift;
	my $content = shift;
	my @vals = split /\|/, $content;
	return "$vals[9]";
    }
    
}
{
    package BibSearchZbl;
    use parent -norequire, "BibSearch";
    use JSON;
    sub new {
	my $class = shift;
	my $fieldname = shift;
	if (!$fieldname) {
	    $fieldname = 'mrnumber';
	}
	my $self = new BibSearch ($fieldname);
	$self->{website} = "https://api.zbmath.org/v1/document/_search";
	return bless $self, $class;
    }
    sub GetSearchParams {
	my $self = shift;
	my $entry = shift;
	my $searchParams;

	my @data;
	
	if ($entry->has('arxiv')) {
	    push @data, "arxiv:".$entry->cleaned_field('arxiv');
	}

	if ($entry->has('author')) {
	    my @authors = $entry->cleaned_author();
	    foreach my $author (@authors) {
		push @data, "au:".$author->last();
	    }
	}

	if ($entry->type() eq 'ARTICLE') {
	    push @data, 'dt:j';	
	} elsif ($entry->type() eq 'INCOLLECTION' ||
		 $entry->type() eq 'INBOOK') {
	    push @data, 'dt:a';
	} elsif ($entry->type() eq 'BOOK') {
	    push @data, 'dt:a';
	} elsif ($entry->type() eq 'MISC') {
	    push @data, 'dt:p';
	}

	if ($entry->has('doi')) {
	    my $doi = $entry->field('doi');
	    $doi =~ s/^http.*doi\.org\///;
	    push @data, "doi:$doi";
	}

	if ($entry->has('editor')) {
	    my @editors = $entry->cleaned_editor();
	    foreach my $editor (@editors) {
		push @data, "ed:".$editor->last();
	    }
	}
	
	if ($entry->has('journal')) {
	    my $journal = $entry->cleaned_field('journal');
	    $journal =~ s/:/ /g;
	    push @data, "so:".$journal;
	}
	if ($entry->has('title')) {
	    my $title =$entry->cleaned_field('title');
	    $title =~ s/:/ /g;
	    push @data, "ti:".$title
	}
	if ($entry->has('year')) {
	    push @data, "py:".$entry->cleaned_field('year');
	}
	
	my $search_string = join("&", @data);

	$searchParams -> {search_string} = $search_string;
	$searchParams -> {page} = 0;
	$searchParams -> {results_per_page} = 1;
	
	return($searchParams);
    }
    sub ExtractValue {
	my $self = shift;
	my $content = shift;
	my $json = decode_json($content);
	if (exists $json->{result}->[0]->{identifier}) {
	    return( $json->{result}->[0]->{identifier});
	} else {
	    return "";
	}
    }
}
{
    package BibSearchDoi;
    use parent -norequire, "BibSearch";
    sub new {
	my $class = shift;
	my $fieldname = shift;
	my $crossrefparams = shift;
	if (!$fieldname) {
	    $fieldname = 'doi';
	}
	my $self = new BibSearch ($fieldname);
	$self->{website} = "http://www.crossref.org/openurl";
	# Query params
	my %defaultparams;
	$defaultparams{redirect}="false";
	if ($crossrefparams->{mode} eq 'free') {
	    $defaultparams{pid}=$crossrefparams->{email};
	} else {
	    $defaultparams{pid}=$crossrefparams->{username}.":".
		$crossrefparams->{password};
	}
	$self->{defaultparams} = \%defaultparams;
	return bless $self, $class;
    }
    sub GetSearchParams {
	my $self = shift;
	my $entry = shift;
	my $searchParams;
	foreach my $key (keys %{$self->{defaultparams}}) {
	    $searchParams->{$key} =
		$self->{defaultparams}->{$key};
	}
	if ($entry->has('issn')) {
	    $searchParams->{issn} = $entry->cleaned_field('issn');
	}
		if ($entry->has('journal')) {
	    $searchParams->{title} = $entry->cleaned_field('journal');
	}
	my @names=$entry->cleaned_author();
	if (scalar(@names)) {
	    my $lastname = $names[0]->last();
	    $searchParams->{aulast}=$lastname;
	}
	if ($entry->has('volume')) {
	$searchParams->{volume} = $entry->cleaned_field('volume');
	}    
	if ($entry->has('number')) {
	$searchParams->{issue} = $entry->cleaned_field('number');
	}    
	if ($entry->has('pages')) {
	    my $pages=$entry->cleaned_field('pages');
	    $pages =~ s/-.*$//;
	    $searchParams->{spage} = $pages;
	}    
	if ($entry->has('year')) {
	   $searchParams->{date} = $entry->cleaned_field('year');
	}    


	return($searchParams);
    }
    sub ExtractValue {
	my $self = shift;
	my $content = shift;
	if ($content =~ m/<doi [^>]*>(.*)<\/doi>/) {
	    return $1;
	} else {
	    return "";
	}
    }
}
