#!/usr/bin/perl
# Make a log wall centered at the origin Args: W H

use Getopt::Std;

getopts("b:");

sub make_box
{
   my($sx, $ex, $sz, $ez, $t, $mat, $name) = @_;
   my($tx) = $sx;
   my($ty) = -$t/2;
   my($tz) = $sz;
   my($w, $h, $d) = ($ex-$sx, $ez-$sz, $t/2);

   return if($sx == $ex || $sz == $ez);
   
   system("genbox $mat $name.$sx$sz $w $t $h | xform -t $tx $ty $tz");
}

die <<USAGE if $#ARGV < 4;
Usage: genstdwall [-b material] material name width_ft height_ft thick_in [hole_data]

   -b mat: Add baseboards with material "mat"

USAGE

$material = $ARGV[0];
$name = $ARGV[1];
$width = $ARGV[2] * 12;
$height = $ARGV[3] * 12;
$thick = $ARGV[4];
$holefile = $ARGV[5];
$baseboard = $opt_b;

if(defined($holefile)) {
   open HOLES, "<$holefile" or warn "No hole data file.\n";

   $nholes = 0;
   %edges = ();

   while($data = <HOLES>) {
      next if $data =~ /^[ \t]*#/;
      next if $data !~ /[0-9]/;
      chomp $data;
      @vals = split /\s+/, $data;
      $vals{bottom} = $vals[0] * 12;
      $vals{top} = $vals[1] * 12;
      $vals{start} = $vals[2] * 12;
      $vals{width} = $vals[3] * 12;
      $holes[$nholes++] = { %vals };
      $edges{$vals{bottom}} = $edges{$vals{top}} = \$holes[$nholes-1];
   }

   close HOLES;
}

@zholes = sort { $a <=> $b } keys %edges;
@xholes = sort { $a->{start} <=> $b->{start} } @holes;

$bb_height = 3;
$oldz = 0;

if(defined($baseboard)) {
   $x = -1;
   for($hole = 0; $hole < $nholes; $hole++) {
      if($holes[$hole]{bottom} < $bb_height) {
         make_box($x, 1 + $holes[$hole]{start}, 0, $bb_height, $thick + 2,
                  $baseboard, $name . "_bb$hole");
         $x = $holes[$hole]{start} + $holes[$hole]{width} - 1;
      }
   }
   make_box($x, 1 + $width, 0, $bb_height, $thick + 2,
            $baseboard, $name . "_bb$hole");
   $oldz = $bb_height;
}

# Build wall around holes
for $z (@zholes)
{
   next if $z <= $oldz;
   $x = 0;
   for($hole = 0; $hole < $nholes; $hole++) {
      if($holes[$hole]{bottom} < $z &&
         $holes[$hole]{top} >= $z) {
         make_box($x, $holes[$hole]{start}, $oldz, $z, $thick, $material, $name);
         $x = $holes[$hole]{start} + $holes[$hole]{width};
      }
   }
   make_box($x, $width, $oldz, $z, $thick, $material, $name) if($x < $width);
   $oldz = $z;
}

make_box(0, $width, $oldz, $height, $thick, $material, $name) if($oldz < $height);

