diff --git a/dmemcache.inc b/dmemcache.inc
index 63af64d..1b73c2f 100644
--- a/dmemcache.inc
+++ b/dmemcache.inc
@@ -1,36 +1,41 @@
 <?php
 
-/*
- * Core dmemcache functions required by:
+/**
+ * @file
+ * A memcache API for Drupal.
+ *
+ * This file contains core dmemcache functions required by:
  *   memcache.inc
- *   memcache.db.inc
- *   session-memcache.inc
- *   session-memcache.db.inc
+ *   memcache-lock.inc
+ *   memcache-lock-code.inc
+ *   memcache-session.inc
  */
 
 global $_dmemcache_stats;
 $_dmemcache_stats = array('all' => array(), 'ops' => array());
 
-/*
- * A memcache API for Drupal.
- */
-
 /**
- *  Place an item into memcache
+ * Place an item into memcache.
  *
- * @param $key The string with which you will retrieve this item later.
- * @param $value The item to be stored.
- * @param $exp Parameter expire is expiration time in seconds. If it's 0, the
- *   item never expires (but memcached server doesn't guarantee this item to be
- *   stored all the time, it could be deleted from the cache to make place for
- *   other items).
- * @param $bin The name of the Drupal subsystem that is making this call.
- *   Examples could be 'cache', 'alias', 'taxonomy term' etc. It is possible to
- *   map different $bin values to different memcache servers.
- * @param $mc Optionally pass in the memcache object.  Normally this value is
- *   determined automatically based on the bin the object is being stored to.
+ * @param string $key
+ *   The string with which you will retrieve this item later.
+ * @param mixed $value
+ *   The item to be stored.
+ * @param int $exp
+ *   Parameter expire is expiration time in seconds. If it's 0, the item never
+ *   expires (but memcached server doesn't guarantee this item to be stored all
+ *   the time, it could be deleted from the cache to make place for other
+ *   items).
+ * @param string $bin
+ *   The name of the Drupal subsystem that is making this call. Examples could
+ *   be 'cache', 'alias', 'taxonomy term' etc. It is possible to map different
+ *   $bin values to different memcache servers.
+ * @param object $mc
+ *   Optionally pass in the memcache object.  Normally this value is determined
+ *   automatically based on the bin the object is being stored to.
  *
  * @return bool
+ *   TRUE on succes, FALSE otherwise.
  */
 function dmemcache_set($key, $value, $exp = 0, $bin = 'cache', $mc = NULL) {
   $collect_stats = dmemcache_stats_init();
@@ -55,25 +60,32 @@ function dmemcache_set($key, $value, $exp = 0, $bin = 'cache', $mc = NULL) {
 }
 
 /**
- *  Add an item into memcache
+ * Add an item into memcache.
  *
- * @param $key The string with which you will retrieve this item later.
- * @param $value The item to be stored.
- * @param $exp Parameter expire is expiration time in seconds. If it's 0, the
+ * @param string $key
+ *   The string with which you will retrieve this item later.
+ * @param mixed $value
+ *   The item to be stored.
+ * @param int $exp
+ *   Parameter expire is expiration time in seconds. If it's 0, the
  *   item never expires (but memcached server doesn't guarantee this item to be
  *   stored all the time, it could be deleted from the cache to make place for
  *   other items).
- * @param $bin The name of the Drupal subsystem that is making this call.
+ * @param string $bin
+ *   The name of the Drupal subsystem that is making this call.
  *   Examples could be 'cache', 'alias', 'taxonomy term' etc. It is possible
  *   to map different $bin values to different memcache servers.
- * @param $mc Optionally pass in the memcache object.  Normally this value is
+ * @param object $mc
+ *   Optionally pass in the memcache object.  Normally this value is
  *   determined automatically based on the bin the object is being stored to.
- * @param $flag If using the older memcache PECL extension as opposed to the
+ * @param int $flag
+ *   If using the older memcache PECL extension as opposed to the
  *   newer memcached PECL extension, the MEMCACHE_COMPRESSED flag can be set
  *   to use zlib to store a compressed copy of the item.  This flag option is
  *   completely ignored when using the newer memcached PECL extension.
  *
  * @return bool
+ *   FALSE if placing the item into memcache failed.
  */
 function dmemcache_add($key, $value, $exp = 0, $bin = 'cache', $mc = NULL, $flag = FALSE) {
   $collect_stats = dmemcache_stats_init();
@@ -100,10 +112,13 @@ function dmemcache_add($key, $value, $exp = 0, $bin = 'cache', $mc = NULL, $flag
 /**
  * Retrieve a value from the cache.
  *
- * @param $key The key with which the item was stored.
- * @param $bin The bin in which the item was stored.
+ * @param string $key
+ *   The key with which the item was stored.
+ * @param string $bin
+ *   The bin in which the item was stored.
  *
- * @return The item which was originally saved or FALSE
+ * @return mixed
+ *   The item which was originally saved or FALSE
  */
 function dmemcache_get($key, $bin = 'cache', $mc = NULL) {
   $collect_stats = dmemcache_stats_init();
@@ -135,10 +150,13 @@ function dmemcache_get($key, $bin = 'cache', $mc = NULL) {
 /**
  * Retrieve multiple values from the cache.
  *
- * @param $keys The keys with which the items were stored.
- * @param $bin The bin in which the item was stored.
+ * @param array $keys
+ *   The keys with which the items were stored.
+ * @param string $bin
+ *   The bin in which the item was stored.
  *
- * @return The item which was originally saved or FALSE
+ * @return mixed
+ *   The item which was originally saved or FALSE
  */
 function dmemcache_get_multi($keys, $bin = 'cache', $mc = NULL) {
   $collect_stats = dmemcache_stats_init();
@@ -201,10 +219,13 @@ function dmemcache_get_multi($keys, $bin = 'cache', $mc = NULL) {
 /**
  * Deletes an item from the cache.
  *
- * @param $key The key with which the item was stored.
- * @param $bin The bin in which the item was stored.
+ * @param string $key
+ *   The key with which the item was stored.
+ * @param string $bin
+ *   The bin in which the item was stored.
  *
- * @return Returns TRUE on success or FALSE on failure.
+ * @return bool
+ *   Returns TRUE on success or FALSE on failure.
  */
 function dmemcache_delete($key, $bin = 'cache', $mc = NULL) {
   $collect_stats = dmemcache_stats_init();
@@ -224,14 +245,18 @@ function dmemcache_delete($key, $bin = 'cache', $mc = NULL) {
 }
 
 /**
- * Immediately invalidates all existing items. dmemcache_flush doesn't actually free any
- * resources, it only marks all the items as expired, so occupied memory will be overwritten by
- * new items.
+ * Flush all stored items.
+ *
+ * Immediately invalidates all existing items. dmemcache_flush doesn't actually
+ * free any resources, it only marks all the items as expired, so occupied
+ * memory will be overwritten by new items.
  *
- * @param $bin The bin to flush. Note that this will flush all bins mapped to the same server
- *   as $bin. There is no way at this time to empty just one bin.
+ * @param string $bin
+ *   The bin to flush. Note that this will flush all bins mapped to the same
+ *   server as $bin. There is no way at this time to empty just one bin.
  *
- * @return Returns TRUE on success or FALSE on failure.
+ * @return bool
+ *   Returns TRUE on success or FALSE on failure.
  */
 function dmemcache_flush($bin = 'cache', $mc = NULL) {
   $collect_stats = dmemcache_stats_init();
@@ -251,11 +276,21 @@ function dmemcache_flush($bin = 'cache', $mc = NULL) {
   return $rc;
 }
 
+/**
+ * Retrieves statistics recorded during memcache operations.
+ *
+ * @param string $stats_bin
+ *   The bin to retrieve statistics for.
+ * @param string $stats_type
+ *   The type of statistics to retrieve when using the Memcache extension.
+ * @param bool $aggregate
+ *   Whether to aggregate statistics.
+ */
 function dmemcache_stats($stats_bin = 'cache', $stats_type = 'default', $aggregate = FALSE) {
   $memcache_bins = variable_get('memcache_bins', array('cache' => 'default'));
   // The stats_type can be over-loaded with an integer slab id, if doing a
   // cachedump.  We know we're doing a cachedump if $slab is non-zero.
-  $slab = (int)$stats_type;
+  $slab = (int) $stats_type;
 
   foreach ($memcache_bins as $bin => $target) {
     if ($stats_bin == $bin) {
@@ -267,13 +302,13 @@ function dmemcache_stats($stats_bin = 'cache', $stats_type = 'default', $aggrega
         // type is NULL or not in {reset, malloc, slabs, cachedump, items,
         // sizes}. If $stats_type is 'default', then no parameter should be
         // passed to the Memcache memcache_get_extended_stats() function.
-        else if ($mc instanceof Memcache) {
+        elseif ($mc instanceof Memcache) {
           if ($stats_type == 'default' || $stats_type == '') {
             $stats[$bin] = $mc->getExtendedStats();
           }
           // If $slab isn't zero, then we are dumping the contents of a
           // specific cache slab.
-          else if (!empty($slab))  {
+          elseif (!empty($slab)) {
             $stats[$bin] = $mc->getStats('cachedump', $slab);
           }
           else {
@@ -286,8 +321,15 @@ function dmemcache_stats($stats_bin = 'cache', $stats_type = 'default', $aggrega
   // Optionally calculate a sum-total for all servers in the current bin.
   if ($aggregate) {
     // Some variables don't logically aggregate.
-    $no_aggregate = array('pid', 'time', 'version', 'pointer_size', 'accepting_conns', 'listen_disabled_num');
-    foreach($stats as $bin => $servers) {
+    $no_aggregate = array(
+      'pid',
+      'time',
+      'version',
+      'pointer_size',
+      'accepting_conns',
+      'listen_disabled_num',
+    );
+    foreach ($stats as $bin => $servers) {
       if (is_array($servers)) {
         foreach ($servers as $server) {
           if (is_array($server)) {
@@ -344,10 +386,10 @@ function dmemcache_instance() {
   static $error = FALSE;
   $extension = dmemcache_extension();
   if ($extension == 'Memcache') {
-    return new Memcache;
+    return new Memcache();
   }
   elseif ($extension == 'Memcached') {
-    $memcache = new Memcached;
+    $memcache = new Memcached();
     $default_opts = array(
       Memcached::OPT_COMPRESSION => FALSE,
       Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
@@ -375,15 +417,17 @@ function dmemcache_instance() {
 /**
  * Initiate a connection to memcache.
  *
- * @param $memcache A memcache instance obtained through dmemcache_instance.
- *
- * @param $server A server string of the format "localhost:11211" or
+ * @param object $memcache
+ *   A memcache instance obtained through dmemcache_instance.
+ * @param string $server
+ *   A server string of the format "localhost:11211" or
  *   "unix:///path/to/socket".
+ * @param bool $connection
+ *   TRUE or FALSE, whether the $memcache instance already has at least one
+ *   open connection.
  *
- * @connection TRUE or FALSE, whether the $memcache instance already has at
- *   least one open connection.
- *
- * @return TRUE or FALSE if connection was successful.
+ * @return bool
+ *   TRUE or FALSE if connection was successful.
  */
 function dmemcache_connect($memcache, $server, $connection) {
   static $memcache_persistent = NULL;
@@ -432,7 +476,7 @@ function dmemcache_connect($memcache, $server, $connection) {
       $rc = $memcache->addServer($host, $port, $memcache_persistent);
     }
   }
-  else if ($extension == 'Memcached') {
+  elseif ($extension == 'Memcached') {
     // Support unix sockets of the format 'unix:///path/to/socket'.
     if ($host == 'unix') {
       // Strip 'unix://' as expected by Memcached extension.
@@ -455,7 +499,7 @@ function dmemcache_close($memcache) {
   if ($extension == 'Memcache' && $memcache instanceof Memcache) {
     $rc = @$memcache->close;
   }
-  else if ($extension == 'Memcached' && $memcache instanceof Memcached) {
+  elseif ($extension == 'Memcached' && $memcache instanceof Memcached) {
     $rc = @$memcache->quit;
   }
   else {
@@ -472,28 +516,30 @@ function dmemcache_close($memcache) {
  * provided by this API or if you need to use legacy code. Otherwise, use the
  * dmemcache (get, set, delete, flush) API functions provided here.
  *
- * @param $bin The bin which is to be used.
- *
- * @param $flush Rebuild the bin/server/cache mapping.
+ * @param string $bin
+ *   The bin which is to be used.
+ * @param bool $flush
+ *   Defaults to FALSE. Rebuild the bin/server/cache mapping.
  *
- * @return a Memcache object or FALSE.
+ * @return mixed
+ *   A Memcache object, or FALSE on failure.
  */
 function dmemcache_object($bin = NULL, $flush = FALSE) {
-  static $memcacheCache = array();
+  static $memcache_cache = array();
   static $memcache_servers = array();
   static $memcache_bins = array();
   static $failed_connections = array();
 
   if ($flush) {
-    foreach ($memcacheCache as $cluster) {
+    foreach ($memcache_cache as $cluster) {
       memcache_close($cluster);
     }
-    $memcacheCache = array();
+    $memcache_cache = array();
   }
 
   $extension = dmemcache_extension();
 
-  if (empty($memcacheCache) || empty($memcacheCache[$bin])) {
+  if (empty($memcache_cache) || empty($memcache_cache[$bin])) {
     if (empty($memcache_servers)) {
       // Load the variables from settings.php if set.
       $memcache_servers = variable_get('memcache_servers', array('127.0.0.1:11211' => 'default'));
@@ -505,8 +551,8 @@ function dmemcache_object($bin = NULL, $flush = FALSE) {
 
     // If not manually set, map this bin to 'cache' which maps to the 'default'
     // cluster.
-    if (empty($memcache_bins[$bin]) && !empty($memcacheCache['cache'])) {
-      $memcacheCache[$bin] = &$memcacheCache['cache'];
+    if (empty($memcache_bins[$bin]) && !empty($memcache_cache['cache'])) {
+      $memcache_cache[$bin] = &$memcache_cache['cache'];
     }
     else {
       // Create a new memcache object for each cluster.
@@ -535,23 +581,34 @@ function dmemcache_object($bin = NULL, $flush = FALSE) {
       }
       if ($connection) {
         // Map the current bin with the new Memcache object.
-        $memcacheCache[$bin] = $memcache;
+        $memcache_cache[$bin] = $memcache;
 
         // Now that all the servers have been mapped to this cluster, look for
         // other bins that belong to the cluster and map them too.
         foreach ($memcache_bins as $b => $c) {
           if ($c == $cluster && $b != $bin) {
             // Map this bin and cluster by reference.
-            $memcacheCache[$b] = &$memcacheCache[$bin];
+            $memcache_cache[$b] = &$memcache_cache[$bin];
           }
         }
       }
     }
   }
 
-  return empty($memcacheCache[$bin]) ? FALSE : $memcacheCache[$bin];
+  return empty($memcache_cache[$bin]) ? FALSE : $memcache_cache[$bin];
 }
 
+/**
+ * Prefixes a key and ensures it is url safe.
+ *
+ * @param string $key
+ *   The key to prefix and encode.
+ * @param string $bin
+ *   The cache bin which the key applies to.
+ *
+ * @return string
+ *   The prefixed and encoded key.
+ */
 function dmemcache_key($key, $bin = 'cache') {
   $prefix = '';
   if ($prefix = variable_get('memcache_key_prefix', '')) {
@@ -578,10 +635,12 @@ function dmemcache_key($key, $bin = 'cache') {
 /**
  * Collect statistics if enabled.
  *
- * Optimized function to determine whether or not we should be collecting statistics. Also starts a
- * timer to track how long individual memcache operations take.
+ * Optimized function to determine whether or not we should be collecting
+ * statistics. Also starts a timer to track how long individual memcache
+ * operations take.
  *
- * @return TRUE or FALSE if statistics should be collected.
+ * @return bool
+ *   TRUE or FALSE if statistics should be collected.
  */
 function dmemcache_stats_init() {
   static $drupal_static_fast;
@@ -593,9 +652,9 @@ function dmemcache_stats_init() {
   $user_access_checked  = &$drupal_static_fast['user_access_checked'];
 
   // Confirm DRUPAL_BOOTSTRAP_VARIABLES has been reached. We don't use
-  // drupal_get_bootstrap_phase() as it's buggy. We can use variable_get() here because
-  // _drupal_bootstrap_variables() includes module.inc immediately after it calls
-  // variable_initialize().
+  // drupal_get_bootstrap_phase() as it's buggy. We can use variable_get() here
+  // because _drupal_bootstrap_variables() includes module.inc immediately
+  // after it calls variable_initialize().
   if (!isset($variable_checked) && function_exists('module_list')) {
     $variable_checked = variable_get('show_memcache_statistics', FALSE);
   }
@@ -618,9 +677,13 @@ function dmemcache_stats_init() {
 /**
  * Save memcache statistics to be displayed at end of page generation.
  *
- * @param $action The action being performed (get, set, etc...).
- * @param $bin The memcache bin the action is being performed in.
- * @param $keys The key the action is being performed on, and whether or not it was a success.
+ * @param string $action
+ *   The action being performed (get, set, etc...).
+ * @param string $bin
+ *   The memcache bin the action is being performed in.
+ * @param array $keys
+ *   Keyed array in the form (string)$cid => (bool)$success. The keys the
+ *   action is being performed on, and whether or not it was a success.
  */
 function dmemcache_stats_write($action, $bin, $keys) {
   global $_dmemcache_stats, $timers;
@@ -628,12 +691,23 @@ function dmemcache_stats_write($action, $bin, $keys) {
   $time = timer_read('dmemcache');
   // Build the 'all' and 'ops' arrays displayed by memcache_admin.module.
   foreach ($keys as $key => $success) {
-    $_dmemcache_stats['all'][] = array(number_format($time, 2), $action, $bin, $key, $success ? 'hit' : 'miss');
+    $_dmemcache_stats['all'][] = array(
+      number_format($time, 2),
+      $action,
+      $bin,
+      $key,
+      $success ? 'hit' : 'miss',
+    );
     if (!isset($_dmemcache_stats['ops'][$action])) {
       $_dmemcache_stats['ops'][$action] = array($action, 0, 0, 0);
     }
     $_dmemcache_stats['ops'][$action][1] += $time;
-    $success ? $_dmemcache_stats['ops'][$action][2]++ : $_dmemcache_stats['ops'][$action][3]++;
+    if ($success) {
+      $_dmemcache_stats['ops'][$action][2]++;
+    }
+    else {
+      $_dmemcache_stats['ops'][$action][3]++;
+    }
   }
   // Reset the dmemcache timer for timing the next memcache operation.
   unset($timers['dmemcache']);
diff --git a/memcache-lock-code.inc b/memcache-lock-code.inc
index 15e3283..fbf459e 100644
--- a/memcache-lock-code.inc
+++ b/memcache-lock-code.inc
@@ -21,11 +21,12 @@ function lock_initialize() {
 /**
  * Acquire (or renew) a lock, but do not block if it fails.
  *
- * @param $name
+ * @param string $name
  *   The name of the lock.
- * @param $timeout
+ * @param int $timeout
  *   A number of seconds (int) before the lock expires (minimum of 1).
- * @return
+ *
+ * @return bool
  *   TRUE if the lock was acquired, FALSE if it failed.
  */
 function lock_acquire($name, $timeout = 30) {
@@ -56,9 +57,10 @@ function lock_acquire($name, $timeout = 30) {
  *
  * If an existing lock has expired, it is removed.
  *
- * @param $name
+ * @param string $name
  *   The name of the lock.
- * @return
+ *
+ * @return bool
  *   TRUE if there is no lock or it was removed, FALSE otherwise.
  */
 function lock_may_be_available($name) {
@@ -74,23 +76,26 @@ function lock_may_be_available($name) {
  * that are acquired very frequently, since the lock is likely to be acquired
  * again by a different request while waiting.
  *
- * @param $name
+ * @param string $name
  *   The name of the lock.
- * @param $delay
+ * @param int $delay
  *   The maximum number of seconds to wait, as an integer.
- * @return
+ *
+ * @return bool
  *   TRUE if the lock holds, FALSE if it is available.
  */
 function lock_wait($name, $delay = 30) {
-  // Pause the process for short periods between calling
-  // lock_may_be_available(). This prevents hitting the database with constant
-  // database queries while waiting, which could lead to performance issues.
-  // However, if the wait period is too long, there is the potential for a
-  // large number of processes to be blocked waiting for a lock, especially
-  // if the item being rebuilt is commonly requested. To address both of these
-  // concerns, begin waiting for 25ms, then add 25ms to the wait period each
-  // time until it reaches 500ms. After this point polling will continue every
-  // 500ms until $delay is reached.
+  /*
+   * Pause the process for short periods between calling
+   * lock_may_be_available(). This prevents hitting the database with constant
+   * database queries while waiting, which could lead to performance issues.
+   * However, if the wait period is too long, there is the potential for a
+   * large number of processes to be blocked waiting for a lock, especially
+   * if the item being rebuilt is commonly requested. To address both of these
+   * concerns, begin waiting for 25ms, then add 25ms to the wait period each
+   * time until it reaches 500ms. After this point polling will continue every
+   * 500ms until $delay is reached.
+   */
 
   // $delay is passed in seconds, but we will be using usleep(), which takes
   // microseconds as a parameter. Multiply it by 1 million so that all
@@ -122,7 +127,7 @@ function lock_wait($name, $delay = 30) {
  *
  * This will release the named lock if it is still held by the current request.
  *
- * @param $name
+ * @param string $name
  *   The name of the lock.
  */
 function lock_release($name) {
diff --git a/memcache-lock.inc b/memcache-lock.inc
index bc0f936..ef176df 100644
--- a/memcache-lock.inc
+++ b/memcache-lock.inc
@@ -15,4 +15,4 @@ $lock_file = dirname(__FILE__) . '/memcache-lock-code.inc';
 if (!dmemcache_object('semaphore')) {
   $lock_file = DRUPAL_ROOT . '/includes/lock.inc';
 }
-require_once $lock_file;
\ No newline at end of file
+require_once $lock_file;
diff --git a/memcache.inc b/memcache.inc
index 41b6bf4..e0600d7 100644
--- a/memcache.inc
+++ b/memcache.inc
@@ -1,18 +1,31 @@
 <?php
 
+/**
+ * @file
+ * Implementation of cache.inc with memcache logic included.
+ */
+
 require_once dirname(__FILE__) . '/dmemcache.inc';
 
 /**
  * Defines the period after which wildcard clears are not considered valid.
  */
 define('MEMCACHE_WILDCARD_INVALIDATE', 86400 * 28);
-
 define('MEMCACHE_CONTENT_CLEAR', 'MEMCACHE_CONTENT_CLEAR');
 
-/** Implementation of cache.inc with memcache logic included **/
-
+/**
+ * Implementation of cache.inc with memcache logic included
+ */
 class MemCacheDrupal implements DrupalCacheInterface {
-  function __construct($bin) {
+  protected $memcache;
+
+  /**
+   * Constructs a MemCacheDrupal object.
+   *
+   * @param string $bin
+   *   The cache bin for which the object is created.
+   */
+  public function __construct($bin) {
     $this->memcache = dmemcache_object($bin);
     $this->bin = $bin;
 
@@ -40,12 +53,18 @@ class MemCacheDrupal implements DrupalCacheInterface {
     $this->reloadVariables();
   }
 
-  function get($cid) {
+  /**
+   * Implements DrupalCacheInterface::get().
+   */
+  public function get($cid) {
     $cache = dmemcache_get($cid, $this->bin, $this->memcache);
     return $this->valid($cid, $cache) ? $cache : FALSE;
   }
 
-  function getMultiple(&$cids) {
+  /**
+   * Implements DrupalCacheInterface::getMultiple().
+   */
+  public function getMultiple(&$cids) {
     $results = dmemcache_get_multi($cids, $this->bin, $this->memcache);
     foreach ($results as $cid => $result) {
       if (!$this->valid($cid, $result)) {
@@ -59,15 +78,26 @@ class MemCacheDrupal implements DrupalCacheInterface {
     return $results;
   }
 
+  /**
+   * Checks if a retrieved cache item is valid.
+   *
+   * @param string $cid
+   *   The cache id of the item
+   * @param mixed $cache
+   *   The cache item.
+   *
+   * @return bool
+   *   Whether the item is valid.
+   */
   protected function valid($cid, $cache) {
     if ($cache) {
       $cache_tables = isset($_SESSION['cache_flush']) ? $_SESSION['cache_flush'] : NULL;
       // Items that have expired are invalid.
       if (isset($cache->expire) && $cache->expire !== CACHE_PERMANENT && $cache->expire <= $_SERVER['REQUEST_TIME']) {
-        // If the memcache_stampede_protection variable is set, allow one process
-        // to rebuild the cache entry while serving expired content to the
-        // rest. Note that core happily returns expired cache items as valid and
-        // relies on cron to expire them, but this is mostly reliant on its
+        // If the memcache_stampede_protection variable is set, allow one
+        // process to rebuild the cache entry while serving expired content to
+        // the rest. Note that core happily returns expired cache items as valid
+        // and relies on cron to expire them, but this is mostly reliant on its
         // use of CACHE_TEMPORARY which does not map well to memcache.
         // @see http://drupal.org/node/534092
         if (variable_get('memcache_stampede_protection', FALSE)) {
@@ -105,7 +135,7 @@ class MemCacheDrupal implements DrupalCacheInterface {
       }
       // Finally, check for wildcard clears against this cid.
       else {
-        if (!$this->wildcard_valid($cid, $cache)) {
+        if (!$this->wildcardValid($cid, $cache)) {
           $cache = FALSE;
         }
       }
@@ -127,9 +157,9 @@ class MemCacheDrupal implements DrupalCacheInterface {
         static $lock_count = 0;
         $lock_count++;
         if ($lock_count <= variable_get('memcache_stampede_wait_limit', 3)) {
-          // The memcache_stampede_semaphore variable was used in previous releases
-          // of memcache, but the max_wait variable was not, so by default divide
-          // the semaphore value by 3 (5 seconds).
+          // The memcache_stampede_semaphore variable was used in previous
+          // releases of memcache, but the max_wait variable was not, so by
+          // default divide the semaphore value by 3 (5 seconds).
           lock_wait("memcache_$cid:$this->bin", variable_get('memcache_stampede_wait_time', 5));
           $cache = $this->get($cid);
         }
@@ -139,16 +169,19 @@ class MemCacheDrupal implements DrupalCacheInterface {
     return (bool) $cache;
   }
 
-  function set($cid, $data, $expire = CACHE_PERMANENT) {
+  /**
+   * Implements DrupalCacheInterface::set().
+   */
+  public function set($cid, $data, $expire = CACHE_PERMANENT) {
     $created = time();
 
     // Create new cache object.
-    $cache = new stdClass;
+    $cache = new stdClass();
     $cache->cid = $cid;
     $cache->data = is_object($data) ? clone $data : $data;
     $cache->created = $created;
     // Record the previous number of wildcard flushes affecting our cid.
-    $cache->flushes = $this->wildcard_flushes($cid);
+    $cache->flushes = $this->wildcardFlushes($cid);
     if ($expire == CACHE_TEMPORARY) {
       // Convert CACHE_TEMPORARY (-1) into something that will live in memcache
       // until the next flush.
@@ -157,7 +190,7 @@ class MemCacheDrupal implements DrupalCacheInterface {
       $cache->temporary = TRUE;
     }
     // Expire time is in seconds if less than 30 days, otherwise is a timestamp.
-    else if ($expire != CACHE_PERMANENT && $expire < 2592000) {
+    elseif ($expire != CACHE_PERMANENT && $expire < 2592000) {
       // Expire is expressed in seconds, convert to the proper future timestamp
       // as expected in dmemcache_get().
       $cache->expire = REQUEST_TIME + $expire;
@@ -189,7 +222,10 @@ class MemCacheDrupal implements DrupalCacheInterface {
     }
   }
 
-  function clear($cid = NULL, $wildcard = FALSE) {
+  /**
+   * Implements DrupalCacheInterface::clear().
+   */
+  public function clear($cid = NULL, $wildcard = FALSE) {
     if ($this->memcache === FALSE) {
       // No memcache connection.
       return;
@@ -248,9 +284,9 @@ class MemCacheDrupal implements DrupalCacheInterface {
 
         if ($this->cache_lifetime) {
           // We store the time in the current user's session which is saved into
-          // the sessions table by sess_write().  We then simulate that the cache
-          // was flushed for this user by not returning cached data to this user
-          // that was cached before the timestamp.
+          // the sessions table by sess_write().  We then simulate that the
+          // cache was flushed for this user by not returning cached data to
+          // this user that was cached before the timestamp.
           if (isset($_SESSION['cache_flush']) && is_array($_SESSION['cache_flush'])) {
             $cache_bins = $_SESSION['cache_flush'];
           }
@@ -262,7 +298,7 @@ class MemCacheDrupal implements DrupalCacheInterface {
         }
       }
       else {
-        // Register a wildcard flush for current cid
+        // Register a wildcard flush for current cid.
         $this->wildcards($cid, TRUE);
       }
     }
@@ -275,15 +311,24 @@ class MemCacheDrupal implements DrupalCacheInterface {
   }
 
   /**
-   * Sum of all matching wildcards.  Checking any single cache item's flush
-   * value against this single-value sum tells us whether or not a new wildcard
-   * flush has affected the cached item.
+   * Sum of all matching wildcards.
+   *
+   * Checking any single cache item's flush value against this single-value sum
+   * tells us whether or not a new wildcard flush has affected the cached item.
+   *
+   * @param string $cid
+   *   The cache id to check.
+   *
+   * @return int
+   *   Sum of all matching wildcards for the given cache id.
    */
-  protected function wildcard_flushes($cid) {
+  protected function wildcardFlushes($cid) {
     return array_sum($this->wildcards($cid));
   }
 
   /**
+   * Retrieves all matching wildcards for the given cache id.
+   *
    * Utilize multiget to retrieve all possible wildcard matches, storing
    * statically so multiple cache requests for the same item on the same page
    * load doesn't add overhead.
@@ -398,17 +443,20 @@ class MemCacheDrupal implements DrupalCacheInterface {
   /**
    * Check if a wildcard flush has invalidated the current cached copy.
    */
-  protected function wildcard_valid($cid, $cache) {
+  protected function wildcardValid($cid, $cache) {
     // Previously cached content won't have ->flushes defined.  We could
     // force flush, but instead leave this up to the site admin.
-    $flushes = isset($cache->flushes) ? (int)$cache->flushes : 0;
-    if ($flushes < (int)$this->wildcard_flushes($cid)) {
+    $flushes = isset($cache->flushes) ? (int) $cache->flushes : 0;
+    if ($flushes < (int) $this->wildcardFlushes($cid)) {
       return FALSE;
     }
     return TRUE;
   }
 
-  function isEmpty() {
+  /**
+   * Implements DrupalCacheInterface::isEmpty().
+   */
+  public function isEmpty() {
     // We do not know so err on the safe side?
     return FALSE;
   }
@@ -416,7 +464,7 @@ class MemCacheDrupal implements DrupalCacheInterface {
   /**
    * Helper function to load locking framework if not already loaded.
    */
-  function lockInit() {
+  public function lockInit() {
     // On a cache miss when page_cache_without_database is enabled, we can end
     // up here without the lock system being initialized. Bootstrap drupal far
     // enough to load the lock system.
@@ -431,7 +479,7 @@ class MemCacheDrupal implements DrupalCacheInterface {
    * This is used by the tests to verify that the cache object used the correct
    * settings.
    */
-  function reloadVariables() {
+  public function reloadVariables() {
     $this->wildcard_flushes = variable_get('memcache_wildcard_flushes', array());
     $this->invalidate = variable_get('memcache_wildcard_invalidate', MEMCACHE_WILDCARD_INVALIDATE);
     $this->cache_lifetime = variable_get('cache_lifetime', 0);
@@ -444,7 +492,7 @@ class MemCacheDrupal implements DrupalCacheInterface {
   /**
    * Re-implementation of variable_set() that writes through instead of clearing.
    */
-  function variable_set($name, $value) {
+  public function variable_set($name, $value) {
     global $conf;
 
     db_merge('variable')
diff --git a/memcache.info b/memcache.info
index 9a36645..5d6d493 100644
--- a/memcache.info
+++ b/memcache.info
@@ -2,6 +2,7 @@ name = Memcache
 description = High performance integration with memcache.
 package = Performance and scalability
 core = 7.x
+files[] = memcache.inc
 files[] = tests/memcache.test
 files[] = tests/memcache-session.test
 files[] = tests/memcache-lock.test
diff --git a/memcache.install b/memcache.install
index a5e4825..26b1a1c 100644
--- a/memcache.install
+++ b/memcache.install
@@ -1,6 +1,43 @@
 <?php
 
 /**
+ * @file
+ * Install, update and uninstall functions for the memcache module.
+ */
+
+/**
+ * Implements hook_enable().
+ */
+function memcache_enable() {
+  $error = FALSE;
+  $memcache = extension_loaded('memcache');
+  $memcached = extension_loaded('memcached');
+  if (!$memcache && !$memcached) {
+    $error = TRUE;
+  }
+  if (!function_exists('dmemcache_object')) {
+    // dmemcache.inc isn't loaded.
+    $error = TRUE;
+  }
+  else {
+    // Make a test connection to all configured memcache servers.
+    $memcache_servers = variable_get('memcache_servers', array('127.0.0.1:11211' => 'default'));
+    $memcache = dmemcache_instance();
+    foreach ($memcache_servers as $server => $bin) {
+      if (dmemcache_connect($memcache, $server, FALSE) === FALSE) {
+        $error = TRUE;
+      }
+      else {
+        dmemcache_close($memcache);
+      }
+    }
+  }
+  if ($error) {
+    drupal_set_message(t('There are problems with your Memcache configuration. Please review %readme and visit the Drupal admin !status page for more information.', array('%readme' => 'README.txt', '!status' => l(t('status report'), 'admin/reports/status'))), 'error');
+  }
+}
+
+/**
  * Implements hook_requirements().
  */
 function memcache_requirements($phase) {
@@ -30,7 +67,7 @@ function memcache_requirements($phase) {
       if ($extension == 'Memcache') {
         $requirements['memcache_extension']['value'] = phpversion('memcache') . _memcache_statistics_link();
       }
-      else if ($extension == 'Memcached') {
+      elseif ($extension == 'Memcached') {
         $requirements['memcache_extension']['value'] = phpversion('memcached') . _memcache_statistics_link();
       }
 
diff --git a/memcache.module b/memcache.module
index f70a91b..4a4bd81 100644
--- a/memcache.module
+++ b/memcache.module
@@ -1,34 +1,9 @@
 <?php
+
 /**
+ * @file
  * Provides very limited functionality such as hook_requirements().
+ *
  * memcache.inc must be configured in settings.php, and memcache.module is not
  * necessary to use memcache as a cache backend.
  */
-function memcache_enable() {
-  $error = FALSE;
-  $memcache = extension_loaded('memcache');
-  $memcached = extension_loaded('memcached');
-  if (!$memcache && !$memcached) {
-    $error = TRUE;
-  }
-  if (!function_exists('dmemcache_object')) {
-    // dmemcache.inc isn't loaded.
-    $error = TRUE;
-  }
-  else {
-    // Make a test connection to all configured memcache servers.
-    $memcache_servers = variable_get('memcache_servers', array('127.0.0.1:11211' => 'default'));
-    $memcache = dmemcache_instance();
-    foreach ($memcache_servers as $server => $bin) {
-      if (dmemcache_connect($memcache, $server, FALSE) === FALSE) {
-        $error = TRUE;
-      }
-      else {
-        dmemcache_close($memcache);
-      }
-    }
-  }
-  if ($error) {
-    drupal_set_message(t('There are problems with your Memcache configuration. Please review %readme and visit the Drupal admin !status page for more information.', array('%readme' => 'README.txt', '!status' => l('status report', 'admin/reports/status'))), 'error');
-  }
-}
diff --git a/memcache_admin/memcache.js b/memcache_admin/memcache.js
index c6b79a0..c28fbf5 100644
--- a/memcache_admin/memcache.js
+++ b/memcache_admin/memcache.js
@@ -1,7 +1,11 @@
+/**
+ * @file
+ * Helper functions for memcache_admin module.
+ */
 
 // Global Killswitch
 if (Drupal.jsEnabled) {
-$(document).ready(function() {
+  $(document).ready(function() {
     $("body").append($("#memcache-devel"));
   });
 }
diff --git a/memcache_admin/memcache_admin.install b/memcache_admin/memcache_admin.install
index 0f2652e..7c5c711 100644
--- a/memcache_admin/memcache_admin.install
+++ b/memcache_admin/memcache_admin.install
@@ -1,7 +1,8 @@
 <?php
 
 /**
- * @file update functions for memcache_admin.
+ * @file
+ * Update functions for memcache_admin.
  */
 
 /**
diff --git a/memcache_admin/memcache_admin.module b/memcache_admin/memcache_admin.module
index 3d78e36..df3bced 100644
--- a/memcache_admin/memcache_admin.module
+++ b/memcache_admin/memcache_admin.module
@@ -1,18 +1,24 @@
 <?php
 
 /**
- * For the collection of memcache stats. This small .js file makes sure that the
- * HTML displaying the stats is inside of the <body> part of the HTML
- * document.
+ * @file
+ * For the collection and display of memcache stats.
+ *
+ * This module adds a small .js file to makes sure that the HTML displaying the
+ * stats is inside of the <body> part of the HTML document.
+ */
+
+/**
+ * Implements hook_init().
  */
 function memcache_admin_init() {
   global $user;
   if (($user->uid == 0) || strstr($_SERVER['PHP_SELF'], 'update.php') || (isset($_GET['q']) && (in_array($_GET['q'], array('upload/js', 'admin/content/node-settings/rebuild')) || substr($_GET['q'], 0, strlen('system/files')) == 'system/files' || substr($_GET['q'], 0, strlen('batch')) == 'batch' || strstr($_GET['q'], 'autocomplete')))) {
-    // update.php relies on standard error handler
+    // update.php relies on standard error handler.
   }
   else {
     if ($user->uid) {
-      drupal_add_js(drupal_get_path('module', 'memcache_admin'). '/memcache.js');
+      drupal_add_js(drupal_get_path('module', 'memcache_admin') . '/memcache.js');
     }
     register_shutdown_function('memcache_admin_shutdown');
   }
@@ -68,9 +74,9 @@ function memcache_admin_menu() {
         }
       }
 
-      $items['admin/reports/memcache/'. $cluster] = array(
+      $items["admin/reports/memcache/$cluster"] = array(
         'title' => $cluster,
-        'type' =>  $count == 0 ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
+        'type' => $count == 0 ? MENU_DEFAULT_LOCAL_TASK : MENU_LOCAL_TASK,
         'page callback' => 'memcache_admin_stats',
         'page arguments' => array($cluster),
         'access arguments' => array('access memcache statistics'),
@@ -79,7 +85,7 @@ function memcache_admin_menu() {
       foreach ($cluster_info['servers'] as $server) {
         $items["admin/reports/memcache/$cluster/$server"] = array(
           'title' => check_plain($server),
-          'type' =>  MENU_CALLBACK,
+          'type' => MENU_CALLBACK,
           'page callback' => 'memcache_admin_stats_raw',
           'page arguments' => array($cluster, $server),
           'access arguments' => array('access memcache statistics'),
@@ -113,6 +119,9 @@ function memcache_admin_admin_settings() {
   return system_settings_form($form);
 }
 
+/**
+ * Helper function. Returns the bin name.
+ */
 function _memcache_admin_default_bin($bin) {
   if ($bin == 'default') {
     return 'cache';
@@ -120,6 +129,9 @@ function _memcache_admin_default_bin($bin) {
   return $bin;
 }
 
+/**
+ * Statistics report: format total and open connections.
+ */
 function _memcache_admin_stats_connections($stats) {
   return t('!current open of !total total', array('!current' => number_format($stats['curr_connections']), '!total' => number_format($stats['total_connections'])));
 }
@@ -169,7 +181,12 @@ function _memcache_admin_stats_counters($stats) {
   if (!is_array($stats)) {
     $stats = array();
   }
-  $stats += array('incr_hits' => 0, 'incr_misses' => 0, 'decr_hits' => 0, 'decr_misses' => 0);
+  $stats += array(
+    'incr_hits' => 0,
+    'incr_misses' => 0,
+    'decr_hits' => 0,
+    'decr_misses' => 0,
+  );
   return t('!incr increments, !decr decrements', array('!incr' => number_format($stats['incr_hits'] + $stats['incr_misses']), '!decr' => number_format($stats['decr_hits'] + $stats['decr_misses'])));
 }
 
@@ -183,7 +200,7 @@ function _memcache_admin_stats_transfer($stats) {
   else {
     $written = $stats['bytes_read'] / $stats['bytes_written'] * 100;
   }
-  return t('!to:!from (!written% to cache)', array('!to' => format_size((int)$stats['bytes_read']), '!from' => format_size((int)$stats['bytes_written']), '!written' => number_format($written, 2)));
+  return t('!to:!from (!written% to cache)', array('!to' => format_size((int) $stats['bytes_read']), '!from' => format_size((int) $stats['bytes_written']), '!written' => number_format($written, 2)));
 }
 
 /**
@@ -233,9 +250,10 @@ function memcache_admin_bin_mapping($bin = 'cache') {
 }
 
 /**
- * Memcache Stats page
+ * Callback for the Memcache Stats page.
  *
  * @return string
+ *   The page output.
  */
 function memcache_admin_stats($bin = 'default') {
   $bin = memcache_admin_bin_mapping($bin);
@@ -344,7 +362,11 @@ function memcache_admin_stats($bin = 'default') {
           $data['memory_evictions']),
       ),
     );
-    $output = theme('memcache_admin_stats_table', array('bin' => $bin, 'servers' => $servers, 'report' => $report));
+    $output = theme('memcache_admin_stats_table', array(
+      'bin' => $bin,
+      'servers' => $servers,
+      'report' => $report,
+    ));
   }
   else {
     $output = '';
@@ -354,29 +376,53 @@ function memcache_admin_stats($bin = 'default') {
   return $output;
 }
 
+/**
+ * Callback for the server statistics page.
+ */
 function memcache_admin_stats_raw($bin, $server, $type = 'default') {
   $cluster = memcache_admin_bin_mapping($bin);
-  $slab = (int)arg(7);
+  $slab = (int) arg(7);
   if (arg(6) == 'cachedump' && !empty($slab) && user_access('access slab cachedump')) {
     $stats = dmemcache_stats($cluster, arg(7), FALSE);
   }
   else {
     $stats = dmemcache_stats($cluster, $type, FALSE);
   }
-  $breadcrumbs = array(l(t('Home'), NULL), l(t('Administer'), 'admin'), l(t('Reports'), 'admin/reports'), l(t('Memcache'), 'admin/reports/memcache'), l(t($bin), "admin/reports/memcache/$bin"));
+  $breadcrumbs = array(
+    l(t('Home'), NULL),
+    l(t('Administer'), 'admin'),
+    l(t('Reports'), 'admin/reports'),
+    l(t('Memcache'), 'admin/reports/memcache'),
+    l(t($bin), "admin/reports/memcache/$bin"),
+  );
   if ($type == 'slabs' && arg(6) == 'cachedump' && user_access('access slab cachedump')) {
     $breadcrumbs[] = l($server, "admin/reports/memcache/$bin/$server");
-    $breadcrumbs[] = l('slabs', "admin/reports/memcache/$bin/$server/$type");
+    $breadcrumbs[] = l(t('slabs'), "admin/reports/memcache/$bin/$server/$type");
   }
   drupal_set_breadcrumb($breadcrumbs);
   if (isset($stats[$cluster][$server]) && is_array($stats[$cluster][$server]) && count($stats[$cluster][$server])) {
-    $output = theme('memcache_admin_stats_raw_table', array('cluster' => $cluster, 'server' => $server, 'stats' => $stats[$cluster][$server], 'type' => $type));
+    $output = theme('memcache_admin_stats_raw_table', array(
+      'cluster' => $cluster,
+      'server' => $server,
+      'stats' => $stats[$cluster][$server],
+      'type' => $type,
+    ));
   }
   elseif ($type == 'slabs' && is_array($stats[$cluster]) && count($stats[$cluster])) {
-    $output = theme('memcache_admin_stats_raw_table', array('cluster' => $cluster, 'server' => $server, 'stats' => $stats[$cluster], 'type' => $type));
+    $output = theme('memcache_admin_stats_raw_table', array(
+      'cluster' => $cluster,
+      'server' => $server,
+      'stats' => $stats[$cluster],
+      'type' => $type,
+    ));
   }
   else {
-    $output = theme('memcache_admin_stats_raw_table', array('cluster' => $cluster, 'server' => $server, 'stats' => array(), 'type' => $type));
+    $output = theme('memcache_admin_stats_raw_table', array(
+      'cluster' => $cluster,
+      'server' => $server,
+      'stats' => array(),
+      'type' => $type,
+    ));
     drupal_set_message(t('No @type statistics for this bin.', array('@type' => $type)));
   }
   return $output;
@@ -388,16 +434,25 @@ function memcache_admin_stats_raw($bin, $server, $type = 'default') {
 function memcache_admin_theme() {
   return array(
     'memcache_admin_stats_table' => array(
-      'variables' => array('bin' => NULL, 'servers' => NULL, 'report' => NULL),
+      'variables' => array(
+        'bin' => NULL,
+        'servers' => NULL,
+        'report' => NULL,
+      ),
     ),
     'memcache_admin_stats_raw_table' => array(
-      'variables' => array('bin' => NULL, 'server' => NULL, 'stats' => NULL, 'type' => NULL),
-    )
+      'variables' => array(
+        'bin' => NULL,
+        'server' => NULL,
+        'stats' => NULL,
+        'type' => NULL,
+      ),
+    ),
   );
 }
 
 /**
- * Theme function for rendering the output from memcache_admin_stats
+ * Theme function for rendering the output from memcache_admin_stats.
  */
 function theme_memcache_admin_stats_table($variables) {
   $bin = $variables['bin'];
@@ -422,6 +477,9 @@ function theme_memcache_admin_stats_table($variables) {
   return $output;
 }
 
+/**
+ * Returns an array of available statistics types.
+ */
 function memcache_admin_stats_types($bin) {
   module_load_include('inc', 'memcache', 'dmemcache');
   if ($mc = dmemcache_object($bin)) {
@@ -442,6 +500,9 @@ function memcache_admin_stats_types($bin) {
   }
 }
 
+/**
+ * Theme function to produce a table of statistics.
+ */
 function theme_memcache_admin_stats_raw_table($variables) {
   $cluster = $variables['cluster'];
   $server = $variables['server'];
@@ -450,14 +511,14 @@ function theme_memcache_admin_stats_raw_table($variables) {
 
   $memcache_bins = variable_get('memcache_bins', array());
   $bin = isset($memcache_bins[$cluster]) ? $memcache_bins[$cluster] : 'default';
-  // Provide navigation for the various memcache stats types
+  // Provide navigation for the various memcache stats types.
   if (count(memcache_admin_stats_types($bin)) > 1) {
     foreach (memcache_admin_stats_types($bin) as $type) {
       if ($current_type == $type) {
-        $links[] = '<strong>' . l(t($type), "admin/reports/memcache/$bin/$server/". ($type == 'default' ? '' : $type)) .'</strong>';
+        $links[] = '<strong>' . l(t($type), "admin/reports/memcache/$bin/$server/" . ($type == 'default' ? '' : $type)) . '</strong>';
       }
       else {
-        $links[] = l(t($type), "admin/reports/memcache/$bin/$server/". ($type == 'default' ? '' : $type));
+        $links[] = l(t($type), "admin/reports/memcache/$bin/$server/" . ($type == 'default' ? '' : $type));
       }
     }
   }
@@ -471,7 +532,7 @@ function theme_memcache_admin_stats_raw_table($variables) {
     $stats = $stats['items'];
   }
   foreach ($stats as $key => $value) {
-    // Add navigation for getting a cachedump of individual slabs
+    // Add navigation for getting a cachedump of individual slabs.
     if (($current_type == 'slabs' || $current_type == 'items') && is_int($key) && user_access('access slab cachedump')) {
       $key = l($key, "admin/reports/memcache/$bin/$server/slabs/cachedump/$key");
     }
@@ -483,7 +544,7 @@ function theme_memcache_admin_stats_raw_table($variables) {
           $k = t('Size');
           $v = format_size($v);
         }
-        else if ($current_type == 'slabs' && user_access('access slab cachedump') && arg(6) == 'cachedump' && $k == 1) {
+        elseif ($current_type == 'slabs' && user_access('access slab cachedump') && arg(6) == 'cachedump' && $k == 1) {
           $k = t('Expire');
           $full_stats = dmemcache_stats($cluster, 'default');
           $infinite = $full_stats[$cluster][$server]['time'] - $full_stats[$cluster][$server]['uptime'];
@@ -495,7 +556,7 @@ function theme_memcache_admin_stats_raw_table($variables) {
           }
         }
         $rs[] = array(check_plain($k), check_plain($v));
-       }
+      }
       $rows[] = array($key, theme('table', array('rows' => $rs)));
     }
     else {
@@ -507,10 +568,13 @@ function theme_memcache_admin_stats_raw_table($variables) {
 }
 
 /**
- * Retrieve the cluster for any given bin
+ * Retrieve the bin for any given cluster.
+ *
+ * @param string $cluster
+ *   Cluster ID
  *
- * @param string $cluster - Cluster ID
  * @return string
+ *   The name of the bin.
  */
 function _memcache_admin_get_bin_for_cluster($cluster) {
   static $cluster_map = array();
@@ -528,11 +592,14 @@ function _memcache_admin_get_bin_for_cluster($cluster) {
   return $cluster_map[$cluster];
 }
 
+/**
+ * Helper function. Calculate a percentage.
+ */
 function _memcache_admin_stats_percent($a, $b) {
   if ($a == 0) {
     return 0;
   }
-  else if ($b == 0) {
+  elseif ($b == 0) {
     return 100;
   }
   else {
@@ -541,8 +608,9 @@ function _memcache_admin_stats_percent($a, $b) {
 }
 
 /**
- * See memcache_admin_init() which registers this function as a shutdown function.
- * Displays memcache stats in the footer.
+ * Displays memcache stats in the footer. This is run as a shutdown function.
+ *
+ * @see memcache_admin_init()
  */
 function memcache_admin_shutdown() {
   global $_dmemcache_stats;
@@ -559,7 +627,16 @@ function memcache_admin_shutdown() {
   if (function_exists('drupal_get_http_header')) {
     $header = drupal_get_http_header('content-type');
     if ($header) {
-      $formats = array('xml', 'javascript', 'json', 'plain', 'image', 'application', 'csv', 'x-comma-separated-values');
+      $formats = array(
+        'xml',
+        'javascript',
+        'json',
+        'plain',
+        'image',
+        'application',
+        'csv',
+        'x-comma-separated-values',
+      );
       foreach ($formats as $format) {
         if (strstr($header, $format)) {
           return;
@@ -579,8 +656,15 @@ function memcache_admin_shutdown() {
         $_dmemcache_stats['ops'][$row][2] = number_format($stats[2]) . " ($hits%)";
         $_dmemcache_stats['ops'][$row][3] = number_format($stats[3]) . " ($misses%)";
       }
-      $variables = array('header' => array(t('operation'), t('total ms'), t('total hits'), t('total misses')),
-                         'rows' => $_dmemcache_stats['ops']);
+      $variables = array(
+        'header' => array(
+          t('operation'),
+          t('total ms'),
+          t('total hits'),
+          t('total misses'),
+        ),
+        'rows' => $_dmemcache_stats['ops'],
+      );
       $output .= theme('table', $variables);
     }
     if (!empty($_dmemcache_stats['all'])) {
@@ -590,14 +674,23 @@ function memcache_admin_shutdown() {
         $_dmemcache_stats['all'][$row][3] = check_plain($stats[3]);
       }
 
-      $variables = array('header' => array(t('ms'), t('operation'), t('bin'), t('key'), t('status')),
-                         'rows' => $_dmemcache_stats['all']);
+      $variables = array(
+        'header' => array(
+          t('ms'),
+          t('operation'),
+          t('bin'),
+          t('key'),
+          t('status'),
+        ),
+        'rows' => $_dmemcache_stats['all'],
+      );
       $output .= theme('table', $variables);
 
     }
     if (!empty($output)) {
-      // this makes sure all of the HTML is within the <body> even though this <script> is outside it
-      print '<div id="memcache-devel"><h2>'. t('Memcache statistics'). '</h2>'. $output. '</div>';
+      // This makes sure all of the HTML is within the <body> even though this
+      // <script> is outside it.
+      print '<div id="memcache-devel"><h2>' . t('Memcache statistics') . '</h2>' . $output . '</div>';
     }
   }
 }
diff --git a/tests/memcache-lock.test b/tests/memcache-lock.test
index 71caf76..29e995c 100644
--- a/tests/memcache-lock.test
+++ b/tests/memcache-lock.test
@@ -1,8 +1,10 @@
 <?php
 
 /**
+ * @file
  * Tests for the lock system.
  */
+
 class MemcacheLockFunctionalTest extends MemcacheTestCase {
   protected $default_bin = '';
 
@@ -14,14 +16,17 @@ class MemcacheLockFunctionalTest extends MemcacheTestCase {
     );
   }
 
-  function setUp() {
+  /**
+   * @see MemcacheTestCase::setUp()
+   */
+  public function setUp() {
     parent::setUp('memcache_test');
   }
 
   /**
    * Confirm that we can acquire and release locks in two parallel requests.
    */
-  function testLockAcquire() {
+  public function testLockAcquire() {
     // Confirm that locks are really acquired in memcache.
     lock_acquire($this->default_cid);
     $this->assertTrue(dmemcache_get($this->default_cid, 'semaphore'), t('Memcache locking is configured correctly.'));
@@ -63,7 +68,7 @@ class MemcacheLockFunctionalTest extends MemcacheTestCase {
     // @todo: this assertion currently fails - the lock_acquire() call returns
     // true. For now, commented out the assertion, uncomment when attempting to
     // fix.
-    //$this->assertFalse(lock_acquire('memcache_test_lock_acquire'), t('Lock cannot be extended by this request.'), t('Lock'));
+    // $this->assertFalse(lock_acquire('memcache_test_lock_acquire'), t('Lock cannot be extended by this request.'), t('Lock'));
 
     // Check the shut-down function.
     $lock_acquired_exit = 'TRUE: Lock successfully acquired in memcache_test_lock_exit()';
diff --git a/tests/memcache-session.test b/tests/memcache-session.test
index 9883ad6..77528b1 100644
--- a/tests/memcache-session.test
+++ b/tests/memcache-session.test
@@ -12,18 +12,21 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
     return array(
       'name' => 'Session tests',
       'description' => 'Memcache session handling tests.',
-      'group' => 'Memcache'
+      'group' => 'Memcache',
     );
   }
 
-  function setUp() {
+  /**
+   * @see MemcacheTestCase::setUp()
+   */
+  public function setUp() {
     parent::setUp('session_test');
   }
 
   /**
    * Tests for drupal_save_session() and drupal_session_regenerate().
    */
-  function testSessionSaveRegenerate() {
+  public function testSessionSaveRegenerate() {
     $this->assertFalse(drupal_save_session(), t('drupal_save_session() correctly returns FALSE (inside of testing framework) when initially called with no arguments.'), t('Session'));
     $this->assertFalse(drupal_save_session(FALSE), t('drupal_save_session() correctly returns FALSE when called with FALSE.'), t('Session'));
     $this->assertFalse(drupal_save_session(), t('drupal_save_session() correctly returns FALSE when saving has been disabled.'), t('Session'));
@@ -48,14 +51,14 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
     $this->drupalGet('session-test/id');
     $matches = array();
     preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
-    $this->assertTrue(!empty($matches[1]) , t('Found session ID before logging in.'));
+    $this->assertTrue(!empty($matches[1]), t('Found session ID before logging in.'));
     $original_session = $matches[1];
 
     // We cannot use $this->drupalLogin($user); because we exit in
     // session_test_user_login() which breaks a normal assertion.
     $edit = array(
       'name' => $user->name,
-      'pass' => $user->pass_raw
+      'pass' => $user->pass_raw,
     );
     $this->drupalPost('user', $edit, t('Log in'));
     $this->drupalGet('user');
@@ -65,7 +68,7 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
     $this->drupalGet('session-test/id');
     $matches = array();
     preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
-    $this->assertTrue(!empty($matches[1]) , t('Found session ID after logging in.'));
+    $this->assertTrue(!empty($matches[1]), t('Found session ID after logging in.'));
     $this->assertTrue($matches[1] != $original_session, t('Session ID changed after login.'));
   }
 
@@ -73,7 +76,7 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
    * Test data persistence via the session_test module callbacks. Also tests
    * drupal_session_count() since session data is already generated here.
    */
-  function testDataPersistence() {
+  public function testDataPersistence() {
     $user = $this->drupalCreateUser(array('access content'));
     // Enable sessions.
     $this->sessionReset($user->uid);
@@ -138,7 +141,7 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
   /**
    * Test that empty anonymous sessions are destroyed.
    */
-  function testEmptyAnonymousSession() {
+  public function testEmptyAnonymousSession() {
     // Verify that no session is automatically created for anonymous user.
     $this->drupalGet('');
     $this->assertSessionCookie(FALSE);
@@ -188,9 +191,10 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
   /**
    * Reset the cookie file so that it refers to the specified user.
    *
-   * @param $uid User id to set as the active session.
+   * @param int $uid
+   *   User id to set as the active session.
    */
-  function sessionReset($uid = 0) {
+  protected function sessionReset($uid = 0) {
     // Close the internal browser.
     $this->curlClose();
     $this->loggedInUser = FALSE;
@@ -206,7 +210,7 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
   /**
    * Assert whether the SimpleTest browser sent a session cookie.
    */
-  function assertSessionCookie($sent) {
+  protected function assertSessionCookie($sent) {
     if ($sent) {
       $this->assertNotNull($this->session_id, t('Session cookie was sent.'));
     }
@@ -218,7 +222,7 @@ class MemcacheSessionTestCase extends MemcacheTestCase {
   /**
    * Assert whether $_SESSION is empty at the beginning of the request.
    */
-  function assertSessionEmpty($empty) {
+  protected function assertSessionEmpty($empty) {
     if ($empty) {
       $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '1', t('Session was empty.'));
     }
diff --git a/tests/memcache.test b/tests/memcache.test
index 007da61..3b3c927 100644
--- a/tests/memcache.test
+++ b/tests/memcache.test
@@ -1,5 +1,10 @@
 <?php
 
+/**
+ * @file
+ * Test cases for the memcache cache backend.
+ */
+
 class MemcacheTestCase extends DrupalWebTestCase {
   protected $profile = 'testing';
   protected $default_bin = 'cache_memcache';
@@ -11,7 +16,7 @@ class MemcacheTestCase extends DrupalWebTestCase {
    *
    * @see DrupalWebTestCase::setUp()
    */
-  function setUp() {
+  public function setUp() {
     global $user, $language, $conf;
 
     // Create the database prefix for this test.
@@ -46,7 +51,8 @@ class MemcacheTestCase extends DrupalWebTestCase {
     // system_rebuild_module_data() (in drupal_install_system()) will register
     // the test's profile as a module. Without this, the installation profile of
     // the parent site (executing the test) is registered, and the test
-    // profile's hook_install() and other hook implementations are never invoked.
+    // profile's hook_install() and other hook implementations are never
+    // invoked.
     $conf['install_profile'] = $this->profile;
 
     // Perform the actual Drupal installation.
@@ -135,7 +141,7 @@ class MemcacheTestCase extends DrupalWebTestCase {
   /**
    * Test that memcache is configured correctly.
    */
-  function testCacheBin() {
+  public function testCacheBin() {
     if ($this->default_bin) {
       // Confirm that the default cache bin is handled by memcache.
       $this->assertEqual(get_class(_cache_get_object($this->default_bin)), 'MemCacheDrupal', t('Memcache caching is configured correctly.'));
@@ -145,13 +151,14 @@ class MemcacheTestCase extends DrupalWebTestCase {
   /**
    * Check whether or not a cache entry exists.
    *
-   * @param $cid
+   * @param string $cid
    *   The cache id.
-   * @param $var
+   * @param mixed $var
    *   The variable the cache should contain.
-   * @param $bin
-   *   The bin the cache item was stored in.
-   * @return
+   * @param string $bin
+   *   Defaults to $this->default_bin. The bin the cache item was stored in.
+   *
+   * @return bool
    *   TRUE on pass, FALSE on fail.
    */
   protected function checkCacheExists($cid, $var, $bin = NULL) {
@@ -167,14 +174,14 @@ class MemcacheTestCase extends DrupalWebTestCase {
   /**
    * Assert or a cache entry exists.
    *
-   * @param $message
+   * @param string $message
    *   Message to display.
-   * @param $var
-   *   The variable the cache should contain.
-   * @param $cid
-   *   The cache id.
-   * @param $bin
-   *   The bin the cache item was stored in.
+   * @param mixed $var
+   *   Defaults to $this->default_value. The variable the cache should contain.
+   * @param string $cid
+   *   Defaults to $this->default_cid. The cache id.
+   * @param string $bin
+   *   Defaults to $this->default_bin. The bin the cache item was stored in.
    */
   protected function assertCacheExists($message, $var = NULL, $cid = NULL, $bin = NULL) {
     if ($bin == NULL) {
@@ -193,14 +200,14 @@ class MemcacheTestCase extends DrupalWebTestCase {
   /**
    * Assert or a cache entry has been removed.
    *
-   * @param $message
+   * @param string $message
    *   Message to display.
-   * @param $cid
-   *   The cache id.
-   * @param $bin
-   *   The bin the cache item was stored in.
+   * @param string $cid
+   *   Defaults to $this->default_cid. The cache id.
+   * @param string $bin
+   *   Defaults to $this->default_bin. The bin the cache item was stored in.
    */
-  function assertCacheRemoved($message, $cid = NULL, $bin = NULL) {
+  public function assertCacheRemoved($message, $cid = NULL, $bin = NULL) {
     if ($bin == NULL) {
       $bin = $this->default_bin;
     }
@@ -214,8 +221,9 @@ class MemcacheTestCase extends DrupalWebTestCase {
 
   /**
    * Perform the general wipe.
-   * @param $bin
-   *   The bin to perform the wipe on.
+   *
+   * @param string $bin
+   *   Defaults to $this->default_bin. The bin to perform the wipe on.
    */
   protected function generalWipe($bin = NULL) {
     if ($bin == NULL) {
@@ -225,7 +233,10 @@ class MemcacheTestCase extends DrupalWebTestCase {
     cache_clear_all(NULL, $bin);
   }
 
-  function resetVariables() {
+  /**
+   * Reloads internal MemCacheDrupal variables.
+   */
+  protected function resetVariables() {
     if ($this->default_bin) {
       $cache = _cache_get_object($this->default_bin);
       if ($cache instanceof MemCacheDrupal) {
@@ -236,54 +247,66 @@ class MemcacheTestCase extends DrupalWebTestCase {
 }
 
 class MemCacheSavingCase extends MemcacheTestCase {
+
   public static function getInfo() {
     return array(
       'name' => 'Memcache saving test',
       'description' => 'Check our variables are saved and restored the right way.',
-      'group' => 'Memcache'
+      'group' => 'Memcache',
     );
   }
 
-  function setUp() {
+  /**
+   * @see MemcacheTestCase::setUp()
+   */
+  public function setUp() {
     parent::setUp();
   }
 
   /**
    * Test the saving and restoring of a string.
    */
-  function testString() {
+  public function testString() {
     $this->checkVariable($this->randomName(100));
   }
 
   /**
    * Test the saving and restoring of an integer.
    */
-  function testInteger() {
+  public function testInteger() {
     $this->checkVariable(100);
   }
 
   /**
    * Test the saving and restoring of a double.
    */
-  function testDouble() {
+  public function testDouble() {
     $this->checkVariable(1.29);
   }
 
   /**
    * Test the saving and restoring of an array.
    */
-  function testArray() {
-    $this->checkVariable(array('drupal1', 'drupal2' => 'drupal3', 'drupal4' => array('drupal5', 'drupal6')));
+  public function testArray() {
+    $this->checkVariable(array(
+      'drupal1',
+      'drupal2' => 'drupal3',
+      'drupal4' => array('drupal5', 'drupal6'),
+    ));
   }
 
   /**
    * Test the saving and restoring of an object.
    */
-  function testObject() {
+  public function testObject() {
     $test_object = new stdClass();
     $test_object->test1 = $this->randomName(100);
     $test_object->test2 = 100;
-    $test_object->test3 = array('drupal1', 'drupal2' => 'drupal3', 'drupal4' => array('drupal5', 'drupal6'));
+    $test_object->test3 = array(
+      'drupal1',
+      'drupal2' => 'drupal3',
+      'drupal4' => array('drupal5', 'drupal6'),
+    );
 
     cache_set('test_object', $test_object, $this->default_bin);
     $cache = cache_get('test_object', $this->default_bin);
@@ -293,21 +316,21 @@ class MemCacheSavingCase extends MemcacheTestCase {
   /**
    * Test save and restoring a string with a long key.
    */
-  function testStringLongKey() {
+  public function testStringLongKey() {
     $this->checkVariable($this->randomName(100), 'ThequickbrownfoxjumpsoverthelazydogThequickbrownfoxjumpsoverthelazydogThequickbrownfoxjumpsoverthelazydogThequickbrownfoxjumpsoverthelazydogThequickbrownfoxjumpsoverthelazydogThequickbrownfoxjumpsoverthelazydogThequickbrownfoxjumpsoverthelazydogThequickbrownfoxjumpsoverthelazydog');
   }
 
   /**
    * Test save and restoring a string using a key with special characters.
    */
-  function testStringSpecialKey() {
+  public function testStringSpecialKey() {
     $this->checkVariable($this->randomName(100), 'Qwerty!@#$%^&*()_+-=[]\;\',./<>?:"{}|£¢');
   }
 
-  /*
+  /**
    * Check or a variable is stored and restored properly.
-   **/
-  function checkVariable($var, $key = 'test_var') {
+   */
+  public function checkVariable($var, $key = 'test_var') {
     cache_set($key, $var, $this->default_bin);
     $cache = cache_get($key, $this->default_bin);
     $this->assertTrue(isset($cache->data) && $cache->data === $var, t('@type is saved and restored properly!key.', array('@type' => ucfirst(gettype($var)), '!key' => ($key != 'test_var') ? t(' with key @key', array('@key' => $key)) : '')));
@@ -327,6 +350,9 @@ class MemCacheGetMultipleUnitTest extends MemcacheTestCase {
     );
   }
 
+  /**
+   * @see MemcacheTestCase::setUp()
+   */
   function setUp() {
     parent::setUp();
   }
@@ -334,7 +360,7 @@ class MemCacheGetMultipleUnitTest extends MemcacheTestCase {
   /**
    * Test cache_get_multiple().
    */
-  function testCacheMultiple() {
+  public function testCacheMultiple() {
     $item1 = $this->randomName(10);
     $item2 = $this->randomName(10);
     cache_set('test:item1', $item1, $this->default_bin);
@@ -372,11 +398,14 @@ class MemCacheClearCase extends MemcacheTestCase {
     return array(
       'name' => 'Cache clear test',
       'description' => 'Check our clearing is done the proper way.',
-      'group' => 'Memcache'
+      'group' => 'Memcache',
     );
   }
 
-  function setUp() {
+  /**
+   * @see MemcacheTestCase::setUp()
+   */
+  public function setUp() {
 
     parent::setUp('memcache_test');
     $this->default_value = $this->randomName(10);
@@ -386,14 +415,14 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test clearing the cache with a cid, no cache lifetime.
    */
-  function testClearCidNoLifetime() {
+  public function testClearCidNoLifetime() {
     $this->clearCidTest();
   }
 
   /**
    * Test clearing the cache with a cid, with cache lifetime.
    */
-  function testClearCidLifetime() {
+  public function testClearCidLifetime() {
     variable_set('cache_lifetime', 6000);
     $this->clearCidTest();
   }
@@ -401,14 +430,14 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test clearing using wildcard prefixes, no cache lifetime.
    */
-  function testClearWildcardNoLifetime() {
+  public function testClearWildcardNoLifetime() {
     $this->clearWildcardPrefixTest();
   }
 
   /**
    * Test clearing using wildcard prefix, with cache lifetime.
    */
-  function testClearWildcardLifetime() {
+  public function testClearWildcardLifetime() {
     variable_set('cache_lifetime', 6000);
     $this->clearWildcardPrefixTest();
   }
@@ -416,7 +445,7 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test full bin flushes with no cache lifetime.
    */
-  function testClearWildcardFull() {
+  public function testClearWildcardFull() {
     cache_set('test_cid_clear1', $this->default_value, $this->default_bin);
     cache_set('test_cid_clear2', $this->default_value, $this->default_bin);
     $this->assertTrue($this->checkCacheExists('test_cid_clear1', $this->default_value)
@@ -431,7 +460,7 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test full bin flushes with cache lifetime.
    */
-  function testClearCacheLifetime() {
+  public function testClearCacheLifetime() {
     variable_set('cache_lifetime', 600);
     $this->resetVariables();
 
@@ -451,7 +480,8 @@ class MemCacheClearCase extends MemcacheTestCase {
     // However permament items should stay in place.
     $this->assertTrue($this->checkCacheExists('test_cid_2', $this->default_value), 'Cache item was not cleared');
 
-    // If $_SESSION['cache_flush'] is not set, then the expired item should be returned.
+    // If $_SESSION['cache_flush'] is not set, then the expired item should
+    // be returned.
     unset($_SESSION['cache_flush']);
     $this->assertTrue($this->checkCacheExists('test_cid', $this->default_value), 'Cache item is still returned due to minimum cache lifetime.');
 
@@ -485,7 +515,7 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test different wildcards to verify the wildcard optimizations.
    */
-  function testWildCardOptimizations() {
+  public function testWildCardOptimizations() {
 
     // Set and clear a cache with a short cid/wildcard.
     cache_set('foo:1', $this->default_value, $this->default_bin);
@@ -528,7 +558,7 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test CACHE_TEMPORARY and CACHE_PERMANENT behaviour.
    */
-  function testClearTemporaryPermanent() {
+  public function testClearTemporaryPermanent() {
     cache_set('test_cid_clear_temporary', $this->default_value, $this->default_bin, CACHE_TEMPORARY);
     cache_set('test_cid_clear_permanent', $this->default_value, $this->default_bin, CACHE_PERMANENT);
     cache_set('test_cid_clear_future', $this->default_value, $this->default_bin, time() + 3600);
@@ -553,7 +583,7 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test clearing using a cid.
    */
-  function clearCidTest() {
+  public function clearCidTest() {
     cache_set('test_cid_clear', $this->default_value, $this->default_bin);
 
     $this->assertCacheExists(t('Cache was set for clearing cid.'), $this->default_value, 'test_cid_clear');
@@ -575,7 +605,7 @@ class MemCacheClearCase extends MemcacheTestCase {
   /**
    * Test cache clears using wildcard prefixes.
    */
-  function clearWildcardPrefixTest() {
+  public function clearWildcardPrefixTest() {
     $this->resetVariables();
     cache_set('test_cid_clear:1', $this->default_value, $this->default_bin);
     cache_set('test_cid_clear:2', $this->default_value, $this->default_bin);
@@ -593,18 +623,18 @@ class MemCacheClearCase extends MemcacheTestCase {
     cache_clear_all('test_', $this->default_bin, TRUE);
     $this->assertFalse($this->checkCacheExists('test_cid_clear:1', $this->default_value), 'The cache was cleared successfully.');
     // Delete the wildcard manually to simulate an eviction.
-    $wildcard = '.wildcard-' . 'test_cid_clear:';
+    $wildcard = '.wildcard-test_cid_clear:';
     dmemcache_delete($wildcard, $this->default_bin);
     // Reset the memcache_wildcards() static cache.
     // @todo: this is a class object in D7.
-    //memcache_wildcards(FALSE, FALSE, FALSE, TRUE);
+    // memcache_wildcards(FALSE, FALSE, FALSE, TRUE);
     $this->assertFalse($this->checkCacheExists('test_cid_clear:1', $this->default_value), 'The cache was cleared successfully.');
   }
 
   /**
    * Test wildcard flushing on separate pages to ensure no static cache is used.
    */
-  function testClearWildcardOnSeparatePages() {
+  public function testClearWildcardOnSeparatePages() {
 
     $random_wildcard = $this->randomName(2) . ':' . $this->randomName(3);
     $random_key = $random_wildcard . ':' . $this->randomName(4) . ':' . $this->randomName(2);
@@ -660,11 +690,14 @@ class MemCacheRealWorldCase extends MemcacheTestCase {
     return array(
       'name' => 'Real world cache tests',
       'description' => 'Test some real world cache scenarios.',
-      'group' => 'Memcache'
+      'group' => 'Memcache',
     );
   }
 
-  function setUp() {
+  /**
+   * @see MemcacheTestCase::setUp()
+   */
+  public function setUp() {
     parent::setUp('menu');
   }
 
@@ -674,12 +707,17 @@ class MemCacheRealWorldCase extends MemcacheTestCase {
    * The menu module clears the affected menu if an menu item is changed using
    * wildcards.
    */
-  function testMenu() {
+  public function testMenu() {
     // Create and login user.
-    $account = $this->drupalCreateUser(array('access administration pages', 'administer blocks', 'administer menu', 'create article content'));
+    $account = $this->drupalCreateUser(array(
+      'access administration pages',
+      'administer blocks',
+      'administer menu',
+      'create article content',
+    ));
     $this->drupalLogin($account);
 
-    // Add Menu Link to test with
+    // Add Menu Link to test with.
     $item = $this->addMenuLink();
     $original_title = $item['link_title'];
 
@@ -688,7 +726,7 @@ class MemCacheRealWorldCase extends MemcacheTestCase {
     $this->assertText($original_title, 'Menu item displayed in frontend');
 
     // Change menu item multiple times and check if the change is reflected.
-    for($i=0; $i < 3; $i++) {
+    for ($i = 0; $i < 3; $i++) {
       // Edit menu link.
       $edit = array();
       $edit['link_title'] = $this->randomName(16);;
@@ -716,20 +754,23 @@ class MemCacheRealWorldCase extends MemcacheTestCase {
    *
    * @see MenuTestCase::addMenuLink()
    */
-  function addMenuLink($plid = 0, $link = '<front>', $menu_name = 'main-menu') {
+  public function addMenuLink($plid = 0, $link = '<front>', $menu_name = 'main-menu') {
     // View add menu link page.
     $this->drupalGet("admin/structure/menu/manage/$menu_name/add");
     $this->assertResponse(200);
 
     $title = '!OriginalLink_' . $this->randomName(16);
     $edit = array(
-        'link_path' => $link,
-        'link_title' => $title,
-        'description' => '',
-        'enabled' => TRUE, // Use this to disable the menu and test.
-        'expanded' => TRUE, // Setting this to true should test whether it works when we do the std_user tests.
-        'parent' =>  $menu_name . ':' . $plid,
-        'weight' => '0',
+      'link_path' => $link,
+      'link_title' => $title,
+      'description' => '',
+      // Use this to disable the menu and test.
+      'enabled' => TRUE,
+      // Setting this to true should test whether it works when we do the
+      // std_user tests.
+      'expanded' => TRUE,
+      'parent' => $menu_name . ':' . $plid,
+      'weight' => '0',
     );
 
     // Add menu link.
@@ -752,11 +793,14 @@ class MemCacheStatisticsTestCase extends MemcacheTestCase {
     return array(
       'name' => 'Statistics tests',
       'description' => 'Test that statistics are being recorded appropriately.',
-      'group' => 'Memcache'
+      'group' => 'Memcache',
     );
   }
 
-  function setUp() {
+  /**
+   * @see MemcacheTestCase::setUp()
+   */
+  public function setUp() {
     parent::setUp('memcache_admin');
 
     $conf['cache_default_class'] = 'MemCacheDrupal';
@@ -770,7 +814,7 @@ class MemCacheStatisticsTestCase extends MemcacheTestCase {
    * enabled and tests that statistics are not recorded when the user doesn't
    * have access or displaying statistics is disabled.
    */
-  function testBootstrapStatistics() {
+  public function testBootstrapStatistics() {
     global $_memcache_statistics;
     // Expected statistics for cache_set() and cache_get().
     $test_full_key = dmemcache_key($this->default_cid, $this->default_bin);
@@ -778,7 +822,13 @@ class MemCacheStatisticsTestCase extends MemcacheTestCase {
     $expected_statistic_get[] = array('get', $this->default_bin, $test_full_key, 1);
 
     // List of bootstrap cids to check for.
-    $cache_bootstrap_cids = array('variables', 'bootstrap_modules', 'lookup_cache', 'system_list', 'module_implements');
+    $cache_bootstrap_cids = array(
+      'variables',
+      'bootstrap_modules',
+      'lookup_cache',
+      'system_list',
+      'module_implements'
+    );
 
     // Turn on memcache statistics.
     variable_set('show_memcache_statistics', TRUE);
diff --git a/unstable/memcache-session.inc b/unstable/memcache-session.inc
index e31712a..60f9d08 100644
--- a/unstable/memcache-session.inc
+++ b/unstable/memcache-session.inc
@@ -13,32 +13,77 @@
 require_once dirname(__FILE__) . '/../dmemcache.inc';
 
 /**
- * Implement hook_user_update() using a required module's namespace since
- * memcache is not a module and thus can't implement hooks directly.
+ * Implements hook_user_update().
+ *
+ * We're using a required module's namespace since the memcache session handler
+ * is not a module and thus can't implement hooks directly.
  */
 function filter_user_update(&$edit, &$account, $category = NULL) {
   // Invalidate cached user object.
   cache_clear_all($account->uid, 'users');
 }
 
+/**
+ * Session handler assigned by session_set_save_handler().
+ *
+ * This function is used to handle any initialization, such as file paths or
+ * database connections, that is needed before accessing session data. Drupal
+ * does not need to initialize anything in this function.
+ *
+ * This function should not be called directly.
+ *
+ * @return bool
+ *   This function will always return TRUE.
+ */
 function _drupal_session_open() {
   return TRUE;
 }
 
+/**
+ * Session handler assigned by session_set_save_handler().
+ *
+ * This function is used to close the current session. Because Drupal stores
+ * session data in the database immediately on write, this function does
+ * not need to do anything.
+ *
+ * This function should not be called directly.
+ *
+ * @return bool
+ *   This function will always return TRUE.
+ */
 function _drupal_session_close() {
   return TRUE;
 }
 
+/**
+ * Reads an entire session from the database (internal use only).
+ *
+ * Also initializes the $user object for the user associated with the session.
+ * This function is registered with session_set_save_handler() to support
+ * database-backed sessions. It is called on every page load when PHP sets
+ * up the $_SESSION superglobal.
+ *
+ * This function is an internal function and must not be called directly.
+ * Doing so may result in logging out the current user, corrupting session data
+ * or other unexpected behavior. Session data must always be accessed via the
+ * $_SESSION superglobal.
+ *
+ * @param string $key
+ *   The session ID of the session to retrieve.
+ *
+ * @return mixed
+ *   The user's session, or an empty string if no session exists.
+ */
 function _drupal_session_read($key) {
   global $user;
 
-  // Write and Close handlers are called after destructing objects since PHP 5.0.5
-  // Thus destructors can use sessions but session handler can't use objects.
-  // So we are moving session closure before destructing objects.
+  // Write and Close handlers are called after destructing objects since
+  // PHP 5.0.5 Thus destructors can use sessions but session handler can't use
+  // objects. So we are moving session closure before destructing objects.
   register_shutdown_function('session_write_close');
 
   // Handle the case of first time visitors and clients that don't store
-  // cookies (eg. web crawlers).
+  // cookies (for example web crawlers).
   if (!isset($_COOKIE[session_name()])) {
     $user = drupal_anonymous_user();
     return '';
@@ -66,19 +111,20 @@ function _drupal_session_read($key) {
  *   1b. With session data.
  *   1c. Session saving has been turned off programatically
  *       (see drupal_save_session()).
- *   1d. Without session data but had session data at the beginning of the request
- *       (thus a write must be made to clear stored session data).
+ *   1d. Without session data but had session data at the beginning of the
+ *       request (thus a write must be made to clear stored session data).
  * 2. Authenticated user.
  *   2a. Without session data.
  *   2b. With session data.
  *   2c. Session saving has been turned off programatically
  *       (see drupal_save_session()).
  *
- * @param $key
+ * @param string $key
  *   The session ID.
- * @param $value
+ * @param mixed $value
  *   Any data to store in the session.
- * @return
+ *
+ * @return bool
  *   TRUE.
  */
 function _drupal_session_write($key, $value) {
@@ -89,7 +135,7 @@ function _drupal_session_write($key, $value) {
   }
 
   // Prepare the information to be saved.
-  $session = new stdClass;
+  $session = new stdClass();
   $session->sid = $key;
   $session->uid = $user->uid;
   $session->cache = isset($user->cache) ? $user->cache : '';
@@ -135,8 +181,8 @@ function _drupal_session_write($key, $value) {
 /**
  * Called by PHP session handling with the PHP session ID to end a user's session.
  *
- * @param  string $sid
- *   the session id
+ * @param string $sid
+ *   The session id.
  */
 function _drupal_session_destroy($sid) {
   dmemcache_delete($sid, 'session');
@@ -149,6 +195,14 @@ function _drupal_session_destroy($sid) {
   _drupal_session_delete_cookie(session_name());
 }
 
+/**
+ * Session handler assigned by session_set_save_handler().
+ *
+ * Does nothing with memcache.
+ *
+ * @param int $lifetime
+ *   The value of session.gc_maxlifetime, passed by PHP.
+ */
 function _drupal_session_garbage_collection($lifetime) {
   // Automatic with memcached.
   // Be sure to adjust 'php_value session.gc_maxlifetime' to a large enough
@@ -190,11 +244,19 @@ function drupal_session_initialize() {
 
 
 /**
- * Counts how many users have sessions. Can count either anonymous sessions, authenticated sessions, or both.
- * Would be insane slow with memcached as we would need to retrieve at least the stats of all object.
+ * Counts how many users have sessions.
+ *
+ * Can count either anonymous sessions, authenticated sessions, or both.
+ * Would be insane slow with memcached as we would need to retrieve at least
+ * the stats of all object.
  * Not implemented.
+ *
+ * @param int $timestamp
+ *   Ignored.
+ * @param bool $anonymous
+ *   Ignored.
  */
-function drupal_session_count($timestamp = 0, $anonymous = true) {
+function drupal_session_count($timestamp = 0, $anonymous = TRUE) {
 }
 
 /**
@@ -306,13 +368,16 @@ function drupal_session_destroy_uid($uid) {
 /**
  * Determine whether to save session data of the current request.
  *
- * This function allows the caller to temporarily disable writing of session data,
- * should the request end while performing potentially dangerous operations, such as
- * manipulating the global $user object.  See http://drupal.org/node/218104 for usage
+ * This function allows the caller to temporarily disable writing of session
+ * data, should the request end while performing potentially dangerous
+ * operations, such as manipulating the global $user object.
+ * See http://drupal.org/node/218104 for usage
  *
- * @param $status
- *   Disables writing of session data when FALSE, (re-)enables writing when TRUE.
- * @return
+ * @param bool $status
+ *   Disables writing of session data when FALSE, (re-)enables writing
+ *   when TRUE.
+ *
+ * @return bool
  *   FALSE if writing session data has been disabled. Otherwise, TRUE.
  */
 function drupal_save_session($status = NULL) {
@@ -326,10 +391,11 @@ function drupal_save_session($status = NULL) {
 /**
  * Create the user object.
  *
- * @param $session
+ * @param object $session
  *   The session object (see sess_write() for the structure).
- * @return $user
- *   The user object.
+ *
+ * @return object
+ *   The $user object.
  */
 function _memcache_session_user_load($session) {
   // We found the client's session record and they are an authenticated user.
@@ -357,7 +423,7 @@ function _memcache_session_user_load($session) {
         $user->session = empty($session->session) ? '' : $session->session;
         $user->data = unserialize($user->data);
 
-        // Add roles element to $user
+        // Add roles element to $user.
         $user->roles = array();
         $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
         $result = db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $user->uid));
@@ -366,7 +432,7 @@ function _memcache_session_user_load($session) {
         }
       }
     }
-    else if ($user->uid) {
+    elseif ($user->uid) {
       // Got a user object from 'users' memcache bin. Mark it in case modules
       // want to know that this user was created from memcache.
       $user->from_cache = TRUE;
@@ -377,8 +443,9 @@ function _memcache_session_user_load($session) {
       // was successfully retrieved from the 'users' bin, and that user
       // object's uid is 0. Not sure why this would ever happen. Leaving former
       // comment in:
-      // This is a rare case that we have a session cached, but no session user object cached.
-      // This usually only happens if you kill memcached and restart it.
+      // This is a rare case that we have a session cached, but no session user
+      // object cached. This usually only happens if you kill memcached and
+      // restart it.
       $user = drupal_anonymous_user();
       $user->session = empty($session->session) ? '' : $session->session;
     }
@@ -396,10 +463,10 @@ function _memcache_session_user_load($session) {
 /**
  * Deletes the session cookie.
  *
- * @param $name
+ * @param string $name
  *   Name of session cookie to delete.
- * @param $force_insecure
- *   Fornce cookie to be insecure.
+ * @param bool $force_insecure
+ *   Force cookie to be insecure.
  */
 function _drupal_session_delete_cookie($name, $force_insecure = FALSE) {
   if (isset($_COOKIE[$name])) {
@@ -408,4 +475,3 @@ function _drupal_session_delete_cookie($name, $force_insecure = FALSE) {
     unset($_COOKIE[$name]);
   }
 }
-
