b4115409a7fcafcf32d832f1ad81e45309fa3cfd
[migration-tools.git] / extract_holdings
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4
5 use XML::Twig;
6 use YAML;
7 use JSON;
8
9 my $marcxml = shift || help();
10
11 open HOLDINGS, '>', "holdings";
12 open X, '>', "holdings.x";
13 open Z, '>', "holdings.z";
14 open ALL852, '>', "holdings.all852";
15
16 $| = 1;
17 my $holdings = {};
18 my $copyid = 0;
19 my $count = 0;
20 my %all852 = ( x => {}, z => {} ); # hash of all subfields in all 852s
21
22 my $t = XML::Twig->new( twig_handlers => { record => \&record } );
23 $t->parsefile($marcxml);
24 #print ALL852 to_json(\%all852);
25 print ALL852 Dump(%all852);
26
27 sub record {
28     my($t, $r)= @_;
29     $holdings = { copies => [] };
30
31     my @dfields = $r->children('datafield');
32     for my $d (@dfields) {
33         process_datafields($d) 
34     }
35
36     for my $copy (@{$holdings->{copies}})
37       { print_reports($copy) }
38     $r->purge;
39     $count++; print "\r$count";
40 }
41
42 sub process_datafields {
43     my ($d) = @_;
44     # get 903
45     if ($d->{'att'}->{'tag'} == 903) {
46         my $s = $d->first_child('subfield');
47         $holdings->{id} = $s->text;;
48     }
49
50     # and holdings data
51     if ($d->{'att'}->{'tag'} == 852) {
52         push @{$holdings->{copies}}, { x =>[], z => [] };
53         $holdings->{copies}[-1]{copyid} = $copyid;
54         my @subs = $d->children('subfield');
55         for my $s (@subs) 
56           { process_subs($s) }
57         $copyid++;
58     }
59 }
60
61 sub process_subs {
62     my ($s) = @_;
63     my $copy = $holdings->{copies}[-1];
64
65     my $code = $s->{'att'}->{'code'};
66     my $value = $s->text;
67
68     if ($code eq 'x' or $code eq 'z') {
69         push @{$copy->{$code}}, $value;
70         my ($k,$v) = split /:/, $value;
71         $all852{$code}{$k} = $v;
72     } else {        
73         $copy->{$code} = $value;
74         $all852{$code} = $value;
75     }
76 }
77
78 sub print_reports {
79     my ($copy) = @_;
80     my $note = 0;
81     for (@{$copy->{x}}) {
82         print X join("\t", $holdings->{id}, $copy->{copyid}, $note, $_), "\n";
83         $note++;
84     }
85     $note = 0;
86     for (@{$copy->{z}}) {
87         print Z join("\t", $holdings->{id}, $copy->{copyid}, $note, $_), "\n";
88         $note++;
89     }
90     print HOLDINGS join("\t", $holdings->{id}, $copy->{copyid},
91                         $copy->{b}, $copy->{p}, $copy->{h}, $copy->{9}), "\n";
92 }
93
94
95 sub help {
96     print <<HELP;
97 Usage is: extract_holdings MARCXML_FILE
98 HELP
99     exit;
100 }