stow_record_data uses named captures now instead of oldstyle automagic capture vars...
[migration-tools.git] / marc-cleanup
index 991b665..f40babb 100755 (executable)
@@ -9,19 +9,22 @@ use Term::ReadLine;
 my $term = new Term::ReadLine 'yaz-cleanup';
 my $OUT = $term->OUT || \*STDOUT;
 
+$| = 1;
+
 # initialization and setup
 my $conf = {};
 initialize($conf);
-populate_trash() if ($conf->{trash});
+populate_trash() if ($conf->{trashfile});
 
 # set up files, since everything appears to be in order
-open MARC, '<:utf8', shift || 'incoming.marc.xml';
-open my $NUMARC, '>:utf8', $conf->{output};
-open my $EXMARC, '>:utf8', $conf->{exception};
-open my $OLD2NEW, '>', 'old2new.incoming.map'
+open MARC, '<:utf8', (shift || 'incoming.marc.xml')
+  or die "Can't open input file $!\n";
+open my $NUMARC, '>:utf8', $conf->{output}
+  or die "Can't open output file $!\n";
+open my $OLD2NEW, '>', 'old2new.map'
   if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
-print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
-print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
+my $EXMARC = 'EX';
+
 
 my @record  = (); # current record storage
 my %recmeta = (); # metadata about current record
@@ -59,7 +62,6 @@ while ( buildrecord() ) {
     }
 
     do_automated_cleanups();
-    stow_record_data();
 
     $ptr = 0;
     until ($ptr == $#record) {
@@ -96,7 +98,7 @@ while ( buildrecord() ) {
     }
     write_record($NUMARC);
 }
-print $NUMARC "</collection>\n";
+#print $NUMARC "</collection>\n";
 print $OUT "\nDone.               \n";
 
 
