#!/usr/bin/perl -w
# --------------------------------------------------------------------------------- 
# Author: James Brunskill (Library/University of Waikato) - brunskil@waikato.ac.nz 
# Original Release Date: 23/03/2007
# Last Updated: 23/03/2007
# Description/Purpose:
# Reads in a marc order file, and splits into files for each currency represented.
# --------------------------------------------------------------------------------- 
use strict;
use IO::File;
use MARC::Batch;


#
#Stuff to pull in from the commandline
#
if( $#ARGV < 0)
{
    die "Please specify an input file. Eg. currencysplit.pl order.mrc";
}

#Global Variables
my $inputfile = $ARGV[0];

#Hashtable to hold the file references for each currency
my %outputfiles;

## Regular Expression to check for valid currencies
### We just want GBP or USD 
my $validcurrencies = "USD|GBP";

## create a MARC::Batch object.

my $batch = MARC::Batch->new('USMARC', $inputfile);

## Variables to use in loop

my $field;
my $price;
my $currency;
my $OUTFILE;

## Get the base filename and extention
$inputfile =~ m/^(.*)\.(.*)$/g;
my $basefilename = $1;
my $ext = $2;


## get a marc record from the MARC::Batch object.
## $record will be a MARC::Record object.

while ( my $record = $batch->next() ) {
    
    $field = $record->field('960'); 
    $currency = $field->subfield('z');
    
    #Check that the currency specified is one we want to process
    if($currency =~ m/$validcurrencies/g)
    {

	#Check that we have a file for this currency, if not create one
	if(!$outputfiles{$currency})
	{
	    $outputfiles{$currency} = new IO::File ">$basefilename-$currency.$ext";
	   #print "DEBUG: Created file called $basefilename-$currency.$ext\n";
	}

	$OUTFILE = $outputfiles{$currency};

	#Save the record to the file...
	print $OUTFILE $record->as_usmarc();
	
	
    }
    else
    {
	print "Invalid Currency:\n";
	print $record->as_formatted(),"\n";
    }
}
## make sure there weren't any problems.
if ( my @warnings = $batch->warnings() ) {
print "\nWarnings were detected!\n", @warnings;
}
