#!/usr/bin/perl

use CGI;
use DBI;
use CGI::Carp (fatalsToBrowser);

$tv = new CGI;

### make the directory list
@dirlist = (CssBackgroundProperties,
  CssBorderProperties,
  CssClassificationProperties,
  CssFontProperties,
  CssClassificationProperties,
  CssFontProperties,
  CssMarginProperties,
  CssPaddingProperties,
  CssTextProperties,
  DomCollectionsAndArrays,
  DomEventHandlers,
  DomMethods,
  DomObjects,
  DomProperties,
  HtmlAttributes,
  HtmlEventHandlers,
  HtmlTags,
  JavaScriptControlStatements,
  JavaScriptGlobalFunctions,
  JavaScriptObjectMethods,
  JavaScriptObjectProperties,
  JavaScriptObjects,
  JavaScriptOperators,
  JavaScriptStatements);  

### connect to the database
$dbh = DBI->connect('DBI:mysql:host=mysql.domain.com;database=databasename', 'username', 'password', {'RaiseError' => 1}) or die "Cannot Connect to Database";

### create the master table
$query = qq{CREATE TABLE master (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tablename VARCHAR (200) NOT NULL,
    category VARCHAR (200)
    )};
$sth = $dbh->prepare($query);
$sth->execute();

$count = "0";
$dirlist_count = "0";
$filelist_count = "0";
$type = "text";
foreach (@dirlist) {
  while ($thisfile = <$dirlist[$dirlist_count]/*.txt>) {
    push @filelist, $thisfile;
  }
  foreach (@filelist) {
    open (FILEHANDLE, "$dirlist[$dirlist_count]/$filelist[$filelist_count]");
    $text = "";
    $newtext = "";
    while (read (FILEHANDLE, $newtext, 1)) {
      $text .= $newtext;
    }
    close FILEHANDLE;
    @split_text = split "\n", $text;
    $split_text_count = "0";
    foreach (@split_text) {
      $split_text[$split_text_count] =~ s/\n+//g;
      $this_split = $split_text[$split_text_count];
      $this_split =~ s/[ ]+//g;
      if ($this_split != "") {
        $query = qq{CREATE TABLE $filelist[$filelist_count] (
          type VARCHAR (200) NOT NULL,
          text BLOB
          )};
        $sth = $dbh->prepare($query);
        $sth->execute();
        
        $query = qq{INSERT INTO $filelist[$filelist_count] (
          type,
          text
          ) VALUES (
          '$type',
          '$split_text[$split_text_count]'
          )};
        $sth = $dbh->prepare($query);
        $sth->execute();

        $query = qq{INSERT INTO master (
          tablename,
          category
          ) VALUES (
          '$filelist[$filelist_count]',
          '$dirlist[$dirlist[$count]'
          )};
        $sth = $dbh->prepare($query);
        $sth->execute();

        ++$split_text_count;
        ++$count;
      }
    ++$filelist_count;
    }
  ++$dirlist_count;
  }

### print da shtuff
print qq{Content-type: text/html\n\n};
print qq{I'm Done!<br>};
print qq{I have created $count tables};
exit;
