#/usr/bin/perl
#
#  @file   make_mysql.pl
#  @author Fukasawa Mitsuo
#
#    Copyright (C) 2001 BEE Co.,Ltd. All rights reserved.
#
# 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.
#

my $host = "localhost";
my $user = "jyugem";
my $password = "jyugem";
my $dbname = "gem";

use POSIX;
use DBI;
use Mysql;

my($query, $dbh, $csvh, $sth);

if ($dbh = Mysql->connect($host, $dbname, $user, $password)) {
    print "ok connect\n";
} else {
    $MySQL::db_errstr ||= "";
    my $onhost = $host ? " (on $host)" : "";
    print STDERR qq{not connected: $MySQL::db_errstr
\tIt looks as if your server$onhost is not up and running.
\tThis test requires a running server.
\tPlease make sure your server is running and retry.
};
    exit;
}

if ($dbh->selectdb($dbname)) {
    print("ok select\n");
} else {
    die qq{not selected: $MySQL::db_errstr
    Please make sure that a database \"$dbname\" exists
    and that you have permission to read and write on it
};
}

$csvh = DBI->connect(qq{DBI:CSV:csv_sep_char=,;csv_eol=\n;});

create_db();
insert_variables();
insert_alarm();
insert_alcd();
insert_config();
insert_event();
insert_evt_action();
insert_evt_report();
insert_report();
insert_rpt_data();
insert_trigger();
insert_traces();
insert_trace_vars();
insert_limit();
insert_limit_attrs();
insert_spool_primitives();
insert_sac();
# insert_recipe();
insert_subsystem();

#
$csvh->disconnect();

exit;

########################################################################
# drop table
#
sub drop { shift->query("drop table if exists $_[0]"); }

########################################################################
# convert value to bool
#
sub conv_bool {
    my $value = @_[0];
    if ($value eq "true" || $value eq "TRUE" ||
        $value eq "false" || $value eq "FALSE") {
        return $value;
    }
    if ($value != 0) {
        return "true";
    }
    return "false";
}

########################################################################
# Create Tables for JYUGEM
#
sub create_db {
    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'gemdb.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();
    my $table_name = "";
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        next SKIP if (length($row->{'ITEM'}) == 0);
        if ($row->{'TABLE'}) {
            if ($table_name) {
                # Create the last table
                print("CREATE TABLE $table_name ($fields)\n");
                drop($dbh, $table_name);
                $dbh->query("CREATE TABLE $table_name ($fields)");
            }
            # Initial new table attributes
            $table_name = $row->{'TABLE'};
            $fields = undef;
        }
        $fields .= ", " unless !$fields;
        my $item_name = $row->{'ITEM'};
        my $item_type = $row->{'TYPE'};
        my $item_size = $row->{'SIZE'};
        my $primary_key = $row->{'KEY'};
        my $not_null = $row->{'NOT NULL'};
        my $default_value = $row->{'DEFAULT'};

        $fields .= "$item_name ";
        if ($item_type eq "VARCHAR") {
            if ($item_size <= 255) {
                $fields .= "VARCHAR";
                $fields .= "($item_size)";
            } elsif ($item_size <= 65535) {
                $fields .= "TEXT";
            } else {
                $fields .= "LONGTEXT";
            }
        } elsif ($item_type eq "INTEGER") {
            if ($item_size <= 3) {
                $fields .= "TINYINT";
            } elsif ($item_size <= 6) {
                $fields .= "SMALLINT";
            } elsif ($item_size <= 10) {
                $fields .= "INT";
            } else {
                $fields .= "BIGINT";
            }
        } elsif ($item_type eq "DATE") {
            $fields .= "DATETIME";
        } elsif ($item_type eq "BOOLEAN") {
            $fields .= "ENUM('false', 'true')";
        }
        if ($primary_key eq "Y") {
            $fields .= " PRIMARY KEY";
        }
        if ($not_null eq "Y") {
            $fields .= " NOT NULL";
        }
        if (length($default_value) > 0) {
            if ($item_type eq "BOOLEAN") {
                my $default_bool = ($default_value != 0) ? 'true' : 'false';
                $fields .= " DEFAULT '$default_bool'";
            } else {
                $fields .= " DEFAULT '$default_value'";
            }
        }
    }
    if ($table_name) {
        print("CREATE TABLE $table_name ($fields)\n");
        drop($dbh, $table_name);
        $dbh->query("CREATE TABLE $table_name ($fields)");
    }
    $sth->finish();
}

