#!/usr/bin/perl

use XML::Twig;

sub sgr {
	my ($t, $sgr) = @_;
	($lastSections, $sections) = ($sections, []);
	push @$sections, defined $_->att("type") && $_->att("type") eq "backref" ?
		$lastSections->[$_->text] : $_->text for $sgr->children("section");
	$sgr->delete;
	$t->flush;
}

sub text {
	my ($t, $text)= @_;
	if(defined $text->att("type") && $text->att("type") eq "sectionlist") {
		my $s = ""; $s .= $sections->[$_] for split / /, $text->text;
		$text->set_text($s); $text->del_att("type");
	}
	$t->flush;
}

$t = XML::Twig->new ( TwigHandlers => { sectiongroup => \&sgr, text => \&text },
	keep_spaces => 1, keep_encoding => 1 );
$t->parse(\*STDIN);
$t->flush;
