#!/bin/env perl -w
#
# Usage: biblinks-client.pl [--debug] [--html | --xml | --table] [proxy cgi]

use SOAP::Lite;

my $debug = (@ARGV and $ARGV[0] eq '--debug') ? shift(@ARGV) : 0;
my $format = (@ARGV and $ARGV[0] =~ s/^--//) ? shift(@ARGV) : 'xml';
my $cgi = @ARGV ? shift(@ARGV) : 'http://ads.harvard.edu/ws/biblinks';

warn "$0: connecting to SOAP proxy $cgi...\n";
SOAP::Trace->import('all') if ($debug);

my $response = SOAP::Lite
    -> uri('http://ads.harvard.edu/BibLinks')
    -> proxy($cgi)
    -> harvest();

die $response->faultcode, ', ', $response->faultstring if ($response->fault);

my $result = $response->result;

if ($format eq 'html') {
    print "<HTML><BODY>Links available: <P><UL>\n";
    foreach my $r (@{$result}) {
	print "<LI> ", &escape($r->{bibcode}), 
	' -- <A HREF="', $r->{url}, '">', &escape($r->{desc}), "</A>\n";
    }
    print "</UL>\n</BODY>\n</HTML>\n";

} elsif ($format eq 'xml') {
    use XML::Simple;
    print XMLout($result, noattr => 1);

} elsif ($format eq 'table') {
    foreach my $r (@{$result}) {
	print $r->{bibcode}, "\t", $r->{url}, "\t", $r->{desc}, "\n";
    }

} else {
    die "$0: unknown format `$format'";
}

sub escape {
    my $s = shift;
    my %Ent = ('&' => 'amp',
	       '>' => 'gt',
	       '<' => 'lt');

    $s =~ s/([<>&])/&$Ent{$1};/g;
    return $s;
}
