#!/usr/bin/perl

use strict;
use Getopt::Std;
use MARC::Field;
use MARC::File::USMARC;
$| = 1;

my %options=();
getopts("t:m:",\%options);
my $target = $options{t};
my $mapList = $options{m};

my ($tag, $code);
if ($target && $target =~ m/^([\d]{3})_([a-z0-9])$/) {
    $tag = $1;
    $code = $2;
}
else {
    die print_help();

}

my $map;
if ($mapList) {
    foreach my $m (split(/,/, $mapList)) {
        if ($m =~ m/^([^\|]+)|([^\|]+)$/) {
            $map->{$1} = $2;
        }
        else {
            die print_help();
        }
    }
}
else {
    die print_help();
}

foreach my $file (@ARGV) {
    my $marcfile = MARC::File::USMARC->in( "$file" );

    while (my $record = $marcfile->next()) {
        $record = map_data($record, $tag, $code, $map);

        print $record->as_usmarc;
    }

    $marcfile->close();
}

exit 0;
################################################################################

sub print_help {
    return <<_STR_;
Please specify field tag ans subfield code using -t parameter:
    $0 -t TAG_CODE -m old1:new1,old2:new2,old3:new3
Ex:
    $0 -t 852_3 -m tmpdata1:data1,tmpdata2:data2,tmpdata3:data3
_STR_
}
############################################################

sub map_data {
    my ($record, $tag, $code, $map) = @_;

    foreach my $field ($record->field($tag)) {
        my @sf_data = $field->subfield($code);
        $field->delete_subfield(code => $code);
        foreach my $data (@sf_data) {
            $field->add_subfields($code => $map->{$data});
        }
    }

    return $record;
}
