#! /usr/bin/perl -w
# now uses sabcmd from Sablotron project (much faster than Xalan)
use strict;

my $tmpfile = "/tmp/xml2any.$$.output";

sub help {
     print "Syntax: xml2any <XML file> <XSLT file> [params]\n\n";
     print "  params given as: param1 value1 ...\n";
}

if (scalar(@ARGV) < 2) {
    print "Error. Not enough arguments!\n";
    help();
    exit(1);
}

my $xmlfile = shift @ARGV;
my $xsltfile = shift @ARGV;

if (!(-e "$xmlfile")) {
    print "Error. File $xmlfile does not exist!\n";
    exit(1);
}

if (!(-e "$xsltfile")) {
    print "Error. File $xsltfile does not exist!\n";
    exit(1);
}

my @params = @ARGV;
if (scalar(@params) % 2 != 0) {
    print "Error. Parameters must consist of one or more param value combinations!\n";
    help();
    exit(1);
}

my $sabcmdparams = "";
for (my $i=0; $i < scalar(@params)/2; $i++) {
    $sabcmdparams .= "\\\$" . $params[$i] . "=" . $params[$i+1] . " ";
}

system("sabcmd $xsltfile $xmlfile $sabcmdparams > $tmpfile");
open(OUTPUT, "<$tmpfile");
my @output = <OUTPUT>;
print @output;

unlink "$tmpfile" if (-e "$tmpfile");