########################################################################
# Insert variable data to G_VARIABLES table
#
sub insert_variables {
    print "insert variables\n";
    $dbh->query("DELETE FROM G_VARIABLES;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'variables.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    my $svid = 1;
    my $ecid = 1;
    my $dvid = 1;
    my $nodeta = 1;
    my $vid = 10000;     # vid is assigned by system
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'NAME'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_name = $row->{'NAME'};
        my $val_class_name = "$row->{'CLASS'}";
        my $val_vid  = "$row->{'VID'}";
        if (length($row->{'VID'}) == 0) {
            $val_vid = $val_name;
######      $val_vid = $vid;
            $vid += 1;
        }
        my $val_class = 0;
        if ($val_class_name eq "SV") {
            $val_class = 1;
        } elsif ($val_class_name eq "ECV") {
            $val_class = 2;
        } elsif ($val_class_name eq "DVVAL") {
            $val_class = 3;
        } elsif ($val_class_name eq "PV") {
            $val_class = 4;
        }
        my $val_esid  = "$row->{'ECSV_ID'}";
        if (length($row->{'ECSV_ID'}) == 0) {
            if ($val_class_name eq "SV") {
                $val_esid = "$row->{'VID'}";
                ### $val_esid = $svid;
                $svid += 1;
            } elsif ($val_class_name eq "ECV") {
                $val_esid = "$row->{'VID'}";
                ### $val_esid = $ecid;
                $ecid += 1;
            } elsif ($val_class_name eq "DVVAL") {
                $val_esid = $dvid;
                $dvid += 1;
            }
        }
        my $val_type  = oct sprintf("0%s", $row->{'VALTYPE'});
        my $val_size  = "$row->{'SIZE'}";
        if (length($row->{'SIZE'}) == 0) {
            if ($row->{'VALTYPE'} == 10) {
                $val_size = 1;
            } elsif ($row->{'VALTYPE'} == 11 || $row->{'VALTYPE'} == 31 ||
                     $row->{'VALTYPE'} == 51) {
                $val_size = 1;
            } elsif ($row->{'VALTYPE'} == 32 || $row->{'VALTYPE'} == 52) {
                $val_size = 2;
            } elsif ($row->{'VALTYPE'} == 34 || $row->{'VALTYPE'} == 44 ||
                     $row->{'VALTYPE'} == 54) {
                $val_size = 4;
            } elsif ($row->{'VALTYPE'} == 30 || $row->{'VALTYPE'} == 40 ||
                     $row->{'VALTYPE'} == 50) {
                $val_size = 8;
            } else {
                $val_size = 0;
            }
        }
        my $val_init = "$row->{'INIT_VAL'}";
        my $val_min  = "$row->{'MIN_VAL'}";
        my $val_max  = "$row->{'MAX_VAL'}";
        if ($row->{'VALTYPE'} == 11) {
            $val_init = conv_bool("$row->{'INIT_VAL'}");
            $val_min  = "false";
            $val_max  = "true";
        }
        my $val_item  = "$row->{'ITEM_NAME'}";
        my $val_objtype = "$row->{'OBJTYPE'}";
        my $val_attribute = "$row->{'ATTRIBUTE'}";
        my $val_substantiator = "$row->{'SUBSTANTIATOR'}";
        my $val_limit = ($row->{'LIMIT'} eq "Y") ? 'true' : 'false';
        my $val_trgid  = "$row->{'TRIGGER'}";
        my $val_devid  = "$row->{'IODEV_ID'}";
        my $val_offset = "$row->{'OFFSET'}";
        if (length($row->{'OFFSET'}) == 0) {
            $val_offset = 0;
        } else {
            $val_offset = oct($row->{'OFFSET'}) if $row->{'OFFSET'} =~ /^0/;
        }
        my $val_unit  = "$row->{'UNIT'}";
        my $val_enable = ($row->{'ENABLED'} eq "N") ? 'false' : 'true';
        my $val_saved = ($row->{'SAVED'} eq "Y") ? 'true' : 'false';

        my $value = "'$val_vid','$val_esid','$val_name',$val_class,$val_type, \
                     $val_size,'$val_init','$val_min','$val_max','$val_item', \
                     '$val_objtype','$val_attribute','$val_substantiator', \
                     '$val_limit','$val_trgid','$val_devid', \
                     $val_offset,'$val_unit','$val_enable','$val_saved'";
        my $items = "VID,ECSV_ID,NAME,CLASS,VALTYPE,SIZE,INIT_VAL,MIN_VAL, \
                     MAX_VAL,ITEM_NAME,OBJTYPE,ATTRIBUTE,SUBSTANTIATOR, \
                     LIMIT_ENABLED,TRIGGER,IODEV_ID,IODEV_OFFSET,UNIT, \
                     ENABLED,SAVED";
        ###   print("INSERT INTO G_VARIABLES($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_VARIABLES($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert alarm data to G_ALARM table
#
sub insert_alarm {
    print "insert alarm\n";
    $dbh->query("DELETE FROM G_ALARM;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'alarm.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    my $vid = 1;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        next SKIP if (! isdigit($row->{'ALID'}));
        next SKIP if (length($row->{'ALID'}) == 0);
        $fields .= ", " unless !$fields;
        my $val_alid = $row->{'ALID'};
        my $val_altx_j = $row->{'ALTX(Japanese)'};
        my $val_altx = $row->{'ALTX(English)'};
        my $val_alcd = $row->{'ALCD'};
        if (length($row->{'ALCD'}) == 0) {
            $val_alcd = 0;
        }
        my $val_disposal = $row->{'DISPOSAL'};
        my $val_aled = true;
        if (length($row->{'ENABLED'}) > 0) {
            if ($row->{'ENABLED'} ne "Y") {
                $val_aled = false;
            }
        }
        my $val_vid = $row->{'VID'};
        my $value = "$val_alid,'$val_altx','false','$val_aled',$val_alcd, \
                     '$val_disposal','$val_vid'";
        my $items = "ALID,ALTX,ALM_STATUS,ENABLED,ALCD,DISPOSAL, \
                     VID";
        ### print("INSERT INTO G_ALARM($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_ALARM($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert alcd data to G_ALCD table
#
sub insert_alcd {
    print "insert alcd\n";
    $dbh->query("DELETE FROM G_ALCD;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'alcd.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();
    my $fields = undef;
    my $vid = 1;
    my $nodeta = 1;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'ALCD'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_alcd = $row->{'ALCD'};
        my $val_note_j = "$row->{'ALCD_TEXT(Japanese)'}";
        my $val_note = "$row->{'ALCD_TEXT(English)'}";
        my $val_danger;
        if ($row->{'DANGER'} eq "IMMINENT") {
            $val_danger = 100;
        } elsif ($row->{'DANGER'} eq "POTENTIAL") {
            $val_danger = 50;
        } else {
            $val_danger = 0;
        }
        my $val_operator = ($row->{'AF_OPERATOR'} eq "Y") ? true : false;
        my $val_equipment = ($row->{'AF_EQUIPMENT'} eq "Y") ? true : false;
        my $val_material = ($row->{'AF_MATERIAL'} eq "Y") ? true : false;
        my $value = "$val_alcd,'$val_note',$val_danger,'$val_operator', \
                     '$val_equipment','$val_material'";
        my $items = "ALCD,ALCD_TEXT,DANGER,AF_OPERATOR,AF_EQUIPMENT,AF_MATERIAL";
        ### print("INSERT INTO G_ALCD($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_ALCD($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert configuration data to G_CONFIG table
#
sub insert_config {
    print "insert configuration data\n";
    $dbh->query("DELETE FROM G_CONFIG;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'config.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
         if (length($row->{'PARM_NAME'}) == 0) {
             if ($nodata == 1) {
                 last;
             } else {
                 $nodata = 1;
                 next SKIP;
             }
         }
         $nodata = 0;
         $fields .= ", " unless !$fields;
         my $parm_name = $row->{'PARM_NAME'};
         my $val_value = "$row->{'VALUE'}";
         my $val_unit = "$row->{'UNIT'}";
         my $category = "$row->{'CATEGORY'}";
         my $sub_category = "$row->{'SUB_CATEGORY'}";
         my $val_vid  = "$row->{'VID'}";
         my $val_note  = "$row->{'NOTE'}";

         my $value = "'$parm_name','$val_value','$val_unit','$category', \
                      '$sub_category','$val_vid','$val_note'";
         my $items = "PARM_NAME,VALUE,UNIT,CATEGORY,SUB_CATEGORY,VID,NOTE";
         ### print("INSERT INTO G_CONFIG($items) VALUES ($value)\n");
         $dbh->query("INSERT INTO G_CONFIG($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert event data to G_EVENT table
#
sub insert_event {
    print "insert event\n";
    $dbh->query("DELETE FROM G_EVENT;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'event.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'CEID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_ceid = $row->{'CEID'};
        my $val_name = $row->{'CENAME'};
        my $val_enable = ($row->{'ENABLED'} eq "N") ? false : true;
        my $category = "$row->{'CATEGORY'}";
        my $val_action = "$row->{'EVT_ACTION'}";

        my $value = "'$val_ceid','$val_name','$val_enable','$category', \
                     '$val_action'";
        my $items = "CEID,CENAME,ENABLED,CATEGORY,EVT_ACTION";
        ### print("INSERT INTO G_EVENT($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_EVENT($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert event action data to G_EVT_ACTION table
#
sub insert_evt_action {
    print "insert event action\n";
    $dbh->query("DELETE FROM G_EVT_ACTION;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'evt_action.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
         if (length($row->{'EVT_ACTION'}) == 0) {
              if ($nodata == 1) {
                  last;
              } else {
                  $nodata = 1;
                  next SKIP;
              }
         }
         $nodata = 0;
         $fields .= ", " unless !$fields;
         my $val_act = $row->{'EVT_ACTION'};
         my $val_note = $row->{'ACT_NOTE'};

         my $value = "'$val_act','$val_note'";
         my $items = "EVT_ACTION,ACT_NOTE";
         ### print("INSERT INTO G_EVENT($items) VALUES ($value)\n");
         $dbh->query("INSERT INTO G_EVT_ACTION($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert event report data to G_EVT_REPORT table
#
sub insert_evt_report {
    print "insert event report\n";
    $dbh->query("DELETE FROM G_EVT_REPORT;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'evt_report.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");

    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'CEID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_ceid = $row->{'CEID'};
        my $val_rptid = $row->{'RPTID'};
        my $val_seq = "$row->{'SEQ_NUM'}";

        my $value = "'$val_ceid','$val_rptid','$val_seq'";
        my $items = "CEID,RPTID,SEQ_NUM";
        ### print("INSERT INTO G_EVENT($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_EVT_REPORT($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert report data to G_REPORT table
#
sub insert_report {
    print "insert report\n";
    $dbh->query("DELETE FROM G_REPORT;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'report.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'RPTID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_rptid = $row->{'RPTID'};
        my $val_rptname = "$row->{'RPT_NAME'}";

        my $value = "'$val_rptid','$val_rptname'";
        my $items = "RPTID,RPT_NAME";
        ###  print("INSERT INTO G_REPORT($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_REPORT($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert report variable data to G_RPT_DATA table
#
sub insert_rpt_data {
    print "insert report data\n";
    $dbh->query("DELETE FROM G_RPT_DATA;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'rpt_data.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'RPTID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_rptid = $row->{'RPTID'};
        my $val_vid = "$row->{'VID'}";
        my $val_seq = "$row->{'SEQ_NUM'}";

        my $value = "'$val_rptid','$val_vid','$val_seq'";
        my $items = "RPTID,VID,SEQ_NUM";
        ### print("INSERT INTO G_RPT_DATA($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_RPT_DATA($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert trigger data to G_TRIGGER table
#
sub insert_trigger {
    print "insert trigger data\n";
    $dbh->query("DELETE FROM G_TRIGGER;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'trigger.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'TRIGGER'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_act = $row->{'TRIGGER'};
        my $val_type = $row->{'TRIGGER_TYPE'};
        my $val_mngr = $row->{'MANAGER'};
        my $val_name = $row->{'TRIGGER_NAME'};
        my $val_vid = $row->{'VID'};
        my $val_priority = $row->{'PRIORITY'};
        if ($row->{'PRIORITY'} < 1) {
            $val_priority = 1;
        }
        my $val_algo = $row->{'ALGORITHM'};

        my $value = "'$val_act','$val_type','$val_mngr','$val_name', \
                     '$val_vid',$val_priority,'$val_algo'";
        my $items = "TRIGGER,TRIGGER_TYPE,MANAGER,TRIGGER_NAME,VID,PRIORITY, \
                     ALGORITHM";
        ### print("INSERT INTO G_TRIGGER($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_TRIGGER($items) VALUES ($value)");
    }

    $sth->finish();
}

########################################################################
# Insert trace data to G_TRACES table
#
sub insert_traces {
    print "insert traces data\n";
    $dbh->query("DELETE FROM G_TRACES;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'traces.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'TRID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_trid = $row->{'TRID'};
        my $val_dsper = "$row->{'DSPER'}";
        my $val_totsmp = "$row->{'TOTSMP'}";
        my $val_repgsz = "$row->{'REPGSZ'}";

        my $value = "'$val_trid','$val_dsper','$val_totsmp','$val_repgsz'";
        my $items = "TRID,DSPER,TOTSMP,REPGSZ";
        ### print("INSERT INTO G_TRACES($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_TRACES($items) VALUES ($value)");
    }

    $sth->finish();
}


########################################################################
# Insert trace variable id to G_TRACE_VARS table
#
sub insert_trace_vars {
    print "insert trace_vars data\n";
    $dbh->query("DELETE FROM G_TRACE_VARS;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'trace_vars.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");
    $sth->execute();

    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'TRID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_trid = $row->{'TRID'};
        my $val_vid = "$row->{'VID'}";
        my $val_seqnum = "$row->{'SEQ_NUM'}";

        my $value = "'$val_trid','$val_vid',$val_seqnum";
        my $items = "TRID,VID,SEQ_NUM";
        ### print("INSERT INTO G_TRACE_VARS($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_TRACE_VARS($items) VALUES ($value)");
    }

    $sth->finish();
}


########################################################################
# Insert limit variable id to G_LIMITS table
#
sub insert_limit {
    print "insert limits data\n";
    $dbh->query("DELETE FROM G_LIMITS;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'limit.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");

    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'VID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_vid = $row->{'VID'};
        my $val_ceid = "$row->{'CEID'}";
        my $val_unit = "$row->{'UNIT'}";
        my $val_maxval = "$row->{'MAX_VAL'}";
        my $val_minval = "$row->{'MIN_VAL'}";
        my $val_enable = ($row->{'ENABLED'} eq "N") ? false : true;
        my $val_limitid = "$row->{'LIMITID'}";
        my $val_transition = "$row->{'TRANSITION'}";

        my $value = "'$val_vid','$val_ceid','$val_unit','$val_maxval', \
                     '$val_minval','$val_enabled','$val_limitid',      \
                     '$val_transition'";
        my $items = "VID,CEID,UNIT,MAX_VAL,MIN_VAL,ENABLED,LIMITID,TRANSITION";
        ### print("INSERT INTO G_LIMITS($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_LIMITS($items) VALUES ($value)");
    }

    $sth->finish();
}


########################################################################
# Insert limit variable id to G_LIMIT_ATTRS table
#
sub insert_limit_attrs {
    print "insert limit_attrs data\n";
    $dbh->query("DELETE FROM G_LIMIT_ATTRS;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'limit_attrs.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");

    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'VID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_vid = $row->{'VID'};
        my $val_limitid = "$row->{'LIMITID'}";
        my $val_lowerdb = "$row->{'LOWERDB'}";
        my $val_upperdb = "$row->{'UPPERDB'}";
        my $val_enable = ($row->{'ENABLED'} eq "N") ? false : true;

        my $value = "'$val_vid','$val_limitid','$val_lowerdb','$val_upperdb', \
                     '$val_enable'";
        my $items = "VID,LIMITID,LOWERDB,UPPERDB,ENABLED";
        ### print("INSERT INTO G_LIMIT_ATTRS($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_LIMIT_ATTRS($items) VALUES ($value)");
    }

    $sth->finish();
}


########################################################################
# Insert spooling stream and function number to G_SPOOL_PRI table
#
sub insert_spool_primitives {
    print "insert spooling primitives\n";
    $dbh->query("DELETE FROM G_SPOOL_PRI;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'spool_pri.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");

    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'STREAM_NUM'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_stream = $row->{'STREAM_NUM'};
        my $val_function = "$row->{'FUNCTION_NUM'}";

        my $value = "'$val_stream','$val_function'";
        my $items = "STREAM_NUM,FUNCTION_NUM";
        ### print("INSERT INTO G_SPOOL_PRI($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_SPOOL_PRI($items) VALUES ($value)");
    }
    $sth->finish();
}


########################################################################
# Insert sub-system info to G_SAC table
#
sub insert_sac {
    print "insert sensor/actuator\n";
    $dbh->query("DELETE FROM G_SAC;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'sac.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");

    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'IODEV_ID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_iodev_id = $row->{'IODEV_ID'};
        my $val_iodev_name = $row->{'IODEV_NAME'};
        my $val_subsys = $row->{'SUBSYS_ID'};
        my $val_iodev_type = $row->{'IODEV_TYPE'};
        if ($row->{'IODEV_TYPE'} eq "CONTROL") {
            $val_iodev_type = 2;
        } elsif ($row->{'IODEV_TYPE'} eq "ACTUATOR") {
            $val_iodev_type = 1;
        } else {
            $val_iodev_type = 0;        # SENSOR
        }
        if ($row->{'IODATA_TYPE'} eq "VECTOR") {
            $val_iodata_type = 2;
        } elsif ($row->{'IODATA_TYPE'} eq "SCALAR") {
            $val_iodata_type = 1;
        } else {
            $val_iodata_type = 0;        # DISCRETE
        }
        my $val_format = $row->{'FORMAT'};
        if ($row->{'FORMAT'} eq "BITSET") {
            $val_format = 2;
        } elsif ($row->{'FORMAT'} eq "WORDSET") {
            $val_format = 4;
        } elsif ($row->{'FORMAT'} eq "STRING") {
            $val_format = 3;
        } elsif ($row->{'FORMAT'} eq "BIT") {
            $val_format = 1;
        } else {
            $val_format = 0;            # WORD
        }
        my $val_datanum = $row->{'DATANUM'};
        if (length($row->{'DATANUM'}) == 0) {
            $val_datanum = 1;
        }
        my $val_interval_time = $row->{'INTERVAL_TIME'};
        if (length($row->{'INTERVAL_TIME'}) == 0) {
            $val_interval_time = 0;
        }
        my $val_vlaue = $row->{'VALUE'};
        my $val_time_enabled = ($row->{'TIME_ENABLED'} eq "Y") ? true : false;
        my $val_access_time = $row->{'ACCESS_TIME'};
        my $val_interlock = $row->{'INTERLOCK'};
        my $val_maxval = $row->{'MAX_VAL'};
        my $val_minval = $row->{'MIN_VAL'};
        my $val_dimension = $row->{'DIMENSION'};
        if (length($row->{'DIMENSION'}) == 0) {
            $val_dimension = 1;
        }
        my $val_deltaval = $row->{'DELTA_VAL'};
        my $val_enabled = ($row->{'RESET'} eq "Y") ? true : false;
        my $val_address = $row->{'ADDRESS'};
        my $val_algorithm = $row->{'ALGORITHM_ID'};
        my $val_enabled = ($row->{'ENABLED'} eq "N") ? false : true;
        if (length($row->{'IODEV_TYPE'}) == 0) {
            my $devname = $row->{'ADDRESS'};
            $devname =~ s/\d+//g;
            %devcode = (
                'X',    1,
                'Y',    2,
                'L',    3,
                'M',    4,
                'SM',   5,
                'F',    6,
                'TT',   7,
                'TC',   8,
                'CT',    9,
                'CC',   10,
                'TN',   11,
                'CN',   12,
                'D',    13,
                'SD',   14,
                'TM',   15,
                'TS',   16,
                'CM',   17,
                'CS',   18,
                'A',    19,
                'Z',    20,
                'V',    21,
                'R',    22,
                'ER',   22001,
                'B',    23,
                'W',    24,
                'QSB',  25,
                'STT',  26,
                'STC',  27,
                'QSW',  28,
                'QV',   30,
                'STN',  35,
                'LX',   1001,
                'LY',   2001,
                'LB',   23001,
                'LW',   24001,
                'LSB',  25001,
                'LSW',  28001,
                'SPG',  29000,
                'MRB',  33,
                'Ww',   36,
                'Wr',   37,
                'SPB',  50,
                'RBM',  32768,
                'RAB',  32800,
                'RX',   32801,
                'RY',   32802,
                'RW',   32804,
                'SB',   32867,
                'SW',   32868,
            );
            # $val_iodev_type = $devcode{$devname};
        }

        my $value = "'$val_iodev_id','$val_iodev_name','$val_subsys', \
                     $val_iodev_type,$val_iodata_type,$val_format,$val_datanum, \
                     $val_interval_time,'$val_vlaue','$val_time_enabled', \
                     '$val_access_time','$val_interlock','$val_maxval', \
                     '$val_minval',$val_dimension,'$val_deltaval', \
                     '$val_address', '$val_reset', \
                     '$val_algorithm', '$val_enabled'";
        my $items = "IODEV_ID,IODEV_NAME,SUBSYS_ID,IODEV_TYPE,IODATA_TYPE, \
                     FORMAT,DATANUM,INTERVAL_TIME,VALUE,TIME_ENABLED,ACCESS_TIME, \
                     INTERLOCK,MAX_VAL,MIN_VAL,DIMENSION,DELTA_VAL,ADDRESS, \
                     RESET,ALGORITHM_ID,ENABLED";
        ### print("INSERT INTO G_SAC($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_SAC($items) VALUES ($value)");
    }
    $sth->finish();
}


########################################################################
# Insert recipe info. to G_RECIPE table
#
sub insert_recipe {
    print "insert recipe info.\n";
    $dbh->query("DELETE FROM G_RECIPE;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'recipe.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");

    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'NAME'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_name = $row->{'NAME'};
        my $val_class = "$row->{'CLASS'}";
        my $val_version = "$row->{'VERSION'}";
        my $val_attrlen = "$row->{'ATTRLENGTH'}";
        my $val_attrtime = "$row->{'ATTRCHGTIME'}";
        my $val_bodylen = "$row->{'BODYLENGTH'}";
        my $val_bodytime = "$row->{'BODYCHGTIME'}";
        my $val_editby = "$row->{'EDITBY'}";
        my $val_bodyfrm = "$row->{'BODYFORMAT'}";
        my $val_verified = ($row->{'VERIFIED'} eq "Y") ? true : false;
        my $val_linked = ($row->{'LINKED'} eq "Y") ? true : false;
        my $val_comments = "$row->{'COMMENTS'}";
        my $val_path = "$row->{'PATH'}";

        my $value = "'$val_name','$val_class','$val_version',$val_attrlen, \
                     '$val_attrtime',$val_bodylen,'$val_bodytime', \
                     '$val_editby',$val_bodyfrm,'$val_verified', \
                     '$val_linked','$val_comments','$val_path'";
        my $items = "NAME,CLASS,VERSION,ATTRLENGTH,ATTRCHGTIME,BODYLENGTH, \
                     BODYCHGTIME,EDITBY,BODYFORMAT,VERIFIED,LINKED,COMMENTS, \
                     PATH";
        ### print("INSERT INTO G_RECIPE($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_RECIPE($items) VALUES ($value)");
    }
    $sth->finish();
}


########################################################################
# Insert subsystem info. to G_SUBSYSTEM table
#
sub insert_subsystem {
    print "insert subsystem info.\n";
    $dbh->query("DELETE FROM G_SUBSYSTEM;");

    $csvh->{'csv_tables'}->{'info'} = { 'file' => 'subsystem.csv'};
    $sth = $csvh->prepare("SELECT * FROM info");

    $sth->execute();
    my $fields = undef;
    SKIP: while (my $row = $sth->fetchrow_hashref) {
        if (length($row->{'SUBSYS_ID'}) == 0) {
            if ($nodata == 1) {
                last;
            } else {
                $nodata = 1;
                next SKIP;
            }
        }
        $nodata = 0;
        $fields .= ", " unless !$fields;
        my $val_subsysid = $row->{'SUBSYS_ID'};
        my $val_sysname = "$row->{'SUBSYS_NAME'}";
        my $val_objspec = "$row->{'OBJSPEC'}";
        my $val_systype = "$row->{'SUBSYS_TYPE'}";
        my $val_reloc = "$row->{'RELOC_NUM'}";
        my $val_matetype = "$row->{'MATERIAL_TYPE'}";
        if ($row->{'MATERIAL_TYPE'} eq "Carrier") {
            $val_matetype = 2;
        } elsif ($row->{'MATERIAL_TYPE'} eq "Wafer") {
            $val_matetype = 3;
        } elsif ($row->{'MATERIAL_TYPE'} eq "Substrate") {
            $val_matetype = 3;
        } elsif ($row->{'MATERIAL_TYPE'} eq "Durable") {
            $val_matetype = 1;
        } elsif ($row->{'MATERIAL_TYPE'} eq "ProcessDurable") {
            $val_matetype = 4;
        } else {
            $val_matetype = 0;
        }
        my $val_locid = "$row->{'LOC_ID'}";
        my $val_enabled = ($row->{'ENABLED'} eq "Y") ? true : false;

        my $value = "'$val_subsysid','$val_sysname','$val_objspec', \
                     '$val_systype',$val_reloc,$val_matetype,'$val_locid', \
                     '$val_enabled'";
        my $items = "SUBSYS_ID,SUBSYS_NAME,OBJSPEC,SUBSYS_TYPE,RELOC_NUM, \
                     MATERIAL_TYPE,LOC_ID,ENABLED";
        ### print("INSERT INTO G_SUBSYSTEM($items) VALUES ($value)\n");
        $dbh->query("INSERT INTO G_SUBSYSTEM($items) VALUES ($value)");
    }
    $sth->finish();
}



