#!/usr/bin/perl -w
# xml2xml: put xml tags on separate lines
# usage: xml2xml < file
# 20050817 erikt@science.uva.nl

$command = $0;
$buffer = "";
$indent = "";
while (<STDIN>) {
   $line = $_;
   chomp($line);
   if ($buffer eq "" and $line !~ /[<>]/) { print "$line\n"; next; }
   @fields = split(/([<>])/,$line);
   while (@fields) {
      $fields[0] =~ s/^\s*//;
      if ($fields[0] eq "") { shift(@fields); next; }
      if ($buffer !~ /^</ and $fields[0] ne "<") {
         # empty buffer and no tag on top of stack
         print "$indent$fields[0]\n";
      } elsif ($buffer =~ /^</) {
         # partial tag in buffer
         $buffer .= $fields[0];
         if ($buffer =~ />$/) { 
            if ($buffer =~ /<\//) { $indent =~ s/ $//; }
            print "$indent$buffer\n";
            if ($buffer !~ /<[\/?]|[\/?]>/) { $indent .= " "; }
            $buffer = "";
         }
      } elsif ($buffer eq "") { 
         # tag in field
         $buffer = $fields[0];  
      } else { die "$command: cannot happen: $buffer # $fields[0]\n"; }
      shift(@fields);
   }
}
if ($buffer ne "") { print "$indent$buffer\n"; }
exit(0);
