11 my $term = new Term::ReadLine 'yaz-cleanup';
12 my $OUT = $term->OUT || \*STDOUT;
14 # initialization and setup
17 populate_trash() if ($conf->{trash});
19 my @record = (); # current record storage
20 my %recmeta = (); # metadata about current record
21 my $recptr = 0; # record index pointer
23 my $input = shift || 'incoming.marc.xml';
25 open MARC, '<:utf8', $input;
26 open my $NUMARC, '>:utf8', $conf->{output};
27 print $NUMARC '<?xml version="1.0" encoding="UTF-8"?>',"\n";
28 print $NUMARC '<collection xmlns="http://www.loc.gov/MARC21/slim">',"\n";
30 open my $EXMARC, '>:utf8', $conf->{exception};
32 # this is the dispatch table which drives command selection in
34 my %commands = ( c => \&print_context,
35 C => \&print_linecontext,
48 my @spinner = qw(- / | \\);
51 while ( buildrecord() ) {
52 print "\rWorking... ", $spinner[$sidx];
53 $sidx = ($sidx == $#spinner) ? 0 : $sidx + 1;
55 do_automated_cleanups();
58 until ($recptr == $#record) {
60 if ($record[$recptr] =~ /&/ && $record[$recptr] !~ /&\w+?;/)
61 { edit("Naked ampersand"); $recptr= 0; next }
63 # tags must be numeric
64 if ($record[$recptr] =~ /<datafield tag="(.+?)"/) {
67 edit("Non-numerics in tag");
73 # subfields can't be non-alphanumeric
74 if ($record[$recptr] =~ /<subfield code="(.*?)"/) {
76 if ($match =~ /\P{IsAlnum}/ or $match eq '') {
77 edit("Junk in subfield code/Null subfield code");
85 write_record($NUMARC);
87 print $NUMARC "</collection>\n";
88 print $OUT "\nDone. \n";
91 #-----------------------------------------------------------------------------------
93 #-----------------------------------------------------------------------------------
95 sub do_automated_cleanups {
97 until ($recptr == $#record) {
98 # catch empty datafield elements
99 if ($record[$recptr] =~ m|</datafield>|) {
100 if ($record[$recptr + 1] =~ m/<datafield tag="..." ind1="." ind2=".">/) {
101 my @a = @record[0, $recptr - 1];
102 my @b = @record[$recptr + 1, $#record];
104 message("Empty datafield scrubbed");
109 # and quasi-empty subfields
110 if ($record[$recptr] =~ m|<subfield code="\s*">\s*</sub|) {
111 delete $record[$recptr];
112 message("Empty subfield scrubbed");
120 for $recptr (0 .. $#record) {
122 if ($record[$recptr] =~ m|<leader>(.+?)</leader>|) {
124 if (length $leader < 24) {
125 $leader .= ' ' x (20 - length($leader));
127 $record[$recptr] = "<leader>$leader</leader>\n";
128 message("Short leader padded");
132 # clean misplaced dollarsigns
133 if ($record[$recptr] =~ m|<subfield code="\$">c?\d+\.\d{2}|) {
134 $record[$recptr] =~ s|"\$">c?(\d+\.\d{2})|"c">\$$1|;
135 message("Dollar sign corrected");
138 # clean up tags with spaces in them
139 $record[$recptr] =~ s/tag=" /tag="00/g;
140 $record[$recptr] =~ s/tag=" /tag="0/g;
141 $record[$recptr] =~ s/tag="-/tag="0/g;
142 $record[$recptr] =~ s/tag="(\d\d) /tag="0$1/g;
144 # stow tag data if we're looking at it
145 if ($record[$recptr] =~ m/<datafield tag="(.{3})" ind1="(.)" ind2="(.)">/) {
151 # automatable subfield maladies
152 $record[$recptr] =~ s/code=" ">c/code="c">/;
153 $record[$recptr] =~ s/code=" ">\$/code="c"$>/;
157 #-----------------------------------------------------------------------------------
159 #-----------------------------------------------------------------------------------
164 Handles the Term::ReadLine loop
170 my $trash = $conf->{trash};
172 return if $trash->{ $recmeta{tag} };
177 my $line = $term->readline('marc-cleanup>');
178 my @chunks = split /\s+/, $line;
180 if (length $chunks[0] == 1)
181 { next unless (defined $commands{$chunks[0]}) }
183 if (defined $commands{$chunks[0]}) {
184 my $term = $commands{$chunks[0]}->(@chunks[1..$#chunks]);
187 $record[$recptr] = "$line\n";
195 Constructs record arrays from the incoming MARC file and returns them
202 return $l unless defined $l;
204 $l = <MARC> until ($l =~ /<record>/);
209 until ($l =~ m|</record>|)
210 { push @record, $l; $l = <MARC>; }
217 my $trash = $conf->{trash};
219 $conf->{rocount}++ if ($FH eq $NUMARC);
220 print $FH '<!-- ', $recmeta{explanation}, " -->\n"
221 if(defined $recmeta{explanation});
223 # excise unwanted tags
224 if (keys %{$trash} or $conf->{autoscrub}) {
227 for my $line (@record) {
229 $istrash = 0 if $line =~ m|</datafield|;
232 if ($line =~ m/<datafield tag="(.{3})"/) {
234 if ($trash->{$tag} or ($conf->{autoscrub} and $tag =~ /\D/)) {
239 push @trimmed, $line;
245 unless ($conf->{nocollapse}) {
246 s/\n// for (@record);
249 # add 903(?) with new record id
251 if ($conf->{'renumber-from'}) {
252 $renumber = join('', '<datafield tag="', $conf->{'renumber-tag'},
253 '" ind1=" " ind2=" ">',
254 '<subfield code="', $conf->{'renumber-subfield'}, '">',
255 $conf->{'renumber-from'}, '</subfield></datafield>');
256 $renumber .= "\n" if $conf->{nocollapse};
257 push @record, $renumber;
258 $conf->{'renumber-from'}++;
262 print $FH "</record>\n";
267 print $OUT "\r", ' ' x 72, "\n";
268 print $OUT "$msg at ",$conf->{ricount},"/",$conf->{rocount} + 1,"\n";
272 #-----------------------------------------------------------------------------------
274 #-----------------------------------------------------------------------------------
277 my ($line_in, @chunks) = @_;
278 my $ofrom = shift @chunks;
279 if ($ofrom =~ /^'/ or !@chunks) {
280 until ($ofrom =~ /'$/)
281 { $ofrom .= join(' ','',shift @chunks) }
282 $ofrom =~ s/^'//; $ofrom =~ s/'$//;
284 my $to = shift @chunks;
286 until ($to =~ /'$/ or !@chunks)
287 { $to .= join(' ','',shift @chunks) }
288 $to =~ s/^'//; $to =~ s/'$//;
292 for my $char (split(//,$ofrom)) {
293 $char = "\\" . $char if ($char =~ /\W/);
294 $from = join('', $from, $char);
296 $record[$recptr] =~ s/$from/$to/;
302 $record[$recptr] =~ s/^\s*<subfield code=".*">//;
303 $record[$recptr - 1] =~ s|<subfield>\n||;
304 $record[$recptr - 1] = join('', $record[$recptr - 1], $record[$recptr]);
310 delete $record[$recptr];
316 my ($line_in, @explanation) = @_;
317 $recmeta{explanation} = join(' ', 'Tag', $recmeta{tag}, @explanation);
318 write_record($EXMARC);
322 sub commit_edit { return 1 }
325 print " Tag:",$recmeta{tag}, " Ind1:'",
326 $recmeta{ind1},"' Ind2:'", $recmeta{ind2}, "'";
331 sub print_linecontext {
332 print $OUT "\n", join(' |','',@context[0..2]);
333 print $OUT '==> |', $context[3];
334 print $OUT ' |', $context[4],"\n";
340 print $OUT "\n$line_in\n";
347 Type a replacement for the indicated line, or enter a command.
349 Commands: c Show record context ('C' for brief context)
350 k Kill indicated line (remove from record)
351 m Merge indicated line with previous line
353 s Substitute ARG1 for ARG2 in indicated line
354 t Commit changes and resume stream edit
355 x Write this record to the exception file instead of output
364 #-----------------------------------------------------------------------------------
366 #-----------------------------------------------------------------------------------
367 # defined a domain-specific language for specifying MARC tags to be dropped from
368 # records during processing. it is line oriented, and is specified as follows:
370 # each line may specify any number of tags to be included, either singly (\d{1,3})
371 # or as a range (\d{1,3}\.\.\d{1,3}
373 # if a single number is given, it must be between '000' and '999', inclusive.
375 # ranges obey the previous rule, and also the first number of the range must be less
376 # than the second number
378 # finally, any single range in a line may be followed by the keyword 'except'. every
379 # number or range after 'except' is excluded from the range specified. all these
380 # numbers must actually be within the range.
382 # specifying a tag twice is an error, to help prevent typos
385 print $OUT ">>> TRASHTAGS FILE FOUND. LOADING TAGS TO BE STRIPPED FROM OUTPUT\n";
386 open TRASH, '<', $conf->{trash}
387 or die "Can't open trash tags file!\n";
389 my $lastwasrange = 0;
390 my %lastrange = ( high => 0, low => 0);
393 my @chunks = split /\s+/;
394 while (my $chunk = shift @chunks) {
397 if ($chunk =~ /^\d{1,3}$/) {
398 trash_add($chunk, $except);
404 if ($chunk =~ /^\d{1,3}\.\.\d{1,3}$/) {
405 my ($low, $high) = trash_add_range($chunk, $except, \%lastrange);
407 %lastrange = (low => $low, high => $high)
413 if ($chunk eq 'except') {
414 die "Keyword 'except' can only follow a range (line $.)\n"
415 unless $lastwasrange;
416 die "Keyword 'except' may only occur once per line (line $.)\n"
422 die "Unknown chunk $chunk in .trashtags file (line $.)\n";
426 # remove original id sequence tag from trash hash if we know it
427 trash_add($conf->{'original-tag'}, 1)
428 if ($conf->{'original-tag'} and $trash{$conf->{'original-tag'}});
431 sub trash_add_range {
432 my ($chunk, $except, $range) = @_;
433 my ($low,$high) = split /\.\./, $chunk;
434 die "Ranges must be 'low..high' ($low is greater than $high on line $.)\n"
437 die "Exception ranges must be within last addition range (line $.)\n"
438 if ($low < $range->{low} or $high > $range->{high});
440 for my $tag ($low..$high) {
441 trash_add($tag, $except)
447 my ($tag, $except) = @_;
448 my $trash = $conf->{trash}
450 die "Trash values must be valid tags (000-999)\n"
451 unless ($tag >= 0 and $tag <= 999);
454 delete $trash->{$tag};
456 die "Trash tag '$tag' specified twice (line $.)\n"
462 #-----------------------------------------------------------------------
466 Performs boring script initialization. Handles argument parsing,
475 # set mode on existing filehandles
476 binmode(STDIN, ':utf8');
478 my $rc = GetOptions( $c,
483 'renumber-from|rf=i',
486 'renumber-subfield|rt=i',
490 show_help() unless $rc;
491 show_help() if ($c->{help});
494 $c->{output} = 'incoming.cleaned.marc.xml' unless defined $c->{output};
495 $c->{exception} = 'incoming.exception.marc.xml' unless defined $c->{exception};
496 $c->{'renumber-tag'} = 903 unless defined $c->{'renumber-tag'};
497 $c->{'renumber-subfield'} = 'a' unless defined $c->{'renumber-subfield'};
499 my @keys = keys %{$c};
500 show_help() unless (@ARGV and @keys);
501 #for my $key ('runtype', 'tag', 'subfield', 'output', 'exception')
502 # { push @missing, $key unless $c->{$key} }
504 # print "Required option: ", join(', ', @missing), " missing!\n";
511 Usage is: $0 [OPTIONS] <filelist>
513 --output -o Cleaned MARCXML output filename (default: incoming.cleaned.marc.xml)
514 --exception -x Exception (dumped records) MARCXML filename (incoming.exception.marc.xml)