 #!/usr/bin/env perl
use File::Path qw(mkpath);


my $filename = $ARGV[0];
my $searchstring = "<SimpleData name=\"domain\">";

my $coordtag = "<coordinates>";
my $endstring = "</coordinates>";

#print "$searchstring\n";



print "Opening file: $filename\n";

open(my $in, "<", "$filename") or die "Can't open $filename: $!\n";

my $folder = $filename;
$folder =~ s/glaciation_//g;
$folder =~ s/.kml//g;
print "$folder\n";

mkpath("$folder");

my $nextline = 0;
my $rocktype = "";
my $age = "";
my $counter = 0;
my $ss = "";

my $filestxt = "files.txt";

open(my $filelisting, ">", $filestxt) or die "Can't open $filestxt: $!\n";

while (<$in>) {

#	print $counter, $nextline, "\n";

	if (/$endstring/) {
	#	print $line;

		open( my $out, ">", $outname) or die "Can't open $outname: $!\n";
		print $out $line;
		close $out;
		$nextline = 0;
		$line = "";

	}


	if ($nextline == 1) {
#		print $filelisting "$outname \n";

		s/^\s+//;
#		s/[A-Za-z\<\>\/]//g;
#		s/,[^,]*[ |\n]/\n/g;
#		s/\s/\n/g;
#		s/ //g;
#		print $out "$ss \n";

		$line = $line . $_;

	}


	if (/$coordtag/) {
		my $line = "";
		$counter++;
		$nextline = 1;
#		print $counter;
		my $counterext = substr("0000$counter",-4);

#		print $rocktype, $age, "\n";

		$outname = "$folder/$folder-$counterext.txt";
#		$outname = "$rocktype\_$age\_$counterext.txt";
		print "\n", $outname, "\n";



	}
}



close $filelisting;
close $in;
