#!/bin/sh
#
# Copyright (C) 1992, Christoph Streit (streit@iam.unibe.ch)
# All rights reserved.
#
# This software may be freely copied, modified, and redistributed
# provided that this copyright notice is preserved on all copies.
#
# You may not distribute this software, in whole or in part, as part of
# any commercial product without the express consent of the authors.
#
# There is no warranty or other guarantee of fitness of this software
# for any purpose.  It is provided solely "as is".
#
# Simulates wind in a birchtree (uses birchtree.anim.lsys).
# 
# usage: birchanim [-R resX resY] [-O outfile]
#                  [-d rayshade|flat] numberOfFrames
#
#

nawk '
BEGIN { 
  resX = 150; 
  resY = 150;
  outfile = "birch.rle";
  renderer = "flat";

  if (ARGC <= 1) 
    usage(); 

  #
  # Parse command line options.
  #
  while (++i < ARGC-1) { 
    if (ARGV[i] ~ /^-R$/) { 
      if (((ARGC-i) > 3) && 
	  ((ARGV[i+1] ~ /^[0-9]+$/) && (ARGV[i+2] ~ /^[0-9]+$/))) { 
	resX = ARGV[++i]; 
	resY = ARGV[++i];
      }
      else
	usage();
    }
    else if (ARGV[i] ~ /^-O$/) {
      if ((ARGC-i) > 2)
        outfile = ARGV[++i];
      else
        usage();
    }
    else if (ARGV[i] ~ /^-d$/) {
      if ((ARGC-i) > 2 && (ARGV[i+1] ~ /^(rayshade|flat)$/))
        renderer = ARGV[++i];
      else
        usage();
    }
    else if (i < ARGC-1)
      usage();
    else 
      break;
  }

  #
  # Get number of frames to be rendered.
  #
  if ((i >= ARGC) || (ARGV[i] !~ /^[0-9]+$/))
    usage();
  else
    numberOfFrames = ARGV[i];

  #
  # Render images...
  #
  for (i=0; i<numberOfFrames; i++) {
    if (renderer == "flat")
      cmd = "graphtal -q -R " resX " " resY \
            " -Diter=" i " -DnumberOfFrames=" numberOfFrames \
            " -d flat birchtree.anim.lsys | ppmtorle | rleflip -v" \
	    " > _frame" i ".rle";
    else
      cmd = "graphtal -q -s -R " resX " " resY \
            " -Diter=" i " -DnumberOfFrames=" numberOfFrames \
            " -d rayshade birchtree.anim.lsys;" \
	    " rayshade -S 2 default.ray > _frame" i ".rle";
    print cmd; 
    if (system(cmd)) exit(1);
    if (i == 0) {
      print "mv _frame" i ".rle " outfile;
      system("mv _frame" i ".rle " outfile);
    }
    else {
      print "rlecat -o tmp.rle " outfile " _frame" i ".rle";
      system ("rlecat -o tmp.rle " outfile " _frame" i ".rle");
      print "mv tmp.rle " outfile;
      system ("mv tmp.rle " outfile);
      system("rm _frame" i ".rle");
    }
  }
}

function usage()
{
  print "usage: birchanim [-R resX resY] [-O outfile]";
  print "                 [-d rayshade|flat] numberOfFrames\n";
  exit(1);
}
' $*