@@ -107,8 +109,11 @@ print $OUT "\nDone.               \n";
 sub do_automated_cleanups {
     $ptr = 0;
     until ($ptr == $#record) {
+        # get datafield/tag data if we have it
+        stow_record_data();
+
         # catch empty datafield elements
-        if ($record[$ptr] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
+        if ($record[$ptr] =~ m/<datafield tag="..."/) {
             if ($record[$ptr + 1] =~ m|</datafield>|) {
                 my @a = @record[0 .. $ptr - 1];
                 my @b = @record[$ptr + 2 .. $#record];
@@ -175,13 +180,22 @@ sub do_automated_cleanups {
 
 sub stow_record_data {
     # get tag data if we're looking at it
-    if ($record[$ptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
-        $recmeta{tag}  = $1;
-        $recmeta{ind1} = $2;
-        $recmeta{ind2} = $3;
+    
+    if ($record[$ptr] =~ m/<datafield tag="(?<TAG>.{3})"/) {
+        $recmeta{tag} = $+{TAG};
+        $record[$ptr] =~ m/ind1="(?<IND1>.)"/;
+        $recmeta{ind1} = $+{IND1} || '';
+        $record[$ptr] =~ m/ind2="(?<IND2>.)"/;
+        $recmeta{ind2} = $+{IND2} || '';
+        
+        unless (defined $recmeta{tag}) {
+            message("Autokill record: no detectable tag");
+            dump_record("No detectable tag") ;
+        }
 
         # and since we are looking at a tag, see if it's the original id
-        if ($conf->{'original-subfield'} and $1 == $conf->{'original-tag'}) {
+        if ($conf->{'original-subfield'} and
+            $recmeta{tag} == $conf->{'original-tag'}) {
             my $line = $record[$ptr]; my $lptr = $ptr;
             my $osub = $conf->{'original-subfield'};
             $recmeta{oid} = 'NONE';
@@ -189,7 +203,7 @@ sub stow_record_data {
             until ($line =~ m|</record>|) {
                 $lptr++;
                 $line = $record[$lptr];
-                $recmeta{oid} = $1
+                $recmeta{oid} = $+{TAG}
                   if ($line =~ /<subfield code="$osub">(.+?)</);
             }
         }
@@ -214,7 +228,7 @@ sub edit {
     print_fullcontext();
 
     # stow original problem line
-    $conf->{origline} = $record[$ptr];
+    $recmeta{origline} = $record[$ptr];
 
     while (1) {
         my $line = $term->readline('marc-cleanup>');
@@ -233,6 +247,7 @@ sub edit {
             my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
             last if $term;
         } else {
+            $recmeta{prevline} = $record[$ptr];
             $record[$ptr] = "$line\n";
             print_context();
         }
@@ -252,7 +267,7 @@ sub buildrecord {
     my $l = '';
     $l = <MARC> while (defined $l and $l !~ /<record>/);
     return $l unless defined $l;
-    @record = ($l);
+    @record = ();
     %recmeta = ();
     $conf->{ricount}++;
 
@@ -266,6 +281,13 @@ sub write_record {
     my ($FH) = @_;
     my $trash = $conf->{trash};
 
+    if ($FH eq 'EX') {
+        $EXMARC = undef;
+        open $EXMARC, '>:utf8', $conf->{exception}
+          or die "Can't open exception file $!\n";
+        $FH = $EXMARC;
+    }
+
     $conf->{rocount}++ if ($FH eq $NUMARC);
     print $FH '<!-- ', $recmeta{explanation}, " -->\n"
       if(defined $recmeta{explanation});
@@ -294,7 +316,7 @@ sub write_record {
     # add 903(?) with new record id
     my $renumber = '';
     if ($conf->{'renumber-from'}) {
-        $recmeta{nid} = $conf->{'renumber=from'};
+        $recmeta{nid} = $conf->{'renumber-from'};
         $renumber = join('', ' <datafield tag="', $conf->{'renumber-tag'},
                          '" ind1=" " ind2=" "> <subfield code="',
                          $conf->{'renumber-subfield'},
@@ -305,16 +327,27 @@ sub write_record {
         $conf->{'renumber-from'}++;
     }
 
-    # scrub newlines
-    unless ($conf->{nocollapse})
+    # scrub newlines (unless told not to or writing exception record)
+    unless ($conf->{nocollapse} or $FH eq $EXMARC)
       { s/\n// for (@record) }
 
     # write to old->new map file if needed
-    print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
-      if ($conf->{'renumber-from'} and $conf->{'original-subfield'});
+    if ($conf->{'renumber-from'} and $conf->{'original-subfield'}) {
+        unless (defined $recmeta{oid}) {
+            my $msg = join(' ', "No old id num found");
+            dump_record($msg);
+        } else {
+            print $OLD2NEW $recmeta{oid}, "\t", $recmeta{nid}, "\n"
+        }
+    }
 
-    # and finally, actually write the record
-    print $FH @record;
+    # actually write the record
+    print $FH @record,"\n";
+
+    # if we were dumping to exception file, nuke the record and set ptr
+    # to terminate processing loop
+    @record = ('a');
+    $ptr = 0;
 }
 
 sub print_fullcontext {
@@ -322,6 +355,7 @@ sub print_fullcontext {
     print $OUT $conf->{editmsg},"\n";
     print $OUT "\r    Tag:",$recmeta{tag}, " Ind1:'",
       $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
+    print $OUT " @ ", $conf->{ricount}, "/", $conf->{rocount} + 1;
     print_context();
     return 0;
 }
@@ -349,11 +383,11 @@ sub message {
 #-----------------------------------------------------------------------------------
 
 sub substitute {
-    my ($line_in, @chunks) = @_;
+    my (@chunks) = @_;
 
     my $ofrom = shift @chunks;
-    if ($ofrom =~ /^'/ or !@chunks) {
-        until ($ofrom =~ /'$/)
+    if ($ofrom =~ /^'/) {
+        until ($ofrom =~ /'$/ or !@chunks)
           { $ofrom .= join(' ','',shift @chunks) }
         $ofrom =~ s/^'//; $ofrom =~ s/'$//;
     }
@@ -370,14 +404,14 @@ sub substitute {
         $from = join('', $from, $char);
     }
 
-    $conf->{prevline} = $record[$ptr];
+    $recmeta{prevline} = $record[$ptr];
     $record[$ptr] =~ s/$from/$to/;
     print_context();
     return 0;
 }
 
 sub merge_lines {
-    $conf->{prevline} = $record[$ptr];
+    $recmeta{prevline} = $record[$ptr];
     # remove <subfield stuff; extract (probably wrong) subfield code
     $record[$ptr] =~ s/^\s*<subfield code="(.*?)">//;
     # and move to front of line
@@ -397,17 +431,17 @@ sub merge_lines {
 }
 
 sub flip_line {
-    unless ($conf->{prevline})
+    unless ($recmeta{prevline})
       { print $OUT "No previously edited line to flip\n"; return }
     my $temp = $record[$ptr];
-    $record[$ptr] = $conf->{prevline};
-    $conf->{prevline} = $temp;
+    $record[$ptr] = $recmeta{prevline};
+    $recmeta{prevline} = $temp;
     print_context();
     return 0;
 }
 
 sub kill_line {
-    $conf->{killline} = $record[$ptr];
+    $recmeta{killline} = $record[$ptr];
     my @a = @record[0 .. $ptr - 1];
     my @b = @record[$ptr + 1 .. $#record];
     @record = (@a, @b);
@@ -416,7 +450,7 @@ sub kill_line {
 }
 
 sub yank_line {
-    unless ($conf->{killline})
+    unless ($recmeta{killline})
       { print $OUT "No killed line to yank\n"; return }
     my @a = @record[0 .. $ptr - 1];
     my @b = @record[$ptr .. $#record];
@@ -425,16 +459,23 @@ sub yank_line {
     return 0;
 }
 
+sub insert_original {
+    $record[$ptr] = $recmeta{origline};
+    print_context();
+    return 0;
+}
+
 sub display_lines {
-    print $OUT "\nOrig. edit line  :", $conf->{origline};
-    print $OUT "Current flip line:", $conf->{prevline} if $conf->{prevline};
-    print $OUT "Last killed line :", $conf->{killline} if $conf->{killline};
+    print $OUT "\nOrig. edit line  :", $recmeta{origline};
+    print $OUT "Current flip line:", $recmeta{prevline} if $recmeta{prevline};
+    print $OUT "Last killed line :", $recmeta{killline} if $recmeta{killline};
     print $OUT "\n";
     return 0;
 }
 
 sub dump_record {
-    my ($line_in, @explanation) = @_;
+    my (@explanation) = @_;
+    print $OUT @explanation;
     $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
     write_record($EXMARC);
     return 1;
@@ -514,7 +555,7 @@ sub quit { exit }
 
 sub populate_trash {
     print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
-    open TRASH, '<', $conf->{trash}
+    open TRASH, '<', $conf->{trashfile}
       or die "Can't open trash tags file!\n";
     while (<TRASH>) {
         my $lastwasrange = 0;
@@ -610,15 +651,16 @@ sub initialize {
                          'autoscrub|a',
                          'exception|x=s',
                          'output|o=s',
+                         'prefix|p=s',
                          'nocollapse|n',
                          'renumber-from|rf=i',
                          'renumber-tag|rt=i',
-                         'renumber-subfield|rs=i',
+                         'renumber-subfield|rs=s',
                          'original-tag|ot=i',
-                         'original-subfield|os=i',
+                         'original-subfield|os=s',
                          'script',
                          'strip-nines',
-                         'trash|t=s',
+                         'trashfile|t=s',
                          'trashhelp',
                          'help|h',
                        );
@@ -627,8 +669,10 @@ sub initialize {
     show_trashhelp() if ($c->{trashhelp});
 
     # defaults
-    $c->{output} = 'cleaned.incoming.marc.xml' unless defined $c->{output};
-    $c->{exception} = 'cleaned.exceptions.marc.xml' unless defined $c->{exception};
+    if ($c->{prefix}) {
+        $c->{output} = join('.',$c->{prefix},'marc','xml');
+        $c->{exception} = join('.',$c->{prefix},'marc','ex');
+    }
     $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
     $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
     $c->{window} = 5;
@@ -648,19 +692,21 @@ sub show_help {
 Usage is: marc-cleanup [OPTIONS] <filelist>
 Options
   --output     -o  Cleaned MARCXML output filename
-                   (default: cleaned.incoming.marc.xml)
   --exception  -x  Exception (dumped records) MARCXML filename
-                   (cleaned.exceptions.marc.xml)
-  --trash          File containing trash tag data (see --trashhelp)
+       or
+  --prefix=<PREFIX>>   -p  Shared prefix for output/exception files. Will
+                           produce PREFIX.marc.xml and PREFIX.ex.xml
+
+  --trashfile  -t  File containing trash tag data (see --trashhelp)
 
-  --renumber-from=NUM -rf  Begin renumbering id sequence with this number
+  --renumber-from     -rf  Begin renumbering id sequence with this number
   --renumber-tag      -rt  Tag to use in renumbering (default: 903)
   --renumber-subfield -rs  Subfield code to use in renumbering (default: a)
   --original-tag      -ot  Original id tag; will be kept in output even if
                            it appears in the trash file
   --original-subfield -os  Original id subfield code. If this is specified
                            and renumbering is in effect, an old-to-new mapping
-                           file (old2new.incoming.map) will be generated.
+                           file (old2new.map) will be generated.
 
   --nocollapse -n  Don't compress records to one line on output
   --autoscrub  -a  Automatically remove non-numeric tags in data