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