#!/usr/bin/perl -w
#
# OpenSCAD tends to export to svg as a single path.
# split closed paths into separate paths, red, 0.2mm stroke
$fNam = $ARGV[0];
$tNam = $fNam . "~";

$pathHdr = "path stroke=\"red\" fill=\"none\" stroke-width=\"0.2\" d=\"\n";
$inPath=0;

&mySystem("mv $fNam $tNam");

open($fi,"<",$tNam) or die "Cannot read from '$tNam'.\n";
open($fo,">",$fNam) or die "Cannot write to '$fNam'.\n";

while (!eof($fi)) {
    print STDERR "eof(inFile)==",eof($fi),"\n";
    &copyToStartOfFirstPath();
    &splitPath();
}

close $fi;
close $fo;

sub copyToStartOfFirstPath() {
  while(<$fi>) {
      if (m/path.*d="/) {
	  s/<path.*d="//;
	  print STDERR "*** Start of path:",$_;
	  print $fo $_;
	  $inPath=1;
	  return();
      }
      print STDERR $_;
      print $fo $_;
  }
}

sub splitPath() {
    while(<$fi>) {
	if (m/z/) {
	    if ($inPath) { # one line path. needs header still
		&printOut("<$pathHdr");
	    }
	    s/z/z"\/>\n/;#<$pathHdr/;
	    $inPath=1;
	    &printOut($_);
	    print STDERR "*** closed path.\n";
	} elsif (m/\/>/) { # end of original path, ignore path settings.  OpenScad does not put path info on line with descriptors
	    s/.*\/>//;
	    &printOut($_);
	    print STDERR "*** skipping metadata on close of path.  done on each z\n";
	    return();
	} else {
	    if ($inPath) {
		&printOut("<$pathHdr");
		$inPath=0;
	    }
	    &printOut($_);
	}
    }
}

sub printOut() {
    local ($msg)=@_;

    # echo to STDERR also
    print STDERR $msg;

    print $fo $msg;
}

sub mySystem() {
  ($_) = @_;

  print "$_\n";
  system($_);
}
