#!/usr/bin/perl -w

# author G.P.H. Josten <gjosten@sci.kun.nl>
# post processing by Michel Rodriguez <m.v.rodriguez@ieee.org>

use strict;
use XML::XSLT qw(serve); 

# we need to replace the entities as <xml:output mode="text" /> does not work
my %ent= ( amp  => '&', quot => '"', apos => "'",
	   lt   => '<', gt   => '>', '#160' => ' ', 
         );

set_filter();    # sets the post-processing filter
my $xslt   = XML::XSLT->new( 'ex_ps_xslt.xslt');
print $xslt->serve( Source => 'REC-xml-19980210.xml');

exit;

# filter applied to the output of the XSLT transformation
sub set_filter
  { return if my $pid= open( STDOUT, "|-");    # magic open
    die "cannot fork: $!" unless defined $pid;
    $|=1;
    my $i=0;
    my $prod='';
    while( <STDIN>)
      { if( m/^\s*\[\]/)
          { unless( $i==0)
              { $prod= add_pos( $prod, $i); 
                print clean( $prod), "\n" ;
              }
            $i++;
            $prod= '';
          }
          $prod .= $_;
        }
    $prod= add_pos( $prod, $i); 
    print clean( $prod), "\n"; 
    exit;
  }
        
        
sub clean { 
        my( $string)= @_;

	# replace entities
        $string=~ s{&(.*?);}{$ent{$1}}g;  
       	
        $string =~ s/\xc2\xa0/ /sg;
        $string =~ s/\s+/ /g; $string=~ s{\s$}{}; $string=~ s{^\s}{};
        return $string;
  }

# needed because XSLT does no yet implement position()
sub add_pos
  { my( $prod, $i)= @_;
    $prod=~ s{^\s*\[\]}{\n[$i]};
    return $prod;
  }
