#!/usr/bin/perl -W


use strict;
use English;


my $outdir = "gen";
my $stem;

# create the output subdir if it doesn't already exist 
if (! ( -d $outdir )) {
  mkdir($outdir) || die ("can't make output dir - $!"); 
}

# process the files
($#ARGV<0)
  and die "Usage: combine_lectures.pl lecture-combination-names\n ".
  "The lecture combinations need to have a file called name.1, a file called name.3, and a directory called name, which contains files to be inserted in the middle, in an alphabetic order\n";
foreach $stem (@ARGV){
  
  # copy the beginning file
  open (IN,"<$stem.1") || die ("can't open $stem.1 - $!");
  my @out_tmp=(<IN>);
  close (IN);
  my $out=join('',@out_tmp);
  my $one_top=$stem;
  #list all the files in the directory
  if (!opendir(DIR, $stem)){
	$one_top=~s/\//\/..\//;#replace just once
	#	print "can't opendir $stem: $!, using $one_top\n";
        opendir(DIR, $one_top) || die "can't opendir $one_top: $!";
  }else{#directory is real, make its index.
  #no need to make indices for hebrew dirs.
  ##create an index for the lectures directory, using a script by Shlomi Fish:
  system ("./gen_index.pl $stem $stem/index.html");	
  }
  my @lectures = grep { /^\d/ && -f "$one_top/$_" } readdir(DIR);
  closedir DIR;
  @lectures = sort { $a cmp $b } @lectures;
 
  
  #insert table opening part
  open (IN,"<table_open") || die ("can't open table_open - $!");
  @out_tmp=(<IN>);
  close (IN);
  $out.=join('',@out_tmp);

  #open and concat all the files in the directory
  my $lec;
  foreach $lec (@lectures){
    open (IN,"<$one_top/$lec") || die ("can't open $one_top/$lec - $!");
    @out_tmp=(<IN>);
    close (IN);
    $out.=join('',@out_tmp);
  }

  # copy the ending file
  open (IN,"<lectures_lists") ||
    die ("can't open lectures_lists - $!");
  @out_tmp=(<IN>);
  close (IN);
  $out.=join('',@out_tmp);

  open (OUT,">$stem.htm") || die "cannot write to $stem.htm - $!";
  print OUT $out;
  close OUT;
}
