#! /usr/bin/perl

foreach $_ ( split(':', $ENV{'PATH'}) ) {
  push(@INC, $_), last if -f "$_/tfm.pl";
}
require 'tfm.pl';

$size = 10;

print "# Generated by: ", join(" ", $0, @ARGV), "\n";

# @subcamdata: azim elev roll  nleft right nbottom top
#               0    1    2     3     4     5       6

sub projectiondata {

    local($azim, $elev, $roll,  $nleft, $right, $nbot, $top, $tiltaz, $tiltel, $tiltro) = @_;

    local(@scflop) = &tfm('x', -90);
    local(@scry) = &tfm('y', $azim);
    local(@scrx) = &tfm('x', $elev);
    local(@scrz) = &tfm('z', $roll);

    local(@sc2c) = &tmul( @scrz, @scrx, @scry, @scflop );

    if($tiltaz ne "") {
	@sc2c = &tmul( @sc2c,
			&tfm('z', $tiltro),
			&tfm('x', $tiltel),
			&tfm('y', $tiltaz) );
    }

    local($lx) = $size * &tandeg( -$nleft );
    local($rx) = $size * &tandeg(  $right );
    local($by) = $size * &tandeg( -$nbot );
    local($ty) = $size * &tandeg(  $top );

    (
	&v3mmul( $lx,$by,-$size, @sc2c ),
	&v3mmul( $lx,$ty,-$size, @sc2c ),
	&v3mmul( $rx,$by,-$size, @sc2c )
    );
}

if(@ARGV == 0 && -t STDIN) {
    print STDERR "Usage: $0 [-s \"cam1 cam2 ...\"] [-t az,el,roll] < subcamfile  > cave-config-fragment
where subcamfile contains lines of the form

subcam <name>  <azim> <elev> <roll>  <negativeleft> <right> <negativebottom> <top>
e.g.
subcam  p2       0.00 24.25   0.00   42.70  42.70   33.20  37.40

Writes to stdout a series of ProjectionData lines,
intended to be pasted into an EVL/VRCO CAVE config file.
With -s option, emits ProjectionData for just the specified
subcameras in the given order; otherwise writes all provided as input.
With -t, tilts the collection of cameras w.r.t. the dome.
";
    exit(1);
}

while($ARGV[0] =~ /^-[st]/) {
  shift(@ARGV), $subcams = shift(@ARGV) if $ARGV[0] =~ /^-s/;
  shift(@ARGV), $tilt = shift(@ARGV) if $ARGV[0] =~ /^-t/;
}

$tilt =~ tr/,/ /;
@tilt = split(' ', $tilt);
@tilt = (0, $tilt[0], 0) if @tilt == 1;

$subcams =~ tr/,/ /;
@subcams = split(' ', $subcams);

while(<>) {
  s/#.*//;
  @F = split(' ');
  if($F[0] eq "subcam" && @F >= 9) {
    $subcam{$F[1]} = join(" ", @F[2..8]);
    push(@allsubcams, $F[1]);
  }
}

@subcams = @allsubcams unless @subcams;

$scrno = 0;
while(@subcams) {
  $which = shift(@subcams);
  if($subcam{$which}) {
    @scam = (split(' ', $subcam{$which}))[0..6];
    printf "ProjectionData screen%d  both wall %.3f %.3f %.3f  %.3f %.3f %.3f  %.3f %.3f %.3f # %s\n",
	$scrno, &projectiondata( @scam, @tilt ), $which;
  } else {
    printf "# no subcam %s\n", $which;
  }
  $scrno++;
}
