diff --git a/drupalvb.admin-pages.inc b/drupalvb.admin-pages.inc
index 6e6cfd8..c8b8d66 100644
--- a/drupalvb.admin-pages.inc
+++ b/drupalvb.admin-pages.inc
@@ -1,24 +1,16 @@
 <?php
-
 /**
  * @file
  * Drupal vB system settings.
  *
- * Most parts forked from Migrator module, http://drupal.org/project/migrator
  */
 
 /**
  * Form builder function for DrupalvB integration settings.
  *
- * @todo Add vBulletin license.
  * @todo Add required vBulletin configuration values; remove drupalvb_get_config().
  */
 function drupalvb_settings_integration() {
-
-  //Check database is ok
-  drupalvb_db_connect();
-  drupalvb_db_disconnect();
-
   $form = array();
   $vb_config = drupalvb_get_config();
 
@@ -63,7 +55,6 @@ function drupalvb_settings_integration() {
     '#description' => t('Select to enable the account synchronization feature.'),
   );
 
-
   $roles = drupalvb_get_roles();
   $form['drupalvb_default_usergroup'] = array(
     '#type' => 'select',
@@ -109,7 +100,7 @@ function drupalvb_settings_database($form, &$form_state) {
       $db[$field] = $config[$vv[0]][$vv[1]];
     }
     if (count($form_state['input']) == 0) {
-      drupal_set_message(t("Verify vb configuration and save form"));
+      drupal_set_message(t("Verify vBulletin configuration and save form"));
     }
   }
 
@@ -169,15 +160,14 @@ function drupalvb_settings_database($form, &$form_state) {
 function drupalvb_settings_database_submit($form, &$form_state) {
   variable_set('drupalvb_db', $form_state['values']);
 
-  //Check database is ok
-  drupalvb_db_connect();
-  drupalvb_db_disconnect();
-
   $mappings = db_query_range("SELECT uid FROM {drupalvb_users}", 0, 1);
-  if (count($mappings) == 0) {
-    // First time setup; initialize DrupalvB's user mapping.
-    module_load_include('inc', 'drupalvb');
-    _drupalvb_init_user_map();
+  if (drupalvb_db_is_valid()) {
+    if (count($mappings) == 0) {
+      // First time setup; initialize DrupalvB's user mapping.
+      module_load_include('inc', 'drupalvb');
+      _drupalvb_init_user_map();
+    }
+    drupal_set_message(t("Database connection successful"));
   }
 }
 
@@ -185,9 +175,7 @@ function drupalvb_settings_database_submit($form, &$form_state) {
  * Form builder function for DrupalvB actions.
  */
 function drupalvb_settings_actions() {
-  //Check database is ok
-  drupalvb_db_connect();
-  drupalvb_db_disconnect();
+  drupalvb_db_is_valid();
 
   $form = array();
   $form['action']['action'] = array(
@@ -233,7 +221,7 @@ function drupalvb_settings_actions_submit($form, &$form_state) {
  */
 function drupalvb_settings_variables() {
   $form = array();
-  $options = drupalvb_get('options');
+  $options = drupalvb_get_options();
 
   $header = array(t('Name'), t('Value'));
   foreach ($options as $key => $value) {
diff --git a/drupalvb.inc b/drupalvb.inc
index c9180fc..8617e9b 100644
--- a/drupalvb.inc
+++ b/drupalvb.inc
@@ -8,77 +8,18 @@
  */
 
 /**
- * Add vB database connection and connect to remote system database.
- *
- * If remote system database connection is identical to Drupal's database
- * connection, we skip switching the connection and alter the prefix only.
- *
- * @see drupalvb_db_disconnect(), drupalvb_get()
- */
-function drupalvb_db_connect() {
-  // Check if remote database is accessible - otherwise prompt
-  // user to enter details.
-  if (drupalvb_db_is_valid()) {
-    db_set_active('drupalvb');
-  }
-  else {
-    if ($_GET['q'] === "user/logout") {
-      return FALSE;
-    }
-
-    if (user_access('administer drupalvb')) {
-      drupal_set_message(t('Invalid database connection for vBulletin. Please configure the connection in <a href="!settings">Drupal vB\'s settings</a>', array('!settings' => url('admin/settings/drupalvb/database'))), 'error');
-      drupal_goto('admin/config/system/drupalvb/database');
-    }
-    else {
-      drupal_set_message(t('There was an error connecting to vBulletin. Please contact the site administrator.'), 'error');
-    }
-  }
-
-  return TRUE;
-}
-
-/**
- * Disconnect from remote system database.
- *
- * @see drupalvb_db_connect(), drupalvb_get()
- */
-function drupalvb_db_disconnect() {
-  db_set_active();
-}
-
-/**
- * Helper function to recall Drupal's default database table prefix.
- *
- * @see drupalvb_set_default_prefix()
- */
-function drupalvb_get_default_db_prefix() {
-  global $db_prefix;
-  static $drupal_db_prefix;
-  if (!isset($drupal_db_prefix)) {
-    $drupal_db_prefix = $db_prefix;
-  }
-  return $drupal_db_prefix;
-}
-
-/**
- * Helper function to reset Drupal's default database table prefix.
- *
- * @see drupalvb_get_default_prefix()
- */
-function drupalvb_set_default_db_prefix() {
-  global $db_prefix;
-  $db_prefix = drupalvb_get_default_db_prefix();
-}
-
-/**
  * Check if a configured remote system database connection is valid.
  *
  * @see drupalvb_settings_system()
  */
 function drupalvb_db_is_valid() {
+  static $is_valid = NULL;
+  if ($is_valid!=NULL) {
+    return $is_valid;
+  }
+
   $db_info = Database::getConnectionInfo();
-  $db = variable_get('drupalvb_db',array_shift($db_info));
+  $db = variable_get('drupalvb_db', array_shift($db_info));
   $drupalvb = array(
     'database' => $db['database'],
     'username' => $db['username'],
@@ -91,36 +32,23 @@ function drupalvb_db_is_valid() {
 
   Database::addConnectionInfo('drupalvb', 'default', $drupalvb);
 
-
   try {
-    $previous = db_set_active('drupalvb');
-    db_query("SELECT COUNT(*) FROM usergroup");
-    db_set_active($previous);
-    return TRUE;
+    Database::getConnection('default', 'drupalvb')->queryRange("SELECT usergroupid FROM {usergroup}", 0, 1);
+    $is_valid = TRUE;
   }
   catch (Exception $e) {
     watchdog("drupalvb", $e->getMessage());
-    return FALSE;
-  }
-}
+    $is_valid = FALSE;
 
-/**
- * Generic database callback for querying pre-defined data from remote system.
- *
- * @param string $op
- *   The get-operation to perform in the remote system.
- */
-function drupalvb_get($op) {
-  $function = 'drupalvb_get_' . $op;
-  if (!function_exists($function)) {
-    return FALSE;
+    if (user_access('administer drupalvb')) {
+      drupal_set_message(t('Invalid database connection for vBulletin. Please configure the connection in <a href="!settings">Drupal vB\'s settings</a>', array('!settings' => url('admin/config/system/drupalvb/database'))), 'error');
+      drupal_goto('admin/config/system/drupalvb/database');
+    }
+    else {
+      drupal_set_message(t('There was an error connecting to vBulletin. Please contact the site administrator.'), 'error');
+    }
   }
-  drupalvb_db_connect();
-  $args = func_get_args();
-  array_shift($args);
-  $result = call_user_func_array($function, $args);
-  drupalvb_db_disconnect();
-  return $result;
+  return $is_valid;
 }
 
 /**
@@ -129,19 +57,10 @@ function drupalvb_get($op) {
  * @see db_query()
  */
 function drupalvb_db_query($query, $args = array(), $options = array()) {
-  drupalvb_db_connect();
-  //todo: make prefix work
-  //$query = db_prefix_tables($query);
-  // 'All arguments in one array' syntax
-  //if (isset($args[0]) and is_array($args[0])) {
-  // $args = $args[0];
-  //}
-  //_db_query_callback($args, TRUE);
-  //$query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
-  //$result = db_query($query,$args);
-  $result = db_query($query, $args, $options);
-  drupalvb_db_disconnect();
-  return $result;
+  if (!drupalvb_db_is_valid()) {
+    return new DatabaseStatementEmpty();
+  }
+  return Database::getConnection('default', 'drupalvb')->query($query, $args, $options);
 }
 
 /**
@@ -149,22 +68,20 @@ function drupalvb_db_query($query, $args = array(), $options = array()) {
  *
  * @see db_query_range()
  */
-function drupalvb_db_query_range($query, $args, $from, $count, $options = array()) {
-  drupalvb_db_connect();
-
-  $result = db_query_range($query, $from, $count, $args, $options);
-
-  drupalvb_db_disconnect();
-  return $result;
+function drupalvb_db_query_range($query, $from, $count, $args = array(), $options = array()) {
+  if (!drupalvb_db_is_valid()) {
+    return new DatabaseStatementEmpty();
+  }
+  return Database::getConnection('default', 'drupalvb')->queryRange($query, $from, $count, $args, $options);
 }
 
 /**
- * Return the last insert id.
+ * Insert into remote system database.
  *
- * Borrowed from Drupal 6.
+ * @see db_insert()
  */
-function drupalvb_db_last_insert_id($table, $field) {
-  return drupalvb_db_query('SELECT userid FROM {user} ORDER BY userid DESC LIMIT 1')->fetchField();
+function drupalvb_db_insert($table, $options = array()) {
+  return Database::getConnection('default', 'drupalvb')->insert($table, $options);
 }
 
 /**
@@ -188,9 +105,10 @@ function _drupalvb_init_user_map() {
   // into our mapping table.
   foreach ($result as $vbuser) {
     if (isset($users[$vbuser->username])) {
-      db_query("INSERT INTO {drupalvb_users} (uid, userid) VALUES (:uid, :userid)", array(
-        ':uid' => $users[$vbuser->username],
-        ':userid' => $vbuser->userid,
+      db_insert("drupalvb_users")
+      ->fields(array(
+        "uid" => $users[$vbuser->username],
+        "userid" => $vbuser->userid
       ));
     }
   }
diff --git a/drupalvb.inc.php b/drupalvb.inc.php
index 8a57b64..c0a0077 100644
--- a/drupalvb.inc.php
+++ b/drupalvb.inc.php
@@ -1,5 +1,4 @@
 <?php
-
 /**
  * @file
  * Drupal vB CRUD functions.
@@ -24,7 +23,7 @@ function drupalvb_set_login_cookies($userid) {
     return FALSE;
   }
 
-  $vb_options = drupalvb_get('options');
+  $vb_options = drupalvb_get_options();
   $cookie_prefix = drupalvb_get_cookieprefix();
   $cookie_path = $vb_options['cookiepath'];
   $now = time();
@@ -66,7 +65,7 @@ function drupalvb_set_login_cookies($userid) {
  * @see drupalvb_logout(), drupalvb_user_logout()
  */
 function drupalvb_clear_cookies($userid = NULL) {
-  $vb_options = drupalvb_get('options');
+  $vb_options = drupalvb_get_options();
 
   $cookie_prefix = drupalvb_get_cookieprefix();
   $cookie_path = $vb_options['cookiepath'];
@@ -85,6 +84,10 @@ function drupalvb_clear_cookies($userid = NULL) {
   //   since this is the cause for broken session handling. Proposal: Use
   //   drupalvb_get_ip() to count the # of sessions; if there exactly one,
   //   kill it.
+  // @ttkaminski's suggestion - validate the sessionhash and userid from the
+  //   cookies against the vBulletin session table.  If it matches, then kill
+  //   the session.
+
   if (!empty($userid)) {
     drupalvb_db_query("DELETE FROM {session} WHERE userid = :userid", array(':userid' => $userid));
     drupalvb_db_query("UPDATE {user} SET lastvisit = :time WHERE userid = :userid", array(":time" => time(), ":userid" => $userid));
@@ -172,17 +175,30 @@ function drupalvb_create_user($account, $edit) {
 
   // Default usergroup id.
   $usergroupid = variable_get('drupalvb_default_usergroup', '2');
-  $lid = drupalvb_get('languageid');
+  $lid = drupalvb_get_languageid();
   if (!isset($lid)) {
     $lid = 1;
   }
-  // Set up the insertion query.
-  $result = drupalvb_db_query("INSERT INTO {user} (username, usergroupid, password, passworddate, usertitle, email, salt, showvbcode, languageid, timezoneoffset, posts, joindate, lastvisit, lastactivity, options) VALUES (:username, :groupid, :password, :passworddate, :usertitle, :email, :salt, 1, :languageid, :timezoneoffset, 0, :joindate, :lastvisit, :lastactivity, :options)", array(":username" => drupalvb_htmlspecialchars($edit['name']), ":groupid" => $usergroupid, ":password" => $passhash, ":passworddate" => $passdate, ":usertitle" => $usertitle, ":email" => $edit['mail'], ":salt" => $salt, ":languageid" => 1, ":timezoneoffset" => $timezone, ":joindate" => $joindate, ":lastvisit" => time(), ":lastactivity" => time(), ":options" => $options));
-
-  $userid = drupalvb_db_last_insert_id('user', 'userid');
-
-  drupalvb_db_query("INSERT INTO {userfield} (userid) VALUES (:userid)", array(":userid" => $userid));
-  drupalvb_db_query("INSERT INTO {usertextfield} (userid) VALUES (:userid)", array(":userid" => $userid));
+  // Insert user to vBulletin
+  $userid = drupalvb_db_insert("user")
+  ->fields( array(
+    "username" => drupalvb_htmlspecialchars($edit['name']),
+    "usergroupid" => $usergroupid,
+    "password" => $passhash,
+    "passworddate" => $passdate,
+    "usertitle" => $usertitle,
+    "email" => $edit['mail'],
+    "salt" => $salt,
+    "languageid" => 1,
+    "timezoneoffset" => $timezone,
+    "joindate" => $joindate,
+    "lastvisit" => time(),
+    "lastactivity" => time(),
+    "options" => $options
+  ))->execute();
+
+  drupalvb_db_insert("userfield")->fields(array("userid" => $userid));
+  drupalvb_db_insert("usertextfield")->fields(array("userid" => $userid));
 
   // Insert new user into mapping table.
   drupalvb_set_mapping($account->uid, $userid);
@@ -236,14 +252,18 @@ function drupalvb_update_user($account, $edit) {
   $fields[] = 'lastactivity = :activity';
   $values[':activity'] = time();
 
-  // Use previous case insensitive username to update conflicting names.
-  $values[':username'] = drupalvb_htmlspecialchars($account->name);
-  drupalvb_db_query("UPDATE {user} SET " . implode(', ', $fields) . " WHERE LOWER(username) = LOWER(:username)", $values);
-
   // Ensure this user exists in the mapping table.
   // When integrating an existing installation, the mapping may not yet exist.
-  $userid = drupalvb_db_query("SELECT userid FROM {user} WHERE username = :name", array(':name' => drupalvb_htmlspecialchars($account->name)))->fetchField();
+  if (isset($edit['userid'])) {
+    $userid = $edit['userid'];
+  }
+  else {
+    $userid = drupalvb_db_query("SELECT userid FROM {user} WHERE username = :name", array(':name' => drupalvb_htmlspecialchars($account->name)))->fetchField();
+  }
   drupalvb_set_mapping($account->uid, $userid);
+
+  $values[':userid'] = $userid;
+  drupalvb_db_query("UPDATE {user} SET " . implode(', ', $fields) . " WHERE userid=:userid", $values);
 }
 
 /**
@@ -264,17 +284,14 @@ function drupalvb_set_mapping($uid, $userid) {
 function drupalvb_export_drupal_users() {
   module_load_include('inc', 'drupalvb');
 
-  $result = db_query("SELECT * FROM {users} ORDER BY uid");
+  $result = db_query("SELECT * FROM {users} WHERE uid>0 ORDER BY uid");
   foreach ($result as $user) {
-    if ($user->uid == 0) {
-      continue;
-    }
     // Let create/update functions know that passwords are hashed already.
     $user->md5pass = $user->pass;
     if (!drupalvb_create_user($user, (array)$user)) {
       // Username already exists, update email and password only.
       // Case insensitive username is required to detect collisions.
-      $vbuser = drupalvb_db_query("SELECT salt FROM {user} WHERE LOWER(username) = LOWER(:name)", array(':name' => drupalvb_htmlspecialchars($user->name)))->fetchAssoc();
+      $vbuser = drupalvb_db_query("SELECT salt,userid FROM {user} WHERE LOWER(username) = LOWER(:name)", array(':name' => drupalvb_htmlspecialchars($user->name)))->fetchAssoc();
       drupalvb_update_user($user, array_merge((array)$user, $vbuser));
     }
   }
@@ -287,7 +304,7 @@ function drupalvb_get_options() {
   static $options = array();
 
   if (empty($options)) {
-    $result = db_query("SELECT varname, value FROM {setting}");
+    $result = drupalvb_db_query("SELECT varname, value FROM {setting}");
     foreach ($result as $var) {
       $options[$var->varname] = $var->value;
     }
@@ -366,7 +383,7 @@ function drupalvb_get_languageid($language = NULL) {
       $vblanguages[$lang->languagecode] = $lang->languageid;
     }
   }
-  $options = drupalvb_get('options');
+  $options = drupalvb_get_options();
   return 1;
   //return (!empty($language) && isset($vblanguages[$language]) ? $vblanguages[$language] : $vblanguages[$options['languageid']]);
 }
@@ -375,7 +392,7 @@ function drupalvb_get_languageid($language = NULL) {
  * Get counts of guests and members currently online.
  */
 function drupalvb_get_users_online() {
-  $vb_options = drupalvb_get('options');
+  $vb_options = drupalvb_get_options();
 
   $datecut          = time() - $vb_options['cookietimeout'];
   $numbervisible    = 0;
@@ -436,7 +453,7 @@ function drupalvb_htmlspecialchars($text) {
  * Get vB cookie prefix.
  */
 function drupalvb_get_cookieprefix() {
-  $vb_config = drupalvb_get('config');
+  $vb_config = drupalvb_get_config();
   $cookie_prefix = (isset($vb_config['Misc']['cookieprefix']) ? $vb_config['Misc']['cookieprefix'] : 'bb');
 
   // Version 4 began using an underscore following the prefix.
diff --git a/drupalvb.install b/drupalvb.install
index 79cacc5..dfd3692 100644
--- a/drupalvb.install
+++ b/drupalvb.install
@@ -1,4 +1,9 @@
 <?php
+/**
+ * @file
+ * Install, update, and uninstall functions for Drupalvb.
+ *
+ */
 
 /**
  * Implements hook_requirements().
@@ -19,14 +24,14 @@ function drupalvb_requirements($phase) {
     $requirements['drupalvb']['severity'] = REQUIREMENT_ERROR;
     $requirements['drupalvb']['description'] = $t('The vBulletin configuration file <code>@filepath-vb</code> is required in <code>@filepath-drupalvb</code> (either as copy or soft link).', array(
       '@filepath-vb' => 'includes/config.php',
-      '@filepath-drupalvb' => conf_path() .'/config.php or ' . drupal_get_path('module', 'drupalvb') . '/config.php',
+      '@filepath-drupalvb' => conf_path() . '/config.php or ' . drupal_get_path('module', 'drupalvb') . '/config.php',
     ));
   }
   return $requirements;
 }
 
 /**
- * Implementation of hook_schema().
+ * Implements hook_schema().
  */
 function drupalvb_schema() {
   $schema['drupalvb_users'] = array(
@@ -44,7 +49,7 @@ function drupalvb_schema() {
 }
 
 /**
- * Implementation of hook_uninstall().
+ * Implements hook_uninstall().
  */
 function drupalvb_uninstall() {
   db_query("DELETE FROM {variable} WHERE name LIKE 'drupalvb_%%'");
diff --git a/drupalvb.module b/drupalvb.module
index c522f4b..0f3ca79 100644
--- a/drupalvb.module
+++ b/drupalvb.module
@@ -1,5 +1,4 @@
 <?php
-
 /**
  * @file
  * Drupal vB module core functions for Drupal.
@@ -7,11 +6,11 @@
  * Note: vBulletin only supports MySQL, queries have been optimized.
  */
 
-require_once drupal_get_path('module', 'drupalvb') .'/drupalvb.inc.php';
-require_once drupal_get_path('module', 'drupalvb') .'/drupalvb.inc';
+require_once drupal_get_path('module', 'drupalvb') . '/drupalvb.inc.php';
+require_once drupal_get_path('module', 'drupalvb') . '/drupalvb.inc';
 
 /**
- * Implementation of hook_theme().
+ * Implements hook_theme().
  */
 function drupalvb_theme() {
   return array(
@@ -34,7 +33,7 @@ function drupalvb_theme() {
 }
 
 /**
- * Implementation of hook_help().
+ * Implements hook_help().
  */
 function drupalvb_help($path, $arg) {
   switch ($path) {
@@ -43,25 +42,25 @@ function drupalvb_help($path, $arg) {
 
     case 'admin/config/system/drupalvb':
       module_load_include('inc', 'drupalvb');
-      $vb_config = drupalvb_get('config');
-      $vb_options = drupalvb_get('options');
+      $vb_config = drupalvb_get_config();
+      $vb_options = drupalvb_get_options();
       if (empty($vb_config)) {
         return '';
       }
       $items = array(
         l(t('View the Forum'), $vb_options['bburl']),
-        l(t('Forum Admin Control Panel'), $vb_options['bburl'] .'/'. $vb_config['Misc']['admincpdir']),
-        l(t('Forum Moderator Control Panel'), $vb_options['bburl'] .'/'. $vb_config['Misc']['modcpdir']),
+        l(t('Forum Admin Control Panel'), $vb_options['bburl'] . '/' . $vb_config['Misc']['admincpdir']),
+        l(t('Forum Moderator Control Panel'), $vb_options['bburl'] . '/' . $vb_config['Misc']['modcpdir']),
       );
-      return theme_item_list(array('type' => 'ul', 'items' => $items));
+      return theme('item_list', array('type' => 'ul', 'items' => $items));
 
     case 'admin/help#drupalvb':
-      return file_get_contents(dirname(__FILE__) .'/README.txt');
+      return file_get_contents(dirname(__FILE__) . '/README.txt');
   }
 }
 
 /**
- * Implementation of hook_menu().
+ * Implements hook_menu().
  */
 function drupalvb_menu() {
   $items = array();
@@ -133,7 +132,7 @@ function drupalvb_acct_generation_access() {
 }
 
 /**
- * Implementation of hook_perm().
+ * Implements hook_permission().
  */
 function drupalvb_permission() {
   return array(
@@ -151,11 +150,11 @@ function drupalvb_settings($form = 'integration') {
   $path = drupal_get_path('module', 'drupalvb');
   module_load_include('inc', 'drupalvb');
   module_load_include('inc', 'drupalvb', 'drupalvb.admin-pages');
-  return drupal_get_form('drupalvb_settings_'. $form);
+  return drupal_get_form('drupalvb_settings_' . $form);
 }
 
 /**
- * Implementation of hook_form_alter().
+ * Implements hook_form_alter().
  *
  * Validate the submitted values of user login forms before Drupal core invokes
  * its regular form validation callback.
@@ -206,7 +205,7 @@ function drupalvb_login_validate($form, &$form_state) {
   if (empty($username) || empty($password)) {
     return;
   }
-  $uid = db_query("SELECT uid FROM users WHERE name=:username", array(":username" => $username))->fetchField();
+  $uid = db_query("SELECT uid FROM {users} WHERE name=:username", array(":username" => $username))->fetchField();
   // If this user already exists in Drupal, no further validation required.
   if ($uid) {
     $finduser = user_load($uid);
@@ -257,7 +256,7 @@ function drupalvb_login_validate($form, &$form_state) {
         );
 
         $user = user_save('', $userinfo);
-        watchdog('drupalvb', t('New external user: %user.', array('%user' => $user->name)), array(), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $user->uid . '/edit'));
+        watchdog('drupalvb', format_string('New external user: %user.', array('%user' => $user->name)), array(), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $user->uid . '/edit'));
 
         // Update the mapping table.
         drupalvb_set_mapping($user->uid, $vbuser['userid']);
@@ -317,9 +316,10 @@ function drupalvb_get_userid($uid) {
 }
 
 /**
+ * Implements hook_user_login().
+ *
  * Log in a user in vB upon login in Drupal.
  *
- * @see drupalvb_user()
  */
 function drupalvb_user_login(&$edit, $account) {
   $vbuser = drupalvb_db_query("SELECT u.userid, ub.liftdate FROM {user} u LEFT JOIN {userban} ub ON ub.userid = u.userid WHERE u.username = :username", array(':username' => drupalvb_htmlspecialchars($account->name)))->fetchAssoc();
@@ -345,21 +345,22 @@ function drupalvb_user_login(&$edit, $account) {
   }
   else {
     drupal_set_message(t('Login to forums failed.'), 'error');
-    watchdog('drupalvb', t('Login to forum failed for user %user.', array('%user' => $account->name)), WATCHDOG_ERROR);
+    watchdog('drupalvb', format_string('Login to forum failed for user %user.', array('%user' => $account->name)), WATCHDOG_ERROR);
     return FALSE;
   }
 }
 
 /**
+ * Implements hook_user_logout.
+ *
  * Log out a user in vB upon logout in Drupal.
  *
- * @see drupalvb_user()
  */
 function drupalvb_user_logout($account) {
   //A check must be made for database connectivity here, otherwise the logout
   //process will be stopped.
   if (!drupalvb_db_is_valid()) {
-    watchdog('drupalvb', t('Forum session was NOT closed for user %username (@uid).', array('%username' => $account->name, '@uid' => $account->uid)), WATCHDOG_ERROR);
+    watchdog('drupalvb', format_string('Forum session was NOT closed for user %username (@uid).', array('%username' => $account->name, '@uid' => $account->uid)), WATCHDOG_ERROR);
     return;
   }
   else {
@@ -367,12 +368,14 @@ function drupalvb_user_logout($account) {
     if ($vbuserid) {
       // Remove all vB cookies for current user.
       drupalvb_clear_cookies($vbuserid);
-      watchdog('drupalvb', t('Forum session closed for user %username (@uid).', array('%username' => $account->name, '@uid' => $account->uid)));
+      watchdog('drupalvb', format_string('Forum session closed for user %username (@uid).', array('%username' => $account->name, '@uid' => $account->uid)));
     }
   }
 }
 
 /**
+ * Implements hook_user_presave.
+ *
  * Ensure a username or e-mail address does not already exist in vB.
  */
 function drupalvb_user_presave(&$edit, $account) {
@@ -403,29 +406,27 @@ function drupalvb_user_presave(&$edit, $account) {
 }
 
 /**
+ * Implements hook_user_insert.
+ *
  * Register a new user in vB upon registration in Drupal.
  *
- * @see drupalvb_user()
  */
 function drupalvb_user_insert($edit, $account) {
   global $user;
 
-  /*if(!drupalvb_user_validate($account->uid, $edit)) {
-    user_delete($account->uid);
-  }*/
-
   if ($userid = drupalvb_create_user($account, (array)$edit)) {
     // Prevent overriding cookies of administrators.
-    if ($edit['name'] === $account->name) {
+    if ($user->uid == $account->uid) {
       drupalvb_set_login_cookies($userid);
     }
   }
 }
 
 /**
+ * Implements hook_user_update.
+ *
  * Update a user in vB upon update in Drupal.
  *
- * @see drupalvb_user()
  */
 function drupalvb_user_update($edit, $account) {
   global $user;
@@ -445,15 +446,16 @@ function drupalvb_user_update($edit, $account) {
   }
 
   // Prevent overriding cookies of administrators.
-  if ($account->name == $user->name) {
+  if ($account->uid == $user->uid) {
     drupalvb_set_login_cookies($vbuser['userid']);
   }
 }
 
 /**
+ * Implements drupalvb_user_delete.
+ *
  * Delete a user in vB upon deletion in Drupal.
  *
- * @see drupalvb_user()
  */
 function drupalvb_user_delete($account) {
   // If vBulletin user exists, delete user account, session and profile data.
@@ -576,7 +578,7 @@ function drupalvb_panels_include_directory($plugintype) {
 }
 
 /**
- * Implements hook_block_info()
+ * Implements hook_block_info().
  */
 function drupalvb_block_info() {
   $blocks = array();
@@ -605,7 +607,7 @@ function drupalvb_block_info() {
 }
 
 /**
- * Implements hook_block_configure()
+ * Implements hook_block_configure().
  */
 function drupalvb_block_configure($delta = '') {
   $form = array();
@@ -676,7 +678,7 @@ function drupalvb_block_configure($delta = '') {
 }
 
 /**
- * Implementation of hook_block_save().
+ * Implements hook_block_save().
  */
 function hook_block_save($delta = '', $edit = array()) {
   if ($delta == 'recent') {
@@ -691,7 +693,7 @@ function hook_block_save($delta = '', $edit = array()) {
 }
 
 /**
- * Implements hook_block_view()
+ * Implements hook_block_view().
  */
 function drupalvb_block_view($delta = '') {
   $block = array();
@@ -747,14 +749,14 @@ function drupalvb_block_view($delta = '') {
 function drupalvb_block_recent($display) {
   $date_cut   = time() - (variable_get('drupalvb_block_recent_limit', 7) * 86400);
   $num_items  = variable_get('drupalvb_block_recent_count', 5);
-  $vb_options = drupalvb_get('options');
+  $vb_options = drupalvb_get_options();
   switch ($display) {
     case 'threads':
-      $result = drupalvb_db_query("SELECT t.threadid, t.title, t.replycount, t.dateline AS created, t.postuserid AS userid, t.postusername AS name FROM {thread} t INNER JOIN {forum} f ON f.forumid = t.forumid WHERE f.showprivate = 0 AND t.lastpost >= :date ORDER BY t.dateline DESC LIMIT 5", array(":date" => $date_cut));
+      $result = drupalvb_db_query_range("SELECT t.threadid, t.title, t.replycount, t.dateline AS created, t.postuserid AS userid, t.postusername AS name FROM {thread} t INNER JOIN {forum} f ON f.forumid = t.forumid WHERE f.showprivate = 0 AND t.lastpost >= :date ORDER BY t.dateline DESC", 0, 5, array(":date" => $date_cut));
       break;
 
     case 'posts':
-      $result = drupalvb_db_query("SELECT p.postid, p.title, p.threadid, p.dateline AS created, p.userid, p.username AS name, t.title AS threadtitle FROM {post} p LEFT JOIN {thread} t ON p.threadid = t.threadid WHERE p.dateline >= :date ORDER BY p.dateline DESC LIMIT :number", array(":date" => $date_cut, ":number" => $num_items));
+      $result = drupalvb_db_query_range("SELECT p.postid, p.title, p.threadid, p.dateline AS created, p.userid, p.username AS name, t.title AS threadtitle FROM {post} p LEFT JOIN {thread} t ON p.threadid = t.threadid WHERE p.dateline >= :date ORDER BY p.dateline DESC", 0, $num_items, array(":date" => $date_cut));
       break;
   }
   $items = $userids = array();
@@ -812,7 +814,7 @@ function theme_drupalvb_block_recent($variables) {
 function drupalvb_block_recent_user($account) {
   if ($vbuserid = drupalvb_get_userid($account->uid)) {
     $num_items  = variable_get('drupalvb_block_recent_count', 5);
-    $vb_options = drupalvb_get('options');
+    $vb_options = drupalvb_get_options();
     $result = drupalvb_db_query("SELECT p.postid, p.title, p.threadid, p.dateline AS created, p.userid, p.username AS name, t.title AS threadtitle, p.pagetext AS body FROM {post} p INNER JOIN {thread} t ON p.threadid = t.threadid INNER JOIN {forum} f ON f.forumid = t.forumid WHERE f.showprivate = 0 AND p.userid = :userid GROUP BY p.threadid ORDER BY p.dateline DESC LIMIT " . $num_items, array(':userid' => $vbuserid));
     $items = array();
     while ($data = $result->fetchAssoc()) {
@@ -865,7 +867,7 @@ function drupalvb_block_top_posters() {
     $items[$data['userid']] = $data;
   }
 
-  $result = db_query("SELECT d.userid, d.uid, u.picture FROM {drupalvb_users} d INNER JOIN {users} u ON u.uid = d.uid WHERE d.userid IN (". implode(',', array_keys($items)) .")");
+  $result = db_query("SELECT d.userid, d.uid, u.picture FROM {drupalvb_users} d INNER JOIN {users} u ON u.uid = d.uid WHERE d.userid IN (" . implode(',', array_keys($items)) . ")");
   while ($data = $result->fetchAssoc()) {
     $items[$data['userid']] = array_merge($items[$data['userid']], $data);
   }
@@ -894,7 +896,7 @@ function drupalvb_block_user_info() {
   global $user;
   module_load_include('inc', 'drupalvb');
 
-  $vb_options = drupalvb_get('options');
+  $vb_options = drupalvb_get_options();
   $display = variable_get('drupalvb_block_user', drupal_map_assoc(array('online', 'recent', 'newposts', 'pms')));
   $header = array(array(
     'data' => l($vb_options['bbtitle'], $vb_options['bburl']),
@@ -1018,12 +1020,12 @@ function drupalvb_private_messages() {
   global $user;
   module_load_include('inc', 'drupalvb');
 
-  $vb_options = drupalvb_get('options');
+  $vb_options = drupalvb_get_options();
 
-  $output = '<p>'. t("Below is a list of private messages you have received.  You may click on a user's name to see their profile, a message's title to view it, or a reply link to message the user in return.") .'</p>';
-  $output .= l('View your inbox.', $vb_options['bburl'] .'/private.php');
+  $output = '<p>' . t("Below is a list of private messages you have received.  You may click on a user's name to see their profile, a message's title to view it, or a reply link to message the user in return.") . '</p>';
+  $output .= l('View your inbox.', $vb_options['bburl'] . '/private.php');
 
-  $result = drupalvb_db_query("SELECT userid, username FROM {user} WHERE username = '%s'", drupalvb_htmlspecialchars($user->name));
+  $result = drupalvb_db_query("SELECT userid, username FROM {user} WHERE username = :username", array(":username" => drupalvb_htmlspecialchars($user->name)) );
 
   // If user exists, then grab and display a list of PMs.
   if ($userinfo = db_fetch_array($result)) {
@@ -1036,14 +1038,14 @@ function drupalvb_private_messages() {
       array('data' => t('Operations')),
     );
 
-    $result = drupalvb_db_query("SELECT pm.pmid, pm.userid, pm.messageread, pmtext.fromusername, pmtext.fromuserid, pmtext.title, pmtext.message, pmtext.dateline FROM {pmtext} AS pmtext LEFT JOIN {pm} AS pm ON (pm.pmtextid = pmtext.pmtextid) WHERE pm.userid = %d AND pm.folderid <> -1 ORDER BY pmtext.dateline DESC", $userinfo['userid']);
+    $result = drupalvb_db_query("SELECT pm.pmid, pm.userid, pm.messageread, pmtext.fromusername, pmtext.fromuserid, pmtext.title, pmtext.message, pmtext.dateline FROM {pmtext} AS pmtext LEFT JOIN {pm} AS pm ON (pm.pmtextid = pmtext.pmtextid) WHERE pm.userid = :userid AND pm.folderid <> -1 ORDER BY pmtext.dateline DESC", array(":userid" => $userinfo['userid']) );
     while ($pm = db_fetch_array($result)) {
       $rows[] = array(
-        l($pm['fromusername'], $vb_options['bburl'] .'/member.php?u='. $pm['fromuserid']),
-        l($pm['title'], $vb_options['bburl'] .'/private.php?do=showpm&pmid='. $pm['pmid']),
+        l($pm['fromusername'], $vb_options['bburl'] . '/member.php?u=' . $pm['fromuserid']),
+        l($pm['title'], $vb_options['bburl'] . '/private.php?do=showpm&pmid=' . $pm['pmid']),
         date('n-d-y g:i a', $pm['dateline']),
-        $pm['messageread'] ? t('Yes') : '<strong>'. t('No') .'</strong>',
-        l('reply', $vb_options['bburl'] .'/private.php?do=newpm&u='. $pm['fromuserid']),
+        $pm['messageread'] ? t('Yes') : '<strong>' . t('No') . '</strong>',
+        l('reply', $vb_options['bburl'] . '/private.php?do=newpm&u=' . $pm['fromuserid']),
       );
     }
     $output .= theme('table', $header, $rows);
@@ -1127,7 +1129,7 @@ function drupalvb_lookup_drupal_user($userid) {
     // the immediate second request tries to do the same again, resulting
     // in an error.
     if ($user->uid) {
-      watchdog('drupalvb', t('New external user: %user (unverified).', array('%user' => $user->name)), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $user->uid . '/edit'));
+      watchdog('drupalvb', format_string('New external user: %user (unverified).', array('%user' => $user->name)), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $user->uid . '/edit'));
 
       // Update the mapping table.
       drupalvb_set_mapping($user->uid, $vbuser['userid']);
@@ -1140,14 +1142,14 @@ function drupalvb_lookup_drupal_user($userid) {
     }
     // We're out of luck...
     else {
-      watchdog('drupalvb', t('Failed to create external user: %user (unverified).', array('%user' => $vbuser['username'])), WATCHDOG_ERROR);
+      watchdog('drupalvb', format_string('Failed to create external user: %user (unverified).', array('%user' => $vbuser['username'])), WATCHDOG_ERROR);
     }
   }
   return 0;
 }
 
 /**
- * Implementation of hook_privatemsg().
+ * Implements hook_privatemsg().
  *
  * This hack requires re-mapping of all requests for /forum/private.php to
  * privatemsg paths using .htaccess rewrite rules. Plus, it messes around with
@@ -1178,7 +1180,7 @@ function drupalvb_privatemsg($message, $op) {
       }
       // pmtextid stores mapping of privatemsg id to pmid, to be able to
       // display accurate message counts in vBulletin.
-      drupalvb_db_query("INSERT INTO {pm} (userid, pmtextid) VALUES (%d, %d)", $userid, $mid);
+      drupalvb_db_insert("pm")->fields(array("userid" => $userid, "pmtextid" => $mid));
       break;
 
     case 'view':
