use strict;

my @top_x;
my @top_y;
my @bottom_x;
my @bottom_y;
my @left_x;
my @left_y;
my @right_x;
my @right_y;

&polyline("top.src", \@top_x, \@top_y);
&polyline("bottom.src", \@bottom_x, \@bottom_y);
&polyline("left.src", \@left_x, \@left_y);
&polyline("right.src", \@right_x, \@right_y);

my $xunits=100;
my $arcunits=5;
#my $radius=5;
my $radius=50;

my $xmin= $top_x[0];
my $xmax= $top_x[$#top_x];

if($xmax != $bottom_x[$#bottom_x] || $xmax != $left_x[$#left_x] || 
		$xmax != $right_x[$#right_x] || $xmin != $right_x[0] ||
		$xmin != $bottom_x[0] || $xmin != $left_x[0]){
	die("all lines must be of same length\n");
}

my $station;

open(OUT, ">boxfuse.scr");
print(OUT "mesh\n");
print(OUT $xunits+1);
print(OUT "\n");
print(OUT 4*($arcunits+2)+ 2);
print(OUT "\n");
for($station= 0; $station <= $xunits;$station++){
	my $cur_x= $station* ($xmax-$xmin)/$xunits+ $xmin;
	my $cur_t= &interpolate(\@top_x, \@top_y, $cur_x);
	my $cur_b= &interpolate(\@bottom_x, \@bottom_y, $cur_x);
	my $cur_l= &interpolate(\@left_x, \@left_y, $cur_x);
	my $cur_r= &interpolate(\@right_x, \@right_y, $cur_x);
	my $cur_c= $radius;
	my $rcount;
	my $segment;

	if($cur_c > ($cur_l- $cur_r)/2){
		$cur_c= ($cur_l- $cur_r)/2;
	}
	if($cur_c > ($cur_t- $cur_b)/2){
		$cur_c= ($cur_t- $cur_b)/2;
	}
	print(OUT "$cur_x,".(($cur_l+ $cur_r)/2).",$cur_t\n");
	for($segment=0;$segment < 4;$segment++){
		my $center_y;
		my $center_z;

		if($segment == 0 || $segment == 3){
			$center_y= $cur_t- $cur_c;
		}else{
			$center_y= $cur_b+ $cur_c;
		}
		if($segment == 0 || $segment == 1){
			$center_z= $cur_l- $cur_c;
		}else{
			$center_z= $cur_r+ $cur_c;
		}
		for($rcount=0;$rcount <= $arcunits+1;$rcount++){
			my $angle= ($rcount+ ($arcunits+ 1)* $segment)* 
					3.14159/(2*($arcunits+1));
			my $delta_y= $cur_c* cos($angle);
			my $delta_z= $cur_c* sin($angle);

			print(OUT "$cur_x,");
			print(OUT $center_z+ $delta_z);
			print(OUT ",");
			print(OUT $center_y+ $delta_y);
			print(OUT "\n");
		}
	}
	print(OUT "$cur_x,".(($cur_l+ $cur_r)/2).",$cur_t\n");
}
close(OUT);

sub interpolate{
	my($xa, $ya, $x)=@_;
	my $counter;
	my $result;

	loo: for($counter=0;$counter <= $#{$xa};$counter++){
		if($xa->[$counter] >= $x){
			if($counter == 0 || $xa->[$counter-1] == 
					$xa->[$counter]){
				$result= $ya->[$counter];
			}else{
				$result= $ya->[$counter-1]+ ($ya->[$counter]-
						$ya->[$counter-1])*
						($x- $xa->[$counter-1])/
						($xa->[$counter]-
						$xa->[$counter-1]);
			}
			last loo;
		}
	}
	return $result;
}

sub polyline{
	my($file,$xs,$ys)=@_;

	open(LINEFILE, $file);
	line: while(<LINEFILE>){
		my $line= $_;

		if(/^\s+Location:\s+X=\s+([0-9\.-]+)\s+Y=\s+([0-9\.-]+)/){
			push @{$xs},$1;
			push @{$ys},$2;
		}
	}
	close(LINEFILE);
}

