]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Utils/MFHD/Caption.pm
Beginning of code to calcuate dates based on publication patterns.
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Utils / MFHD / Caption.pm
1 package MFHD::Caption;
2 use strict;
3 use integer;
4 use Carp;
5
6 use Data::Dumper;
7
8 use DateTime;
9
10 use base 'MARC::Field';
11
12 sub new
13 {
14     my $proto = shift;
15     my $class = ref($proto) || $proto;
16     my $self = shift;
17     my $last_enum = undef;
18
19     $self->{_mfhdc_ENUMS} = {};
20     $self->{_mfhdc_CHRONS} = {};
21     $self->{_mfhdc_PATTERN} = {};
22     $self->{_mfhdc_COPY} = undef;
23     $self->{_mfhdc_UNIT} = undef;
24     $self->{_mfhdc_COMPRESSIBLE} = 1;   # until proven otherwise
25
26     foreach my $subfield ($self->subfields) {
27         my ($key, $val) = @$subfield;
28         if ($key eq '8') {
29             $self->{LINK} = $val;
30         } elsif ($key =~ /[a-h]/) {
31             # Enumeration Captions
32             $self->{_mfhdc_ENUMS}->{$key} = {CAPTION => $val,
33                                              COUNT => undef,
34                                              RESTART => undef};
35             if ($key =~ /[ag]/) {
36                 $last_enum = undef;
37             } else {
38                 $last_enum = $key;
39             }
40         } elsif ($key =~ /[i-m]/) {
41             # Chronology captions
42             $self->{_mfhdc_CHRONS}->{$key} = $val;
43         } elsif ($key eq 'u') {
44             # Bib units per next higher enumeration level
45             carp('$u specified for top-level enumeration')
46               unless defined($last_enum);
47             $self->{_mfhdc_ENUMS}->{$last_enum}->{COUNT} = $val;
48         } elsif ($key eq 'v') {
49             carp '$v specified for top-level enumeration'
50               unless defined($last_enum);
51             $self->{_mfhdc_ENUMS}->{$last_enum}->{RESTART} = ($val eq 'r');
52         } elsif ($key =~ /[npwz]/) {
53             # Publication Pattern info ('o' == type of unit, 'q'..'t' undefined)
54             $self->{_mfhdc_PATTERN}->{$key} = $val;
55         } elsif ($key =~ /x/) {
56             # Calendar change can have multiple comma-separated values
57             $self->{_mfhdc_PATTERN}->{x} = [split /,/, $val];
58         } elsif ($key eq 'y') {
59             $self->{_mfhdc_PATTERN}->{y} = {}
60               unless exists $self->{_mfhdc_PATTERN}->{y};
61             update_pattern($self, $val);
62         } elsif ($key eq 'o') {
63             # Type of unit
64             $self->{_mfhdc_UNIT} = $val;
65         } elsif ($key eq 't') {
66             $self->{_mfhdc_COPY} = $val;
67         } else {
68             carp "Unknown caption subfield '$key'";
69         }
70     }
71
72     # subsequent levels of enumeration (primary and alternate)
73     # If an enumeration level doesn't document the number
74     # of "issues" per "volume", or whether numbering of issues
75     # restarts, then we can't compress.
76     foreach my $key ('b', 'c', 'd', 'e', 'f', 'h') {
77         if (exists $self->{_mfhdc_ENUMS}->{$key}) {
78             my $pattern = $self->{_mfhdc_ENUMS}->{$key};
79             if (!$pattern->{RESTART} || !$pattern->{COUNT}
80                 || ($pattern->{COUNT} eq 'var')
81                 || ($pattern->{COUNT} eq 'und')) {
82                 $self->{_mfhdc_COMPRESSIBLE} = 0;
83                 last;
84             }
85         }
86     }
87
88     my $pat = $self->{_mfhdc_PATTERN};
89
90     # Sanity check publication frequency vs publication pattern:
91     # if the frequency is a number, then the pattern better
92     # have that number of values associated with it.
93     if (exists($pat->{w}) && ($pat->{w} =~ /^\d+$/)
94         && ($pat->{w} != scalar(@{$pat->{y}->{p}}))) {
95         carp("Caption::new: publication frequency '$pat->{w}' != publication pattern @{$pat->{y}->{p}}");
96     }
97
98
99     # If there's a $x subfield and a $j, then it's compressible
100     if (exists $pat->{x} && exists $self->{_mfhdc_CHRONS}->{'j'}) {
101         $self->{_mfhdc_COMPRESSIBLE} = 1;
102     }
103
104     bless ($self, $class);
105
106     return $self;
107 }
108
109 sub update_pattern {
110     my $self = shift;
111     my $val = shift;
112     my $pathash = $self->{_mfhdc_PATTERN}->{y};
113     my ($pubcode, $pat) = unpack("a1a*", $val);
114
115     $pathash->{$pubcode} = [] unless exists $pathash->{$pubcode};
116     push @{$pathash->{$pubcode}}, $pat;
117 }
118
119 sub decode_pattern {
120     my $self = shift;
121     my $pattern = $self->{_mfhdc_PATTERN}->{y};
122
123     # XXX WRITE ME (?)
124 }
125
126 sub compressible {
127     my $self = shift;
128
129     return $self->{_mfhdc_COMPRESSIBLE};
130 }
131
132 sub chrons {
133     my $self = shift;
134     my $key = shift;
135
136     if (exists $self->{_mfhdc_CHRONS}->{$key}) {
137         return $self->{_mfhdc_CHRONS}->{$key};
138     } else {
139         return undef;
140     }
141 }
142
143 sub capfield {
144     my $self = shift;
145     my $key = shift;
146
147     if (exists $self->{_mfhdc_ENUMS}->{$key}) {
148         return $self->{_mfhdc_ENUMS}->{$key};
149     } elsif (exists $self->{_mfhdc_CHRONS}->{$key}) {
150         return $self->{_mfhdc_CHRONS}->{$key};
151     } else {
152         return undef;
153     }
154 }
155
156 sub capstr {
157     my $self = shift;
158     my $key = shift;
159     my $val = $self->capfield($key);
160
161     if (ref $val) {
162         return $val->{CAPTION};
163     } else {
164         return $val;
165     }
166 }
167
168 sub calendar_change {
169     my $self = shift;
170
171     return $self->{_mfhdc_PATTERN}->{x};
172 }
173
174 # If items are identified by chronology only, with no separate
175 # enumeration (eg, a newspaper issue), then the chronology is
176 # recorded in the enumeration subfields $a - $f.  We can tell
177 # that this is the case if there are $a - $f subfields and no
178 # chronology subfields ($i-$k), and none of the $a-$f subfields
179 # have associated $u or $v subfields, but there's a $w and no $x
180
181 sub enumeration_is_chronology {
182     my $self = shift;
183
184     # There is always a '$a' subfield in well-formed fields.
185     return 0 if exists $self->{_mfhdc_CHRONS}->{i}
186       || exists $self->{_mfhdc_PATTERN}->{x};
187
188     foreach my $key ('a' .. 'f') {
189         my $enum;
190
191         last if !exists $self->{_mfhdc_ENUMS}->{$key};
192
193         $enum = $self->{_mfhdc_ENUMS}->{$key};
194         return 0 if defined $enum->{COUNT} || defined $enum->{RESTART};
195     }
196
197     return (exists $self->{_mfhdc_PATTERN}->{w});
198 }
199
200 my %daynames = (
201                 'mo' => 1,
202                 'tu' => 2,
203                 'we' => 3,
204                 'th' => 4,
205                 'fr' => 5,
206                 'sa' => 6,
207                 'su' => 7,
208                );
209
210 my $daypat = '(mo|tu|we|th|fr|sa|su)';
211 my $weekpat = '(99|98|97|00|01|02|03|04|05)';
212 my $weeknopat;
213 my $monthpat = '(01|02|03|04|05|06|07|08|09|10|11|12)';
214 my $seasonpat = '(21|22|23|24)';
215
216 # Initialize $weeknopat to be '(01|02|03|...|51|52|53)'
217 $weeknopat = '(';
218 foreach my $weekno (1..52) {
219     $weeknopat .= sprintf('%02d|', $weekno);
220 }
221 $weeknopat .= '53)';
222
223 sub match_day {
224     my $pat = shift;
225     my @date = @_;
226     # Translate daynames into day of week for DateTime
227     # also used to check if dayname is valid.
228
229     if (exists $daynames{$pat}) {
230         # dd
231         # figure out day of week for date and compare
232         my $dt = DateTime->new(year  => $date[0],
233                                month => $date[1],
234                                day   => $date[2]);
235         return ($dt->day_of_week == $daynames{$pat});
236     } elsif (length($pat) == 2) {
237         # DD
238         return $pat == $date[2];
239     } elsif (length($pat) == 4) {
240         # MMDD
241         my ($mon, $day) = unpack("a2a2", $pat);
242
243         return (($mon == $date[1]) && ($day == $date[2]));
244     } else {
245         carp "Invalid day pattern '$pat'";
246         return 0;
247     }
248 }
249
250 sub subsequent_day {
251     my $pat = shift;
252     my $cur = shift;
253     my $dt = DateTime->new(year  => $cur->[0],
254                            month => $cur->[1],
255                            day   => $cur->[2]);
256
257     if (exists $daynames{$pat}) {
258         # dd: published on the given weekday
259         my $dow = $dt->day_of_week;
260         my $corr = ($dow - $daynames{$pat} + 7) % 7;
261
262         if ($dow == $daynames{$pat}) {
263             # the next one is one week hence
264             $dt->add(days => 7);
265         } else {
266             # the next one is later this week,
267             # or it is next week (ie, on or after next Monday)
268             # $corr will take care of it.
269             $dt->add(days => $corr);
270         }
271     } elsif (length($pat) == 2) {
272         # DD: published on the give day of every month
273         if ($dt->day >= $pat) {
274             # current date is on or after $pat: next one is next month
275             $dt->set(day => $pat);
276             $dt->add(months => 1);
277             $cur->[0] = $dt->year;
278             $cur->[1] = $dt->month;
279             $cur->[2] = $dt->day;
280         }
281         # current date is before $pat: set month to pattern
282         # or we've adjusted the year to next year, now fix the month
283         $cur->[1] = $pat;
284     } elsif (length($pat) == 4) {
285         # MMDD: published on the given day of the given month
286         my ($mon, $day) = unpack("a2a2", $pat);
287
288         if (on_or_after($mon, $day, $cur->[1], $cur->[2])) {
289             # Current date is on or after pattern; next one is next year
290             $cur->[0] += 1;
291         }
292         # Year is now right. Either it's next year (because of on_or_before)
293         # or it's this year, because the current date is NOT on or after
294         # the pattern. Just fix the month and day
295         $cur->[1] = $mon;
296         $cur->[2] = $day;
297     } else {
298         carp "Invalid day pattern '$pat'";
299         return undef;
300     }
301
302     return $cur;
303 }
304
305
306 # Calculate date of 3rd Friday of the month (for example)
307 # 1-5: count from beginning of month
308 # 99-97: count back from end of month
309 sub nth_week_of_month {
310     my $dt = shift;
311     my $week = shift;
312     my $day = shift;
313     my ($nth_day, $dow, $day);
314
315     $day = $daynames{$day};
316
317     if (0 < $week && $week <= 5) {
318         $nth_day = DateTime->clone($dt)->set(day => 1);
319     } elsif ($week >= 97) {
320         $nth_day = DateTime->last_day_of_month(year  => $dt->year,
321                                                month => $dt->month);
322     } else {
323         return undef;
324     }
325
326     $dow = $nth_day->day_of_week();
327
328     if ($week <= 5) {
329         # count forwards
330         $nth_day->add(days => ($day - $dow + 7) % 7,
331                       weeks=> $week - 1);
332     } else {
333         # count backwards
334         $nth_day->subtract(days => ($day - $nth_day->day_of_week + 7) % 7);
335
336         # 99: last week of month, 98: second last, etc.
337         for (my $i = 99 - $week; $i > 0; $i--) {
338             $nth_day->subtract(weeks => 1);
339         }
340     }
341
342     # There is no nth "day" in the month!
343     return undef if ($dt->month != $nth_day->month);
344
345     return $nth_day;
346 }
347
348 #
349 # Internal utility function to match the various different patterns
350 # of month, week, and day
351 #
352 sub check_date {
353     my $dt = shift;
354     my $month = shift;
355     my $weekno = shift;
356     my $day = shift;
357
358     if (!defined $day) {
359         # MMWW
360         return (($dt->month == $month)
361                 && (($dt->week_of_month == $weekno)
362                     || ($weekno >= 97
363                         && ($dt->week_of_month == nth_week_of_month($dt, $weekno, $day)->week_of_month))));
364     }
365
366     # simple cases first
367     if ($daynames{$day} != $dt->day_of_week) {
368         # if it's the wrong day of the week, rest doesn't matter
369         return 0;
370     }
371
372     if (!defined $month) {
373         # WWdd
374         return (($weekno == 0)  # Every week
375                 || ($dt->weekday_of_month == $weekno) # this week
376                 || (($weekno >= 97) && ($dt->weekday_of_month == nth_week_of_month($dt, $weekno, $day)->weekday_of_month)));
377     }
378
379     # MMWWdd
380     if ($month != $dt->month) {
381         # If it's the wrong month, then we're done
382         return 0;
383     }
384
385     # It's the right day of the week
386     # It's the right month
387
388     if (($weekno == 0) ||($weekno == $dt->weekday_of_month)) {
389         # If this matches, then we're counting from the beginning
390         # of the month and it matches and we're done.
391         return 1;
392     }
393
394     # only case left is that the week number is counting from
395     # the end of the month: eg, second last wednesday
396     return (($weekno >= 97)
397             && (nth_week_of_month($dt, $weekno, $day)->weekday_of_month == $dt->weekday_of_month));
398 }
399
400 sub match_week {
401     my $pat = shift;
402     my @date = @_;
403     my $dt = DateTime->new(year  => $date[0],
404                            month => $date[1],
405                            day   => $date[2]);
406
407     if ($pat =~ m/^$weekpat$daypat$/) {
408         # WWdd: 03we = Third Wednesday
409         return check_date($dt, undef, $1, $2);
410     } elsif ($pat =~ m/^$monthpat$weekpat$daypat$/) {
411         # MMWWdd: 0599tu Last Tuesday in May XXX WRITE ME
412         return check_date($dt, $1, $2, $3);
413     } elsif ($pat =~ m/^$monthpat$weekpat$/) {
414         # MMWW: 1204: Fourth week in December XXX WRITE ME
415         return check_date($dt, $1, $2, undef);
416     } else {
417         carp "invalid week pattern '$pat'";
418         return 0;
419     }
420 }
421
422 #
423 # Use $pat to calcuate the date of the issue following $cur
424 #
425 sub subsequent_week {
426     my $pat = shift;
427     my $cur = shift;
428     my $candidate;
429     my $dt = DateTime->new(year => $cur->[0],
430                            month=> $cur->[1],
431                            day  => $cur->[2]);
432
433     if ($pat =~ m/^$weekpat$daypat$/) {
434         # WWdd: published on given weekday of given week of every month
435         my ($week, $day) = ($1, $2);
436
437         if ($week eq '00') {
438             # Every week
439             $candidate = DateTime->clone($dt);
440             if ($dt->day_of_week == $daynames{$day}) {
441                 # Current is right day, next one is a week hence
442                 $candidate->add(days => 7);
443             } else {
444                 $candidate->add(days => ($dt->day_of_week - $daynames{$day} + 7) % 7);
445             }
446         } else {
447             # 3rd Friday of the month (eg)
448             $candidate = nth_week_of_month($dt, $week, $day);
449         }
450
451         if ($candidate < $dt) {
452             # If the n'th week of the month happens before the
453             # current issue, then the next issue is published next
454             # month, otherwise, it's published this month.
455             # This will never happen for the "00: every week" pattern
456             $candidate = DateTime->clone($dt)->add(months => 1)->set(day => 1);
457             $candidate = nth_week_of_month($dt, $week, $day);
458         }
459     } elsif ($pat =~ m/^$monthpat$weekpat$daypat$/) {
460         # MMWWdd: published on given weekday of given week of given month
461         my ($month, $week, $day) = ($1, $2, $3);
462
463         $candidate = DateTime->new(year => $dt->year,
464                                    month=> $month,
465                                    day  => 1);
466         $candidate = nth_week_of_month($candidate, $week, $day);
467         if ($candidate < $dt) {
468             # We've missed it for this year, next one that matches
469             # will be next year
470             $candidate->add(years => 1)->set(day => 1);
471             $candidate = nth_week_of_month($candidate, $week, $day);
472         }
473     } elsif ($pat =~ m/^$monthpat$weekpat$/) {
474         # MMWW: published during given week of given month
475         my ($month, $week) = ($1, $2);
476
477         $candidate = nth_week_of_month(DateTime->new(year => $dt->year,
478                                                      month=> $month,
479                                                      day  => 1),
480                                        $week,
481                                        'th');
482         if ($candidate < $dt) {
483             # Already past the pattern date this year, move to next year
484             $candidate->add(years => 1)->set(day => 1);
485             $candidate = nth_week_of_month($candidate, $week, 'th');
486         }
487     } else {
488         carp "invalid week pattern '$pat'";
489         return undef;
490     }
491
492     $cur->[0] = $candidate->year;
493     $cur->[1] = $candidate->month;
494     $cur->[2] = $candidate->day;
495
496     return $cur;
497 }
498
499 sub match_month {
500     my $pat = shift;
501     my @date = @_;
502
503     return ($pat eq $date[1]);
504 }
505
506 sub match_season {
507     my $pat = shift;
508     my @date = @_;
509
510     return ($pat eq $date[1]);
511 }
512
513 sub match_year {
514     my $pat = shift;
515     my @date = @_;
516
517     # XXX WRITE ME
518     return 0;
519 }
520
521 sub match_issue {
522     my $pat = shift;
523     my @date = @_;
524
525     # We handle enumeration patterns separately. This just
526     # ensures that when we're processing chronological patterns
527     # we don't match an enumeration pattern.
528     return 0;
529 }
530
531 my %dispatch = (
532                 'd' => \&match_day,
533                 'e' => \&match_issue, # not really a "chron" code
534                 'w' => \&match_week,
535                 'm' => \&match_month,
536                 's' => \&match_season,
537                 'y' => \&match_year,
538 );
539
540 sub regularity_match {
541     my $self = shift;
542     my $pubcode = shift;
543     my @date = @_;
544
545     # we can't match something that doesn't exist.
546     return 0 if !exists $self->{_mfhdc_PATTERN}->{y}->{$pubcode};
547
548     foreach my $regularity (@{$self->{_mfhdc_PATTERN}->{y}->{$pubcode}}) {
549         my $chroncode= substr($regularity, 0, 1);
550         my @pats = split(/,/, substr($regularity, 1));
551
552         if (!exists $dispatch{$chroncode}) {
553             carp "Unrecognized chroncode '$chroncode'";
554             return 0;
555         }
556
557         # XXX WRITE ME
558         foreach my $pat (@pats) {
559             $pat =~ s|/.+||;    # If it's a combined date, match the start
560             if ($dispatch{$chroncode}->($pat, @date)) {
561                 return 1;
562             }
563         }
564     }
565
566     return 0;
567 }
568
569 sub is_omitted {
570     my $self = shift;
571     my @date = @_;
572
573     return $self->regularity_match('o', @date);
574 }
575
576 sub is_published {
577     my $self = shift;
578     my @date = @_;
579
580     return $self->regularity_match('p', @date);
581 }
582
583 sub is_combined {
584     my $self = shift;
585     my @date = @_;
586
587     return $self->regularity_match('c', @date);
588 }
589
590 sub enum_is_combined {
591     my $self = shift;
592     my $subfield = shift;
593     my $iss = shift;
594     my $level = ord($subfield) - ord('a') + 1;
595
596     return 0 if !exists $self->{_mfhdc_PATTERN}->{y}->{c};
597
598     foreach my $regularity (@{$self->{_mfhdc_PATTERN}->{y}->{c}}) {
599         next unless $regularity =~ m/^e$level/o;
600
601         my @pats = split(/,/, substr($regularity, 2));
602
603         foreach my $pat (@pats) {
604             $pat =~ s|/.+||;    # if it's a combined issue, match the start
605             return 1 if ($iss eq $pat);
606         }
607     }
608
609     return 0;
610 }
611
612
613 my %increments = (
614                   a => {years => 1}, # annual
615                   b => {months => 2}, # bimonthly
616                   c => {days => 3}, # semiweekly
617                   d => {days => 1}, # daily
618                   e => {weeks => 2}, # biweekly
619                   f => {months => 6}, # semiannual
620                   g => {years => 2},  # biennial
621                   h => {years => 3},  # triennial
622                   i => {days => 2}, # three times / week
623                   j => {days => 10}, # three times /month
624                   # k => continuous
625                   m => {months => 1}, # monthly
626                   q => {months => 3}, # quarterly
627                   s => {days => 15},  # semimonthly
628                   t => {months => 4}, # three times / year
629                   w => {weeks => 1},  # weekly
630                   # x => completely irregular
631 );
632
633 sub incr_date {
634     my $incr = shift;
635     my @new = @_;
636
637     if (scalar(@new) == 1) {
638         # only a year is specified. Next date is easy
639         $new[0] += $incr->{years} || 1;
640     } elsif (scalar(@new) == 2) {
641         # Year and month or season
642         if ($new[1] > 20) {
643             # season
644             $new[1] += ($incr->{months}/3) || 1;
645             if ($new[1] > 24) {
646                 # carry
647                 $new[0] += 1;
648                 $new[1] -= 4;   # 25 - 4 == 21 == Spring after Winter
649             }
650         } else {
651             # month
652             $new[1] += $incr->{months} || 1;
653             if ($new[1] > 12) {
654                 # carry
655                 $new[0] += 1;
656                 $new[1] -= 12;
657             }
658             $new[1] = '0' . $new[1] if ($new[1] < 10);
659         }
660     } elsif (scalar(@new) == 3) {
661         # Year, Month, Day: now it gets complicated.
662
663         if ($new[2] =~ /^[0-9]+$/) {
664             # A single number for the day of month, relatively simple
665             my $dt = DateTime->new(year => $new[0],
666                                    month=> $new[1],
667                                    day  => $new[2]);
668             $dt->add(%{$incr});
669             $new[0] = $dt->year;
670             $new[1] = $dt->month;
671             $new[2] = $dt->day;
672         }
673         $new[1] = '0' . $new[1] if ($new[1] < 10);
674         $new[2] = '0' . $new[2] if ($new[2] < 10);
675     } else {
676         warn("Don't know how to cope with @new");
677     }
678
679     return @new;
680 }
681
682 # Test to see if $m1/$d1 is on or after $m2/$d2
683 # if $d2 is undefined, test is based on just months
684 sub on_or_after {
685     my ($m1, $d1, $m2, $d2) = @_;
686
687     return (($m1 > $m2)
688             || ($m1 == $m2 && ((!defined $d2) || ($d1 >= $d2))));
689 }
690
691 sub calendar_increment {
692     my $self = shift;
693     my $cur = shift;
694     my @new = @_;
695     my $cal_change = $self->calendar_change;
696     my $month;
697     my $day;
698     my $cur_before;
699     my $new_on_or_after;
700
701     # A calendar change is defined, need to check if it applies
702     if ((scalar(@new) == 2 && $new[1] > 20) || (scalar(@new) == 1)) {
703         carp "Can't calculate date change for ", $self->as_string;
704         return;
705     }
706
707     foreach my $change (@{$cal_change}) {
708         my $incr;
709
710         if (length($change) == 2) {
711             $month = $change;
712         } elsif (length($change) == 4) {
713             ($month, $day) = unpack("a2a2", $change);
714         }
715
716         if ($cur->[0] == $new[0]) {
717             # Same year, so a 'simple' month/day comparison will be fine
718             $incr = (!on_or_after($cur->[1], $cur->[2], $month, $day)
719                      && on_or_after($new[1], $new[2], $month, $day));
720         } else {
721             # @cur is in the year before @new. There are
722             # two possible cases for the calendar change date that
723             # indicate that it's time to change the volume:
724             # (1) the change date is AFTER @cur in the year, or
725             # (2) the change date is BEFORE @new in the year.
726             # 
727             #  -------|------|------X------|------|
728             #       @cur    (1)   Jan 1   (2)   @new
729
730             $incr = (on_or_after($new[1], $new[2], $month, $day)
731                      || !on_or_after($cur->[1], $cur->[2], $month, $day));
732         }
733         return $incr if $incr;
734     }
735 }
736
737 sub next_date {
738     my $self = shift;
739     my $next = shift;
740     my $carry = shift;
741     my @keys = @_;
742     my @cur;
743     my @new;
744     my $incr;
745     my @candidate;
746
747     my $reg = $self->{_mfhdc_REGULARITY};
748     my $pattern = $self->{_mfhdc_PATTERN};
749     my $freq = $pattern->{w};
750
751     foreach my $i (0..$#keys) {
752         $new[$i] = $cur[$i] = $next->{$keys[$i]} if exists $next->{$keys[$i]};
753     }
754
755     # If the current issue has a combined date (eg, May/June)
756     # get rid of the first date and base the calculation
757     # on the final date in the combined issue.
758     $new[-1] =~ s|^[^/]+/||;
759
760     # XXX Insert new date generation code in here that uses publication
761     # patterns.
762
763 ###
764 ### Old code: only works for simple cases
765 ###
766     # If $frequency is not one of the standard codes defined in %increments
767     # then there has to be a $yp publication regularity pattern that
768     # lists the dates of publication. Use that that list to find the next
769     # date following the current one.
770     # XXX: the code doesn't handle this case yet.
771     if (!defined($freq)) {
772         carp "Undefined frequency in next_date!";
773     } elsif (!exists $increments{$freq}) {
774         carp "Don't know how to deal with frequency '$freq'!";
775     } else {
776         #
777         # One of the standard defined issue frequencies
778         #
779         @new = incr_date($increments{$freq}, @new);
780
781         while ($self->is_omitted(@new)) {
782             @new = incr_date($increments{$freq}, @new);
783         }
784
785         if ($self->is_combined(@new)) {
786             my @second_date = incr_date($increments{$freq}, @new);
787
788             # I am cheating: This code assumes that only the smallest
789             # time increment is combined. So, no "Apr 15/May 1" allowed.
790             $new[-1] = $new[-1] . '/' . $second_date[-1];
791         }
792     }
793
794     for my $i (0..$#new) {
795         $next->{$keys[$i]} = $new[$i];
796     }
797
798     # Figure out if we need to adust volume number
799     # right now just use the $carry that was passed in.
800     # in long run, need to base this on ($carry or date_change)
801     if ($carry) {
802         # if $carry is set, the date doesn't matter: we're not
803         # going to increment the v. number twice at year-change.
804         $next->{a} += $carry;
805     } elsif (defined $pattern->{x}) {
806         $next->{a} += $self->calendar_increment(\@cur, @new);
807     }
808 }
809
810 sub next_alt_enum {
811     my $self = shift;
812     my $next = shift;
813
814     # First handle any "alternative enumeration", since they're
815     # a lot simpler, and don't depend on the the calendar
816     foreach my $key ('h', 'g') {
817         next if !exists $next->{$key};
818         if (!$self->capstr($key)) {
819             warn "Holding data exists for $key, but no caption specified";
820             $next->{$key} += 1;
821             last;
822         }
823
824         my $cap = $self->capfield($key);
825         if ($cap->{RESTART} && $cap->{COUNT}
826             && ($next->{$key} == $cap->{COUNT})) {
827             $next->{$key} = 1;
828         } else {
829             $next->{$key} += 1;
830             last;
831         }
832     }
833 }
834
835 sub next_enum {
836     my $self = shift;
837     my $next = shift;
838     my $carry;
839
840     # $carry keeps track of whether we need to carry into the next
841     # higher level of enumeration. It's not actually necessary except
842     # for when the loop ends: if we need to carry from $b into $a
843     # then $carry will be set when the loop ends.
844     #
845     # We need to keep track of this because there are two different
846     # reasons why we might increment the highest level of enumeration ($a)
847     # 1) we hit the correct number of items in $b (ie, 5th iss of quarterly)
848     # 2) it's the right time of the year.
849     #
850     $carry = 0;
851     foreach my $key (reverse('b'..'f')) {
852         next if !exists $next->{$key};
853
854         if (!$self->capstr($key)) {
855             # Just assume that it increments continuously and give up
856             warn "Holding data exists for $key, but no caption specified";
857             $next->{$key} += 1;
858             $carry = 0;
859             last;
860         }
861
862         # If the current issue has a combined issue number (eg, 2/3)
863         # get rid of the first issue number and base the calculation
864         # on the final issue number in the combined issue.
865         if ($next->{$key} =~ m|/|) {
866             $next->{$key} =~ s|^[^/]+/||;
867         }
868
869         my $cap = $self->capfield($key);
870         if ($cap->{RESTART} && $cap->{COUNT}
871             && ($next->{$key} eq $cap->{COUNT})) {
872             $next->{$key} = 1;
873             $carry = 1;
874         } else {
875             # If I don't need to "carry" beyond here, then I just increment
876             # this level of the enumeration and stop looping, since the
877             # "next" hash has been initialized with the current values
878
879             $next->{$key} += 1;
880             $carry = 0;
881         }
882
883         # You can't have a combined issue that spans two volumes: no.12/1
884         # is forbidden
885         if ($self->enum_is_combined($key, $next->{$key})) {
886             $next->{$key} .= '/' . ($next->{$key} + 1);
887         }
888
889         last if !$carry;
890     }
891
892     # The easy part is done. There are two things left to do:
893     # 1) Calculate the date of the next issue, if necessary
894     # 2) Increment the highest level of enumeration (either by date
895     #    or because $carry is set because of the above loop
896
897     if (!$self->subfield('i')) {
898         # The simple case: if there is no chronology specified
899         # then just check $carry and return
900         $next->{'a'} += $carry;
901     } else {
902         # Figure out date of next issue, then decide if we need
903         # to adjust top level enumeration based on that
904         $self->next_date($next, $carry, ('i'..'m'));
905     }
906 }
907
908 sub next {
909     my $self = shift;
910     my $holding = shift;
911     my $next = {};
912
913     # Initialize $next with current enumeration & chronology, then
914     # we can just operate on $next, based on the contents of the caption
915
916     if ($self->enumeration_is_chronology) {
917         foreach my $key ('a' .. 'h') {
918             $next->{$key} = $holding->{_mfhdh_SUBFIELDS}->{$key}
919               if defined $holding->{_mfhdh_SUBFIELDS}->{$key};
920         }
921         $self->next_date($next, 0, ('a' .. 'h'));
922
923         return $next;
924     }
925
926     foreach my $key ('a' .. 'h') {
927         $next->{$key} = $holding->{_mfhdh_SUBFIELDS}->{$key}->{HOLDINGS}
928           if defined $holding->{_mfhdh_SUBFIELDS}->{$key};
929     }
930
931     foreach my $key ('i'..'m') {
932         $next->{$key} = $holding->{_mfhdh_SUBFIELDS}->{$key}
933           if defined $holding->{_mfhdh_SUBFIELDS}->{$key};
934     }
935
936     if (exists $next->{'h'}) {
937         $self->next_alt_enum($next);
938     }
939
940     $self->next_enum($next);
941
942     return($next);
943 }
944
945 1;