#!/usr/bin/perl
#Converts XylBot roles to a CSV spreadsheet

# Perl trim function to remove whitespace from the start and end of the string
sub trim($) {
  my $string = shift;
  $string =~ s/^\s+//;
  $string =~ s/\s+$//;
  return $string;
}

print "Enter the path to the XylBot roles: ";
$file = <>;
open(ROLES, $file);
@lines = <ROLES>;
close(ROLES);

print "Enter the path to the output file: ";
$file = <>;
open(OUTPUT, ">$file");

$status = 0;

@csvheader = qw(id name roletext actions status minteam minplayers minscum changeto setup power rarity theme);
@csvline = qw(id name roletext actions status minteam minplayers minscum changeto setup power rarity theme);
$numheaders = 13;

foreach $line(@lines) {
  $line = trim($line);
  if(substr($line, 0, 1) eq "}") {
    if($status) {
      $status = 0;
      #print "status = \" $statustext\"\n";
      @csvline[4] = "\" $statustext\"";
    }
  }
  if((substr($line, 0, 1) ne "#") && (substr($line, 0, 1) ne "}")) {
    $middle = index($line, "=>");
    if($middle != 0) {
      $field = trim(substr($line, 0, $middle)."\n");
      $value = trim(substr($line, $middle+2)."\n");
      if(rindex($value, ",") == 0) {
	chop($value);#Remove the trailing comma
      }
      $value =~ s/\'/\"/g;#Change single-quotes to double-quotes
      $value =~ s/\"//g;#Remove double-quotes
      if($value eq "{") {
	if($field eq "status") {
	  $status = 1;
	  $statustext = "";
	} else {
	  for($i = 0; $i < $numheaders; $i++) {
	    print OUTPUT @csvline[$i].",";
	    @csvline[$i] = "";
	  }
	  print OUTPUT "\n";
	  #print "id = \"$field\"\n";
	  @csvline[0] = "\"$field\"";
	}
      } else {
	if($status) {
	  $statustext .= "$field = $value; ";
	} else {
	  #print $field." = \"".$value."\"\n";
	  $good = 0;
	  for($i = 0; ($i < $numheaders); $i++) {
	    if($field eq @csvheader[$i]) {
	      @csvline[$i] = "\"$value\"";
	      $good = 1;
	    }
	  }
	  if(!$good) {
	    print "The data Stanley was given didn't include a $field field. Please ask him to fix this.\n";
	  }
	}
      }
    }
  }
}

for($i = 0; $i < $numheaders; $i++) {
  print OUTPUT @csvline[$i].",";
  @csvline[$i] = "";
}
print OUTPUT "\n";

close(OUTPUT);
