#!/usr/bin/env perl

# this thing will just parse the votables and print out in 'ken schema style'

$wiki=1;
#$csv = 1;
$infield = 0;
$intable = 0;
while (<>) {
    
    if ($_ =~/\<FIELD/) {
	#print "here\n";
	chomp $_;
	$name = $_;
	$name =~ s/.*name=\"//;
	$name =~ s/\".*//g;
#	print "\nxxx$name","xxx\n";

	$arraysize = $_;
	$arraysize =~ s/.*arraysize=\"//;
	$arraysize =~ s/\".*//g;
	$datatype = $_;
	$datatype =~ s/.*datatype=\"//;
	$datatype =~ s/\".*//g;
	#this sets all the sizes
	$datatype1 = "$datatype($arraysize)";
	if($datatype eq "float") {$datatype1 = "REAL 4";}
	if($datatype eq "double") {$datatype1 = "FLOAT 8";}
	if($datatype eq "char") {$datatype1 = "VARCHAR($arraysize)";}
	if($datatype eq "int") {$datatype1 = "INT 4";}
	if($datatype eq "short") {$datatype1 = "SMALLINT 2";}
	if($datatype eq "unsignedByte") {$datatype1 = "TINYINT 1";}
	if($datatype eq "long") {$datatype1 = "BIGINT 8";}

	if ($csv) {
	    $datatype1 =~ s/ .//;

	}

	if ($_ =~ /.*default=\"/) {

	    $default = $_;
	    $default =~ s/.*default=\"//;
	    $default =~ s/\".*//g;

	} else {$default="";}
	if ($_ =~ /.*unit=\"/) {
	    $unit = $_;
	    $unit =~ s/.*unit=\"//;
	    $unit =~ s/\".*//g;
	} else {$unit = "";}
	if ($wiki) {
	printf("||%-17s||   %-15s||   %-15s ||   %-5s||",$name, $unit, $datatype1, $default);
	} elsif ($csv) {
	    printf("%s,%s,%s,%s,\"",$name, $unit, $datatype1, $default);
	}
	

	$infield = 1;
    } else {
	if ($infield) {
	    if ($_ =~ /\<\/DESCRIPTION/) {
		$t = $_;
		chomp $t;
		$t =~ s/\s+\<DESCRIPTION\>//;
		$t =~ s/\<\/DESCRIPTION\>//;
		print $t;
		$infield = 1;
	    }
	    
	    if ($_ =~ /\<\/FIELD/) {
		if ($wiki) { print "||";}
		if ($csv) {print "\"";}
		print "\n";
		$infield = 0;
	    }
	    
	} else {
	    #not in field something new
	    if ($_ =~ /\<TABLE /) {
		chomp $_;
		$name = $_;
		$name =~ s/.*name=\"//;
		$name =~ s/\".*//g;
		$intable = 1;
	        if ($csv) {
		    print "$name\n";
		} else {
		    print "---------------------------\n";
		    printf ("%-16s   ", $name);
		}
	    } else {
		if ($intable) {
		    if ($_ =~ /\<\/DESCRIPTION/) {
			$t = $_;
			chomp $t;
			$t =~ s/\s+\<DESCRIPTION\>//;
			$t =~ s/\<\/DESCRIPTION\>//;
			if ($csv) {
			    $dostuff = 1;
			} else {
			    print "$t\n";
			    print "---------------------------\n";
			}
			$intable = 1;
			
		    }
		    
		}
	    }
	    if ($_ =~ /\<\/TABLE\>/) {
		$intable = 0;
	    }

	    
	}
    }
    

}
