#!/usr/bin/perl 

my $a, $b, $c, $s, $out;
my @l;
my @p;

while (<>) {
  s@ id="[^"]*"@@;
  if (m@<chapter@) {
    pop (@l);
    $c++;
    $s = "<chapter id=\"A_" . $c . "_\"";
    s@<chapter@$s@;
  }
  if (m@</chapter@) {
  }
  if (m@<section@) {
    if ($out) {
      push ( @l, pop (@l) + 1 );
    }
    else {
      push @l, 1;
    }
    $out = 0;
    $s = "<section id=\"A_" . "$c" . "_" . join ( "_", @l ) . "\"";
    s@<section@$s@;
  }
  if (m@</section@) {
    if ($out) {
      pop @l;
    }
    else {
    }
    $out = 1;
  }
  print;
}
