#!/usr/bin/perl -w

=head1 NAME

isbn2lccn - a script to read a book's ISBN and convert it to a Library of
Congress call number

=head1 DESCRIPTION

This converts an ISBN to Library of Congress Call Number using
their Z39.50 interface.

=head1 README

This perl script converts a single ISBN to Library of Congress Call Number using
their Z39.50 interface.

=head1 PREREQUISITES

This script requires the following modules or apps, either directly or
indirectly through dependencies: yaz, libyaz, libyaz-devel (from
http://www.indexdata.dk/yaz/) C<Search-Z3950-0.05>, C<Net-Z3950-0.44>,
C<Event-1.00>, C<YAML-0.35>, C<MARC-Record-1.38>

=head1 LICENSE

Copyright (C) 2004 Steve W Bonds, all rights reserved.

This program is free software; you can redistribute it and/or modify it under
the same terms as Perl.

=pod SCRIPT CATEGORIES

Web

=cut

# by Steve Bonds
# June 12 2004
# Copyright 2004, all rights reserved.

# This is Free Software.  You may redistribute this script under the terms of
# either the GNU General Public License version 2.0 or the Perl
# Artistic License.

use Search::Z3950;

my ($isbn) = shift;

# Trim out dashes
$isbn=~ s/\-//g;

unless ($isbn =~ /\S+/) { die "Please provide ISBN" };

# I could do some data sanity checks on the ISBN, but if it's not valid, the
# DB query will probably fail later.

$z = Search::Z3950->new(
			'delay' => 0.5,
			'preferredRecordSyntax' => 19,
			'port' => 7090,
			'host' => 'z3950.loc.gov',
			'databaseName' => 'Voyager',
			'search_types' => [
					   {
					    'name' => 'isbn',
					    'multiple' => 0,
					    'templates' => {
							    'prefix' => '@attr 1=7 @attr 4=1 "%s"'
							   }
					   },
					  ],
			'querytype' => 'prefix',
		       );

my $results = $z->search('isbn' => $isbn);
my $records = $results->count;
if ($records < 1) {
  print "**No results for ISBN $isbn\n";
  exit 1;
} elsif ($records > 1) {
  print STDERR "Multiple records found for ISBN $isbn-- shouldn't happen\n";
  exit 1;
}
my $MARC = $results->record(1);
#my $title = $MARC->field('245')->subfield("a");
#print "Title: $title\n";
#my $author = $MARC->field('100')->subfield("a");
#print "Author: $author\n";
my $lccn = $MARC->field('050')->subfield("a");
print "$lccn\n";