capture warnings in a variable if asked
[scpubgit/stemmatology.git] / base / lib / Text / Tradition / Parser / CTE.pm
1 package Text::Tradition::Parser::CTE;
2
3 use strict;
4 use warnings;
5 use feature 'say';
6 use Encode qw/ decode /;
7 use Text::Tradition::Error;
8 use Text::Tradition::Parser::Util qw/ collate_variants /;
9 use XML::LibXML;
10 use XML::LibXML::XPathContext;
11 use TryCatch;
12
13 binmode( STDERR, ':utf8' );
14
15 =head1 NAME
16
17 Text::Tradition::Parser::CTE
18
19 =head1 DESCRIPTION
20
21 Parser module for Text::Tradition, given a TEI file exported from
22 Classical Text Editor.
23
24 =head1 METHODS
25
26 =head2 parse
27
28 my @apparatus = read( $xml_file );
29
30 Takes a Tradition object and a TEI file exported from Classical Text
31 Editor using double-endpoint-attachment critical apparatus encoding; 
32 initializes the Tradition from the file.
33
34 =cut
35
36 my %sigil_for;  # Save the XML IDs for witnesses.
37 my %apps;       # Save the apparatus XML for a given ID.    
38 my %has_ac;     # Keep track of witnesses that have corrections.
39
40 sub parse {
41         my( $tradition, $opts ) = @_;
42         my $c = $tradition->collation;  # Some shorthand
43         
44         ## DEBUG/TEST
45         $opts->{interpret_transposition} = 1;
46         
47         # First, parse the XML.
48     my( $tei, $xpc ) = _remove_formatting( $opts );
49     return unless $tei; # we have already warned.
50
51         # CTE uses a DTD rather than any xmlns-based parsing.  Thus we
52         # need no namespace handling.
53         # Get the witnesses and create the witness objects.
54         %sigil_for = ();
55         %apps = ();
56         %has_ac = ();
57         foreach my $wit_el ( $xpc->findnodes( '//sourceDesc/listWit/witness' ) ) {
58                 # The witness xml:id is used internally, and is *not* the sigil name.
59                 my $id= $wit_el->getAttribute( 'xml:id' );
60                 # If the witness element has an abbr element, that is the sigil. Otherwise
61                 # the whole thing is the sigil.
62                 my $sig = $xpc->findvalue( 'abbr', $wit_el );
63                 my $identifier = 'CTE witness';
64                 if( $sig ) {
65                         # The sigil is what is in the <abbr/> tag; the identifier is anything
66                         # that follows. 
67                         $identifier = _tidy_identifier( 
68                                 $xpc->findvalue( 'child::text()', $wit_el ) );
69                 } else {
70                         my @sig_parts = $xpc->findnodes( 'descendant::text()', $wit_el );
71                         $sig = _stringify_sigil( @sig_parts );
72                 }
73                 do_warn( $opts, "Adding witness $sig ($identifier)" );
74                 $tradition->add_witness( sigil => $sig, identifier => $identifier, 
75                         sourcetype => 'collation' );
76                 $sigil_for{'#'.$id} = $sig;  # Make life easy by keying on the ID ref syntax
77         }
78         
79         # Now go through the text and find the base tokens, apparatus tags, and
80         # anchors.  Make a giant array of all of these things in sequence.
81         # TODO consider combining this with creation of graph below
82         my @base_text;
83         foreach my $pg_el ( $xpc->findnodes( '/TEI/text/body/p' ) ) {
84                 foreach my $xn ( $pg_el->childNodes ) {
85                         push( @base_text, _get_base( $xn ) );
86                 }
87         }
88         # We now have to work through this array applying the alternate 
89         # apparatus readings to the base text.  Essentially we will put 
90         # everything on the graph, from which we will delete the apps and
91         # anchors when we are done.
92         
93         # First, put the base tokens, apps, and anchors in the graph. Save the
94         # app siglorum separately as it has to be processed in order.
95         my @app_sig;
96         my @app_crit;
97         my $counter = 0;
98         my $last = $c->start;
99         foreach my $item ( @base_text ) {
100             my $r;
101         if( $item->{'type'} eq 'token' ) {
102             $r = $c->add_reading( { id => 'n'.$counter++, 
103                                                         text => $item->{'content'} } );
104         } elsif ( $item->{'type'} eq 'anchor' ) {
105             $r = $c->add_reading( { id => '__ANCHOR_' . $item->{'content'} . '__', 
106                                                         is_ph => 1 } );
107         } elsif ( $item->{'type'} eq 'app' ) {
108             my $tag = '__APP_' . $counter++ . '__';
109             $r = $c->add_reading( { id => $tag, is_ph => 1 } );
110             my $app = $item->{'content'};
111             $apps{$tag} = $app;
112             # Apparatus should be differentiable by type attribute; apparently
113             # it is not. Peek at the content to categorize it.
114             # Apparatus criticus is type a1; app siglorum is type a2
115             my @sigtags = $xpc->findnodes( 'descendant::*[name(witStart) or name(witEnd)]', $app );
116             if( @sigtags ) {
117                         push( @app_sig, $tag );
118                 } else {
119                     push( @app_crit, $tag );
120                 }
121         }
122         $c->add_path( $last, $r, $c->baselabel );
123         $last = $r;
124     }
125     $c->add_path( $last, $c->end, $c->baselabel );
126     
127     # Now we can parse the apparatus entries, and add the variant readings 
128     # to the graph.
129     foreach my $app_id ( @app_crit ) {
130         _add_readings( $c, $app_id, $opts );
131     }
132     _add_lacunae( $c, @app_sig );
133     
134     # Finally, add explicit witness paths, remove the base paths, and remove
135     # the app/anchor tags.
136     try {
137             _expand_all_paths( $c, $opts );
138         } catch( Text::Tradition::Error $e ) {
139                 throw( $e->message );
140         } catch {
141                 throw( $@ );
142         }
143
144     # Save the text for each witness so that we can ensure consistency
145     # later on
146     unless( $opts->{'nocalc'} ) {
147         try {
148                         $tradition->collation->text_from_paths();       
149                         $tradition->collation->calculate_ranks();
150                         $tradition->collation->flatten_ranks();
151                 } catch( Text::Tradition::Error $e ) {
152                         throw( $e->message );
153                 } catch {
154                         throw( $@ );
155                 }
156         }
157 }
158
159 sub _stringify_sigil {
160     my( @nodes ) = @_;
161     my @parts = grep { /\w/ } map { $_->data } @nodes;
162     my $whole = join( '', @parts );
163     $whole =~ s/\W//g;
164     return $whole;
165 }
166
167 sub _tidy_identifier {
168         my( $str ) = @_;
169         $str =~ s/^\W+//;
170         return $str;
171 }
172
173 # Get rid of all the formatting elements that get in the way of tokenization.
174 sub _remove_formatting {
175         my( $opts ) = @_;
176         
177         # First, parse the original XML
178         my $parser = XML::LibXML->new();
179     my $doc;
180     if( exists $opts->{'string'} ) {
181         $doc = $parser->parse_string( $opts->{'string'} );
182     } elsif ( exists $opts->{'file'} ) {
183         $doc = $parser->parse_file( $opts->{'file'} );
184     } elsif ( exists $opts->{'xmlobj'} ) {
185         $doc = $opts->{'xmlobj'};
186     } else {
187         warn "Could not find string or file option to parse";
188         return;
189     }
190
191     # Second, remove the formatting
192         my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
193         my @useless = $xpc->findnodes( '//hi' );
194         foreach my $n ( @useless ) {
195                 my $parent = $n->parentNode();
196                 my @children = $n->childNodes();
197                 my $first = shift @children;
198                 if( $first ) {
199                         $parent->replaceChild( $first, $n );
200                         foreach my $c ( @children ) {
201                                 $parent->insertAfter( $c, $first );
202                                 $first = $c;
203                         }
204                 } else {
205                         $parent->removeChild( $n );
206                 }
207         }
208         
209         # Third, write out and reparse to merge the text nodes.
210         my $enc = $doc->encoding || 'UTF-8';
211         my $result = decode( $enc, $doc->toString() );
212         my $tei = $parser->parse_string( $result )->documentElement;
213         unless( $tei->nodeName =~ /^tei(corpus)?$/i ) {
214                 throw( "Parsed document has non-TEI root element " . $tei->nodeName );
215         }
216         $xpc = XML::LibXML::XPathContext->new( $tei );
217         return( $tei, $xpc );
218 }
219
220 ## Helper function to help us navigate through nested XML, picking out 
221 ## the words, the apparatus, and the anchors.
222
223 sub _get_base {
224         my( $xn ) = @_;
225         my @readings;
226         if( $xn->nodeType == XML_TEXT_NODE ) {
227             # Base text, just split the words on whitespace and add them 
228             # to our sequence.
229                 my $str = $xn->data;
230                 $str =~ s/^\s+//;
231                 my @tokens = split( /\s+/, $str );
232                 push( @readings, map { { type => 'token', content => $_ } } @tokens );
233         } elsif( $xn->nodeName eq 'app' ) {
234                 # Apparatus, just save the entire XML node.
235                 push( @readings, { type => 'app', content => $xn } );
236         } elsif( $xn->nodeName eq 'anchor' ) {
237                 # Anchor to mark the end of some apparatus; save its ID.
238                 if( $xn->hasAttribute('xml:id') ) {
239                         push( @readings, { type => 'anchor', 
240                             content => $xn->getAttribute( 'xml:id' ) } );
241                 } # if the anchor has no XML ID, it is not relevant to us.
242         } elsif( $xn->nodeName !~ /^(note|seg|milestone|emph)$/ ) {  # Any tag we don't know to disregard
243             say STDERR "Unrecognized tag " . $xn->nodeName;
244         }
245         return @readings;
246 }
247
248 sub _append_tokens {
249         my( $list, @tokens ) = @_;
250         if( @$list && $list->[-1]->{'content'} =~ /\#JOIN\#$/ ) {
251                 # The list evidently ended mid-word; join the next token onto it.
252                 my $t = shift @tokens;
253                 if( ref $t && $t->{'type'} eq 'token' ) {
254                         # Join the word
255                         $t = $t->{'content'};
256                 } elsif( ref $t ) {
257                         # An app or anchor intervened; end the word.
258                         unshift( @tokens, $t );
259                         $t = '';
260                 }
261                 $list->[-1]->{'content'} =~ s/\#JOIN\#$/$t/;
262         }
263         foreach my $t ( @tokens ) {
264                 unless( ref( $t ) ) {
265                         $t = { 'type' => 'token', 'content' => $t };
266                 }
267                 push( @$list, $t );
268         }
269 }
270
271 sub _add_readings {
272     my( $c, $app_id, $opts ) = @_;
273     my $xn = $apps{$app_id};
274     my $anchor = _anchor_name( $xn->getAttribute( 'to' ) );
275     
276     # Get the lemma, which is all the readings between app and anchor,
277     # excluding other apps or anchors.
278         my @lemma = _return_lemma( $c, $app_id, $anchor );
279         my $lemma_str = join( ' ',  map { $_->text } grep { !$_->is_ph } @lemma );
280         
281     # For each reading, send its text to 'interpret' along with the lemma,
282     # and then save the list of witnesses that these tokens belong to.
283     my %wit_rdgs;  # Maps from witnesses to the variant text
284     my $ctr = 0;
285     my $tag = $app_id;
286     $tag =~ s/^\__APP_(.*)\__$/$1/;
287
288     foreach my $rdg ( $xn->getChildrenByTagName( 'rdg' ) ) {
289         my @witlist = split( /\s+/, $rdg->getAttribute( 'wit' ) );
290         my @text;
291         foreach ( $rdg->childNodes ) {
292             push( @text, _get_base( $_ ) );
293         }
294         my( $interpreted, $flag ) = ( '', undef );
295         if( @text ) {
296                 ( $interpreted, $flag ) = interpret( 
297                         join( ' ', map { $_->{'content'} } @text ), $lemma_str, $anchor, $opts );
298         }
299         next if( $interpreted eq $lemma_str ) && !keys %$flag;  # Reading is lemma.
300         
301         my @rdg_nodes;
302         if( $interpreted eq '#LACUNA#' ) {
303                 push( @rdg_nodes, $c->add_reading( { id => 'r'.$tag.".".$ctr++,
304                                                                                          is_lacuna => 1 } ) );
305         } elsif( $flag->{'TR'} ) {
306                 # Our reading is transposed to after the given string. Look
307                 # down the collation base text and try to find it.
308                 # The @rdg_nodes should remain blank here, so that the correct
309                 # omission goes into the graph.
310                 my @transp_nodes;
311                 foreach my $w ( split(  /\s+/, $interpreted ) ) {
312                         my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
313                                                                                    text => $w } );
314                                 push( @transp_nodes, $r );
315                         }
316                         if( $anchor && @lemma ) {
317                                 my $success = _attach_transposition( $c, \@lemma, $anchor, 
318                                         \@transp_nodes, \@witlist, $flag->{'TR'}, $opts );
319                                 unless( $success ) {
320                                         # If we didn't manage to insert the displaced reading,
321                                         # then restore it here rather than silently deleting it.
322                                         push( @rdg_nodes, @transp_nodes );
323                                 }
324                         }
325         } else {
326                         foreach my $w ( split( /\s+/, $interpreted ) ) {
327                                 my $r = $c->add_reading( { id => 'r'.$tag.".".$ctr++,
328                                                                                    text => $w } );
329                                 push( @rdg_nodes, $r );
330                         }
331         }
332         
333         # For each listed wit, save the reading.
334         # If an A.C. or P.C. reading is implied rather than explicitly noted,
335         # this is where it will be dealt with.
336         foreach my $wit ( @witlist ) {
337                         $wit .= '_ac' if $flag->{'AC'};
338             $wit_rdgs{$wit} = \@rdg_nodes;
339             # If the PC flag is set, there is a corresponding AC that
340             # follows the lemma and has to be explicitly declared.
341             if( $flag->{'PC'} ) {
342                 $wit_rdgs{$wit.'_ac'} = \@lemma;
343             }
344         }
345                         
346         # Does the reading have an ID? If so it probably has a witDetail
347         # attached, and we need to read it. If an A.C. or P.C. reading is
348         # declared explicity, this is where it will be dealt with.
349         if( $rdg->hasAttribute( 'xml:id' ) ) {
350                 warn "Witdetail on meta reading" if $flag; # this could get complicated.
351             my $rid = $rdg->getAttribute( 'xml:id' );
352             my $xpc = XML::LibXML::XPathContext->new( $xn );
353             my @details = $xpc->findnodes( './witDetail[@target="'.$rid.'"]' );
354             foreach my $d ( @details ) {
355                 _parse_wit_detail( $d, \%wit_rdgs, \@lemma );
356             }
357         }
358     }       
359         
360     # Now collate the variant readings, since it is not done for us.
361     collate_variants( $c, \@lemma, values %wit_rdgs );
362         
363     # Now add the witness paths for each reading. If we don't have an anchor
364     # (e.g. with an initial witStart) there was no witness path to speak of.
365         foreach my $wit_id ( keys %wit_rdgs ) {
366                 my $witstr = _get_sigil( $wit_id, $c->ac_label );
367                 my $rdg_list = $wit_rdgs{$wit_id};
368                 _add_wit_path( $c, $rdg_list, $app_id, $anchor, $witstr );
369         }
370 }
371
372 sub _anchor_name {
373     my $xmlid = shift;
374     $xmlid =~ s/^\#//;
375     return sprintf( "__ANCHOR_%s__", $xmlid );
376 }
377
378 sub _return_lemma {
379     my( $c, $app, $anchor ) = @_;
380     my @nodes = grep { $_->id !~ /^__A(PP|NCHOR)/ } 
381         $c->reading_sequence( $c->reading( $app ), $c->reading( $anchor ),
382                 $c->baselabel );
383     return @nodes;
384 }
385
386 # Make a best-effort attempt to attach a transposition farther down the line.
387 # $lemmaseq contains the Reading objects of the lemma
388 # $anchor contains the point at which we should start scanning for a match
389 # $rdgseq contains the Reading objects of the transposed reading 
390 #       (should be identical to the lemma)
391 # $witlist contains the list of applicable witnesses
392 # $reftxt contains the text to match, after which the $rdgseq should go.
393 sub _attach_transposition {
394         my( $c, $lemmaseq, $anchor, $rdgseq, $witlist, $reftxt, $opts ) = @_;
395         my @refwords = split( /\s+/, $reftxt );
396         my $checked = $c->reading( $anchor );
397         my $found;
398         my $success;
399         while( $checked ne $c->end && !$found ) {
400                 my $next = $c->next_reading( $checked, $c->baselabel );
401                 if( $next->text eq $refwords[0] ) {
402                         # See if the entire sequence of words matches.
403                         $found = $next;
404                         foreach my $w ( 1..$#refwords ) {
405                                 $found = $c->next_reading( $next, $c->baselabel );
406                                 unless( $found->text eq $refwords[$w] ) {
407                                         $found = undef;
408                                         last;
409                                 }
410                         }
411                 }
412                 $checked = $next;
413         }
414         if( $found ) {
415                 # The $found variable should now contain the reading after which we
416                 # should stick the transposition.
417                 my $fnext = $c->next_reading( $found, $c->baselabel );
418                 my $aclabel = $c->ac_label;
419                 foreach my $wit_id ( @$witlist ) {
420                         my $witstr = _get_sigil( $wit_id, $aclabel );
421                         _add_wit_path( $c, $rdgseq, $found->id, $fnext->id, $witstr );
422                 }
423                 # ...and add the transposition relationship between lemma and rdgseq.
424                 if( @$lemmaseq == @$rdgseq ) {
425                         foreach my $i ( 0..$#{$lemmaseq} ) {
426                                 $c->add_relationship( $lemmaseq->[$i], $rdgseq->[$i],
427                                         { type => 'transposition', annotation => 'Detected by CTE' } );
428                         }
429                 $success = 1;
430                 } else {
431                         throw( "Lemma at $found and transposed sequence different lengths?!" );
432                 }
433         } else {
434                 do_warn( $opts, "WARNING: Unable to find $reftxt in base text for transposition" );
435         }
436         return $success;
437 }
438
439 =head2 interpret( $reading, $lemma )
440
441 Given a string in $reading and a corresponding lemma in $lemma, interpret what
442 the actual reading should be. Used to deal with apparatus-ese shorthands for
443 marking transpositions, prefixed or suffixed words, and the like.
444
445 =cut
446
447 sub interpret {
448         # A utility function to change apparatus-ese into a full variant.
449         my( $reading, $lemma, $anchor, $opts ) = @_;
450         return $reading if $reading eq $lemma;
451         my $oldreading = $reading;
452         # $lemma =~ s/\s+[[:punct:]]+$//;
453         my $flag = {};  # To pass back extra info about the interpretation
454         my @words = split( /\s+/, $lemma );
455         # Discard any 'sic' notation - that rather goes without saying.
456         $reading =~ s/([[:punct:]]+)?sic([[:punct:]]+)?//g;
457         
458         # Now look for common jargon.
459         if( $reading =~ /^(.*) praem.$/ || $reading =~ /^praem\. (.*)$/ ) {
460                 $reading = "$1 $lemma";
461         } elsif( $reading =~ /^(.*) add.$/ || $reading =~ /^add\. (.*)$/ ) {
462                 $reading = "$lemma $1";
463         } elsif( $reading =~ /locus [uv]acuus/
464             || $reading eq 'def.'
465             || $reading eq 'illeg.'
466             || $reading eq 'desunt'
467             ) {
468                 $reading = '#LACUNA#';
469         } elsif( $reading eq 'om.' ) {
470                 $reading = '';
471         } elsif( $reading =~ /^in[uv]\.$/ 
472                          || $reading =~ /^tr(ans(p)?)?\.$/ ) {
473                 # Hope it is two words.
474                 do_warn( $opts, "WARNING: want to invert a lemma that is not two words" )
475                         unless scalar( @words ) == 2;
476                 $reading = join( ' ', reverse( @words ) );
477         } elsif( $reading =~ /^iter(\.|at)$/ ) {
478                 # Repeat the lemma
479                 $reading = "$lemma $lemma";
480         } elsif( $reading =~ /^(.*?)\s*\(?in marg\.\)?$/ ) {
481                 $reading = $1;
482                 if( $reading ) {
483                         # The given text is a correction.
484                         $flag->{'PC'} = 1;
485                 } else {
486                         # The lemma itself was the correction; the witness carried
487                         # no reading pre-correction.
488                         $flag->{'AC'} = 1;
489                 }
490         } elsif( $reading =~ /^(.*) \.\.\. (.*)$/ ) {
491                 # The first and last N words captured should replace the first and
492                 # last N words of the lemma.
493                 my @begin = split( /\s+/, $1 );
494                 my @end = split( /\s+/, $2 );
495                 if( scalar( @begin ) + scalar ( @end ) > scalar( @words ) ) {
496                         # Something is wrong and we can't do the splice.
497                         throw( "$lemma is too short to accommodate $oldreading" );
498                 } else {
499                         splice( @words, 0, scalar @begin, @begin );
500                         splice( @words, -(scalar @end), scalar @end, @end );
501                         $reading = join( ' ', @words );
502                 }
503         } elsif( $opts->{interpret_transposition} &&
504                          ( $reading =~ /^post\s*(?<lem>.*?)\s+tr(ans(p)?)?\.$/ || 
505                            $reading =~ /^tr(ans(p)?)?\. post\s*(?<lem>.*)$/) ) {
506                 # Try to deal with transposed readings
507                 ## DEBUG
508                 say STDERR "Will attempt transposition: $reading at $anchor";
509                 $reading = $lemma;
510                 $flag->{'TR'} = $+{lem};
511         }
512         return( $reading, $flag );
513 }
514
515 sub _parse_wit_detail {
516     my( $detail, $readings, $lemma ) = @_;
517     my $wit = $detail->getAttribute( 'wit' );
518     my $content = $detail->textContent;
519     if( $content =~ /^a\.?\s*c(orr)?\.$/ ) {
520         # Replace the key in the $readings hash
521         my $rdg = delete $readings->{$wit};
522         $readings->{$wit.'_ac'} = $rdg;
523         $has_ac{$sigil_for{$wit}} = 1;
524     } elsif( $content =~ /^p\.?\s*c(orr)?\.$/ || $content =~ /^s\.?\s*l\.$/ ) {
525         # If no key for the wit a.c. exists, add one pointing to the lemma
526         unless( exists $readings->{$wit.'_ac'} ) {
527             $readings->{$wit.'_ac'} = $lemma;
528         }
529         $has_ac{$sigil_for{$wit}} = 1;
530     } else {  #...not sure what it is?
531         say STDERR "WARNING: Unrecognized sigil annotation $content";
532     }
533 }
534
535 sub _add_lacunae {
536         my( $c, @app_id ) = @_;
537         # Go through the apparatus entries in order, noting where to start and stop our
538         # various witnesses.
539         my %lacunose;
540         my $ctr = 0;
541         foreach my $tag ( @app_id ) {
542                 my $app = $apps{$tag};
543                 # Find the anchor, if any. This marks the point where the text starts
544                 # or ends.
545                 my $anchor = $app->getAttribute( 'to' );
546                 my $aname;
547                 if( $anchor ) {
548                         $anchor =~ s/^\#//;
549                         $aname = _anchor_name( $anchor );
550                 }
551
552                 foreach my $rdg ( $app->getChildrenByTagName( 'rdg' ) ) {
553                 my @witlist = map { _get_sigil( $_, $c->ac_label ) }
554                         split( /\s+/, $rdg->getAttribute( 'wit' ) );
555                         my @start = $rdg->getChildrenByTagName( 'witStart' );
556                         my @end = $rdg->getChildrenByTagName( 'witEnd' );
557                         if( @start && @end ) {
558                                 throw( "App sig entry at $anchor has both witStart and witEnd!" );
559                         }
560                         if( @start && $anchor &&
561                                 $c->prior_reading( $aname, $c->baselabel ) ne $c->start ) {
562                                 # We are picking back up after a hiatus. Find the last end and
563                                 # add a lacuna link between there and here.
564                                 foreach my $wit ( @witlist ) {
565                                         my $stoppoint = delete $lacunose{$wit};
566                                         my $stopname = $stoppoint ? _anchor_name( $stoppoint ) : $c->start->id;
567                                         say STDERR "Adding lacuna for $wit between $stopname and $anchor";
568                                         my $lacuna = $c->add_reading( { id => "as_$anchor.".$ctr++,
569                                         is_lacuna => 1 } );
570                                 _add_wit_path( $c, [ $lacuna ], $stopname, $aname, $wit );
571                                 }
572                         } elsif( @end && $anchor && 
573                                 $c->next_reading( $aname, $c->baselabel ) ne $c->end ) {
574                                 # We are stopping. If we've already stopped for the given witness,
575                                 # flag an error; otherwise record the stopping point.
576                                 foreach my $wit ( @witlist ) {
577                                         if( $lacunose{$wit} ) {
578                                                 throw( "Trying to end $wit at $anchor when already ended at "
579                                                         . $lacunose{$wit} );
580                                         }
581                                         $lacunose{$wit} = $anchor;
582                                 }
583                         }
584                 }
585         }
586         
587         # For whatever remains in the %lacunose hash, add a lacuna between that spot and
588         # $c->end for each of the witnesses.
589         foreach my $wit ( keys %lacunose ) {
590                 next unless $lacunose{$wit};
591                 my $aname = _anchor_name( $lacunose{$wit} );
592                 say STDERR "Adding lacuna for $wit from $aname to end";
593                 my $lacuna = $c->add_reading( { id => 'as_'.$lacunose{$wit}.'.'.$ctr++,
594                         is_lacuna => 1 } );
595                 _add_wit_path( $c, [ $lacuna ], $aname, $c->end, $wit );
596         }
597 }
598
599 sub _get_sigil {
600     my( $xml_id, $layerlabel ) = @_;
601     if( $xml_id =~ /^(.*)_ac$/ ) {
602         my $real_id = $1;
603         return $sigil_for{$real_id} . $layerlabel;
604     } else {
605         return $sigil_for{$xml_id};
606     }
607 }
608
609 sub _expand_all_paths { 
610     my( $c, $opts ) = @_;
611     
612     # Walk the collation and fish out the paths for each witness
613     foreach my $wit ( $c->tradition->witnesses ) {
614         my $sig = $wit->sigil;
615         my @path = grep { !$_->is_ph } 
616             $c->reading_sequence( $c->start, $c->end, $sig );
617         $wit->path( \@path );
618         if( $has_ac{$sig} ) {
619             my @ac_path = grep { !$_->is_ph } 
620                 $c->reading_sequence( $c->start, $c->end, $sig.$c->ac_label );
621             $wit->uncorrected_path( \@ac_path );
622         }
623     }   
624     
625     # Delete the anchors
626     foreach my $anchor ( grep { $_->is_ph } $c->readings ) {
627         $c->del_reading( $anchor );
628     }
629     # Delete the base edges
630     map { $c->del_path( $_, $c->baselabel ) } $c->paths;
631     
632     # Make the path edges
633     $c->make_witness_paths();
634     
635     # Now remove any orphan nodes, and warn that we are doing so.
636     my %suspect_apps;
637     while( $c->sequence->predecessorless_vertices > 1 ) {
638         foreach my $v ( $c->sequence->predecessorless_vertices ) {
639                 my $r = $c->reading( $v );
640                 next if $r->is_start;
641                 my $tag = $r->id;
642                 $tag =~ s/^r(\d+)\.\d+/$1/;
643                 do_warn( $opts, "Deleting orphan reading $r / " . $r->text );
644                 push( @{$suspect_apps{$tag}}, $r->id ) if $tag =~ /^\d+$/;
645                 $c->del_reading( $r );
646         }
647     }
648     if( $c->sequence->successorless_vertices > 1 ) {
649         my @bad = grep { $_ ne $c->end->id } $c->sequence->successorless_vertices;
650         foreach( @bad ) {
651                 my $tag = $_;
652                 next unless $tag =~ /^r/;
653                 $tag =~ s/^r(\d+)\.\d+/$1/;
654                 push( @{$suspect_apps{$tag}}, $_ );
655         }
656                 _dump_suspects( $opts, %suspect_apps );
657         throw( "Remaining hanging readings: @bad" );
658         }
659         _dump_suspects( $opts, %suspect_apps ) if keys %suspect_apps;
660 }
661
662 sub _add_wit_path {
663     my( $c, $rdg, $app, $anchor, $wit ) = @_;
664     my @nodes = @$rdg;
665     push( @nodes, $c->reading( $anchor ) );
666     
667     my $cur = $c->reading( $app );
668     foreach my $n ( @nodes ) {
669         $c->add_path( $cur, $n, $wit );
670         $cur = $n;
671     }
672 }
673
674 sub _dump_suspects {
675         my $opts = shift;
676         my %list = @_;
677         my @warning = "Suspect apparatus entries:";
678         foreach my $suspect ( sort { $a <=> $b } keys %list ) {
679                 my @badrdgs = @{$list{$suspect}};
680                 push( @warning, _print_apparatus( $suspect ) );
681                 push( @warning, "\t(Linked to readings @badrdgs)" );
682         }
683         do_warn( $opts, join( "\n", @warning ) );
684 }
685
686 sub _print_apparatus {
687         my( $appid ) = @_;
688         my $tag = '__APP_' . $appid . '__';
689         my $app = $apps{$tag};
690         my $appstring = '';
691         # Interpret the XML - get the lemma and readings and print them out.
692         my $xpc = XML::LibXML::XPathContext->new( $app );
693         my $anchor = $app->getAttribute('to');
694         if( $anchor ) {
695                 # We have a lemma, so we construct it.
696                 $anchor =~ s/^#//;
697                 $appstring .= "(Anchor $anchor) ";
698                 my $curr = $app;
699                 while( $curr ) {
700                         last if $curr->nodeType eq XML_ELEMENT_NODE 
701                                 && $curr->hasAttribute( 'xml:id' ) 
702                                 && $curr->getAttribute( 'xml:id' ) eq $anchor;
703                         $appstring .= $curr->data if $curr->nodeType eq XML_TEXT_NODE;
704                         $curr = $curr->nextSibling;
705                 }
706         }
707         $appstring .= '] ';
708         my @readings;
709         foreach my $rdg_el ( $xpc->findnodes( 'child::rdg' ) ) {
710                 my $rdgtext = '';
711                 my $startend = '';
712                 my %detail;
713                 foreach my $child_el ( $rdg_el->childNodes ) {
714                         if( $child_el->nodeType eq XML_TEXT_NODE ) {
715                                 $rdgtext .= $child_el->data;
716                         } elsif( $child_el->nodeName =~ /^wit(Start|End)$/ ) {
717                                 my $startend = lc( $1 );
718                         } elsif( $child_el->nodeName eq 'witDetail' ) {
719                                 foreach my $wit ( map { _get_sigil( $_ ) } 
720                                         split( /\s+/, $child_el->getAttribute('wit') ) ) {
721                                         $detail{$wit} = $child_el->textContent;
722                                 }
723                         }
724                 }
725                 
726                 my @witlist;
727                 foreach my $witrep (  map { _get_sigil( $_ ) } 
728                         split( /\s+/, $rdg_el->getAttribute('wit') ) ) {
729                         if( exists $detail{$witrep} ) {
730                                 $witrep .= '(' . $detail{$witrep} . ')'
731                         }
732                         if( $startend eq 'start' ) {
733                                 $witrep = '*' . $witrep;
734                         } elsif( $startend eq 'end' ) {
735                                 $witrep .= '*';
736                         }
737                         push( @witlist, $witrep );
738                 }
739                 $rdgtext .= " @witlist";
740                 push( @readings, $rdgtext );
741         }
742         $appstring .= join( '  ', @readings );
743         return $appstring;
744 }
745
746 sub do_warn {
747         my( $opts, $message ) = @_;
748         if( $opts->{'warnings_to'} ) {
749                 push( @{$opts->{'warnings_to'}}, $message );
750         } else {
751                 say STDERR $message;
752         }
753 }
754
755 sub throw {
756         Text::Tradition::Error->throw( 
757                 'ident' => 'Parser::CTE error',
758                 'message' => $_[0],
759                 );
760 }
761
762 =head1 LICENSE
763
764 This package is free software and is provided "as is" without express
765 or implied warranty.  You can redistribute it and/or modify it under
766 the same terms as Perl itself.
767
768 =head1 AUTHOR
769
770 Tara L Andrews, aurum@cpan.org
771
772 =cut
773
774 1;
775