#!/usr/bin/perl 
# 20140301 - After some effort to get it installed, do NOT like what it does
# {"@encoding":"UTF-8","@version":"1.0",
# "ProceduresDB":{"Airport":
#   {"Star":[
#   {"@Name":"BSR2",
#   "Star_Waypoint":[
#   {"Longitude":{"$t":"-121.642111"},
#   "AltitudeCons":{"$t":"0"},
#   "Latitude":{"$t":"36.181294"},
# *** UGLY RUBBISH ***
# However the 2nd method found, namely load the XML using XML::Simple, and convert it using JSON::Any
# worked FINE
#use JSON::XS;
use JSON::Any;
use XML::XML2JSON;
use XML::Simple;

my $PATH_SEP = "\\";
my $temp_dir = 'C:\GTools\perl';
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $out_file = $temp_dir.$PATH_SEP."tempxml2json.json";
my $out_file2 = $temp_dir.$PATH_SEP."tempxml2json2.json";
        
my $XML = '<test><element foo="bar"/></test>';
##my $in_file = 'C:\Users\user\Downloads\LDS767\ZWWW.xml';
my $in_file = 'C:\Users\user\Downloads\LDS767\KSFO.xml';

my $XML2JSON = XML::XML2JSON->new();
        
my $JSON = $XML2JSON->convert($XML);
        
print $JSON."\n";
        
# my $RestoredXML = $XML2JSON->json2xml($JSON);

sub prt($) { print shift; }

sub write2file {
	my ($txt,$fil) = @_;
	open WOF, ">$fil" or die("ERROR: Unable to open $fil! $!\n");
	print WOF $txt;
	close WOF;
}


sub load_file() {
    if (! -f $in_file) {
        prt("Error: Can NOT locate file $in_file\n");
        return;
    }
    if (! open INF, "<$in_file") {
        prt("Error: Can NOT open file $in_file\n");
        return;
    }
    my @lines = <INF>;
    close INF;
    my $line = join("",@lines);
    ### prt("$line\n");
    my $X2J = XML::XML2JSON->new();
    my $json = $X2J->convert($line);
    #prt("$json\n");
    write2file($json,$out_file);
    prt("JSON written to [$out_file]\n");
}


sub load_file2() {
    if (! -f $in_file) {
        prt("Error: Can NOT locate file $in_file\n");
        return;
    }
    my $xml = XMLin($in_file);
    my $json = JSON::Any->new()->objToJson($xml);
    write2file($json,$out_file2);
    prt("JSON written to [$out_file2]\n");
}

#load_file();
load_file2();

# eof
