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..42765c5 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,33 @@ 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;
+
+    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');
+    }
   }
+  return $is_valid;
 }
 
 /**
- * Generic database callback for querying pre-defined data from remote system.
+ * Query remote system database.
  *
- * @param string $op
- *   The get-operation to perform in the remote system.
+ * @see db_select()
  */
-function drupalvb_get($op) {
-  $function = 'drupalvb_get_' . $op;
-  if (!function_exists($function)) {
-    return FALSE;
-  }
-  drupalvb_db_connect();
-  $args = func_get_args();
-  array_shift($args);
-  $result = call_user_func_array($function, $args);
-  drupalvb_db_disconnect();
-  return $result;
+function drupalvb_db_select($table, $alias = NULL, array $options = array()) {
+  drupalvb_db_is_valid();
+  return Database::getConnection('default','drupalvb')->select($table, $alias, $options);
 }
 
 /**
@@ -129,19 +67,8 @@ 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;
+  drupalvb_db_is_valid();
+  return Database::getConnection('default', 'drupalvb')->query($query, $args, $options);
 }
 
 /**
@@ -149,22 +76,19 @@ 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()) {
+  drupalvb_db_is_valid();
+  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()) {
+  drupalvb_db_is_valid();
+  return Database::getConnection('default', 'drupalvb')->insert($table, $options);
 }
 
 /**
@@ -188,9 +112,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..41d1b67 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));
@@ -133,56 +136,73 @@ function drupalvb_get_ip() {
  */
 function drupalvb_create_user($account, $edit) {
   // Ensure we are not duplicating a user.
-  if (drupalvb_db_query("SELECT COUNT(userid) FROM {user} WHERE LOWER(username) = LOWER(:name)", array(':name' => drupalvb_htmlspecialchars($edit['name'])))->fetchField() > 0) {
-    return FALSE;
-  }
-
-  $salt = '';
-  for ($i = 0; $i < 3; $i++) {
-    $salt .= chr(rand(32, 126));
-  }
-  // Note: Password is already hashed during user export.
-  if (isset($edit['md5pass'])) {
-    $passhash = md5($edit['md5pass'] . $salt);
-  }
-  else {
-    $passhash = md5(md5($edit['pass']) . $salt);
-  }
-
-  $time = $account->created;
-  $passdate = date('Y-m-d', $time);
-  $joindate = $time;
-
-  // Attempt to grab the user title from the database.
-  $result = drupalvb_db_query("SELECT title FROM {usertitle} WHERE minposts = 0");
-  if ($resarray = $result->fetchAssoc()) {
-    $usertitle = $resarray['title'];
-  }
-  else {
-    $usertitle = 'Junior Member';
-  }
-
-  // Divide timezone by 3600, since vBulletin stores hours.
-  $timezone = variable_get('date_default_timezone', 0);
-  $timezone = ($timezone != 0 ? $timezone / 3600 : 0);
-
-  // Default new user options: I got these by setting up a new user how I
-  // wanted and looking in the database to see what options were set for him.
-  $options = variable_get('drupalvb_default_options', '3415');
-
-  // Default usergroup id.
-  $usergroupid = variable_get('drupalvb_default_usergroup', '2');
-  $lid = drupalvb_get('languageid');
-  if (!isset($lid)) {
-    $lid = 1;
+  $userid = drupalvb_db_select("user","u")
+          ->fields("u", array("userid") )
+          ->condition("username", drupalvb_htmlspecialchars($edit['name']) )
+          ->execute()
+          ->fetchColumn(0);
+
+  if(!$userid) {
+    $salt = '';
+    for ($i = 0; $i < 3; $i++) {
+      $salt .= chr(rand(32, 126));
+    }
+    // Note: Password is already hashed during user export.
+    if (isset($edit['md5pass'])) {
+      $passhash = md5($edit['md5pass'] . $salt);
+    }
+    else {
+      $passhash = md5(md5($edit['pass']) . $salt);
+    }
+  
+    $time = $account->created;
+    $passdate = date('Y-m-d', $time);
+    $joindate = $time;
+  
+    // Attempt to grab the user title from the database.
+    $result = drupalvb_db_query("SELECT title FROM {usertitle} WHERE minposts = 0");
+    if ($resarray = $result->fetchAssoc()) {
+      $usertitle = $resarray['title'];
+    }
+    else {
+      $usertitle = 'Junior Member';
+    }
+  
+    // Divide timezone by 3600, since vBulletin stores hours.
+    $timezone = variable_get('date_default_timezone', 0);
+    $timezone = ($timezone != 0 ? $timezone / 3600 : 0);
+  
+    // Default new user options: I got these by setting up a new user how I
+    // wanted and looking in the database to see what options were set for him.
+    $options = variable_get('drupalvb_default_options', '3415');
+  
+    // Default usergroup id.
+    $usergroupid = variable_get('drupalvb_default_usergroup', '2');
+    $lid = drupalvb_get_languageid();
+    if (!isset($lid)) {
+      $lid = 1;
+    }
+    // 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" => $account->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));
   }
-  // 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 new user into mapping table.
   drupalvb_set_mapping($account->uid, $userid);
@@ -194,7 +214,7 @@ function drupalvb_create_user($account, $edit) {
 /**
  * Update a user in vBulletin.
  */
-function drupalvb_update_user($account, $edit) {
+function drupalvb_update_user($account, $edit) { 
   $fields = $values = array();
 
   foreach ($edit as $field => $value) {
@@ -207,15 +227,9 @@ function drupalvb_update_user($account, $edit) {
         $values[':name'] = drupalvb_htmlspecialchars($value);
         break;
 
-      case 'pass':
+      case 'current_pass':
         $fields[] = "password = :password";
-        // Note: Password is already hashed during user export.
-        if (isset($edit['md5pass'])) {
-          $values[':password'] = md5($edit['md5pass'] . $edit['salt']);
-        }
-        else {
-          $values[':password'] = md5(md5($value) . $edit['salt']);
-        }
+        $values[':password'] = md5(md5($value) . $edit['salt']);
         $fields[] = "salt = :salt";
         $values[':salt'] = $edit['salt'];
         $fields[] = "passworddate = :date";
@@ -236,14 +250,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 +282,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 +302,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 +381,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 +390,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 +451,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..b1f5097 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.
@@ -189,13 +188,58 @@ function drupalvb_form_alter(&$form, $form_state, $form_id) {
   elseif ($form_id == 'user_pass') {
     $form['#validate'] = array_merge(array('drupalvb_user_pass_validate'), $form['#validate']);
   }
+  elseif ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
+    $form['#validate'] = array_merge(array('drupalvb_user_account_form_validate'), $form['#validate']);
+  }
+}
+
+/*
+ * Validate User Account form
+ */
+function drupalvb_user_account_form_validate($form, &$form_state) {
+  $account = $form['#user'];
+  $val = $form_state['values'];
+  
+  $userid = drupalvb_get_userid($account->uid);
+  if(!$userid) $userid = 0;
+  
+  // If registering, do not allow the reuse of username or email in forums
+  // If updating profile, do not allow changing the username to another forum username if it's already in use
+  
+  if($form['#form_id'] == 'user_register_form' || ($userid>1 && $account->name!=$val['name']) ) {
+  
+    $count = drupalvb_db_query("SELECT count(*) FROM {user} 
+                               WHERE userid<>:userid AND username=:username", 
+                               array(':userid' => $userid, ':username' => drupalvb_htmlspecialchars($val['name'])))->fetchField();
+                               
+    if($count>0) {
+      form_set_error('name', t('The name %name is already taken in the forums.', array('%name' => $val['name'])));    
+    }
+  }
+  
+  
+  if($form['#form_id'] == 'user_register_form') {
+    $count = drupalvb_db_query("SELECT count(*) FROM {user} 
+                                 WHERE userid<>:userid AND email=:mail", 
+                                 array(':userid' => $userid, ':mail' => drupalvb_htmlspecialchars($val['mail'])))->fetchField();
+                                 
+    if($count>0) {
+      form_set_error('mail', t('The e-mail address %email is already registered in the forums. <a href="@password">Have you forgotten your password?</a>', array('%email' => $val['mail'], '@password' => url('user/password'))));
+    }
+  }
+  
+  // Pass the plain text password to current_pass so we can update the forum password on hook_user_update
+  if(!empty($form_state['values']['pass']) && empty($form_state['values']['current_pass'])) {
+    $form_state['values']['current_pass'] = $form_state['values']['pass'];
+  }
 }
 
 /**
  * Validate login against vBulletin user database.
  */
 function drupalvb_login_validate($form, &$form_state) {
-  global $user;
+  if (!empty($form_state['uid'])) return;  // Already found the user from a previous validation function
+   
   if (!variable_get('drupalvb_dual_login', TRUE)) {
     return;
   }
@@ -206,28 +250,15 @@ 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();
-  // If this user already exists in Drupal, no further validation required.
-  if ($uid) {
-    $finduser = user_load($uid);
-    if ($finduser && $finduser->uid) {
-      $account_uid = user_authenticate($username, $password);
-      if ($account_uid) {
-        $user = user_load($account_uid);
-        user_login_finalize($form_state);
-        return TRUE;
-      }
-      else {
-        return;
-      }
-    }
-  }
 
   module_load_include('inc', 'drupalvb');
   if (!drupalvb_db_is_valid()) {
     return;
   }
-  if ($vbuser = drupalvb_db_query("SELECT userid, username, password, salt, email, joindate FROM {user} WHERE username = :username", array(":username" => drupalvb_htmlspecialchars($username)))->fetchAssoc()) {
+  if ($vbuser = drupalvb_db_query("SELECT userid, username, password, salt, email, joindate 
+                                   FROM {user} 
+                                   WHERE username = :username", 
+                                   array(":username" => drupalvb_htmlspecialchars($username)))->fetchAssoc()) {
     // Rebuild the password.
     $vbpassword = md5(md5($password) . $vbuser['salt']);
     if ($vbuser['password'] === $vbpassword) {
@@ -240,7 +271,7 @@ function drupalvb_login_validate($form, &$form_state) {
         // Only update the password of the existing Drupal user record.
         $account = user_load($uid);
         $userinfo['pass'] = $password;
-        $user = user_save($account, $userinfo);
+        $form_state['uid'] = $uid; 
       }
       else {
         // This user is completely unknown to Drupal, register a new account.
@@ -256,16 +287,13 @@ function drupalvb_login_validate($form, &$form_state) {
           'status' => 1,
         );
 
-        $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'));
+        $user = user_save(NULL, $userinfo);
+        watchdog('drupalvb', 'New external user: %user.', array('%user' => $user->name), WATCHDOG_NOTICE, l(t('edit'), 'user/' . $user->uid . '/edit'));
 
         // Update the mapping table.
         drupalvb_set_mapping($user->uid, $vbuser['userid']);
-        $user = user_load(user_authenticate($username, $password));
-        user_login_finalize($form_state);
-        drupal_goto();
+        $form_state['uid'] = $user->uid;
       }
-      return TRUE;
     }
   }
 }
@@ -282,7 +310,7 @@ function drupalvb_login_validate($form, &$form_state) {
 function drupalvb_user_pass_validate($form, $form_state) {
   $name = $form_state['values']['name'];
   // Return if the given user exists in Drupal.
-  if (user_load(array('name' => $name)) || user_load(array('mail' => $name))) {
+  if (user_load_by_name($name) || user_load_by_mail($name)) {
     return;
   }
 
@@ -317,9 +345,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 +374,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', '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', 'Forum session was NOT closed for user %username (@uid).', array('%username' => $account->name, '@uid' => $account->uid), WATCHDOG_ERROR);
     return;
   }
   else {
@@ -367,71 +397,39 @@ 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', 'Forum session closed for user %username (@uid).', array('%username' => $account->name, '@uid' => $account->uid));
     }
   }
 }
 
 /**
- * Ensure a username or e-mail address does not already exist in vB.
- */
-function drupalvb_user_presave(&$edit, $account) {
-  $uid = isset($account->uid) ? $account->uid : 0;
-  $userid = drupalvb_get_userid($uid);
-  if (!$userid) {
-    $userid = 0;
-  }
-  // Validate the username.
-  if (arg(1) == 'register' || user_access('change own username') || user_access('administer users')) {
-    if (drupalvb_db_query("SELECT COUNT(userid) FROM {user} WHERE userid <> :userid AND LOWER(username) = LOWER(:name)", array(":userid" => $userid, ":name" => drupalvb_htmlspecialchars($edit['name'])))->fetchField() > 0) {
-      form_set_error('name', t('The name %name is already taken.', array('%name' => $edit['name'])));
-      drupal_goto($_GET['q']);
-    }
-  }
-
-  // Validate the e-mail address.
-  $email_count = drupalvb_db_query("SELECT COUNT(userid) FROM {user} WHERE userid <> :userid AND LOWER(email) = LOWER(:email)", array(":userid" => $userid, ":email" => drupalvb_htmlspecialchars($edit['mail'])))->fetchField();
-
-  if ($userid == 0 && $email_count == 1) {
-    //This is a user that exists in VB but is not currently in Drupal
-    return TRUE;
-  }
-  if ($email_count > 0) {
-    form_set_error('mail', t('The e-mail address %email is already registered. <a href="@password">Have you forgotten your password?</a>', array('%email' => $edit['mail'], '@password' => url('user/password'))));
-    drupal_goto($_GET['q']);
-  }
-}
-
-/**
+ * 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;
 
   // Update data if user exists.
-  if ($vbuser = drupalvb_db_query_range("SELECT userid, salt FROM {user} WHERE username = :name", array(":name" => drupalvb_htmlspecialchars($account->name)), 0, 1)->fetchAssoc()) {
+  if ($vbuser = drupalvb_db_query_range("SELECT userid, salt FROM {user} WHERE username = :name", 0,1, array(":name" => drupalvb_htmlspecialchars($account->name)))->fetchAssoc()) {
     // Merge current username, salt, and finally edited values into one array,
     // so usernames may be altered (if allowed).
     drupalvb_update_user($account, array_merge(array('name' => $account->name), $vbuser, $edit));
@@ -445,15 +443,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 +575,7 @@ function drupalvb_panels_include_directory($plugintype) {
 }
 
 /**
- * Implements hook_block_info()
+ * Implements hook_block_info().
  */
 function drupalvb_block_info() {
   $blocks = array();
@@ -605,7 +604,7 @@ function drupalvb_block_info() {
 }
 
 /**
- * Implements hook_block_configure()
+ * Implements hook_block_configure().
  */
 function drupalvb_block_configure($delta = '') {
   $form = array();
@@ -676,7 +675,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 +690,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 +746,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 +811,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 +864,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 +893,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 +1017,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 +1035,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 +1126,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', '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 +1139,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', '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 +1177,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':
