#!/usr/bin/perl

# Convert marcdump output back to marc file

use warnings;
use strict;

use MARC::Record;
use Data::Dump qw(dump);
use Encode;

my @fields;

sub parse_subfields {
	my $text = shift;
	if ( $text =~ /^_([a-z])(.+)$/ ) {
		return ( $1, $2 );
	} else {
		$text =~ s/^ // || warn "no space in front of: '$text'\n";
		return $text;
	}
}

my $leader;

while(<>) {
	chomp;
	$_ = decode('utf-8', $_);

	if ( /^LDR (.+)$/ ) {
		$leader = $1;
	} elsif ( /^(\d\d\d) (.)(.) (.+)$/ ) {
		if ( $1 < 10 ) {
			push @fields, [ $1, parse_subfields($4) ];
		} else {
			push @fields, [ $1, $2, $3, parse_subfields($4) ];
		}
	} elsif ( /^\s{7}_([a-z])(.+)$/ ) {
		push @{ $fields[ $#fields ] }, $1, $2;
	} elsif ( /^$/ ) {
		warn dump( @fields );

		my $marc = new MARC::Record;
		$marc->encoding( 'utf-8' );
		$marc->leader( $leader );
		$marc->add_fields( @fields );

		warn $marc->as_formatted;
		print $marc->as_usmarc;

		@fields = ();
	} else {
		warn "IGNORED: $_\n";
	}

}
