#!/usr/bin/perl
use strict; $|=1;
#######################################################################
# SFS-extract.pl - Perl extractor for KSP savegame data. 
# By Ed T. Toton III, NecroBones Enterprises - necrobones.com
#######################################################################

foreach my $file (@ARGV) {
	if ($file =~ /\.sfs$/) {
		extract_parts($file);
	} else {
		warn "Unknown KSP save file type: $file\n";
	}
}

die "Must supply savegame SFS filenames.\n" if (!@ARGV);

exit;

#######################################################################

sub extract_parts {
	my $fn = shift;
	my $basename = $fn; $basename =~ s/^.*\///g;

	my %sectiondata = ();
	my %vesseldata  = ();

	my $section = '';
	my $name    = '';
	my $data    = '';
	my $type    = '';

	open SFS, "<$fn";
	while (my $line = <SFS>) {
		if ($section) {
			#print "$section: $line";
			if (
				($section eq 'VESSEL' && $line =~ /^\t\t\}/) ||
				($section eq 'SCENARIO' && $line =~ /^\t\}/) ||
				($section eq 'ROSTER' && $line =~ /^\t\}/)
			   ) {
				$data .= $line;
				#print "SAVE $fn,$section,$type,$name\n";

				if (lc($type) ne 'debris') {
					save_data($fn,$section,$type,$name,$data);
					$sectiondata{$section} .= $data;
					$vesseldata{$type} .= $data if ($section eq 'VESSEL');
				}
				$section = '';
				$data    = '';
				$name    = '';
				$type    = '';
			} else {
				$data .= $line;

				if (!$name && $line =~ /^\s*name =\s+(.*\S)\s*$/) {
					$name = $1;
				}
				if ($section eq 'VESSEL' && !$type && $line =~ /^\s*type =\s+(.*\S)\s*$/) {
					$type = $1;
				}
			}
		} else {
			#print "No section: $line";
			if ($line =~ /^\tROSTER/) {
				$section = 'ROSTER';
			} elsif ($line =~ /^\tSCENARIO/) {
				$section = 'SCENARIO';
			} elsif ($line =~ /^\t\tVESSEL/) {
				$section = 'VESSEL';
			}

			if ($section) {
				$data = $line;
				$name = '';
				$type = '';
				#print "Section '$section' found\n";
			}
		}
	}
	close SFS;

	foreach my $section (keys %sectiondata) {
		save_data($fn,$section,'','',$sectiondata{$section}) if ($section ne 'ROSTER');
	}
	foreach my $type (keys %vesseldata) {
		save_data($fn,'VESSEL',$type,'',$vesseldata{$type}) if (lc($type) ne 'debris');
	}
}

#######################################################################

sub save_data {
	my ($filename,$section,$type,$name,$data) = @_;

	my $use_name = 1;
	$use_name = 0 if ($section eq 'ROSTER' || !$name);

	$filename =~ s/\.sfs$//;
	my $fn = "$filename-$section-$name.txt";
	$fn = "$filename-$section.txt" if (!$use_name);

	$fn =~ s/$section/$section-$type/ if ($type);
	$fn =~ s/[^\w\.\-\_]/\_/g;
	$fn =~ s/\_{2,}/\_/g;
	$fn =~ s/\-{2,}/\-/g;
	$fn =~ s/[\-\_]+\.txt/\.txt/g;

	print "Saving $section='$name' as $fn\n" if ($use_name);
	print "Saving $section as $fn\n" if (!$use_name);

	open OUT, ">$fn";
	print OUT $data;
	close OUT;
}

#######################################################################

