namespace eval sql {
  variable error 0
  variable dbms_initialized 0

#
# Initialize the database driver (Load the .DLL)
  proc initDBMS { } {
    if { $sql::dbms_initialized } {
	return 1
    }
      
    incr sql::dbms_initialized
    if { [ string equal $::tcl_platform(platform) "unix" ] } {
    	load /usr/local/lib/libtclsqlite3.so
	return 2
    } else {
    	load libtclsqlite3.dll
	return 3
    }

    set sql::dbms_initialized 0
    return 0

  }
  
# 
# Open the Database ...
  proc openDBMS { {path "Backup.dbms"} } {
    initDBMS
    set sql::error [ catch { sqlite3 db $path } ret ]
    return $ret
  }
  
# 
# Close the Database ...
  proc closeDBMS { {db "db"} } {
    return [ catch { db close } ]
  }
  
  proc printRows { query } {
    db eval $query row {
    	parray row
    }
  }

#
# Get machine specific resources from the table
# tied to the SQLite table Resource (name/value) ...
  proc readResources { } {
    array unset ::X
    set n 0 
    db eval "select * from resource" {
    	set ::X($name) $value
        incr n
    }
    return $n 
  }
  
#
# Return the variable names of an SQL table ...
  proc tbl_Vars { table } {
  
    set query [ format "select * from %s limit 1 ;" $table ] 
    db eval $query row {
    }
    return $row(*)
  }
  
#
# Cache an entire table contents ...
  proc cache_tbl_Data { table } {
  
    global Q_results
    global Q_ix
    global Q_n_Rows
    global Q_var_Names
  
    set Q_var_Names [ tbl_Vars $table ] 
    set query [ format "select * from %s ;" $table ] 
    set i 0 
    db eval $query row {
    	foreach fld $Q_var_Names {
          if [ string equal $fld "passwd" ] {
              set clear [sys::decrypt $row($fld) ]
              set Q_results($i,$fld) $clear
          } else {
              set Q_results($i,$fld) $row($fld)
          }
    	}
    	incr i
    }
    set Q_n_Rows $i
    set Q_ix 0 
    return $i
  }

#
# Return 1 row of a previously Cached table ...
  proc get_tbl_Row { ix } {
    array set ret {}
    if { $ix > $::Q_n_Rows } {
      return $ret
    }
    foreach var $::Q_var_Names {
      set ret($var) $::Q_results($ix,$var)
    }
    return [ array get ret ]
  }
  
  
}
