#!/usr/bin/perl
#
# Add Tier info to Database table
#
###############################################################################
#
# Copyright R.J.J.H. van Son © 2000, 2001
#
# Author Rob van Son
# Institute of Phonetic Sciences & ACLC
# University of Amsterdam
# Herengracht 338
# NL-1016CG Amsterdam, The Netherlands
# Email: Rob.van.Son@hum.uva.nl
#        rob.van.son@workmail.com
# WWW  : http://www.fon.hum.uva.nl/rob/
# mail:  Institute of Phonetic Sciences
#        University of Amsterdam
#        Herengracht 338
#        NL-1016CG Amsterdam
#        The Netherlands
#        tel +31 205252183
#        fax +31 205252197
#
# License for use and disclaimers
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#
#######################################################
#
no utf8;
#
$HomeDir = '../../..';
require "$HomeDir/Links.pl";

# Remove password for writing access
$DBMSpassword = '';
require "$HomeDir/connectDBD.pl";

my $Target = "phoneme";

@ARGV = ( 'phonemes', 'syllparts', 
'syllables', 'lexsyll', 'words', 'cgn', 'lexcgn'
, 'translit') unless @ARGV;

# Skip sentence margins
my ($prevIDposition, $nextIDposition) = (0, 0);

my $Tier;
foreach $Tier (@ARGV)
{
      # A list of all ID's already entered (to prevent double entries)
      my %IdTable = ();
      my $DatabaseCreated = 0;

      $Tier = uc($Tier);

      my $TableName = "${Tier}$Target";

      my @Columns = ();
      my @ValueTypes = ();
      # Limit the glob to 4 character speaker ID codes to prevent name-in-name errors
      my @FileList = glob("$DatabaseTables/$Target/[FM][0-9][0-9][A-Z]$TableName.txt.gz");
      foreach $FilePath (@FileList)
      {

	   open(INPUT, "gunzip -qc $FilePath|") || die "gunzip -qc $FilePath|: $!\n";

	   # Get the first line
	   my $Header = <INPUT>;
	   chomp($Header);
	   # Remove leading #
	   $Header =~ s/^\s*\#[\>]?\s*//g;

	   # Skip comments
	   while(($Line = <INPUT>) =~ /^\s*(\#[\>]?\s*|$)/)
	   { 
	   	if($Line =~ /^\s*\#[\>]\s*/)
		{
			$Header .= "\t$'";
	   		chomp($Header);
		};
	   };

	   unless($DatabaseCreated)
	   {
		   # Remove old table
		   $result = $conn->do("DROP TABLE $TableName");

                   print STDERR $conn->errstr, 
                                   ":\nDROP TABLE $TableName;\n" if $conn->err;
                        
		   # Create new table	
		   # Column names
		   @Columns = split(/[\t]+/, $Header);
		   @ValueTypes = map {/\[([^\]]+)\]/; $1;} @Columns;
# Kludge to correct header error
@ValueTypes = map {s/INT1/INT2/g; $_;} @ValueTypes;
		   @Columns = map {/\s+\[([^\]]+)\]/i; $`;} @Columns;

		   # Construct table definition for CREATE
		   my $i;
		   $ColumnDef = "";

		   for($i=0; $i < scalar(@Columns); ++$i)
		   {
	        	   $Columns[$i] = "EndTime" if $Columns[$i] eq 'End';
			   $ColumnDef .= "$Columns[$i] $ValueTypes[$i], \n";
			   $prevIDposition = $i if $Columns[$i] =~ 'prevID';
			   $nextIDposition = $i if $Columns[$i] =~ 'nextID';
		   };
		   $ColumnDef =~ s/\,\s*$//g;
		   # Create table
		   $result = $conn->do("CREATE TABLE $TableName ($ColumnDef);");

		   print STDERR $conn->errstr,  
				   ":\nCREATE TABLE $TableName ($ColumnDef);\n" if $conn->err;

		   $DatabaseCreated = scalar(@Columns);
	   };

	   # Fill Table (NOTE: the first line has already been read!)
	   while($Line)
	   {
		   # Skip comments and empty lines
		   ($Line = <INPUT>, next) if $Line =~ /^\s*(\#|$)/;
		   chomp($Line);
		   $Line =~ s/\s+$//g;

		   my @Values = split(/\t/, $Line);
		   
		   # Add '-quotes to char values
		   my $InsertList = "";
		   my $i;
		   for($i=0; $i < scalar(@Values); ++$i)
		   {
	        	   $Values[$i] =~ s/\'/\\\'/g;
			   $Values[$i] = "E'$Values[$i]'" if($ValueTypes[$i] =~ /char|text/i 
			    				&& $Values[$i] ne 'NULL');
		   };

		   # Read next line
		   $Line = <INPUT>;

		   # Make sure NO values are entered that do NOT have a the first two entries
		   next unless $Values[0] && $Values[1];

		   if(scalar(@Values) != $DatabaseCreated)
		   {
	     	  print STDERR "ERROR: ", scalar(@Values), " found where $DatabaseCreated expected\n";
		      print STDERR join("\t", @Columns), "\n";
		      print STDERR join("\t", @Values), "\n";

		      next;
		   };

          # Do not process double entries! (supposes that the 4 value is unit ID)
          next if ++$IdTable{$Values[4]} > 1;
		  
          # Construct the insert list
		   my $InsertList = join(", ", @Values);

		   # Insert the record
		   $result = $conn->do("INSERT INTO $TableName VALUES ($InsertList);");

		   if($conn->err)
		   {
			   print STDERR $conn->errstr,  
				   ":\nINSERT INTO $TableName VALUES ($InsertList);\n";

			   while(@Values || @ValueTypes)
			   {
				   print STDERR shift(@Values), "\t", shift(@ValueTypes), "\n";
			   };

			   # die "$ColumnDef\n";
		   }; 
	   };

      };

      # Create indices on ID
      $result = $conn->do("CREATE INDEX ${TableName}_index ON $TableName (id);");

      print STDERR $conn->errstr, 
	    ": create index ${TableName}_index on $TableName (id);\n" if $conn->err;

      # Grant SELECT to user ANONYMOUS
      $conn->do("GRANT SELECT on $TableName TO PUBLIC");
      print "GRANT SELECT on $TableName TO PUBLIC: ",$conn->errstr, "\n";

      my @ary = $conn->selectrow_array("select count(id) from $TableName");

      print "Query $TableName: ",$conn->errstr, " ", $ary[0], "\n";

};
