#!/usr/bin/perl
# mod cfb 7B19
# also requires expat-2.0.1, XML::Parser, XML::Writer
use OAI2::Harvester;
use strict;

my $home_url='http://oai.repec.openlib.org';
my $h = new OAI2::Harvester(-baseURL=>$home_url);

#
# get the metadataPrefix from the first argument
#
my $metadataPrefix=$ARGV[0];
if(not $metadataPrefix eq 'amf' 
   and not $metadataPrefix eq 'oai_dc') {
  print "not a valid metadataPrefix: $metadataPrefix\n";
}
#
# get the record set from the second argument
#
my $series=$ARGV[1];
my $response = $h->ListRecords('set'=>$series,-metadataPrefix=>$metadataPrefix);
if( $response->is_error ) {
  print "Error: ", $response->code," (", $response->message, ")\n";
  exit();
}

print "<$metadataPrefix>\n";
while( my $rec = $response->next ) {
  if( $rec->is_error ) {
    die $rec->message;
  }
  my $out=$rec->metadata;
  # clear oai envelope, non-XML way
  $out=~s|</?metadata>||g;
  $out=~s|^<$metadataPrefix [^>]+>\n||g;
  $out=~s|</$metadataPrefix>||g;
  $out=~s|\n+|\n|g;
  print $out;
}
print "</$metadataPrefix>\n";
