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