#!/usr/bin/perl -w
use strict;

convert_tab_to_xml();

sub convert_tab_to_xml {
    my $txtFile = $ARGV[0] || return usage("missing file parameter");

    my $xmlFile = $txtFile;
    $xmlFile =~ s/\.(\w+)$/\.xml/;

    open INPUT,  "<$txtFile" or die "Couldn't open input file $txtFile: $!";
    open OUTPUT, ">$xmlFile" or die "Couldn't open output file $xmlFile: $!";

    my $headerLine = <INPUT>;
    chomp($headerLine);
    my @fields = split( /\t/, $headerLine );

    print OUTPUT "<royalty>\n";

    while ( my $line = <INPUT> ) {
        chomp($line);
        my @values = split( /\t/, $line );

        if ( $#values == $#fields ) {
            print OUTPUT "\t<sale>\n";
            foreach my $i ( 0 .. $#fields ) {
                print OUTPUT "\t\t<" . $fields[$i] . ">" . $values[$i] . "</" . $fields[$i] . ">\n";
            }
            print OUTPUT "\t</sale>\n";
        }
    }

    print OUTPUT "</royalty>\n";

    close(OUTPUT);
    close(INPUT);

    print "Done!\nFile created: $xmlFile\n";
}

sub usage {
    my $err = shift;

    print "ERROR: $err\n";
    print "Usage: $0 FILE \n";

    return 1;
}

