#!/usr/bin/perl

#use utf8;
use strict;
use CGI;
use Opals::Context;use POSIX qw(
    ceil
);
use Opals::Context;
use MARC::File::USMARC;
use MARC::File::XML;
use MARC::Field;


my $cgi = CGI->new;
my $input= $cgi->Vars();
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $rid = $input->{'rid'};

my $fname=recordPath($rid)."/$rid.xml";
my $marc="";
my $xml ="";
my $fileExt="";
if(-f $fname){
    open MARC ,"<$fname";
    while(<MARC>){
        $xml .= $_ if($_ !~ m/<subfield code="-">/g);
    }
    #$xml =~ s/<datafield tag="710" ind1="([\d ])" ind2="([\d ])">(.*?)<\/datafield>//gs;
    if($input->{'format'} eq 'usmarc'){
        my $marcRec = MARC::File::XML->decode($xml);
        $marc= $marcRec->as_usmarc();
    }
    else{
        $marc=$xml;
         $fileExt="xml";
    }

    close MARC;
}
=item
print $cgi->header(
        -type    => 'text/xml',
        -expires => 'now',
    ),$marc;
=cut
   print "Content-Type:application/x-download\n";
   print "Content-Disposition:attachment;filename=$rid.$fileExt\n\n";     
   print $marc;

#####################################################
sub recordPath {
    my ($rid) = @_;
    
    my $zRoot   = Opals::Context->config('zRoot');
    my $zPort   = Opals::Context->config('zPort');
    my $zDatabase = Opals::Context->config('zDatabase');
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);

    return $dir;
}

