function creation($_GET)
{
    # get vars
    extract($_GET);
    require_lib("validate");
    $v = new validate();
    $v->isOk($name, "string", 2, 100, "Invalid company name.");
    if (!preg_match("/[\\d]/", $code)) {
        $v->isOk($code, "comp", 4, 4, "Error assigning company code. Please try again.");
    } else {
        $v->isOk($code, "comp", 10, 5, "Error assigning company code. Please try again.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirmCust = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirmCust .= "<li class='err'>" . $e["msg"] . "</li>";
        }
        return newcomp($confirmCust, $name, $code);
    }
    # Change code to lowercase
    $code = strtolower($code);
    # Check Code and Name
    if (newlib_ex("cubit", "companies", "code", $code)) {
        return newcomp("<li class='err'> Error assigning company code. Please try again.", $name, $code);
    }
    if (newlib_ex("cubit", "companies", "name", $name)) {
        return newcomp("<li class=err> Company with the entered name already exists.", $name, $code);
    }
    if (!exists_compdb($code)) {
        // create Cubits from the templates
        db_exec("CREATE DATABASE cubit_{$code} WITH template=cubit_blk1") or errDie("Unable to create company database.", SELF);
    }
    db_conn("cubit");
    $sql = "INSERT INTO companies (code, name, ver, status) VALUES ('{$code}', '{$name}', '" . CUBIT_VERSION . "', 'active')";
    $Rs = db_exec($sql) or errDie("Unable to insert company into Database.", SELF);
    global $CUBIT_MODULES;
    foreach ($CUBIT_MODULES as $modname) {
        $sql = "INSERT INTO comp_modules (code, module, version)\n\t\t\t\tVALUES('{$code}', '{$modname}', '" . CUBIT_VERSION . "')";
        db_exec($sql);
    }
    //$branch = branch("HO", "Head Office", "Head Office", $code);
    //$user = user($branch, $code);
    global $_SESSION;
    if (isset($_SESSION["USER_NAME"])) {
        $create = "\n\t\t\t<h3>New Company has been created.</h3>\n\t\t\t<p>\n\t\t\t<table border=0 cellpadding='1' cellspacing='1'>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='company-view.php'>View Companies</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        $create = "\n\t\t\t<script>\n\t\t\t\tdocument.location.href='index.php';\n\t\t\t</script>";
    }
    return $create;
}
function importFile()
{
    global $_FILES, $_POST, $psql_exec;
    extract($_POST);
    $OUTPUT = "<h3>Import Company</h3>";
    $v =& new Validate();
    if (!$v->isOk($compname, "string", 1, 250, "")) {
        return "<li class='err'>Invalid Company Name</li>" . selectFile();
    }
    // generate code
    $code = "aaaa";
    // make sure it 4 chars long by padding with a's
    $code = str_replace(" ", "", $code);
    $code = str_pad($code, 4, 'a', STR_PAD_RIGHT);
    while (1) {
        // check if the code exists
        db_con("cubit");
        $rslt = db_exec("SELECT * FROM companies WHERE code='{$code}'");
        // not exist! YAY!!
        if (pg_numrows($rslt) < 1 && !exists_compdb($code)) {
            break;
        }
        // increase
        $code[3] = chr(ord($code[3]) + 1);
        for ($i = 3; $i >= 0; $i--) {
            if (ord($code[$i]) > ord('z')) {
                $code[$i] = 'a';
                if ($i > 0) {
                    $code[$i - 1] = chr(ord($code[$i - 1]) + 1);
                }
                if (substr($code, 0, 3) == "zzz") {
                    $code = "aaaa";
                }
            }
        }
    }
    require_lib("progress");
    displayProgress("newtemplate.php");
    # Change code to lowercase
    $code = strtolower($code);
    // parse the import file
    if (PLATFORM == "windows") {
        $importfile = cfs::tempnam("cubitimport_");
    } else {
        $importfile = cfs::tempnam("cubitimport_");
    }
    if (!ucfs::valid("compfile")) {
        return "<li class='err'>" . ucfs::ferror("compfile") . "</li>";
    }
    $fd_in = ucfs::fopen("compfile", "r");
    $fd_out = cfs::fopen($importfile, "w", true);
    if ($fd_in === false) {
        return "<li class='err'>Unable to open import file.</li>";
    }
    if ($fd_out === false) {
        return "<li class='err'>Unable to open temporary file required to import company.</li>";
    }
    $company_ver = "";
    while (!cfs::feof($fd_in)) {
        $buf = cfs::fgets($fd_in, 4096);
        // get the version of imported company if on this line
        $pos = strpos($buf, "-- V'e'r's'i'o'n:");
        if ($pos !== false && $pos == 0) {
            $company_ver = trim(substr($buf, 17));
        }
        // check if it valid platform
        $pos = strpos($buf, "-- P'l'a't'f'o'r'm:");
        if ($pos !== false && $pos == 0) {
            $comp_platform = trim(substr($buf, 19));
            if (PLATFORM != $comp_platform) {
                $OUTPUT .= "You cannot import another platform's company!<br>\n\t\t\t\t\tOnly from Windows to Windows or Linux to Linux.<br><Br>\n\t\t\t\t\tYour platform: " . PLATFORM . "<Br>\n\t\t\t\t\tProposed Imported Company Platform: {$comp_platform}<br>";
                return $OUTPUT;
            }
        }
        // parse the create database code variable if on this line
        $pos = strpos($buf, "CREATE DATABASE");
        if ($pos !== false && strpos($buf, "%c'o'd'e%") > 0) {
            $buf = str_replace("%c'o'd'e%", $code, $buf);
        }
        // parse the company code variable if on this line
        $pos = strpos($buf, "\\c ");
        if ($pos !== false && strpos($buf, "%c'o'd'e%") > 0) {
            $buf = str_replace("%c'o'd'e%", $code, $buf);
        }
        fputs($fd_out, $buf);
    }
    fclose($fd_in);
    fclose($fd_out);
    // get the version of current cubit
    db_con("cubit");
    $cubit_ver = CUBIT_VERSION;
    // check if versions are the same (TEMPORARY HACK, ai tog)
    if ($cubit_ver != $company_ver) {
        return $OUTPUT . "Versions do not match:<br>\n\t\t\tProposed Imported Company version is \"{$company_ver}\"<br>\n\t\t\tYour Cubit version is \"{$cubit_ver}\"<br>\n\t\t\t<br>\n\t\t\tCheck for updates for your Cubit to support the functionality of importing non matching versions.";
    }
    // import
    exec("{$psql_exec}/" . PSQL_EXE . " -U postgres template1 < {$importfile}");
    // insert the company
    db_con("cubit");
    db_exec("INSERT INTO companies (code,name,ver,status) VALUES('{$code}', '{$compname}', '{$company_ver}', 'active')");
    // if only one company in list, we can safely assume this was the first company
    // and forward to the login screen
    $sql = "SELECT * FROM companies";
    $rslt = db_exec($sql);
    if (!isset($_SESSION["USER_ID"]) && $rslt && pg_num_rows($rslt) > 0) {
        $_SESSION["code"] = $code;
        $_SESSION["comp"] = $compname;
        $OUTPUT = "<script>top.document.location.href='doc-index.php';</script>";
        return $OUTPUT;
        header("Location: main.php");
        exit;
    }
    $OUTPUT .= "\n\tCompany has been imported successfully.<br>\n\tCompany Name: {$compname}<br>\n\tCompany Code: {$code}<br>";
    return $OUTPUT;
}