#!/usr/bin/perl

=head1 NAME

xmlchar2utf8trans - convert XSLT 2.0 character maps to utf8trans character maps

=head1 SYNOPSIS

xmlchar2utf8trans [xslt-charmap-file]

=head1 DESCRIPTION

This script converts a XML character map in XSLT 2.0 format
to the plain text format used by utf8trans(1).

Note:  The parsing of the XSLT 2.0 character map is really
minimal, and does not conform to the full specification.

=cut

use XML::SAX::ParserFactory;
use strict;

package OutputCharacterHandler;
use base qw(XML::SAX::Base);

sub start_element {
    my ($self, $elem) = @_;
    
    if($elem->{NamespaceURI} eq 'http://www.w3.org/1999/XSL/Transform')
    {
        if($elem->{LocalName} eq 'output-character') {
            my $char_code = ord($elem->{Attributes}->{'{}character'}->{Value});
            my $string = $elem->{Attributes}->{'{}string'}->{Value};

            $string =~ tr/\n\0/  /;
        
            printf "%x %s\n", $char_code, $string;
        }
    }
}

sub comment {
    my ($self, $node) = @_;
    my @lines = split(/\n/, $node->{Data});
    
    print "\n" if @lines > 1;
    
    foreach my $line (@lines) {
        $line =~ s/^[ \t]+//;
        print "# $line\n";
    }
}

package main;

unshift(@ARGV, '-') unless @ARGV;
my $parser = XML::SAX::ParserFactory->parser(
                DocumentHandler => OutputCharacterHandler->new);

binmode(STDOUT, ":utf8") unless $] < 5.008;

foreach my $file (@ARGV)
{
    if($file eq '-') {
        $parser->parse_file(\*STDIN);
    } else {
        $parser->parse_uri($file);
    }
}



