#!/usr/bin/perl
#
# fped2d2z.pl - Convert fped 2D stacks into 2.5D paths with Z information
#
# Written 2012 by Werner Almesberger
# Copyright 2012 Werner Almesberger
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#


sub usage
{
	print STDERR "usage: $0 [-r|-t Zmax] [Zin=Zout ...] prefix ".
	    "[file ...]\n\n";
	print STDERR "  Zin=Zout  replace Zin with Zout\n";
	print STDERR "  -t Zmax   set the top of the piece\n";
	print STDERR "  -r        reverse Z stacking. Also swaps X and Y.\n";
	exit(1);
}


if ($ARGV[0] eq "-r") {
	shift @ARGV;
	$reverse = 1;
}
if ($ARGV[0] eq "-t") {
	shift @ARGV;
	$top = shift @ARGV;
}
&usage if $ARGV[0] =~ /^-[^0-9]/;

while ($ARGV[0] =~ /=/) {
	$map{$`} = $';
	shift @ARGV;
}

$pfx = shift @ARGV;
&usage unless defined $pfx;

$skip = 1;
while (<>) {
	if (/^# $pfx.*?(\d+(\.\d*)?)\s*$/) {
		$z = $1;
		$skip = 0;
	} elsif (/^# /) {
		$skip = 1;
	}
	next if $skip;
	$z{$z} .= $_;
	$zmax = $z if $z > $zmax || !defined $zmax;
}

if ($reverse) {
	for (keys %z) {
		($t{$zmax-$_} = $z{$_}) =~
		    s/^(-?\d+(\.\d*)?)\s+(-?\d+(\.\d*)?)/$3 $1/mg;
	}
	%z = %t;
	print "0 0 $zmax\n\n";
} elsif (defined $top) {
	for (keys %z) {
		($t{$top-$_} = $z{$_}) =~
		    s/^(-?\d+(\.\d*)?)\s+(-?\d+(\.\d*)?)/$1 $3/mg;
	}
	%z = %t;
} else {
	print "0 0 0\n\n";
}

# sort, to make output easier to examine manually
for (sort { $b <=> $a } keys %z) {
	$s = defined $map{$_} ? $map{$_} : $_;
	$z{$_} =~ s/\s+-?\d+(\.\d*)?$/$& $s/gm;
	print $z{$_};
}