#!/usr/local/bin/perl
##################################################################################

  $basedir = "";   # base directory where to find the text file
  $biot_ext = ".inf";
  $vrml_ext = ".wrl";
  $template = "template.html";
  $name_subst = "%%%";
  $file_lock = 0;


  $biot = $ENV{'QUERY_STRING'}; 


  &open_file("INFILE","","$basedir$biot$biot_ext");
 
  $header = read_file("INFILE");
  $body = read_file("INFILE");
  $footer = read_file("INFILE");
  $leaflines = read_file("INFILE");
  $count = read_file("INFILE");

  close_file("INFILE");

  # send the last prepared scene

  print "Content-type: text/html\n\n";

  # print the html containing the name of the scene
  $vrml = $biot.$count.$vrml_ext;
  &open_file("TEMPLATEFILE","","$basedir$template");
  @lines = <TEMPLATEFILE>;
  foreach $line (@lines) {
    $line=~ s/$name_subst/$vrml/g;
    print $line;
    }
  close_file("TEMPLATEFILE");

  # now make the new scene

  $count += 1;
  $vrml = $biot.$count.$vrml_ext;
  &open_file("VRMLFILE","",">$basedir$vrml");

  # print the beginning of the scene
  &open_file("HEADERFILE","","$basedir$header");
  while ($line = &read_file("HEADERFILE")) {
    write_file("VRMLFILE", $line);
    }
  close_file("HEADERFILE");

  # print the according number of the biot parts

  &open_file("BODYFILE","","$basedir$body");
  $counter = 0;
  while (($line = &read_file("BODYFILE")) && ($counter < ($count*$leaflines))) {
    write_file("VRMLFILE", $line);
    $counter += 1;
    }
  close_file("BODYFILE");

  # print the rest of the scene
  &open_file("FOOTERFILE","","$basedir$footer");
  while ($line = &read_file("FOOTERFILE")) {
    write_file("VRMLFILE", $line);
    }
  close_file("FOOTERFILE");

  close_file("VRMLFILE");

  # can call gzip to compress the scene


  # when ready write the new biot info file

  &open_file("INFILE","",">$basedir$biot$biot_ext");
 
  write_file("INFILE", $header);
  write_file("INFILE", $body);
  write_file("INFILE", $footer);
  write_file("INFILE", $leaflines);
  write_file("INFILE", $count);

  close_file("INFILE");







sub open_file {

  $LOCK_EX=2;

  local ($filevar, $filemode, $filename) = @_;
  open ($filevar,$filemode . $filename) ||
     die ("Can't open $filename");
  if ($file_lock) { flock($filevar, $LOCK_EX); }
}

sub read_file {

  local ($filevar) = @_;
  <$filevar>;  
}

sub write_file {

  local ($filevar, $line) = @_;
  print $filevar ($line);
}

sub close_file {

  $LOCK_UN=8;
  local($filevar)=@_;
  if ($file_lock) { flock($filevar, $LOCK_UN); }
}


