#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Path::Tiny qw(path);
use MIME::Base64;
use MARC::File::USMARC;
use MARC::File::XML ( BinaryEncoding => 'utf8', RecordFormat => 'USMARC' );
use Encode qw(encode_utf8);

my $fail = $ARGV[0] ? 0 : 1;

binmode(STDOUT,':utf8');
binmode(STDERR,':utf8');

# create a fresh record

my $usmarc_base64 = create_record_usmarc_base64();

my $usmarc = decode_base64($usmarc_base64);
say "Start of USMARC: ".substr($usmarc,0,70);

my $record = MARC::Record->new_from_usmarc($usmarc);

my $f100 =  $record->field('100');
if ($f100) {
    say 'subfield a: '.$f100->subfield('a');
    say "End of long subfield x: ...".substr($f100->subfield('x'),-15);
}
else {
    say "\nCould not read back field!!";
}


sub create_record_usmarc_base64 {
    my $record = MARC::Record->new();
    $record->encoding( 'UTF-8' );

    my $long_string = '123456789 ' x (998 + $fail) ;
    say "Length of long subfield value: ".length($long_string);

    $record->append_fields(
        MARC::Field->new(
            100, " ", " ",
            a => "Some Name",
            x => $long_string,
        )
    );
    my $usmarc = $record->as_usmarc();
    return encode_base64(encode_utf8($usmarc));
}
