#!/usr/bin/perl -w

# igmmak, 3 Nov 1996, by Randy Winch <gumby@edge.net>
#
#############################################################################
#
# This program provides for on-the-fly index page generation
#
#############################################################################
# PERL 4 users should comment this BEGIN {}
#
# The ../cgi-bin will work if the program is installed under the user

BEGIN {
  unshift(@INC,'../cgi'); # Should point to the users cgi-bin directory
}
$Program='IGMMak';
$Version='2.X';
$|=1;
require 'igmini';
require 'igmlib';

print "\n$Program Version $Version\n";
print "Copyright (c) Randy Winch <gumby\@edge.net>, 1996\n\n";
print "A component of the Indexed GEDCOM Method of GenWeb authoring.\n\n";

die "Usage: igmmak gedcom1 [gedcom2 [gedcom3] ...]\n" unless @ARGV || !-t;

foreach $DB (@ARGV) {
  print "Processing $DB\n";
  $emailname='';
  $emailaddr='';
  $NewTitle='';
  &IGMEmail;
  open(GEDCOM,"$LocIGMDir/$DB/$DB.ged") || die "Error opening $DB.ged.";
  if ($UseDBM) {
#
# Remove old DB file in whatever format and create new one
#
    unlink "$LocIGMDir/$DB/$DB";
    unlink "$LocIGMDir/$DB/$DB.pag";
    unlink "$LocIGMDir/$DB/$DB.dir";
    unlink "$LocIGMDir/$DB/$DB.db";
    dbmopen(%idx,"$LocIGMDir/$DB/$DB",0644);
  } else {
    open(INDEX,"> $LocIGMDir/$DB/$DB.idx") || die "Error opening $INDEX.";
  }
#
# Build list from name, xref id and seek address. Also write index file.
#
  @list=();
  @photolist=();
  $type='';
  $currseek=0;
  $LineCount=0;
  $NameCount=0;
  $PersonCount=0;
  $PhotoCount=0;
  $ignore='y';
  $gotdata='n';
  $count=0;
  while (<GEDCOM>) {
      chomp;
      s/^\W+//;
      s/[^\S]$//;
    ($lvl,$tag,$rest)=/^(\d+)\s+(\S+) ?(.*)$/;
#    $rest=~s/ // if ($rest=~/^ .*/);
    $LineCount++;
#
# Wait for first individual
#
    if ($lvl eq '0') {
      if ($gotdata eq 'y') {
        foreach $name (@names) {
          ($lastname)=($name=~m#/(.*)/#);
#
# Handle multiple surnames by sorting by year, month and day
#
          $tmp=join(' ',reverse(split(/\s/,$birthdate)));
          push(@list,"\U$lastname\@$name\E\@$tmp\@$lastname\@$name\@$birthdate\@$birthplace\@$deathdate\@$deathplace\@$seek\@$photo");
          $NameCount++;
          if ($photo) {
            push(@photolist,"\U$lastname\@$name\E\@$tmp\@$lastname\@$name\@$birthdate\@$birthplace\@$deathdate\@$deathplace\@$seek\@$photo");
          }
        }
        $gotdata='n';
      }
#
# If this has an index then write to index file
#
      if ($tag=~/@(.*)@/) {
        $id=$1;
        $seek=$currseek;
        if ($UseDBM) {
          $idx{$id}=$seek;
        } else {
          print INDEX "$id $seek\n";
        }
        if ($rest eq 'INDI') {
          @names=();
          $name='';
          $birthdate='';
          $photo='';
          $birthplace='';
          $deathdate='';
          $deathplace='';
          $ignore='n';
          $gotdata='y';
          $PersonCount++;
          $seek=$id if ($UseXrefTags);
          next;
        }
      }
    }
    next if ($ignore eq 'y');
# Get persons name
    if ($tag eq 'NAME') {
      push(@names,$rest);
      $count++;
      print "$count\r" unless ($count % 100);
      next;
    }
    if (($tag eq 'ALIA') && ($IndexAliases)) {
      push(@names,$rest);
      $count++;
      print "$count\r" unless ($count % 100);
      next;
    }
    if ($tag eq 'DATE') {
      $birthdate=$rest if ($type eq 'BIRT');
      $deathdate=$rest if ($type eq 'DEAT');
      next;
    }
    if ($tag eq 'PLAC') {
      $birthplace=$rest if ($type eq 'BIRT');
      $deathplace=$rest if ($type eq 'DEAT');
      next;
    }
    if ($tag eq 'PHOT') {
      $PhotoCount++;
      $photo=$rest;
      next;
    }
  } continue {
    $type=$tag if ($rest eq '');
    $currseek=tell;
  }
  print "$count\nDone scanning ged file\n";
  if ($UseDBM) {
    dbmclose(%idx);
  } else {
    close(INDEX);
  }
#
# Scan ged file for submitter info and load
#
  print "Loading Submitter Information.\r";
  seek(GEDCOM,0,0);
  $Submitter='';
  $flag=0;
  while (<GEDCOM>) {
      chomp;
      s/^\W+//;
      s/[^\S]$//;
    ($lvl,$tag,$rest)=/^(\d+)\s+(\S+) ?(.*)$/;
    if ($lvl==0) {
      last if ($flag==1);
      $flag=1 if (($tag eq 'SUBM') || ($rest eq 'SUBM'));
    }
    if ($flag==1) {
      if (( $tag eq 'NAME') || ($tag eq 'ADDR') || ($tag eq 'CONT')) {
        $Submitter.="$rest<br>\n";
      }
    }
  }
  print "Submitter Information Loaded.              \n";
  $Submitter="$emailname<br>\n" unless ($Submitter);
  $Submitter.="<A HREF=\"mailto:$emailaddr\">$emailaddr</A>";
  close(GEDCOM);

#
# Save last update time
#
  $Updated=&wtime(time);

#
# Sort the list into surname order
#
  print "Sorting List\n";
  @list=sort @list;
  @photolist=sort @photolist;
  print "Writing GENDEX file\n";
#
# Write the GENDEX compatable file
#
  $count=0;
  open(GENDEX,"> $LocIGMDir/$DB/$DB.gdx");
  foreach $list (@list) {
    ($j1,$j2,$j3,$lastname,$name,$birthdate,$birthplace,$deathdate,$deathplace,$seek)=split(/\@/,$list);
    print GENDEX "$seek|$lastname|$name|$birthdate|$birthplace|$deathdate|$deathplace|\n";
    $count++;
    print "$count\r" unless ($count % 100);
  }
  close(GENDEX);
#
# Build HTML index files.
#
  print "\nBuilding HTML index files\n";
  open(SUR,"> $LocIGMDir/$DB/$DB-surname.html");
  select(SUR);
  &heading('Surname');
  open(INDEX,"> $LocIGMDir/$DB/$DB.html");
  select(INDEX);
  &heading('Master');
  select(STDOUT);
  $count=0;
  $indx=1;
  $surcount=0;
  $Lastsurname='';
  $LastFirstLetter='';
  foreach $list (@list) {
    ($Surname,$j1,$j2,$j3,$name,$birthdate,$birthplace,$deathdate,$deathplace,$seek,$photo)=split(/\@/,$list);
    $name=&IGMConvert($name);
#
# Reorder name
#
    ($firstname,$lastname,$title)=$name=~m#(.*)/(.*)/,*\s*(.*)#;
    $PrintName="$lastname, $firstname $title";
    $PrintName=~s/\s+/ /g;
#
# Handle sub index boundry
#
    if (!($count%$MaxInIndex)) {
      if ($count) {
#
# End last index file and close, skipped first time
#
        print INDEX " - $LastName</A>\n";
        select(SUB);
        print "</ul>\n</ul>\n";
        if ($indx>1) {
          print "<A HREF=\"./$DB",($indx-1),".html\">Previous Index Page</A><BR>\n";
        }
        print "<A HREF=\"./$DB",($indx+1),".html\">Next Index Page</A>\n";
        print "<br>$HomePage\n" if ($HomePage);
        &IGMRKW;
        close(SUB);
        $indx++;
        select(STDOUT);
      }
      print INDEX "<LI><A HREF=\"./$DB$indx.html\">$PrintName";
#
# Open next index file and output heading
#
      open(SUB,"> $LocIGMDir/$DB/$DB$indx.html");
      select(SUB);
      &heading('');
      select(STDOUT);
    }
#
# Surname stuff
#
    if (($Surname ne '') && ($Surname ne $Lastsurname)) {
      $FirstLetter=substr($Surname,0,1);
      if (($LastFirstLetter ne '') && ($FirstLetter ne $LastFirstLetter)) {
        print SUR "[$surcount]\n<hr>\n";
      } else {
        print SUR "[$surcount], \n" if ($Lastsurname ne '');
      }
      print SUR "<A HREF=\"./$DB$indx.html#$Surname\">$Surname</A>";
      $Lastsurname=$Surname;
      $LastFirstLetter=$FirstLetter;
      print SUB "<A NAME=\"$Surname\"></A>\n";
      $surcount=1;
    } else {
      $surcount++
    }
#
# Output name to sub index file
#
    print SUB "<LI><A HREF=\"/$WebCGIDir/$GetScript/n=$DB?$seek\">$PrintName</A> ($birthdate - $deathdate)\n";
    if ($photo) {
      print SUB "<IMG SRC=\"/$WebIGMDir/$Photo\" ALT=\"*Photo*\">\n";
    }

    $LastName=$PrintName;

    $count++;
  }
#
# Finish off sub index
#
  select(SUB);
  print "</ul>\n</ul>\n";
  if ($indx>1) {
    print "<A HREF=\"./$DB",($indx-1),".html\">Previous Index Page</A><BR>\n";
  }
  print "<br>$HomePage\n" if ($HomePage);
  &IGMRKW;
  close(SUB);
#
# Finish off master index
#
  select(INDEX);
  print INDEX " - $LastName</A>\n</ul>\n</ul>\n";        
  print "<br>$HomePage\n" if ($HomePage);
  &IGMRKW;
  close(INDEX);
#
# Finish off Surname Index
#
  select(SUR);
	  print "[$surcount]" if ($surcount);
  print "\n</ul>\n";
  print "<br>$HomePage\n" if ($HomePage);
  &IGMRKW;
  close(SUR);
  select(STDOUT);
#
# Create Photo index
#
  if ($PhotoCount>0) {
    open(PHOTO,">$LocIGMDir/$DB/$DB-photo.html") || die("Error creating photo index");
    select(PHOTO);
    &heading ('Photo');
    foreach $list (@photolist) {
      ($Surname,$j1,$j2,$j3,$name,$birthdate,$birthplace,$deathdate,$deathplace,$seek,$photo)=split(/\@/,$list);
      $name=&IGMConvert($name);
#
# Reorder name
#
      ($firstname,$lastname,$title)=$name=~m#(.*)/(.*)/,*\s*(.*)#;
      $PrintName="$lastname, $firstname $title";
      $PrintName=~s/\s+/ /g;
      print "<LI><A HREF=\"/$WebCGIDir/$GetScript/n=$DB?$seek\">$PrintName</A> ($birthdate - $deathdate)\n";
    }
#
# Finish off Photo Index
#
    print "\n</ul>\n</ul>\n";
    print "<br>$HomePage\n" if ($HomePage);
    &IGMRKW;
    close(PHOTO);
    select(STDOUT);
  }
#
# Create Log File if needed
#
  $file = "$LocIGMDir/$DB/igmlog.html";
  if (!( -e $file ))  {
    open ( INDEX, "> $file" ) || die ( "Error opening $file." );
    select(INDEX);
    &IGMHeader('Access Log');
    close (INDEX);
    select(STDOUT);
  }
  chmod(0666,$file);
#
# Create access count file if needed
#
  $file="$LocIGMDir/$DB/$DB.cnt";
  if (!( -e $file ))  {
    open (INDEX, "> $file") || die ( "Error opening $file." );
    print INDEX '1';
    close (INDEX);
  }
  chmod(0666,$file);

  print "HTML Generation Complete.                    \n";
}
#
# HTML Page heading subroutine
#
sub heading {
  local($Type)=@_;         # = Master Photo "" Surname
  &IGMHeader("$Type Index");

  if ($Type eq 'Master') {
    print "This database contains $PersonCount people, $NameCount names, ";
    if ($PhotoCount>0) {
      print "$PhotoCount photographs, ";
    }
    print "and is derived from a $LineCount line GEDCOM file.\n<br>";
    print "GEDCOM file last updated $Updated. ";
  }
  print "For further information, contact:\n";
  print "<BLOCKQUOTE>$Submitter</BLOCKQUOTE>\n";

  print "The $NewTitle genealogical database can be searched several ways:\n<UL>\n";

  if ($Type ne 'Master') {
    print "<LI><A HREF=\"./$DB.html\">Return to the Master Index</A>\n";
  }

  print "<LI><A HREF=\"/$WebCGIDir/$SrchScript/n=$DB\">Search for a name in the database.</A>";
  if ($AllowFind) {
    print "<LI><A HREF=\"/$WebCGIDir/$FindScript/n=$DB\">Search for a string in the database.</A>";
    print " Very slow. Use sub-indexes below for surname searches.\n";
  }

  if ($Type ne 'Surname') {
    print "<LI><A HREF=\"$DB-surname.html\">Search an index of ALL surnames in the $NewTitle database.</A>\n";
  }

  if ( $Type ne 'Photo') {
    if ( $PhotoCount > 0 ) {
      print "<LI><A HREF=\"$DB-photo.html\">Search an index of individuals with photographs in the ";
      print "$NewTitle database.</A>\n";
    }
  }

  print "<LI><A HREF=\"igmlog.html\">Look at the $NewTitle Database Access Log</A>\n";

#  print "<BR><BR>\n";

  if ($Type eq 'Master') {
    print '<LI>Search the following sub-indexes:';
  } elsif ($Type eq 'Surname') {
    print '<LI>View individuals with the following surnames:';
  } else {
    print '<LI>View information for the following individuals:';
  }

  print "<UL>\n";
}
