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