From dcf84dd2fb82ee0fdac2734febb6f4cd606f887a Mon Sep 17 00:00:00 2001
From: Lars Toomre <ltoomre@23809.no-reply.drupal.org>
Date: Tue, 3 Apr 2012 02:31:54 -0400
Subject: [PATCH] First set of documentation and code standard changes.

---
 biblio.module                   |  863 ++++++++++++++++++++++++-----------
 includes/biblio.pages.inc       |  963 ++++++++++++++++++++++++++-------------
 includes/biblio_theme.inc       |   37 +-
 styles/biblio_style_classic.inc |   75 ++-
 4 files changed, 1325 insertions(+), 613 deletions(-)

diff --git a/biblio.module b/biblio.module
index 7d27043..6cbaa6d 100644
--- a/biblio.module
+++ b/biblio.module
@@ -1,9 +1,13 @@
 <?php
 /**
- *   biblio.module for Drupal
+ * @file
+ * Main file for Drupal module biblio.
  *
- *   Copyright (C) 2006-2008  Ron Jerome
+ * Copyright (C) 2006-2008  Ron Jerome
  *
+ *
+
+
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the GNU General Public License as published by
  *   the Free Software Foundation; either version 2 of the License, or
@@ -21,6 +25,18 @@
  */
 define('BIBLIO_VERSION', '6.x-2.x-dev');
 
+/**
+ * Retrieves author types based upon author category and biblio type.
+ *
+ * @param string $auth_category
+ *   A string representing the category of author.
+ * @param string $biblio_type
+ *   A string representing the type of biblio item.
+ *
+ * @return array|null
+ *   An associative array keyed by author category and biblio type.  NULL is
+ *   returned if no matches could be found.
+ */
 function _biblio_get_auth_types($auth_category, $biblio_type) {
   static $auth_types = array();
   if (empty($auth_types)) {
@@ -29,16 +45,45 @@ function _biblio_get_auth_types($auth_category, $biblio_type) {
       $auth_types[$row->auth_category][$row->biblio_type][] = $row->auth_type;
     }
   }
-  $result = isset($auth_types[$auth_category][$biblio_type])?$auth_types[$auth_category][$biblio_type]:null;
-  // fall back to defaults, if no author types are defined for this biblio_type
+  $result = isset($auth_types[$auth_category][$biblio_type])
+            ? $auth_types[$auth_category][$biblio_type]
+            : NULL;
+  // Fall back to defaults if no author types are defined for this biblio_type.
   if (empty($result)) $result = $auth_types[$auth_category][0];
   return $result;
 }
+
+/**
+ * Retrieves primary author type based on author category and biblio type.
+ *
+ * @param string $auth_category
+ *   A string representing the category of author.
+ * @param string $biblio_type
+ *   A string representing the type of biblio item.
+ *
+ * @return string|null
+ *   A string with the primary author type. NULL is returned if no matches could
+ *   be found.
+ */
 function _biblio_get_auth_type($auth_category, $biblio_type) {
-  $result = (array)_biblio_get_auth_types($auth_category, $biblio_type);
-  // return first element of the array
+  $result = (array) _biblio_get_auth_types($auth_category, $biblio_type);
+  // Return first element of the author types array.
   return empty($result) ? NULL : current($result);
 }
+
+/**
+ * Retrieves field information based upon biblio type.
+ *
+ * @param string $biblio_type
+ *   The type of biblio to retrieve field information about.
+ * @param bool $only_visible
+ *   (optional) A logical flag indicating whether to only return visible fields.
+ *   The default is FALSE which indicates information on all fields for this
+ *   biblio_type should be returned.
+ *
+ * @return array
+ *   An associative array keyed by integer of field ID.
+ */
 function _biblio_get_field_information($biblio_type, $only_visible = FALSE) {
   $fields = array();
   $visible = $only_visible ? ' AND (bt.common = 1 OR bt.visible=1) ' : '';
@@ -57,8 +102,16 @@ function _biblio_get_field_information($biblio_type, $only_visible = FALSE) {
 }
 
 /**
- * Translate field titles and hints through the interface translation system, if
- * the i18nstrings module is enabled.
+ * Translates interface field titles and hints.
+ *
+ * If the i18nstrings module is enabled, this function translates field titles
+ * and hints through the interface translation system.
+ *
+ * @param array $fields
+ *   An associative array with field information (passed by reference) keyed by
+ *   field ID number with two elements:
+ *   - title: A string with the title of the field.
+ *   - hint: A string with the hint text for the field.
  */
 function _biblio_localize_fields(&$fields) {
   if (module_exists('i18nstrings')) {
@@ -70,20 +123,21 @@ function _biblio_localize_fields(&$fields) {
 }
 
 /**
- * Translate a publication type through the interface translation system, if
- * the i18nstrings module is enabled.
+ * Translates a publication type for the interface.
+ *
+ * If the i18nstrings module is enabled, this function translates a publication
+ * type through the interface translation system.
  *
  * @param integer $tid
  *   The biblio publication type identifier.
- *
  * @param string $value
  *   The string to translate.
- *
  * @param string $field
- *   The publication type field to translate (either 'name' or 'description').
+ *   (optional) The publication type field to translate (either 'name' or
+ *   'description'). The default value is 'name'.
  *
- * @return
- *   Translated value.
+ * @return string
+ *   The translated text for publication type.
  */
 function _biblio_localize_type($tid, $value, $field = 'name') {
   if (module_exists('i18nstrings')) {
@@ -93,7 +147,7 @@ function _biblio_localize_type($tid, $value, $field = 'name') {
 }
 
 /**
- * Implementation of hook_locale().
+ * Implements hook_locale().
  */
 function biblio_locale($op = 'groups', $group = NULL) {
   switch ($op) {
@@ -110,11 +164,12 @@ function biblio_locale($op = 'groups', $group = NULL) {
 }
 
 /**
- * Refresh all translatable field strings.
+ * Refreshes all translatable field strings.
  *
  * @param integer $tid
- *   Biblio publication type id whose field strings are to be refreshed. If not
- *   specified, strings for all fields will be refreshed.
+ *   (optional) Biblio publication type ID whose field strings are to be
+ *   refreshed. If not specified, strings for all fields will be refreshed. The
+ *   default value is NULL.
  */
 function biblio_locale_refresh_fields($tid = NULL) {
   if (module_exists('i18nstrings')) {
@@ -132,11 +187,12 @@ function biblio_locale_refresh_fields($tid = NULL) {
 }
 
 /**
- * Refresh all publication type strings.
+ * Refreshes all publication type strings.
  *
  * @param integer $tid
- *   Biblio publication type id whose field strings are to be refreshed. If not
- *   specified, strings for all fields will be refreshed.
+ *   (optional) Biblio publication type ID whose field strings are to be
+ *   refreshed. If not specified, strings for all fields will be refreshed. The
+ *   default value is NULL.
  */
 function biblio_locale_refresh_types($tid = NULL) {
   if (module_exists('i18nstrings')) {
@@ -153,22 +209,31 @@ function biblio_locale_refresh_types($tid = NULL) {
   }
 }
 
+/**
+ * Implements hook_init().
+ */
 function biblio_init() {
   global $user, $conf;
   drupal_add_css(drupal_get_path('module', 'biblio') .'/biblio.css');
 
-  if ($user->uid === 0) { // Prevent caching of biblio pages for anonymous users so session variables work and thus filering works
+  // Prevent caching of biblio pages for anonymous users so session variables
+  // work and hence filering also works.
+  if ($user->uid === 0) {
     $base = variable_get('biblio_base', 'biblio');
     if (drupal_match_path($_GET['q'], "$base\n$base/*"))
       $conf['cache'] = FALSE;
   }
 }
 
+/**
+ * Implements hook_cron().
+ */
 function biblio_cron() {
-  require_once(drupal_get_path('module', 'biblio') .'/includes/biblio.contributors.inc');
-  require_once(drupal_get_path('module', 'biblio') .'/includes/biblio.keywords.inc');
+  require_once(drupal_get_path('module', 'biblio') . '/includes/biblio.contributors.inc');
+  require_once(drupal_get_path('module', 'biblio') . '/includes/biblio.keywords.inc');
 
-  $interval = variable_get('biblio_orphan_clean_interval', 24*60*60); //defaults to once per day
+  // Defaults to a value of daily (24*60*60 or 86,400 seconds).
+  $interval = variable_get('biblio_orphan_clean_interval', 86400);
 
   if (time() >= variable_get('biblio_orphan_clean_next_execution', 0)) {
     biblio_delete_orphan_authors();
@@ -177,6 +242,9 @@ function biblio_cron() {
   }
 }
 
+/**
+ * Implements hook_theme().
+ */
 function biblio_theme() {
   $path = drupal_get_path('module', 'biblio');
   return array(
@@ -307,27 +375,46 @@ function biblio_theme() {
     ),
   );
 }
+
+/**
+ *
+ *
+ * @param $field
+ *
+ * @param string $string
+ *   (optional)
+ */
 function biblio_autocomplete($field, $string = '') {
   $matches = array();
   if ($field == 'contributor') {
-    $result = db_query_range("SELECT * FROM {biblio_contributor_data} WHERE LOWER(lastname) LIKE LOWER('%s%%') OR LOWER(firstname) LIKE LOWER('%s%%') ORDER BY lastname ASC ", array($string, $string), 0, 10);
+  	$sql = "SELECT * FROM {biblio_contributor_data} " .
+  	       "WHERE LOWER(lastname) LIKE LOWER('%s%%') OR LOWER(firstname) LIKE LOWER('%s%%') " .
+  	       "ORDER BY lastname ASC ";
+    $result = db_query_range($sql, array($string, $string), 0, 10);
     while ($data = db_fetch_object($result)) {
       $matches[$data->name] = check_plain($data->name);
     }
-  }elseif ($field == 'biblio_keywords') {
+  }
+  elseif ($field == 'biblio_keywords') {
     $sep = check_plain(variable_get('biblio_keyword_sep', ','));
-    $sep_pos = strrpos($string, $sep); //find the last separator
-    $start   = trim(drupal_substr($string, 0, $sep_pos)); // first part of the string upto the last separator
-    $end_sep = ($sep_pos) ? $sep_pos + 1 :$sep_pos;
-    $end     = trim(drupal_substr($string, $end_sep));  // part of the string after the last separator
-    $result = db_query_range("SELECT * FROM {biblio_keyword_data} WHERE LOWER(word) LIKE LOWER('%s%%') ORDER BY word ASC ", array($end), 0, 10);
+    // Locate the position of last separator in the string.
+    $sep_pos = strrpos($string, $sep);
+    // The beginning of the string until the last separator.
+    $start   = trim(drupal_substr($string, 0, $sep_pos));
+    $end_sep = ($sep_pos) ? $sep_pos + 1 : $sep_pos;
+    // The balance of the string after the last separator.
+    $end     = trim(drupal_substr($string, $end_sep));
+    $sql = "SELECT * FROM {biblio_keyword_data} WHERE LOWER(word) LIKE LOWER('%s%%') ORDER BY word ASC ";
+    $result = db_query_range($sql, array($end), 0, 10);
     while ($data = db_fetch_object($result)) {
-      // now glue the word found onto the end of the original string...
+      // Glue the word found onto the end of the original string.
       $keywords = ($sep_pos) ? $start . ', ' . check_plain($data->word) : check_plain($data->word);
       $matches[$keywords] = $keywords;
     }
-  }else{
-    $result = db_query_range("SELECT %s FROM {biblio} WHERE LOWER(%s) LIKE LOWER('%s%%') ORDER BY %s ASC", array($field, $field, $string, $field) , 0, 10);
+  }
+  else {
+  	$sql = "SELECT %s FROM {biblio} WHERE LOWER(%s) LIKE LOWER('%s%%') ORDER BY %s ASC";
+    $result = db_query_range($sql, array($field, $field, $string, $field), 0, 10);
     while ($data = db_fetch_object($result)) {
       $matches[$data-> $field] = check_plain($data-> $field);
     }
@@ -335,36 +422,42 @@ function biblio_autocomplete($field, $string = '') {
   print drupal_to_js($matches);
   exit();
 }
+
+/**
+ * Generates a page of translated help text applicable to the biblio module.
+ *
+ * @return string
+ *   An HTML formatted string with possibly translated content for this module.
+ */
 function biblio_help_page() {
   $base = variable_get('biblio_base', 'biblio');
-  $text = "<h3>". t('General:') ."</h3>";
-  $text .= "<p>". t('By default, the !url page will list all of the entries in the database sorted by Year in descending order. If you wish to sort by "Title" or "Type",  you may do so by clicking on the appropriate links at the top of the page.  To reverse the sort order, simply click the link a second time.', array(
-    '!url' => l('',
-  $base
-  ))) ."</p>";
-  $text .= "<h3>". t('Filtering Search Results:') ."</h3>";
-  $text .= "<p>". t('If you wish to filter the results, click on the "Filter" tab at the top of the page.  To add a filter, click the radio button to the left of the filter type you wish to apply, then select the filter criteria from the drop down list on the right, then click the filter button.') ."</p>";
-  $text .= "<p>". t('It is possible to create complex filters by returning to the <i>Filter</i> tab and adding additional filters.  Simply follow the steps outlined above and press the "Refine" button.') ."</p>";
-  $text .= "<p>". t('All filters can be removed by clicking the <i>Clear All Filters</i> link at the top of the result page, or on the <i>Filter</i> tab they can be removed one at a time using the <i>Undo</i> button, or you can remove them all using the <i>Clear All</i> button.') ."</p>";
-  $text .= "<p>". t('You may also construct URLs which filter.  For example, /biblio/year/2005 will show all of the entries for 2005.  /biblio/year/2005/author/smith will show all of entries from 2005 for smith.') ."</p>";
-  $text .= "<h3>". t('Exporting Search Results:') ."</h3>";
-  $text .= "<p>". t('Assuming this option has been enabled by the administrator, you can export search results directly into EndNote.  The link at the top of the result page will export all of the search results, and the links on individual entries will export the information related to that single entry.') ."</p>";
-  $text .= "<p>". t('The information is exported in EndNote "Tagged" format similar to this...') ."<pre>". t('
+  $text = "<h3>" . t('General:') . "</h3>";
+  $text .= "<p>" . t('By default, the !url page will list all of the entries in the database sorted by Year in descending order. If you wish to sort by "Title" or "Type",  you may do so by clicking on the appropriate links at the top of the page.  To reverse the sort order, simply click the link a second time.',
+                     array('!url' => l('', $base))) . "</p>";
+  $text .= "<h3>" . t('Filtering Search Results:') . "</h3>";
+  $text .= "<p>" . t('If you wish to filter the results, click on the "Filter" tab at the top of the page.  To add a filter, click the radio button to the left of the filter type you wish to apply, then select the filter criteria from the drop down list on the right, then click the filter button.') . "</p>";
+  $text .= "<p>" . t('It is possible to create complex filters by returning to the <i>Filter</i> tab and adding additional filters.  Simply follow the steps outlined above and press the "Refine" button.') . "</p>";
+  $text .= "<p>" . t('All filters can be removed by clicking the <i>Clear All Filters</i> link at the top of the result page, or on the <i>Filter</i> tab they can be removed one at a time using the <i>Undo</i> button, or you can remove them all using the <i>Clear All</i> button.') ."</p>";
+  $text .= "<p>" . t('You may also construct URLs which filter.  For example, /biblio/year/2005 will show all of the entries for 2005.  /biblio/year/2005/author/smith will show all of entries from 2005 for smith.') ."</p>";
+  $text .= "<h3>" . t('Exporting Search Results:') ."</h3>";
+  $text .= "<p>" . t('Assuming this option has been enabled by the administrator, you can export search results directly into EndNote.  The link at the top of the result page will export all of the search results, and the links on individual entries will export the information related to that single entry.') ."</p>";
+  $text .= "<p>" . t('The information is exported in EndNote "Tagged" format similar to this...') . "<pre>" . t('
                   %0  Book
                   %A  John Smith
                   %D  1959
                   %T  The Works of John Smith
-                  ...') .'</pre></p>';
-  $text .= "<p>". t('Clicking on one of the export links should cause your browser to ask you whether you want to Open, or Save To Disk, the file endnote.enw.  If you choose to open it, Endnote should start and ask you which library you would like store the results in.  Alternatively, you can save the file to disk and manually import it into EndNote.') ."</p>";
+                  ...') . '</pre></p>';
+  $text .= "<p>" . t('Clicking on one of the export links should cause your browser to ask you whether you want to Open, or Save To Disk, the file endnote.enw.  If you choose to open it, Endnote should start and ask you which library you would like store the results in.  Alternatively, you can save the file to disk and manually import it into EndNote.') . "</p>";
   return ($text);
 }
+
 /**
- * Implementation of hook_help().
+ * Implements hook_help().
  *
  * Throughout Drupal, hook_help() is used to display help text at the top of
  * pages. Some other parts of Drupal pages get explanatory text from these hooks
- * as well. We use it here to provide a description of the module on the
- * module administration page.
+ * as well. We use it here to provide a description of the module on the module
+ * administration page.
  */
 function biblio_help($path, $arg) {
   switch ($path) {
@@ -374,61 +467,79 @@ function biblio_help($path, $arg) {
       // This description is shown in the listing at admin/modules.
       return t('Manages a list of scholarly papers on your site');
     case 'node/add#biblio' :
-      // This description shows up when users click "create content."
+      // This description appears when users click "create content."
       return t('This allows you to add a bibliographic entry to the database');
   }
 }
+
+/**
+ * Implements hook_node_info().
+ */
 function biblio_node_info() {
   return array(
     'biblio' => array(
       'name' => t('Biblio'),
       'module' => 'biblio',
       'description' => t('Manages bibliographies')
-  )
+    )
   );
 }
+
 /**
- * Implementation of hook_access().
+ * Implements hook_access().
  *
- * Node modules may implement node_access() to determine the operations
- * users may perform on nodes. This example uses a very common access pattern.
+ * Node modules may implement node_access() to determine the operations users
+ * may perform on nodes. This function uses a very common access pattern.
  */
 function biblio_access($op, $node = '', $user = '') {
   switch ($op) {
     case 'create':
       return user_access('create biblio');
+
     case 'delete':
     case 'update':
       if (user_access('edit all biblio entries')) return TRUE;
-      if (user_access('edit own biblio entries') && $user->uid == $node->uid) return TRUE;
+      if (user_access('edit own biblio entries') && isset($user->uid) && isset($node->uid) && $user->uid == $node->uid) return TRUE;
       break;
+
     case 'view':
-      if ((variable_get('biblio_view_only_own', 0)) && $user->uid != $node->uid) return FALSE;
+      if ((variable_get('biblio_view_only_own', 0)) && isset($user->uid) && isset($node->uid) && $user->uid != $node->uid) return FALSE;
       break;
+
     case 'admin':
       return user_access('administer biblio');
+
     case 'import':
       return user_access('import from file');
+
     case 'export':
       return user_access('show export links');
+
     case 'edit_author':
         if (user_access('administer biblio') || user_access('edit biblio authors')) return TRUE;
         break;
+
     case 'download':
-      if (user_access('show download links') || (user_access('show own download links') && ($user->uid == $node->uid))) return TRUE;
+      if (user_access('show download links') ||
+         (user_access('show own download links') &&
+         (isset($user->uid) && isset($node->uid) && $user->uid == $node->uid))) return TRUE;
       break;
+
     case 'rss':
       return variable_get('biblio_rss', 0);
+
     default:
+      break;
   }
   return;
 }
+
 /**
- * Implementation of hook_perm().
+ * Implements hook_perm().
  *
- * Since we are limiting the ability to create new nodes to certain users,
- * we need to define what those permissions are here. We also define a permission
- * to allow users to edit the nodes they created.
+ * Since we are restricting users in various ways when they wish to create,
+ * view, update and/or delete biblio content, we need to define what those
+ * permissions are here.
  */
 function biblio_perm() {
   return array(
@@ -447,11 +558,12 @@ function biblio_perm() {
     'view full text'
     );
 }
+
 /**
- * Implementation of hook_link().
+ * Implements hook_link().
  *
- * This is implemented so that an edit link is displayed for users who have
- * the rights to edit a node.
+ * This is implemented so that an edit link is displayed for users who have the
+ * correct permission(s) to edit a node.
  */
 function biblio_link($type, $node = NULL, $teaser = FALSE) {
   $links = array();
@@ -464,17 +576,19 @@ function biblio_link($type, $node = NULL, $teaser = FALSE) {
         'title' => t('edit this entry'),
         'href' => "node/$node->nid/edit"
       );
-
     }
     if (biblio_access('export', $node)) {
       $show_link = variable_get('biblio_lookup_links', array('google' => TRUE));
-      if ($show_link['google']) $links['biblio_google_scholar'] = theme('google_scholar_link', $node);
+      if ($show_link['google']) {
+      	$links['biblio_google_scholar'] = theme('google_scholar_link', $node);
+      }
     }
   }
   return $links;
 }
+
 /**
- * Implementation of hook_link_alter to modifiy taxonomy links
+ * Implements hook_link_alter to modifiy taxonomy links.
  *
  * @param $links
  * @param $node
@@ -488,13 +602,14 @@ function biblio_link($type, $node = NULL, $teaser = FALSE) {
 //    }
 //  }
 //}
+
 /**
- * Implementation of hook_user().
+ * Implements hook_user().
  */
-function biblio_user($type, & $edit, & $account, $category = NULL) {
+function biblio_user($type, &$edit, &$account, $category = NULL) {
   global $user;
 
-  if ($type == 'form' && $category == 'account' ) {
+  if ($type == 'form' && $category == 'account') {
     $form = array();
     module_load_include('inc', 'biblio', 'includes/biblio.admin');
     $show_form = variable_get('biblio_show_user_profile_form', '1')     ||
@@ -536,13 +651,17 @@ function biblio_user($type, & $edit, & $account, $category = NULL) {
   if ($type == 'update' && $category == 'account') {
     if (isset($edit['biblio_contributor_id'])) {
       db_query("UPDATE {biblio_contributor_data} SET drupal_uid = 0 WHERE drupal_uid = %d", $account->uid);
-      db_query('UPDATE {biblio_contributor_data} set drupal_uid = %d WHERE cid = %d ', $account->uid, $edit['biblio_contributor_id']);
+      db_query('UPDATE {biblio_contributor_data} SET drupal_uid = %d WHERE cid = %d ', $account->uid, $edit['biblio_contributor_id']);
     }
   }
   if ($type == 'categories') {
     //  return array(array('name' => 'account', 'title' => t('Account settings'), 'weight' => 1));
   }
 }
+
+/**
+ *
+ */
 function biblio_forms() {
   $forms['biblio_admin_author_types_form_new'] = array(
     'callback' => 'biblio_admin_author_types_form',
@@ -551,31 +670,49 @@ function biblio_forms() {
     'callback' => 'biblio_admin_author_types_form',
   );
   return $forms;
-
 }
+
 /**
- * Return actual argument for %biblio_user placeholders in menu paths
+ * Determines actual argument for %biblio_user placeholders in menu paths.
+ *
+ * This function returns the current user ID when called from a module like
+ * tracker (aka with an empty arg).  It also is used to get the current user ID
+ * when called from a menu item with a % for the current user account link.
+ *
+ * @param mixed $arg
+ *   A variable representing the user identifier.
+ *
+ * @return mixed
+ *   If $arg is empty or equal to '%', the user ID is returned; otherwise, the
+ *   value of the input $arg variable is returned.
  */
 function biblio_user_to_arg($arg) {
-  // Give back the current user uid when called from eg. tracker, aka.
-  // with an empty arg. Also use the current user uid when called from
-  // the menu with a % for the current account link.
   return (empty($arg) || $arg == '%') ? $GLOBALS['user']->uid : $arg;
 }
+
 /**
- * load user object from arg, used for %biblio_user placeholders in menu paths
- * @param $uid
- * @return $user
+ * Loads a user object based upon user ID.
+ *
+ * This is used with %biblio_user placeholders in resolving user menu paths.
+ *
+ * @param integer $uid
+ *   An integer identifier of a user object to retrieve from data table(s).
+ *
+ * @return object
+ *   The user object with identifier $uid.
  */
 function biblio_user_load($uid) {
   return user_load($uid);
 }
+
 /**
- * Implementation of hook_menu().
- *
- * Here we define some built in links for the biblio module, links exposed are:
- *
+ * Implements hook_menu().
  *
+ * This function defines all of the menu items that are handled by the biblio
+ * module.  The variables 'biblio_base' and 'biblio_base_title" allow what is
+ * presented to the user to vary from biblio.  Hence, what is by default
+ * 'biblio/authors' could be changed to 'journal/authors' by setting the
+ * variable 'biblio_base' to 'journal'.
  */
 function biblio_menu() {
   global $user;
@@ -783,14 +920,15 @@ function biblio_menu() {
     'page callback'     => 'drupal_get_form',
     'page arguments'    => array('biblio_admin_io_mapper_add_form', 4, 5),
     'access arguments'  => array('administer biblio'),
-    'tab_parent'						=> 'admin/settings/biblio/iomap',
-  'file'              => '/includes/biblio.admin.inc',
+    'tab_parent'            => 'admin/settings/biblio/iomap',
+    'file'              => '/includes/biblio.admin.inc',
     'type'              => MENU_CALLBACK,
     'weight'            => -1
-  );  $items['admin/settings/biblio/fields/type'] = array(
+  );
+  $items['admin/settings/biblio/fields/type'] = array(
     'title'             => 'Publication Types',
     'page callback'     => 'biblio_admin_types_form',
-//    'page arguments'    => array('biblio_admin_types_form'),
+//  'page arguments'    => array('biblio_admin_types_form'),
     'access arguments'  => array('administer biblio'),
     'file'              => 'includes/biblio.admin.inc',
     'type'              => MENU_LOCAL_TASK,
@@ -868,7 +1006,7 @@ function biblio_menu() {
     'access callback'   => 'biblio_access',
     'access arguments'  => array('edit_author'),
     'file'              => 'includes/biblio.admin.inc',
-   	'type'              => MENU_CALLBACK,
+    'type'              => MENU_CALLBACK,
     'weight'            => -6
   );
   $items['admin/settings/biblio/author/orphans'] = array(
@@ -1041,35 +1179,62 @@ function biblio_menu() {
   );
   return $items;
 }
+
+/**
+ * Implements hook_filter_clear().
+ */
 function biblio_filter_clear() {
   $_SESSION['biblio_filter'] = array();
   $base = variable_get('biblio_base', 'biblio');
+  $options = '';
   if (isset($_GET['sort'])) {
-    $options .= "sort=". $_GET['sort'];
+    $options .= "sort=" . $_GET['sort'];
   }
   if (isset($_GET['order'])) {
-    $options .= $options['query'] ? "&" : "";
-    $options .= "order=". $_GET['order'];
+    $options .= empty($options) ? "" : "&";
+    $options .= "order=" . $_GET['order'];
   }
   drupal_goto($base, $options);
 }
+
+/**
+ * Removes curly braces from a string.
+ *
+ * @param string $title_string
+ *   The text string to remove curly braces from.
+ *
+ * @return string
+ *   The resulting string with curly braces removed.
+ */
 function biblio_remove_brace($title_string){
-    //$title_string = utf8_encode($title_string);
-    $matchpattern = '/\{\$(?:(?!\$\}).)*\$\}|(\{[^}]*\})/';
-    $output = preg_replace_callback($matchpattern,'biblio_remove_brace_callback',$title_string);
-    return $output;
+  //$title_string = utf8_encode($title_string);
+  $matchpattern = '/\{\$(?:(?!\$\}).)*\$\}|(\{[^}]*\})/';
+  $output = preg_replace_callback($matchpattern, 'biblio_remove_brace_callback', $title_string);
+  return $output;
 }
 
-function biblio_remove_brace_callback($match){
-        if(isset($match[1])){
-                $braceless = str_replace('{', '', $match[1]);
-                $braceless = str_replace('}', '', $braceless);
-                return $braceless;
-        }
-        return $match[0];
+/**
+ * Assists in the removal of curly braces with preg_replace_callback().
+ *
+ * @param array $match
+ *
+ *
+ * @return string
+ *
+ */
+function biblio_remove_brace_callback($match) {
+  if (isset($match[1])) {
+    $braceless = str_replace('{', '', $match[1]);
+    $braceless = str_replace('}', '', $braceless);
+    return $braceless;
+  }
+  return $match[0];
 }
 
-function biblio_nodeapi(& $node, $op, $a3, $a4) {
+/**
+ * Implements hook_nodeapi().
+ */
+function biblio_nodeapi(&$node, $op, $a3, $a4) {
   if ($node->type == 'biblio') {
     switch ($op) {
       case 'delete revision' :
@@ -1077,6 +1242,7 @@ function biblio_nodeapi(& $node, $op, $a3, $a4) {
         db_query('DELETE FROM {biblio_contributor} WHERE nid = %d AND vid = %d', array($node->nid, $node->vid));
         db_query('DELETE FROM {biblio_keyword} WHERE nid = %d AND vid = %d', array($node->nid, $node->vid));
         break;
+
         /*   case 'presave':
          if ($node->type == 'biblio')
          {
@@ -1088,12 +1254,14 @@ function biblio_nodeapi(& $node, $op, $a3, $a4) {
          }
          break;
          */
+
       case 'insert':
         if (variable_get('biblio_index', 0)) {
           _node_index_node($node);
           search_update_totals();
         }
         break;
+
       case 'update':
         if (variable_get('biblio_index', 0)) {
           // _node_index_node performs a node_load without resetting the node_load cache,
@@ -1104,23 +1272,31 @@ function biblio_nodeapi(& $node, $op, $a3, $a4) {
           search_update_totals();
         }
         break;
+
       case 'view':
         if ($node->type == 'biblio' && variable_get('biblio_hide_bibtex_braces', 0) && !empty($a4)) {
           drupal_set_title(filter_xss($node->title, biblio_get_allowed_tags()));
         }
         break;
     }
-
   }
 }
 
+/**
+ * Implements hook_form_alter().
+ *
+ * @param string $form_id
+ *   The machine name of the form on which alterations are to be performed.
+ */
 function biblio_form_alter(&$form, $form_state, $form_id) {
-
-  if ($form_id == "biblio_node_form") { // this next bit is to remove all the form elements execpt the pub type select box the first time through
+  if ($form_id == "biblio_node_form") {
+  	// For the first display of the biblio node form, this section removes all
+  	// the form elements execpt the publication type select box.
     if (!isset($form_state['values']['biblio_type']) &&
         empty($form_state['post']['biblio_type']) &&
         empty($form_state['submitted']) &&
-        empty($form['vid']['#value'])) {
+        empty($form['vid']['#value'])
+       ) {
 
       foreach (element_children($form) as $form_element) {
         if (strstr($form_element, 'biblio_')) continue;
@@ -1142,44 +1318,46 @@ function biblio_form_alter(&$form, $form_state, $form_id) {
             '#collapsed' => FALSE,
           );
         }
-        $form['taxonomy']['#description'] = t('Select taxonomy terms which will be related to this %biblio_base_title entry.', array('%biblio_base_title' =>variable_get('biblio_base_title', 'Biblio')));
+        $form['taxonomy']['#description'] = t('Select taxonomy terms which will be related to this %biblio_base_title entry.',
+                                              array('%biblio_base_title' => variable_get('biblio_base_title', 'Biblio')));
         $form['taxonomy']['copy_to_biblio'] = array(
           '#type' => 'checkbox',
           '#title' => t('Copy these terms to the biblio keyword database'),
           '#return_value' => 1,
           '#default_value' =>  variable_get('biblio_copy_taxo_terms_to_keywords', 0),
-          '#description' => t('If this option is selected, the selected taxonomy terms will be copied to the %biblio_base_title keyword database and be displayed as keywords (as well as taxonomy terms) for this entry.', array('%biblio_base_title' =>variable_get('biblio_base_title', 'Biblio')))
+          '#description' => t('If this option is selected, the selected taxonomy terms will be copied to the %biblio_base_title keyword database and be displayed as keywords (as well as taxonomy terms) for this entry.',
+                              array('%biblio_base_title' => variable_get('biblio_base_title', 'Biblio')))
         );
       }
       $kw_vocab = variable_get('biblio_keyword_vocabulary', 0);
       $freetagging = variable_get('biblio_keyword_freetagging', 0);
       if ($freetagging && $kw_vocab && isset($form['taxonomy']['tags'][$kw_vocab])) {
         unset($form['taxonomy']['tags'][$kw_vocab]);
-
       }
     }
   }
   return $form;
 }
+
 /**
- * Implementation of hook_form().
+ * Implements hook_form().
  *
- * Create the form for collecting the information
- * specific to this node type. This hook requires us to return some HTML
- * that will be later placed inside the form.
+ * This function creates the form for collecting the information specific to the
+ * biblio node type. This hook requires us to return a $form array that later
+ * will be incorporated into a complete form.
  */
 function biblio_form($node, $form_state) {
   global $user;
   $fields = array();
-  $tid = isset($form_state['storage']['biblio_type']) ?
-               $form_state['storage']['biblio_type']  :
-               ( isset($node->biblio_type) ? $node->biblio_type : '');
+  $tid = isset($form_state['storage']['biblio_type'])
+           ? $form_state['storage']['biblio_type']
+           : (isset($node->biblio_type) ? $node->biblio_type : '');
   $show_fields = !empty($tid);
 
   $form['#validate'][] = 'biblio_form_validate';
   $form['#cache'] = TRUE;
 
-  /* publication type */
+  // Create a select box for the publication type of this biblio node
   $param['options'] = array(
     "enctype" => "multipart/form-data"
     );
@@ -1201,6 +1379,8 @@ function biblio_form($node, $form_state) {
     '#multiple' => FALSE,
     '#required' => TRUE
       );
+
+  // If the biblio type is defined, add various fields to the form
   if ($show_fields) {
 
     $form['title'] = array(
@@ -1210,8 +1390,8 @@ function biblio_form($node, $form_state) {
       '#default_value' => trim((($form_state['values']['title']) ? $form_state['values']['title'] : $node->title)),
       '#size' => 60,
       '#maxlength' => 255,
-      '#weight' => -4
-        );
+      '#weight' => -4,
+    );
     // Build the field array used to make the form
     $result = db_query("SELECT * FROM {biblio_fields} b
               INNER JOIN {biblio_field_type} bt ON b.fid = bt.fid
@@ -1258,10 +1438,10 @@ function biblio_form($node, $form_state) {
         if ($key == 'biblio_keywords' ) {
           module_load_include('inc', 'biblio', 'includes/biblio.keywords');
           $sep = check_plain(variable_get('biblio_keyword_sep', ','));
-          // is the kewords are in array form, then implode them into a string.
+          // If the kewords are in array form, then implode them into a string.
           if (isset($form_state['values']['biblio_keywords']) &&
-             is_array($form_state['values']['biblio_keywords'])) {
-             $form_state['values']['biblio_keywords'] = biblio_implode_keywords($form_state['values']['biblio_keywords']);
+              is_array($form_state['values']['biblio_keywords'])) {
+            $form_state['values']['biblio_keywords'] = biblio_implode_keywords($form_state['values']['biblio_keywords']);
           }
           if (isset($node->$key) && is_array($node->$key)) {
             $node->$key = biblio_implode_keywords($node->$key);
@@ -1271,32 +1451,30 @@ function biblio_form($node, $form_state) {
           }
         }
 
-
-         $field_widget = array(
-            '#default_value' => ($form_state['values'][$key]?$form_state['values'][$key]:$node->$key),
-            '#type' => $fld['type'],
-            '#title' => check_plain($fld['title']),
-            '#size' => $fld['size'],
-            '#required' => $fld['required'],
-            '#maxlength' => $fld['maxsize'],
-            '#weight' => $fld['weight'] / 10,
-            '#autocomplete_path' => ($fld['autocomplete']) ? 'biblio/autocomplete/'. $fld['name'] : '',
-            '#description' => check_plain($fld['hint']),
+        $field_widget = array(
+          '#default_value' => ($form_state['values'][$key]?$form_state['values'][$key]:$node->$key),
+          '#type' => $fld['type'],
+          '#title' => check_plain($fld['title']),
+          '#size' => $fld['size'],
+          '#required' => $fld['required'],
+          '#maxlength' => $fld['maxsize'],
+          '#weight' => $fld['weight'] / 10,
+          '#autocomplete_path' => ($fld['autocomplete']) ? 'biblio/autocomplete/' . $fld['name'] : '',
+          '#description' => check_plain($fld['hint']),
+        );
+        if ($key == 'biblio_refereed' ) {
+          $field_widget['#options'] = array(
+            '' => t('None'),
+            'Refereed' => t('Refereed'),
+            'Non-Refereed' => t('Non-Refereed'),
+            'Does Not Apply' => t('Does Not Apply'),
+            'Unknown' => t('Unknown'),
           );
-         if ($key == 'biblio_refereed' ) {
-           $field_widget['#options'] = array(
-              '' => t('None'),
-              'Refereed' => t('Refereed'),
-              'Non-Refereed' => t('Non-Refereed'),
-              'Does Not Apply' => t('Does Not Apply'),
-              'Unknown' => t('Unknown'),
-            );
-           $field_widget['#description'] = t('If you are not sure, set this to Unknown or Does Not Apply');
-         }
-          //        '#options' => $options,
-
+          $field_widget['#description'] = t('If you are not sure, set this to Unknown or Does Not Apply');
+        }
         if ($fld['type'] == 'textarea') {
-          /* wrap all textarea fields in collapsed field sets to save space on the page */
+          // Wrap all textarea fields in collapsed field sets in order to save
+          // space on the page.
           $field_widget = array(
             '#type' => 'fieldset',
             '#collapsible' => TRUE,
@@ -1307,21 +1485,20 @@ function biblio_form($node, $form_state) {
             $key => $field_widget,
             'format' =>  filter_form($node->biblio_formats[$key], 20, array('biblio_formats', $key)),
           );
-          $key = $fld['name'] .'_field';
+          $key = $fld['name'] . '_field';
         }
-        // embed field directly or in "Other Fields" fieldset
+        // Embed field directly into the form or into "Other Fields" fieldset.
         if ($main_area) {
           $form[$key] = $field_widget;
           $max_visible_weight = max($max_visible_weight, $field_widget['#weight']);
         }
-        elseif (!variable_get('biblio_hide_other_fields', 0))
-        {
+        elseif (!variable_get('biblio_hide_other_fields', 0)) {
           $form['other_fields'][$key] = $field_widget;
         }
       }
     }
 
-    // place 'Other biblio fields' directly below visible fields
+    // Place the 'Other biblio fields' directly below the visible fields.
     $form['other_fields']['#weight'] = $max_visible_weight + 0.1;
     $form['body_field'] = array(
       '#type' => 'fieldset',
@@ -1329,7 +1506,7 @@ function biblio_form($node, $form_state) {
       '#collapsed' => TRUE,
       '#title' => t('Full Text'),
       '#description' => '',
-      '#weight' => $max_visible_weight + 0.2
+      '#weight' => $max_visible_weight + 0.2,
     );
     $form['body_field']['body'] = array(
       '#type' => 'textarea',
@@ -1338,23 +1515,31 @@ function biblio_form($node, $form_state) {
       '#rows' => 10,
       '#required' => FALSE,
       '#description' => t('You may enter a full text or HTML version of the publication here.'),
-      '#weight' => 19
+      '#weight' => 19,
     );
-//    // embed filter form in "Full Text" fieldset, because it applies to the full text only
+    // Embed the filter form into the "Full Text" fieldset because it applies
+    // only to the full text element.
     $form['body_field']['format'] = filter_form($node->format, 20);
   }
- // $form['format'] = filter_form($node->format);
-
   return $form;
 }
 
 /**
- * @param $node
- * @param $fld
- * @param $auth_category
- * @param $biblio_type
- * @param $other_fields
- * @return contributor fieldset form
+ * Defines a contributor widget to be used as part of biblio node form.
+ *
+ * @param object|array $node
+ *   An object or node with information about about the biblio item.
+ * @param array $fld
+ *   An array of information about a field.
+ * @param string $auth_category
+ *   A string representing the category of author.
+ * @param string $biblio_type
+ *   A string indicating the type of biblio item.
+ * @param bool $other_fieldset
+ *   (optional) A logical flag indicating
+ *
+ * @return array
+ *   Associative array with form element keys for this contributor widget.
  */
 function _biblio_contributor_widget($node, $fld, $auth_category, $biblio_type, $other_fieldset = FALSE) {
   $init_count = variable_get('biblio_init_auth_count', 4);
@@ -1370,10 +1555,10 @@ function _biblio_contributor_widget($node, $fld, $auth_category, $biblio_type, $
   $contributor_count = max($init_count, count($contributors));
 
   $ctypes = _biblio_get_auth_types($auth_category, $biblio_type);
-  // if no author types are available skip this widget
+  // If no author types are available, return nothing for this widget.
   if (!isset($ctypes)) return array();
-  $ctypes = db_query('SELECT * FROM {biblio_contributor_type_data}
-                      WHERE auth_type IN ('. implode(',', $ctypes) .')');
+  $ctypes = db_query('SELECT * FROM {biblio_contributor_type_data} ' .
+                     'WHERE auth_type IN (' . implode(',', $ctypes) . ')');
   while ($ctype = db_fetch_object($ctypes)) {
     $options[$ctype->auth_type] = $ctype->title;
   }
@@ -1383,36 +1568,38 @@ function _biblio_contributor_widget($node, $fld, $auth_category, $biblio_type, $
     '#tree' => TRUE,
     '#type' => 'fieldset',
     '#collapsible' => TRUE,
-    '#collapsed' => !$fld['required'] && (count($contributors)==0),
+    '#collapsed' => !$fld['required'] && (count($contributors) == 0),
     '#title' => check_plain($fld['title']),
     '#weight' => $fld['weight'] / 10,
     '#description' => t('Enter a single name per line using a format such as "Smith, John K" or "John K Smith" or "J.K. Smith"'),
     '#prefix' => '<div class="clear-block" id="'. $type .'-wrapper">',
-    '#suffix' => '</div>'
-    );
-  // Container for just the contributors.
+    '#suffix' => '</div>',
+  );
+  // Define a container for just the contributors.
   $wrapper['biblio_contributors'][$auth_category] = array(
     '#prefix' => '<div id="'. $type .'">',
     '#suffix' => '</div>',
     '#theme' => 'biblio_contributors',
     '#id' => $fldname,
     '#hideRole' => count($options) <= 1,
-    );
+  );
   // Add the current choices to the form.
   $default_values = array('name' => '', 'cid' => '', 'auth_type' => key($options));
   for ($delta = 0; $delta < $contributor_count; $delta++) {
-    if (isset($contributors[$delta])) { // contributor already exists
+    // The contributor already exists.
+    if (isset($contributors[$delta])) {
       $values = $contributors[$delta];
     }
-    else { // contributor is new
+    // This is a new contributor
+    else {
       $values = $default_values;
     }
     $values['rank'] = $delta;
-    $wrapper['biblio_contributors'][$auth_category][$delta]
-      = _biblio_contributor_form($delta, $auth_category, $values, $options, $fld['autocomplete']);
+    $wrapper['biblio_contributors'][$auth_category][$delta] =
+      _biblio_contributor_form($delta, $auth_category, $values, $options, $fld['autocomplete']);
   }
-  // We name our button 'contrib_more' to avoid conflicts with other modules using
-  // AHAH-enabled buttons with the id 'more'.
+  // We name our button 'contrib_more' to avoid conflicts with other modules
+  // using AHAH-enabled buttons with the id 'more'.
   $path = 'biblio/js/'. $biblio_type .'/'. $auth_category;
   if ($other_fieldset) $path .= '/1';
   $wrapper[$fldname .'_more'] = array(
@@ -1420,25 +1607,43 @@ function _biblio_contributor_widget($node, $fld, $auth_category, $biblio_type, $
     '#value' => t('More @title', array('@title' => $fld['title'])),
     '#description' => t("If there aren't enough boxes above, click here to add more."),
     '#weight' => 1,
-    '#submit' => array('biblio_more_contributors_submit'), // If no javascript action.
+     // In the event of no javascript action, execute this submit function.
+    '#submit' => array('biblio_more_contributors_submit'),
     '#ahah' => array(
       'path' => $path,
       'wrapper' => $type,
       'method' => 'replace',
-      'effect' => 'fade'
-      )
-    );
+      'effect' => 'fade',
+    )
+  );
 
-  $form['contributors'. $auth_category .'_wrapper'] = $wrapper;
+  $form['contributors' . $auth_category . '_wrapper'] = $wrapper;
   return $form;
 }
 
+/**
+ * Creates contributor form elements for contributor widget and JSON callback.
+ *
+ * @param $delta
+ *
+ * @param string $author_category
+ *
+ * @param array $values
+ *
+ * @param array $types
+ *   (optional)
+ * @param bool $autocomplete
+ *   (optional) A logical flag indicating whether ...  The default value is TRUE.
+ *
+ * @return array $form
+ *   An associative array of form definition elements.
+ */
 function _biblio_contributor_form($delta, $auth_category, $values, $types = NULL, $autocomplete = TRUE) {
   $form = array(
     '#tree' => TRUE
   );
-  // We'll manually set the #parents property of these fields so that
-  // their values appear in the $form_state['values']['choice'] array.
+  // Manually set the #parents property of these fields so that their values
+  // appear in the $form_state['values']['choice'] array.
   $form['name'] = array(
     '#type' => 'textfield',
     '#title' => t('Name'),
@@ -1481,6 +1686,11 @@ function _biblio_contributor_form($delta, $auth_category, $values, $types = NULL
   );
   return $form;
 }
+
+/**
+ * Prepares a JSON response for the contributor widget.
+ *
+ */
 function biblio_contributors_js($tid, $auth_category, $other_fields = FALSE) {
   $delta = count($_POST['biblio_contributors'][$auth_category]);
   // Build our new form element.
@@ -1528,22 +1738,20 @@ function biblio_contributors_js($tid, $auth_category, $other_fields = FALSE) {
   exit();
 }
 
-
-
 /**
  * Implementation of hook_validate().
  *
  *
  * Errors should be signaled with form_set_error().
  */
-function biblio_form_validate($form, & $form_state) {
+function biblio_form_validate($form, &$form_state) {
 
   $op = isset($form['#post']['op'])?$form['#post']['op'] :
         ($form['#post']['biblio_type'] > 0 ? t('Save') : '');
   switch ($op) {
     case t('Save'):
       if ($form_state['storage']['biblio_type'] == $form_state['values']['biblio_type'] ||
-         (!empty($form['#node']->biblio_type) && $form['#node']->biblio_type == $form_state['values']['biblio_type']))  {
+         (!empty($form['#node']->biblio_type) && $form['#node']->biblio_type == $form_state['values']['biblio_type'])) {
         unset ($form_state['storage']);
       }
       else {
@@ -1577,6 +1785,15 @@ function biblio_form_validate($form, & $form_state) {
   }
 }
 
+/**
+ *
+ *
+ * @param mixed $year
+ *   A variable representing a year or string like 'In Press' or ;Submitted'.
+ *
+ * @return mixed
+ *
+ */
 function _biblio_numeric_year($year) {
   if (!is_numeric($year)) {
     if (drupal_strtoupper($year) == drupal_strtoupper(t("In Press")))  return 9998;
@@ -1587,15 +1804,28 @@ function _biblio_numeric_year($year) {
   }
 }
 
+/**
+ *
+ *
+ * @param mixed $year
+ *   A variable representing a year value.
+ *
+ * @reutrn mixed
+ *
+ */
 function _biblio_text_year($year) {
   if ($year == 9998) return check_plain(variable_get('biblio_inpress_year_text', t('In Press')));
   if ($year == 9999) return check_plain(variable_get('biblio_no_year_text', t('Submitted')));
   return $year;
 }
+
 /**
- * Prepare a node for submit to database. Contains code common to insert and update.
- * @param $node
- * @return none
+ * Prepares a biblio node for submit to database. 
+ *
+ * This function contains code common to both insert and update operations.
+ *
+ * @param object $node
+ *   An object with bibliographic information as well as other elements.
  */
 function _biblio_prepare_submit($node) {
   $node->biblio_sort_title = biblio_normalize_title($node->title);
@@ -1613,7 +1843,7 @@ function _biblio_prepare_submit($node) {
   }
 }
 /**
- * Implementation of hook_insert().
+ * Implements hook_insert().
  *
  * As a new node is being inserted into the database, we need to do our own
  * database inserts.
@@ -1629,7 +1859,7 @@ function biblio_insert($node) {
   drupal_write_record('biblio', $node);
 }
 /**
- * Implementation of hook_update().
+ * Implements hook_update().
  *
  * As an existing node is being updated in the database, we need to do our own
  * database updates.
@@ -1650,11 +1880,10 @@ function biblio_update($node) {
   else {
     drupal_write_record('biblio', $node, 'vid');
   }
-
-
 }
+
 /**
- * Implementation of hook_delete().
+ * Implements hook_delete().
  *
  * When a node is deleted, we need to clean up related tables.
  */
@@ -1667,10 +1896,9 @@ function biblio_delete($node) {
   biblio_delete_keywords($node);
 }
 /**
- * Implementation of hook_load().
+ * Implements hook_load().
  *
- * This hook is called
- * every time a node is loaded, and allows us to do some loading of our own.
+ * This hook is called every time a node is loaded, and allows us to do some loading of our own.
  *
  */
 function biblio_load($node) {
@@ -1693,6 +1921,16 @@ function biblio_load($node) {
   }
   return $additions;
 }
+
+/**
+ *
+ *
+ * @param object $node
+ *
+ *
+ * @return string
+ *
+ */
 function biblio_citekey_generate($node) {
   $php = check_plain(variable_get('biblio_citekey_phpcode', ''));
   if (empty($php)) {
@@ -1711,10 +1949,10 @@ function biblio_citekey_generate($node) {
 }
 
 /**
- * Implementation of hook_view().
+ * Implements hook_view().
  *
  */
-function biblio_view(& $node, $teaser = FALSE, $page = FALSE) {
+function biblio_view(&$node, $teaser = FALSE, $page = FALSE) {
   if (strlen(trim($node->body))) $node = node_prepare($node, $teaser);
   $style = biblio_get_style();
   $base  = variable_get('biblio_base', 'biblio');
@@ -1730,6 +1968,7 @@ function biblio_view(& $node, $teaser = FALSE, $page = FALSE) {
       case 'ft' :
         $node->content['body']['#value'] = theme('biblio_long', $node, $base, $style);
         break;
+        
       case 'tabular' :
       default :
         $node->content['body']['#value'] = theme('biblio_tabular', $node, $base, $teaser);
@@ -1745,8 +1984,9 @@ function biblio_view(& $node, $teaser = FALSE, $page = FALSE) {
   }
   return $node;
 }
+
 /**
- * Implementation of hook_block().
+ * Implements hook_block().
  *
  * Generates a block containing the latest poll.
  */
@@ -1800,6 +2040,11 @@ function biblio_block($op = 'list', $delta = 0) {
     }
   }
 }
+
+/**
+ *
+ *
+ */
 function biblio_recent_feed() {
   $query = "SELECT *
             FROM {node} AS n
@@ -1818,15 +2063,16 @@ function biblio_recent_feed() {
   }
   node_feed($nids, $channel);
 }
+
 /**
  * This function creates a feed from a filter type query (i.e. biblio/author/jones)
  *
  * @param $query
- *    the SQL string to be used in the call to db_query
- * @param $terms
- *    the terms that are used to replace any place holders in the query
- * @param $rss_info
- *    an array which contains the title,link and description info for the rss feed
+ *   The SQL string to be used in the call to db_query.
+ * @param array $terms
+ *   (optional) The terms that are used to replace any place holders in the query.
+ * @param array $rss_info
+ *   (optional) Array which contains the title, link and description info for rss feed.
  */
 function biblio_filter_feed($query, $terms = NULL, $rss_info = NULL) {
   $base = variable_get('biblio_base', 'biblio');
@@ -1840,6 +2086,10 @@ function biblio_filter_feed($query, $terms = NULL, $rss_info = NULL) {
   }
   node_feed($nids, $channel);
 }
+
+/**
+ *
+ */
 function biblio_get_db_fields() {
   $fields = array();
   $fields[] = 'nid';
@@ -1852,11 +2102,17 @@ function biblio_get_db_fields() {
   return $fields;
 }
 
-/*******************************************
+/**
  * Filter
+ *
  * Largely inspired from the footnote module
  *
- *******************************************/
+ * @param string $citekey
+ *
+ *
+ * @return string
+ *
+ */
 function _biblio_citekey_print($citekey) {
   $nid = db_fetch_object(db_query("SELECT nid FROM {biblio} WHERE biblio_citekey = '%s' ORDER BY vid DESC", $citekey));
   if ($nid->nid > 0) {
@@ -1869,8 +2125,9 @@ function _biblio_citekey_print($citekey) {
     return t("Citekey @cite not found", array('@cite' => $citekey));
   }
 }
+
 /**
- * Implementation of hook_filter_tips().
+ * Implements hook_filter_tips().
  *
  * This hook allows filters to provide help text to users during the content
  * editing process. Short tips are provided on the content editing screen, while
@@ -1889,8 +2146,9 @@ function biblio_filter_tips($delta, $format, $long = FALSE) {
       break;
   }
 }
+
 /**
- * Implementation of hook_filter().
+ * Implements hook_filter().
  *
  * The bulk of filtering work is done here. This hook is quite complicated, so
  * we'll discuss each operation it defines.
@@ -1919,24 +2177,27 @@ function biblio_filter($op, $delta = 0, $format = -1, $text = '') {
         // filter tips which are shown in the content editing interface.
         case 'description' :
           return t('Use &lt;bib&gt;citekey&lt;/bib&gt; or [bib]citebkey[/bib]to insert automatically numbered references.');
-          // We don't need the "prepare" operation for this filter, but it's required
-          // to at least return the input text as-is.
-          //TODO: May need to escape <fn> if we use HTML filter too, but Footnotes could be first
+        
+        // We don't need the "prepare" operation for this filter, but it's required
+        // to at least return the input text as-is.
+        //TODO: May need to escape <fn> if we use HTML filter too, but Footnotes could be first
         case 'prepare' :
           return $text;
-          // The actual filtering is performed here. The supplied text should be
-          // returned, once any necessary substitutions have taken place.
+     
+        // The actual filtering is performed here. The supplied text should be
+        // returned, once any necessary substitutions have taken place.
         case 'process' :
           $pattern = array('|\[bib](.*?)\[/bib]|s', '|<bib>(.*?)</bib>|s');
-          if (variable_get('biblio_footnotes_integration', 0) && module_exists('footnotes')) { // this is used with footnote module integration to replace the <bib> tags with <fn> tags
+          // This is used with footnote module integration to replace the <bib> tags with <fn> tags
+          if (variable_get('biblio_footnotes_integration', 0) && module_exists('footnotes')) { 
             $text = preg_replace_callback($pattern, '_biblio_filter_footnote_callback', $text);
             return $text;
           }
           else {
             $text = preg_replace_callback($pattern, '_biblio_filter_replace_callback', $text);
-            //Replace tag <footnotes> with the list of footnotes.
-            //If tag is not present, by default add the footnotes at the end.
-            //Thanks to acp on drupal.org for this idea. see http://drupal.org/node/87226
+            // Replace tag <footnotes> with the list of footnotes.
+            // If tag is not present, by default add the footnotes at the end.
+            // Thanks to acp on drupal.org for this idea. see http://drupal.org/node/87226
             $footer = '';
             $footer = _biblio_filter_replace_callback(NULL, 'output footer');
             if (preg_match('/<bibliography(\/( )?)?>/', $text) > 0) {
@@ -1949,42 +2210,52 @@ function biblio_filter($op, $delta = 0, $format = -1, $text = '') {
           }
       }
       break;
-   case 1 :
+      
+    case 1 :
       switch ($op) {
         // This description is shown in the administrative interface, unlike the
         // filter tips which are shown in the content editing interface.
         case 'description' :
           return t('Use &lt;ibib&gt;citekey&lt;/ibib&gt; or [ibib]citebkey[/ibib]to insert inline references.');
-          // We don't need the "prepare" operation for this filter, but it's required
-          // to at least return the input text as-is.
-          //TODO: May need to escape <fn> if we use HTML filter too, but Footnotes could be first
+
+        // We don't need the "prepare" operation for this filter, but it's required
+        // to at least return the input text as-is.
+        //TODO: May need to escape <fn> if we use HTML filter too, but Footnotes could be first
         case 'prepare' :
           return $text;
-          // The actual filtering is performed here. The supplied text should be
-          // returned, once any necessary substitutions have taken place.
+
+        // The actual filtering is performed here. The supplied text should be
+        // returned, once any necessary substitutions have taken place.
         case 'process' :
           $pattern = array('|\[ibib](.*?)\[/ibib]|s', '|<ibib>(.*?)</ibib>|s');
           $text = preg_replace_callback($pattern, '_biblio_inline_filter_replace_callback', $text);
           return $text;
       }
       break;
-
   }
 }
 
+/**
+ *
+ */
 function _biblio_inline_filter_replace_callback($matches) {
-    $text =  _biblio_citekey_print($matches[1]) ;
+  $text = _biblio_citekey_print($matches[1]);
   return $text;
 }
 
+/**
+ *
+ */
 function _biblio_filter_footnote_callback($matches, $square_brackets = FALSE) {
-  if ($square_brackets)  {
-    $text = '[fn]'. _biblio_citekey_print($matches[1]) ."</fn>";
-  } else {
-    $text = '<fn>'. _biblio_citekey_print($matches[1]) ."</fn>";
+  if ($square_brackets) {
+    $text = '[fn]' . _biblio_citekey_print($matches[1]) . "</fn>";
+  }
+  else {
+    $text = '<fn>' . _biblio_citekey_print($matches[1]) . "</fn>";
   }
   return $text;
 }
+
 /**
  * Helper function called from preg_replace_callback() above
  *
@@ -2036,6 +2307,9 @@ function _biblio_filter_replace_callback($matches, $op = '') {
   return $text;
 }
 
+/**
+ * Implements hook_taxonomy().
+ */
 function biblio_taxonomy($op, $type, $array = NULL) {
   if ($op == 'delete' && $type == 'vocabulary' && $array['vid'] == variable_get('biblio_keyword_vocabulary', -1)) {
     variable_del('biblio_keyword_freetagging');
@@ -2043,18 +2317,27 @@ function biblio_taxonomy($op, $type, $array = NULL) {
   }
 }
 
+/**
+ *
+ */
 function biblio_term_path($term) {
   $base = variable_get('biblio_base','biblio');
-  if ($term->vid == variable_get('biblio_collection_vocabulary',0) ) {
+  if ($term->vid == variable_get('biblio_collection_vocabulary', 0)) {
     return ("$base/collection/$term->name");
   }
-  elseif ($term->vid == variable_get('biblio_keyword_vocabulary',0) ) {
+  elseif ($term->vid == variable_get('biblio_keyword_vocabulary', 0)) {
     return ("$base/term_id/$term->tid");
   }
-  else return;
-
+  else {
+  	return;
+  }
 }
 
+/**
+ *
+ * @return integer
+ *   The node ID of a potential duplicate biblio content.
+ */
 function biblio_hash($node) {
   static $sums = array();
   $duplicate = null;
@@ -2081,7 +2364,9 @@ function biblio_hash($node) {
 }
 
 /**
- * An implementation of hook_diff (from the diff module)
+ * Implements hook_diff().
+ *
+ * This is a hook provided by the diff module.
  * @param $old_node
  * @param $new_node
  * @return unknown_type
@@ -2099,7 +2384,7 @@ function biblio_diff(&$old_node, &$new_node) {
     '#new' => array($new_type->name),
     '#format' => array(
       'show_header' => FALSE,
-  )
+    ),
   );
 
   $old_node->biblio_contributors = biblio_load_contributors($old_node->vid);
@@ -2129,20 +2414,29 @@ function biblio_diff(&$old_node, &$new_node) {
       '#old' => explode("\n", $old),
       '#new' => explode("\n", $new),
     );
-
   }
   return $result;
 }
+
+/**
+ *
+ */
 function biblio_token_list($type = 'all') {
   module_load_include('inc', 'biblio', '/includes/biblio.tokens');
   return _biblio_token_list($type);
 }
 
+/**
+ *
+ */
 function biblio_token_values($type, $object = NULL) {
   module_load_include('inc', 'biblio', '/includes/biblio.tokens');
   return _biblio_token_values($type, $object);
 }
 
+/**
+ *
+ */
 function _biblio_profile_access($user, $type = 'profile') {
   if ($type == 'profile') $key = 'biblio_show_profile';
   else if ($type == 'menu' && $user->uid > 0) $key = 'biblio_my_pubs_menu';
@@ -2153,6 +2447,7 @@ function _biblio_profile_access($user, $type = 'profile') {
     return variable_get($key, '0'); // return site default
   else return $user->$key; // return user setting
 }
+
 /*
  * Helper function to get either the user or system style
  */
@@ -2162,6 +2457,9 @@ function biblio_get_style() {
   return  module_exists('biblio_citeproc') ? variable_get('biblio_citeproc_style', 'ama.csl') : variable_get('biblio_style', 'cse');
 }
 
+/**
+ *
+ */
 function biblio_get_styles() {
   $styles = array();
   if (module_exists('biblio_citeproc')) {
@@ -2186,7 +2484,7 @@ function biblio_get_styles() {
 }
 
 /**
- * Implementation of hook_views_api().
+ * Implements hook_views_api().
  */
 function biblio_views_api() {
   return array(
@@ -2195,6 +2493,9 @@ function biblio_views_api() {
   );
 }
 
+/**
+ *
+ */
 function biblio_fix_isi_links(&$node) {
   $isi = check_plain(variable_get('biblio_isi_url', 'http://apps.isiknowledge.com/InboundService.do?Func=Frame&product=WOS&action=retrieve&SrcApp=EndNote&Init=Yes&SrcAuth=ResearchSoft&mode=FullRecord&UT='));
   if (isset($node->biblio_url) && preg_match ('/Go\s*to\s*ISI/',$node->biblio_url)){
@@ -2205,10 +2506,20 @@ function biblio_fix_isi_links(&$node) {
   }
 }
 
+/**
+ *
+ 
+ * @return array
+ *   An array of allowed HTML tags as values in array.
+ *
+ */
 function biblio_get_allowed_tags() {
   return array('a', 'b', 'i', 'u', 'sub', 'sup', 'span');
 }
 
+/**
+ *
+ */
 function biblio_get_title_url_info($node, $base = NULL, $inline = FALSE) {
   $new_window = NULL;
   if (!isset($base)) {
@@ -2220,25 +2531,34 @@ function biblio_get_title_url_info($node, $base = NULL, $inline = FALSE) {
   else {
     $language = isset($node->language) ? $node->language : '';
     $view_mode = ($inline) ? 'viewinline' : 'view';
-    $node_path = 'node/'. $node->nid;
-    $path = $base .'/'. $view_mode. '/'. $node->nid;
+    $node_path = 'node/' . $node->nid;
+    $path = $base . '/' . $view_mode . '/' . $node->nid;
     $path_alias = drupal_get_path_alias($node_path, $language);
     $path = ($path_alias != $node_path)? $path_alias : drupal_get_path_alias($path, $language);
   }
   if (variable_get('biblio_links_target_new_window',null)){
-    $new_window = array('target'=>'_blank');
+    $new_window = array('target' => '_blank');
   }
 
-  return array('link' => $path ,
-               'options' =>
-                   array('attributes' => $new_window, 'html' => TRUE),
-                );
+  return array(
+    'link' => $path ,
+    'options' => array(
+      'attributes' => $new_window,
+      'html' => TRUE
+    )
+  );
 }
 
 /**
- * @param string $type (can be one of "type_names", "type_map" or "field_map")
- * @param string $format (tagged, ris, endnote_xml8 etc...)
+ *
+ *
+ * @param string $type
+ *   Possible values include  (can be one of "type_names", "type_map" or "field_map") 
+ * @param string $format
+ *   keys like (tagged, ris, endnote_xml8 etc...)
+ *
  * @return array $map
+ *
  */
 function biblio_get_map($type, $format) {
   $map = unserialize(db_result(db_query("SELECT %s FROM {biblio_type_maps} WHERE format='%s'", array($type, $format))));
@@ -2261,9 +2581,24 @@ function biblio_set_map($type, $format, $map) {
     drupal_write_record('biblio_type_maps', $map, 'format');
 }
 
+/**
+ * Implemnts hook_reset_map().
+ * 
+ * @param string $type
+ *
+ * @param string $format
+ *
+ */
 function biblio_reset_map($type, $format) {
-   module_invoke_all($format.'_map_reset', $type);
+   module_invoke_all($format . '_map_reset', $type);
 }
+
+/**
+ *
+ *
+ * @param object $node
+ *   A node object (passed by reference) with populated with biblio type.
+ */
 function _biblio_export_visibility(&$node) {
   static $visibility = array();
   if (!isset($visibility[$node->biblio_type])) {
@@ -2278,10 +2613,21 @@ function _biblio_export_visibility(&$node) {
     $visibility[$node->biblio_type] =  $fields;
   }
   foreach ($visibility[$node->biblio_type] as $field_name => $visible) {
-    if (!$visible && isset($node->$field_name)) unset($node->$field_name);
+    if (!$visible && isset($node->$field_name)) {
+      unset($node->$field_name);
+    }
   }
-
 }
+
+/**
+ *
+ *
+ * @param string $type_name
+ *   
+ *
+ * @return array
+ *   An array of definitions for extra fields defined in teh biblio module.
+ */
 function biblio_content_extra_fields($type_name) {
   if ($type_name == 'biblio') {
     module_load_include('inc', 'biblio', 'includes/content.biblio');
@@ -2289,6 +2635,9 @@ function biblio_content_extra_fields($type_name) {
   }
 }
 
+/**
+ * Implements hook_preprocess_page for page display with page.tpl.php.
+ */
 function biblio_preprocess_page(&$variables) {
   if (isset($variables['node']) && $variables['node']->type == 'biblio') {
     $node = $variables['node'];
diff --git a/includes/biblio.pages.inc b/includes/biblio.pages.inc
index 497f01e..131aaaf 100644
--- a/includes/biblio.pages.inc
+++ b/includes/biblio.pages.inc
@@ -1,32 +1,50 @@
 <?PHP
 /**
+ * @file
+ * Functions in the biblio module related to filtering and page generation.
  *
- *   Copyright (C) 2006-2008  Ron Jerome
  *
- *   This program is free software; you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation; either version 2 of the License, or
- *   (at your option) any later version.
+ * Copyright (C) 2006-2008  Ron Jerome
  *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
+ * This program is free software; you can redistribute it and/or modify it under
+ * the terms of the GNU General Public License as published by the Free Software
+ * Foundation; either version 2 of the License, or (at your option) any later
+ * version.
  *
- *   You should have received a copy of the GNU General Public License along
- *   with this program; if not, write to the Free Software Foundation, Inc.,
- *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+ * details.
  *
- ****************************************************************************/
+ * You should have received a copy of the GNU General Public License along with
+ * this program; if not, write to the Free Software Foundation, Inc., 
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ */
 
+/**
+ * Redirects the page display to that of the specified node ID.
+ *
+ * @param integer $nid
+ *   Integer ID of the node which the page request will be changed to view.
+ */
 function biblio_view_node($nid) {
-  drupal_goto('node/'.(int)$nid, NULL, NULL, 301); // set a 301 response code
+  drupal_goto('node/'.(int) $nid, NULL, NULL, 301); // set a 301 response code
 }
+
 /**
- * @return unknown_type
+ * Page callback: Displays a listing of biblio type of content.
+ *
+ * This function is responsible for generating the page that is displayed on the
+ * primary menu path of the biblio module (ie /biblio).
+ *
+ * @return null|string
+ *   If an rss feed is desired, there will be no return value.  Otherwise, an
+ *   HTML string suitable for display in a browser will be returned.
+ *
+ * @see biblio_menu()
  */
 function biblio_db_search() {
-
   $arg_list = array();
   $arg_list = func_get_args();
   foreach ($_GET as $key => $value) {
@@ -36,7 +54,6 @@ function biblio_db_search() {
     }
   }
 
-
   // Drupal search? It returns an array of search results. We store the nids
   // of the result nodes and make them a "where n.nid in {..}" filter.
   // After installing the filter, we can go on as usual.
@@ -50,7 +67,7 @@ function biblio_db_search() {
     // Special case: if search is activated via URL, i.e., biblio/search/...,
     // we reset the search session filter. Two searches are not combinable.
     $base =  variable_get('biblio_base', 'biblio');
-    if (preg_match('+'.$base.'/search/+', $_GET['q'])) {
+    if (preg_match('+' . $base . '/search/+', $_GET['q'])) {
       $_SESSION['biblio_filter'] = array();
     }
   }
@@ -65,7 +82,7 @@ function biblio_db_search() {
       if ($result = biblio_build_search_query($keys)) {
         $node_list = '';
         while ($nid = db_result($result)) {
-          $node_list .= $nid.",";
+          $node_list .= $nid . ",";
         }
         // No node search result. Make sure we find nothing, too. Node -1 does not exist.
         if (empty($node_list)) $node_list = '-1';
@@ -82,51 +99,73 @@ function biblio_db_search() {
         }
       }
       // Wrong query (too short, only negative words etc.). Warning has been issued.
-      else $_SESSION['biblio_filter'] = array();
+      else {
+        $_SESSION['biblio_filter'] = array();
+      }
     }
   }
 
   $inline = in_array('inline', $arg_list);
-  $inline = in_array('profile', $arg_list)?'profile':$inline;
+  $inline = in_array('profile', $arg_list) ? 'profile' : $inline;
 
   $query_info = biblio_build_query($arg_list);
-  if ($query_info['rss']['feed']){
+
+  // If desired, prepare a listing in rss feed format which will print directly
+  // to the screen with no return value.
+  if ($query_info['rss']['feed']) {
     biblio_filter_feed($query_info['query'], $query_info['query_terms'], $query_info['rss']);
+    return;
   }
-  else{
-    //$count = db_result(db_query($query_info['count_query'],$query_info['query_terms']));
-    $nodes = array();
-    $result = pager_query($query_info['query'], variable_get('biblio_rowsperpage', 25),0,$query_info['count_query'],$query_info['query_terms']);
-    $query_info['filter_line'] = _biblio_filter_info_line($query_info['args']);
-
-    while ($res = db_fetch_array($result)) {
-      $node = node_load($res['nid']);
-      foreach($res as $key => $value) {
-        if (!isset($node->$key)) {
-          $node->$key = $value;
-        }
+
+  // Prepare an HTML formatted string for display in browser
+  $nodes = array();
+  $result = pager_query(
+              $query_info['query'],
+              variable_get('biblio_rowsperpage', 25),
+              0,
+              $query_info['count_query'],
+              $query_info['query_terms']
+            );
+  $query_info['filter_line'] = _biblio_filter_info_line($query_info['args']);
+
+  while ($res = db_fetch_array($result)) {
+    $node = node_load($res['nid']);
+    foreach($res as $key => $value) {
+      if (!isset($node->$key)) {
+        $node->$key = $value;
       }
-      $nodes[] = $node;
     }
-
-    return biblio_show_results($nodes, $query_info, $inline);
+    $nodes[] = $node;
   }
-
+  return biblio_show_results($nodes, $query_info, $inline);
 }
-/*
+
+/**
+ * Creates an SQL query to select and order biblio type content.
+ *
  * biblio_db_search builds the SQL query which will be used to
  * select and order "biblio" type nodes.  The query results are
  * then passed to biblio_show_results for output
  *
+ * @param $arg_list
+ *
  *
+ * @return array
+ *   An associative array with the following keys:
+ *   - query:
+ *   - query_terms:
+ *   - count_query:
+ *   - args:
+ *   - sort_attrib:
+ *   - rss:
  */
 function biblio_build_query($arg_list) {
   global $user, $db_type;
   static $bcc; //biblio_contributor (bc) count , increase for every invocation
   static $tcc; //term counter, increase for every invocation
-  if ( !isset( $bcc ) ) $bcc = 0;
-  if ( !isset( $tcc ) ) $tcc = 0;
-  $inline = $rss_info['feed'] = false;
+  if (!isset($bcc)) $bcc = 0;
+  if (!isset($tcc)) $tcc = 0;
+  $inline = $rss_info['feed'] = FALSE;
   $joins = array();
   $selects = array();
   $count_selects = array();
@@ -134,8 +173,6 @@ function biblio_build_query($arg_list) {
 
   $selects[] = "DISTINCT(n.nid)";
   $count_selects[] = "DISTINCT(n.nid)";
-  //$selects[] = "n.*";
-  //$selects[] = "b.*";
   $selects[] = "bt.name as biblio_type_name";
 
   $joins[] = "left join {biblio} b  on n.vid=b.vid ";
@@ -176,125 +213,149 @@ function biblio_build_query($arg_list) {
 
   if (count($arg_list) ) {
     $args = array();
+
+    // Initialize various counters and variables
+    $bkd = 0;
+    $operator = '';
+
     while ($arg_list) {
       $type = $arg_list[0];
       array_shift($arg_list);
-      $operator = ($operator)?$operator:" AND "; //defaults to AND
+      // The default operator is AND.
+      $operator = empty($operator) ? " AND " : $operator;
       switch ($type) {
         case 'no_filters':
           break;
+
         case 'and':
           $operator = " AND ";
           break;
+
         case 'or':
           $operator = " OR ";
           break;
+
         case 'inline':
-          $inline = true;
+          $inline = TRUE;
           break;
+
         case 'rss.xml':
-          $rss_info['feed'] = true;
-          $count_limit = 'LIMIT '. variable_get('biblio_rss_number_of_entries', 10);
+          $rss_info['feed'] = TRUE;
+          $count_limit = 'LIMIT ' . variable_get('biblio_rss_number_of_entries', 10);
           break;
+
         case 'profile':
           $inline = "profile";
           break;
+
         case 'cid':
         case 'aid':
           $bcc++;
           $term = explode("?",array_shift($arg_list));
-          $joins[] = "inner join {biblio_contributor} as bc". $bcc ." on n.vid = bc". $bcc .".vid";
-          $where[] = "bc". $bcc .".cid = '%d' ";
+          $joins[] = "inner join {biblio_contributor} as bc" . $bcc . " on n.vid = bc" . $bcc . ".vid";
+          $where[] = "bc" . $bcc . ".cid = '%d' ";
           $terms[] = db_escape_string($term[0]);
           array_push($args, $type, $term[0]);
           break;
+
         case 'term':
         case 'term_id':
           $term = explode("?",array_shift($arg_list));
-          $joins[] = "inner join {term_node} as tn". $tcc ." on n.vid = tn".$tcc.".vid";
+          $joins[] = "inner join {term_node} as tn" . $tcc . " on n.vid = tn" . $tcc . ".vid";
           if ($type == 'term') {
-            $joins[] = "inner join  {term_data} as td on tn". $tcc .".tid= td.tid";
+            $joins[] = "inner join {term_data} as td on tn" . $tcc . ".tid= td.tid";
             $where[] = "td.name = '%s' ";
-          }elseif ($type == 'term_id') {
-            $where[] = "tn". $tcc .".tid = '%d' ";
+          }
+          elseif ($type == 'term_id') {
+            $where[] = "tn" . $tcc . ".tid = '%d' ";
           }
           $terms[] = db_escape_string($term[0]);
           array_push($args, $type, $term[0]);
           $tcc++;
           break;
+
         case 'tg':
-          $term = explode("?",array_shift($arg_list));
+          $term = explode("?", array_shift($arg_list));
           $where[] = "substring($sort_title,1 ,1)" . $match_op . " LOWER('%s')";
           $terms[] = db_escape_string($term[0]);
           array_push($args, $type, $term[0]);
           $operator = NULL;
           break;
-        case 'ag': //selects entries whoose authors firstname starts with the letter provided
-          $term = explode("?",array_shift($arg_list));
+
+        // Selects biblio content with the first name of authors that start with
+        // the specified letter.
+        case 'ag':
+          $term = explode("?", array_shift($arg_list));
           $where[] = " UPPER(substring(bcd.lastname,1,1)) = '%s' ";
-          //$where['bc-rank'] = "bc.rank=0";
           $joins['bc'] = '  INNER JOIN {biblio_contributor} as bc on b.vid = bc.vid ';
           $joins['bcd'] = '  JOIN {biblio_contributor_data} as bcd on bc.cid = bcd.cid ';
           $terms[] = db_escape_string(strtoupper($term[0]));
           array_push($args, $type, $term[0]);
           $operator = NULL;
           break;
+
         case 'author':
           $bcc++;
           $term = explode("?",array_shift($arg_list));
 
           if (is_numeric($term[0])){
-            $joins[] = "inner join {biblio_contributor} as bc". $bcc ." on n.vid = bc". $bcc .".vid";
-            $cids = db_query('SELECT cid FROM {biblio_contributor_data}
-                              WHERE cid = %d OR aka = (SELECT aka FROM {biblio_contributor_data} WHERE cid = %d)'
-                              ,$term[0], $term[0]);
+            $joins[] = "inner join {biblio_contributor} as bc" . $bcc . " on n.vid = bc" . $bcc . ".vid";
+            $cids = db_query('SELECT cid FROM {biblio_contributor_data} ' .
+                             'WHERE cid = %d OR aka = (SELECT aka FROM {biblio_contributor_data} WHERE cid = %d)',
+                             $term[0], $term[0]);
+            $wr = '';
             while ($cid = db_fetch_object($cids) ){
-              $wr .= empty($wr)?'':' OR ';
-              $wr .= "bc". $bcc .".cid = $cid->cid ";
+              $wr .= empty($wr) ? '' : ' OR ';
+              $wr .= "bc" . $bcc . ".cid = $cid->cid ";
             }
-            $where[] = (!empty($wr)) ? $wr : "bc". $bcc .".cid = -1 ";
-          }else{
-            $where[] = " bcd". $bcc .'.name '. $match_op .' "[[:<:]]%s[[:>:]]" ';
-            $joins[] = " JOIN {biblio_contributor} as bc". $bcc ." on b.vid = bc". $bcc .".vid ";
-            $joins[] = " JOIN {biblio_contributor_data} as bcd". $bcc ." on bc". $bcc .".cid = bcd".$bcc .".cid ";
+            $where[] = (!empty($wr)) ? $wr : "bc" . $bcc . ".cid = -1 ";
+          }
+          else {
+            $where[] = " bcd" . $bcc . '.name ' . $match_op . ' "[[:<:]]%s[[:>:]]" ';
+            $joins[] = " JOIN {biblio_contributor} as bc" . $bcc . " on b.vid = bc" . $bcc . ".vid ";
+            $joins[] = " JOIN {biblio_contributor_data} as bcd" . $bcc . " on bc" . $bcc . ".cid = bcd" . $bcc . ".cid ";
             $terms[] = db_escape_string($term[0]);
             $operator = NULL;
             $rss_info['title'] = t("Publications by " . $term[0]);
-            $rss_info['description'] = t("These publications by %author are part of the works listed at %sitename", array('%author' => $term[0], '%sitename' => variable_get('site_name', 'Drupal')));
+            $rss_info['description'] = t("These publications by %author are part of the works listed at %sitename", array(
+                                         '%author' => $term[0],
+                                         '%sitename' => variable_get('site_name', 'Drupal')
+                                       ));
             $rss_info['link'] = '/author/' . $term[0];
           }
           array_push($args, $type, $term[0]);
           break;
+
         case 'publisher':
-          $term = explode("?",array_shift($arg_list));
-          $where[] = "b.biblio_publisher ". $match_op ." '%s' ";
+          $term = explode("?", array_shift($arg_list));
+          $where[] = "b.biblio_publisher " . $match_op . " '%s' ";
           $terms[] = db_escape_string($term[0]);
           array_push($args, $type, $term[0]);
           $operator = NULL;
           break;
+
         case 'year':
           $term = db_escape_string(array_shift($arg_list));
           $where[] = "b.biblio_year=%d ";
-          //$limit .= " AND b.biblio_year=%d ";
-          $terms[] = (int)$term;
-          array_push($args, $type, (int)$term);
+          $terms[] = (int) $term;
+          array_push($args, $type, (int) $term);
           $operator = NULL;
           break;
+
         case 'uid':
           $term = db_escape_string(array_shift($arg_list));
           $where[] = "n.uid=%d ";
-          //$limit .= " AND b.biblio_year=%d ";
-          $terms[] = (int)$term;
-          array_push($args, $type, (int)$term);
+          $terms[] = (int) $term;
+          array_push($args, $type, (int) $term);
           $operator = NULL;
           break;
+
         case 'keyword':
           $bkd++;
-          $term = explode("?",array_shift($arg_list));
-          if (is_numeric($term[0])){
+          $term = explode("?", array_shift($arg_list));
+          if (is_numeric($term[0])) {
             $terms[] = db_escape_string($term[0]);
             $joins[] = "inner join {biblio_keyword} as bk$bkd on n.vid = bk$bkd.vid";
-          //$joins[] = "inner join {biblio_keyword_data} as bkd on bk.kid= bkd.kid";
             $where[] = "bk$bkd.kid = %d ";
           }
           elseif (strlen($term[0]) == 1) {
@@ -303,40 +364,43 @@ function biblio_build_query($arg_list) {
             $selects[] = "bkd.word as biblio_keyword";
             $where[] = " UPPER(substring(bkd.word,1,1)) = '%s' ";
             $terms[] = db_escape_string(strtoupper($term[0]));
-            //array_push($args, $type, $term[0]);
           }
-          else{
-            $where[] = " bkd". $bkd .'.word '. $match_op .' "[[:<:]]%s[[:>:]]" ';
-            $joins[] = " JOIN {biblio_keyword} as bk". $bkd ." on b.vid = bk". $bkd .".vid ";
-            $joins[] = " JOIN {biblio_keyword_data} as bkd". $bkd ." on bk". $bkd .".kid = bkd".$bkd .".kid ";
+          else {
+            $where[] = " bkd" . $bkd . '.word ' . $match_op . ' "[[:<:]]%s[[:>:]]" ';
+            $joins[] = " JOIN {biblio_keyword} as bk" . $bkd . " on b.vid = bk" . $bkd . ".vid ";
+            $joins[] = " JOIN {biblio_keyword_data} as bkd" . $bkd . " on bk" . $bkd . ".kid = bkd" . $bkd . ".kid ";
             $terms[] = db_escape_string($term[0]);
             $operator = NULL;
             $rss_info['title'] = t("Keyword " . $term[0]);
-            $rss_info['description'] = t("These publications, containing the keyword: %keyword, are part of the works listed at %sitename", array('%keyword' => $term[0], '%sitename' => variable_get('site_name', 'Drupal')));
+            $rss_info['description'] = t("These publications, containing the keyword: %keyword, are part of the works listed at %sitename",
+                                         array('%keyword' => $term[0], '%sitename' => variable_get('site_name', 'Drupal')));
             $rss_info['link'] = '/keyword/' . $term[0];
           }
           array_push($args, $type, $term[0]);
           $operator = NULL;
           break;
+
         case 'citekey':
-          $term = explode("?",array_shift($arg_list));
+          $term = explode("?", array_shift($arg_list));
           $terms[] = db_escape_string($term[0]);
           $where[] = "b.biblio_citekey= '%s' ";
           array_push($args, $type, $term[0]);
           $operator = NULL;
           break;
+
         case 'type':
           $term = db_escape_string(array_shift($arg_list));
           $where[] = "b.biblio_type=%d ";
-          //$limit .= $operator. "b.biblio_type=%d ";
-          $terms[] = (int)$term;
-          array_push($args, $type, (int)$term);
+          $terms[] = (int) $term;
+          array_push($args, $type, (int) $term);
           $operator = NULL;
           break;
+
         case 'order':
-          $term = (db_escape_string(strtolower(array_shift($arg_list))) == 'desc')?'desc':'asc';
+          $term = (db_escape_string(strtolower(array_shift($arg_list))) == 'desc') ? 'desc' : 'asc';
           $sort_attrib['order'] = $term;
           break;
+
         case 'sort':
           $term = db_escape_string(array_shift($arg_list));
           $sort_attrib['sort'] = $term;
@@ -345,10 +409,12 @@ function biblio_build_query($arg_list) {
               $sortby = "ORDER BY bt.name %s, $sort_title";
               $selects[] = "bt.name, $sort_title";
               break;
+
             case 'title':
               $sortby = "ORDER BY $sort_title %s";
               $selects[] = $sort_title;
               break;
+
             case 'author':
               $sortby = "ORDER BY bcd.lastname %s ";
               $where['bc-rank'] = "bc.rank=0";
@@ -357,64 +423,72 @@ function biblio_build_query($arg_list) {
               $joins['bcd'] = '  JOIN {biblio_contributor_data} as bcd on bc.cid = bcd.cid ';
               $selects[] = "bcd.lastname";
               break;
-            case 'keyword': // added msh 070808
+
+            case 'keyword':
               $sortby = "ORDER BY bkd.word %s ";
               $joins['bk'] = '  JOIN {biblio_keyword} as bk on b.vid = bk.vid ';
               $joins['bkd'] = '  LEFT JOIN {biblio_keyword_data} as bkd on bk.kid = bkd.kid ';
               $selects[] = "bkd.word as biblio_keyword";
-              //$count_selects[] = "bkd.word";
               break;
+
             case 'year':
             default:
               $sortby = "ORDER BY b.biblio_year %s, b.biblio_date %s, $sort_title %s";
               $selects[] = "b.biblio_year, b.biblio_date";
               $selects[] = $sort_title;
-          } //end switch
+          }
           break;
+
         case 'search':
           $term = explode("?",array_shift($arg_list));
-              $result_nids = split(',', $term[0]);
-              $where[] = "n.nid in (".db_placeholders($result_nids).")";
-              foreach ($result_nids as $result_nid) {
-                $terms[] = db_escape_string($result_nid);
-                array_push($args, $type, $result_nid);
-              }
-        // Save search keyword to show in the filter list.
-              $term = array_shift($arg_list);
-              array_push($args, $type, $term);
-              $operator = NULL;
-              break;
-            default:
-              $fields = biblio_get_db_fields();
-              $term = explode("?",array_shift($arg_list));
-              if (in_array("biblio_$type",$fields))
-              {
-                $where[] = "b.biblio_$type ".$match_op ." '%s' ";
-                $terms[] = db_escape_string($term[0]);
-                array_push($args, $type, $term[0]);
-                $operator = NULL;
-              }
-              break;
+          $result_nids = split(',', $term[0]);
+          $where[] = "n.nid in (" . db_placeholders($result_nids) . ")";
+          foreach ($result_nids as $result_nid) {
+            $terms[] = db_escape_string($result_nid);
+            array_push($args, $type, $result_nid);
+          }
+          // Save search keyword to show in the filter list.
+          $term = array_shift($arg_list);
+          array_push($args, $type, $term);
+          $operator = NULL;
+          break;
+
+        default:
+          $fields = biblio_get_db_fields();
+          $term = explode("?", array_shift($arg_list));
+          if (in_array("biblio_$type",$fields)) {
+            $where[] = "b.biblio_$type " . $match_op . " '%s' ";
+            $terms[] = db_escape_string($term[0]);
+            array_push($args, $type, $term[0]);
+            $operator = NULL;
+          }
+          break;
       }
     }
   }
   $where[] = "n.type='biblio' ";
+  // Only allow super admin user to view unpublished biblio content.
   if ($user->uid != 1 ) {
     $where[] = 'n.status = 1 ';
-  }//show only published entries to everyone except admin
+  }
 
   $select = implode(', ', $selects);
   $count_select = implode(', ', $count_selects);
   $join = implode(' ', $joins);
 
-  $where_clause = count($where) > 1 ? '('. implode(') AND (', $where) .')': $where[0];
+  $where_clause = count($where) > 1 ? '(' . implode(') AND (', $where) . ')' : $where[0];
 
-  $query = db_rewrite_sql("SELECT $select FROM {node} n $join  WHERE $where_clause $limit $sortby $count_limit");
-  $count_query = db_rewrite_sql("SELECT COUNT($count_select) FROM {node} n $join  WHERE $where_clause $limit $count_limit");
+  $query = db_rewrite_sql("SELECT $select FROM {node} n $join WHERE $where_clause $limit $sortby $count_limit");
+  $count_query = db_rewrite_sql("SELECT COUNT($count_select) FROM {node} n $join WHERE $where_clause $limit $count_limit");
   $_SESSION['last_biblio_query'] = $query;
-  $terms[] = $sort_attrib['order']; // this is either asc or desc to be inserted into the first term of the ORDER clause
-  if($sort_attrib['sort'] == 'year') {
-    $terms[] = $sort_attrib['order']; // we need any extra order term when sorting by year since there are to date terms biblio_year and biblio_date
+
+  // This will be either asc or desc that needs to be inserted into the first
+  // term of the ORDER BY clause.
+  $terms[] = $sort_attrib['order'];
+  if ($sort_attrib['sort'] == 'year') {
+    // An extra order term is needed when sorting by year since there are to
+    // date terms biblio_year and biblio_date.
+    $terms[] = $sort_attrib['order'];
     $terms[] = 'asc';
   }
   $_SESSION['last_biblio_query_terms'] = $terms;
@@ -426,31 +500,37 @@ function biblio_build_query($arg_list) {
                'sort_attrib' => $sort_attrib,
                'rss'         => $rss_info
   ));
-
 }
 
 /**
+ *
+ *
  * biblio_show_results takes the query results from biblio_db_search and
  * adds some controls to the page then loops through the results applying
  * the selected style to each entry
  *
- * @param $result
- * @param $count
- * @param $attrib
- * @param $args
- * @param $inline
- * @return unknown_type
+ * @param $nodes
+ *
+ * @param array $query_info
+ *
+ * @param bool $inline
+ *   (optional) A logical flag indicating whether the biblio items should be
+ *   formatted in a inline manner.  The default is FALSE.
+ *
+ * @return string
+ *   An HTML string suitable for display in a browser.
  */
-function biblio_show_results($nodes, $query_info, $inline=false) {
+function biblio_show_results($nodes, $query_info, $inline = FALSE) {
   global $pager_total_items;
-  $profile = false;
-  $attrib = $query_info['sort_attrib'];
-  $args   = $query_info['args'];
-  $base =  variable_get('biblio_base', 'biblio');
-  $style = biblio_get_style();
+  $content = '';
+  $profile = FALSE;
+  $attrib  = $query_info['sort_attrib'];
+  $args    = $query_info['args'];
+  $base    = variable_get('biblio_base', 'biblio');
+  $style   = biblio_get_style();
   if ($inline === 'profile') {
-    $profile = true;
-    $inline  = false;
+    $profile = TRUE;
+    $inline  = FALSE;
   }
   if (module_exists('popups')){
      popups_add_popups();
@@ -458,7 +538,7 @@ function biblio_show_results($nodes, $query_info, $inline=false) {
   if (!$inline && !$profile) {
 
     if (variable_get('biblio_rss', 0)) {
-      drupal_set_html_head('<link rel="alternate" type="application/rss+xml" title="'.variable_get('site_name', 'Drupal').' RSS" href="'.url("$base/rss.xml").'" />');
+      drupal_set_html_head('<link rel="alternate" type="application/rss+xml" title="' . variable_get('site_name', 'Drupal') . ' RSS" href="' . url("$base/rss.xml") . '" />');
     }
     // Search box. Has same permissions as the filter tab.
     $content = '<div id="biblio-header" class="clear-block">';
@@ -481,11 +561,14 @@ function biblio_show_results($nodes, $query_info, $inline=false) {
     }
   }
 
-  if ($inline === true) print '<div class="biblio-inline">';
+  if ($inline === TRUE) print '<div class="biblio-inline">';
 
-  if ($_GET['sort'] == 'title' ||
+  if (isset($_GET['sort']) &&
+     ($_GET['sort'] == 'title' ||
       $_GET['sort'] == 'author' ||
-      $_GET['sort'] == 'keyword') {
+      $_GET['sort'] == 'keyword')
+     ) {
+    $value = $_GET['q'];
     if (strpos($_GET['q'],'ag') ||
         strpos($_GET['q'],'tg') ||
         strpos($_GET['q'],'keyword')) {
@@ -506,42 +589,68 @@ function biblio_show_results($nodes, $query_info, $inline=false) {
     if (variable_get('biblio_fix_isi_links', 0)) biblio_fix_isi_links($node);
 
 
-    // output separator bar if needed
+    // Add a separator bar if needed.
     $content .= _biblio_category_separator_bar($attrib, $node);
 
-    $inline_links = ($inline && variable_get('biblio_inlinemode_in_links',0)) ? true : false;
+    $inline_links = ($inline && variable_get('biblio_inlinemode_in_links', 0)) ? TRUE : FALSE;
+    $content .= theme('biblio_entry', $node, $base, $style, $inline_links);
+  }
 
-    $content .= theme('biblio_entry', $node,$base,$style,$inline_links);
-  } //end while
   if ($count) $content .= '</div><!-- end category-section -->';
   $content .= theme('pager', 0, variable_get('biblio_rowsperpage', 25));
   if ($count == 0) {
-    $content .= "<h3>".t("No items found")."</h3>";
+    $content .= "<h3>" . t("No items found") . "</h3>";
     if (strstr($content, "Filters:")) {
-      $content .= t('!modify_link or !remove_link your filters and try again.', array('!modify_link' => l(t('Modify'),"$base/filter"), '!remove_link' => l(t('remove'),"$base/filter/clear")));
+      $content .= t('!modify_link or !remove_link your filters and try again.', array(
+        '!modify_link' => l(t('Modify'), "$base/filter"),
+        '!remove_link' => l(t('remove'), "$base/filter/clear")
+      ));
     }
   }
-  if ($profile === true)  return $content;
-  if ($inline === true)   return $content . "</div>";
-  if ($inline === false)  {
+  if ($profile === TRUE) {
+    return $content;
+  }
+  elseif ($inline === TRUE) {
+    return $content . "</div>";
+  }
+  elseif ($inline === FALSE) {
     drupal_set_title(check_plain(variable_get('biblio_base_title', 'Biblio')));
     return $content;
   }
-
 }
 
+/**
+ *
+ *
+ * @param $attrib
+ *
+ * @param array $options
+ *   (optional) An associative array with following possible keys:
+ *
+ * @return string $content
+ *   An HTML formatted string?
+ */
 function _biblio_sort_tabs($attrib, $options = NULL) {
   global $base_path;
   $content = '';
   $sort_links = array();
   $tabs = variable_get('biblio_sort_tabs_style', 0);
-  $order = ($attrib['order'] == "desc" || $attrib['order'] == "DESC")?"asc":"desc";
-  $cur_order = ($attrib['order'] == "desc" || $attrib['order'] == "DESC")?"desc":"asc";
-  $path = drupal_get_path('module','biblio');
-  $order_arrow = ($order == 'asc') ? ' <img src ="'. $base_path . $path. '/misc/arrow-asc.png" alt =" (Desc)" />':' <img src ="'. $base_path . $path .'/misc/arrow-desc.png" alt = " (Asc)" />';
-  $sort_links =  variable_get('biblio_sort_tabs', array('author'=>'author', 'title'=>'title', 'type'=>'type', 'year'=>'year', 'keyword'=>'keyword'));
+  // What is the default for $order in event $attrib['order'] not defined?
+  $order = ($attrib['order'] == "desc" || $attrib['order'] == "DESC") ? "asc" : "desc";
+  $cur_order = ($attrib['order'] == "desc" || $attrib['order'] == "DESC") ? "desc" : "asc";
+  $path = drupal_get_path('module', 'biblio');
+  $order_arrow = ($order == 'asc')
+                   ? ' <img src ="' . $base_path . $path . '/misc/arrow-asc.png" alt =" (Desc)" />'
+                   : ' <img src ="' . $base_path . $path . '/misc/arrow-desc.png" alt = " (Asc)" />';
+  $sort_links =  variable_get('biblio_sort_tabs', array(
+                   'author' => 'author',
+                   'title' => 'title',
+                   'type' => 'type',
+                   'year' => 'year',
+                   'keyword' => 'keyword'
+                 ));
   ksort($sort_links);
-  $content .= $tabs ? '<ul class="tabs secondary ">':'';
+  $content .= $tabs ? '<ul class="tabs secondary">' : '';
 
   foreach($sort_links as $key => $title) {
     $tab['path'] = $_GET['q'];
@@ -556,7 +665,6 @@ function _biblio_sort_tabs($attrib, $options = NULL) {
       $tab['sfx'] = '] ';
       $tab['arrow'] = $order_arrow;
       $content .= _biblio_sort_tab($tab, $tabs);
-
     }
     elseif ($key === $title ) {
       $tab['query'] = array('sort' => $title, 'order' => $order);
@@ -566,35 +674,60 @@ function _biblio_sort_tabs($attrib, $options = NULL) {
       $tab['arrow'] = '';
       $content .= _biblio_sort_tab($tab, $tabs);
     }
-
   }
-  if (!$tabs) $content = t('Sort by').': '.$content;
-  $content .= $tabs ? '</ul>':'';
+  if ($tabs) {
+    $content .= '</ul>';
+  }
+  else {
+    $content = t('Sort by') . ': ' . $content;
+  }
 
   return $content;
 }
 
+/**
+ * Page callback: Creates ...
+ *
+ * @param array $tab
+ *   An associative array with the following elements:
+ *   - text:
+ *   - arrow:
+ *   - attributes: An array with an optional class key.
+ * @param bool $tabs
+ *   (optional)
+ *
+ * @return string
+ *
+ */
 function _biblio_sort_tab($tab, $tabs = FALSE) {
   if ($tabs) {
-    $text  = '<span class="a"><span class="b">'.$tab['text'].$tab['arrow'].'</span></span>';
-    $class = ($tab['attributes']['class']) ? 'class="active"' : '';
+    $text  = '<span class="a"><span class="b">' . $tab['text'] . $tab['arrow'] . '</span></span>';
+    $class = (isset($tab['attributes']['class']) && $tab['attributes']['class']) ? 'class="active"' : '';
     $link  = l($text, $tab['path'], $tab);
     return "<li $class >" . str_replace('class="active"', $class, $link) . '</li>';
   }
   else {
-    return $tab['pfx']. l($tab['text'], $tab['path'], $tab) . $tab['arrow'] . $tab['sfx'];
+    return $tab['pfx'] . l($tab['text'], $tab['path'], $tab) . $tab['arrow'] . $tab['sfx'];
   }
-  return;
 }
 
-function _biblio_filter_info_line($args) {
+/**
+ * Page callback: Creates ...
+ *
+ * @param array $args
+ *
+ *
+ * @return string $content
+ *   An HTML formatted string ...
+ */
+function _biblio_filter_info_line(array $args) {
   module_load_include('inc', 'biblio', 'includes/biblio.contributors');
   $content = '';
   $filtercontent = '';
   $search_content = '';
   $base =  variable_get('biblio_base', 'biblio');
   $session = &$_SESSION['biblio_filter'];
-  // if there are any filters in place, print them at the top of the list
+  // If there are any filters in place, print them at the top of the list.
   if (count($args)) {
     $i = 0;
     while ($args) {
@@ -620,9 +753,8 @@ function _biblio_filter_info_line($args) {
         elseif (is_string($value) && strlen($value) == 1) {
           $type = t("First letter of keyword ");
         }
-
       }
-      if ($type == 'uid' ) {
+      if ($type == 'uid') {
         $user = user_load($value);
         $value = $user->name;
         $type = t("Drupal user");
@@ -632,12 +764,10 @@ function _biblio_filter_info_line($args) {
         $value = $author->name;
         $type = t("Author");
       }
-      if ($type == 'ag' ) {
-        //return;
+      if ($type == 'ag') {
         $type = t("First letter of last name");
       }
-      if ($type == 'tg' ) {
-        //return;
+      if ($type == 'tg') {
         $type = t("First letter of title");
       }
       if ($type == 'type' && $value > 0) {
@@ -647,44 +777,62 @@ function _biblio_filter_info_line($args) {
         }
       }
       array_shift($args);
-      $params = array('%a' =>  check_plain(ucwords($type)) , '%b' =>  check_plain($value) );
-      $filtercontent .= ($i++ ? t('<em> and</em> <strong>%a</strong> is <strong>%b</strong>', $params) : t('<strong>%a</strong> is <strong>%b</strong>', $params)) ;
+      $params = array('%a' => check_plain(ucwords($type)), '%b' =>  check_plain($value));
+      $filtercontent .= ($i++)
+                          ? t('<em> and</em> <strong>%a</strong> is <strong>%b</strong>', $params)
+                          : t('<strong>%a</strong> is <strong>%b</strong>', $params);
     }
     if ($search_content) {
-      $content .= '<div class="biblio-current-filters"><b>'.t('Search results for ').'</b>';
-      $content .= '<em>'. check_plain($search_content) .'</em>';
+      $content .= '<div class="biblio-current-filters"><b>' . t('Search results for ') . '</b>';
+      $content .= '<em>' . check_plain($search_content) . '</em>';
       if ($filtercontent) {
-        $content .= '<br><b>'.t('Filters').': </b>';
+        $content .= '<br><b>' . t('Filters') . ': </b>';
       }
     }
     else {
-      $content .= '<div class="biblio-current-filters"><b>'.t('Filters').': </b>';
+      $content .= '<div class="biblio-current-filters"><b>' . t('Filters') . ': </b>';
     }
     $content .= $filtercontent;
 
     $link_options = array();
     if (isset($_GET['sort'])) {
-      $link_options['query']  .= "sort=" . $_GET['sort'];
+      $link_options['query'] = "sort=" . $_GET['sort'];
     }
     if (isset($_GET['order'])) {
-      $link_options['query']   .= $link_options['query'] ? "&" : "" ;
-      $link_options['query']   .= "order=" . $_GET['order'];
+      $link_options['query'] .= $link_options['query'] ? "&" : "" ;
+      $link_options['query'] .= "order=" . $_GET['order'];
     }
 
     if ($search_content) {
-      $content .= '&nbsp;&nbsp;'.l('['.t('Reset Search').']',"$base/filter/clear", $link_options);
-    } else {
-      $content .= '&nbsp;&nbsp;'.l('['.t('Clear All Filters').']',"$base/filter/clear", $link_options);
+      $content .= '&nbsp;&nbsp;' . l('[' . t('Reset Search') . ']', "$base/filter/clear", $link_options);
+    }
+    else {
+      $content .= '&nbsp;&nbsp;' . l('[' . t('Clear All Filters') . ']', "$base/filter/clear", $link_options);
     }
     $content .= '</div>';
   }
-
   return $content;
 }
 
+/**
+ * Page callback: Creates ...
+ *
+ * @param array $attrib
+ *
+ * @param object $node
+ *
+ * @param bool $reset
+ *
+ *
+ * @return null|string
+ *
+ */
 function _biblio_category_separator_bar($attrib, $node, $reset = FALSE) {
   static $_text = '';
-  if ($reset) { $_text = ''; return;}
+  if ($reset) {
+    $_text = '';
+    return;
+  }
   $content = '';
 
   switch ($attrib['sort']) {
@@ -699,35 +847,35 @@ function _biblio_category_separator_bar($attrib, $node, $reset = FALSE) {
         $content .= theme_biblio_separator_bar($_text);
       }
       break;
+
     case 'author':
       if ( (isset($node->biblio_contributors[1][0]['lastname'])) &&
-      (drupal_substr(drupal_ucfirst(ltrim($node->biblio_contributors[1][0]['lastname'])), 0, 1) != $_text))
-      {
+        (drupal_substr(drupal_ucfirst(ltrim($node->biblio_contributors[1][0]['lastname'])), 0, 1) != $_text)) {
         if ($_text != '' ) {
           $content .= theme_biblio_end_category_section();
         }
-        $_text = drupal_substr(drupal_ucfirst(ltrim($node->biblio_contributors[1][0]['lastname'])), 0, 1) ;
+        $_text = drupal_substr(drupal_ucfirst(ltrim($node->biblio_contributors[1][0]['lastname'])), 0, 1);
         $content .= theme_biblio_separator_bar($_text);
       }
       break;
+
     case 'type':
       if ($node->biblio_type_name != $_text) {
         if ($_text != '' ) {
           $content .= theme_biblio_end_category_section();
         }
         $_text = $node->biblio_type_name;
-        //      $name = db_result(db_query("SELECT name FROM {biblio_types} as t where t.tid=%d", $node->biblio_type)) ;
         $content .= theme_biblio_separator_bar(_biblio_localize_type($node->biblio_type, $_text));
       }
       break;
-    case 'keyword':   // added msh 08 aug 07
-      // $kw = array_shift($node->biblio_keyword);
+
+    case 'keyword':
       $tok = $node->biblio_keyword;
       if (empty($tok)) {
         $tok = t("No Keywords");
       }
       if ($tok != $_text) {
-        if ($_text != '' ) {
+        if ($_text != '') {
           $content .= theme_biblio_end_category_section();
         }
         $_text = $tok;
@@ -736,6 +884,7 @@ function _biblio_category_separator_bar($attrib, $node, $reset = FALSE) {
         }
       }
       break;
+
     case 'year':
     default:
       if ($node->biblio_year != $_text) {
@@ -745,25 +894,41 @@ function _biblio_category_separator_bar($attrib, $node, $reset = FALSE) {
         $_text = $node->biblio_year;
         $content .= theme_biblio_separator_bar($_text);
       }
-  } //end switch
+      break;
+  }
   return $content;
 }
+
+/**
+ * Returns HTML for a biblio separator bar.
+ *
+ * @param string $text
+ *
+ */
 function theme_biblio_separator_bar($text) {
   $content = "\n".'<div class="biblio-separator-bar">' . check_plain($text) . "</div>\n";
   $content .= "\n".'<div class ="biblio-category-section">';
   return $content;
 }
 
+/**
+ * Returns HTML for end of a biblio category section.
+ */
 function theme_biblio_end_category_section() {
   return "\n</div><!-- end category-section -->";
 }
 
 /**
- * Add a search field on the main biblio page.
- */
-/**
- * @param $form_state
- * @return unknown_type
+ * Form constructor for the search form used on the main biblio page.
+ *
+ * @param array $form_state
+ *   This variable is not referenced in this function...
+ *
+ * @return array
+ *   An associative array with the form definition elements for a search field.
+ *
+ * @see biblio_search_form_submit()
+ * @ingroup forms
  */
 function biblio_search_form(&$form_state) {
   $form['biblio_search'] = array(
@@ -783,10 +948,17 @@ function biblio_search_form(&$form_state) {
 }
 
 /**
+ * Creates a query for the do_search algorithm in seach module.
+ *
  * Build the query following the do_search algorithm in search.module.
  * Unfortunately we cannot reuse anything from do_search as everything
  * is hard-coded :-(
+ *
  * @param $keys
+ *   (optional)
+ *
+ * @return false|database resource
+ *
  */
 function biblio_build_search_query($keys = '') {
   if ($keys != '')  {
@@ -797,20 +969,20 @@ function biblio_build_search_query($keys = '') {
     }
     if ($query === NULL || $query[0] == '') return FALSE;
 
-    $where = '('.$query[2].')';
+    $where = '(' . $query[2] . ')';
     $args = $query[3];
     if (!$query[5]) {
       $where .= " AND ($query[0])";
       $args = array_merge($args, $query[1]);
       $join = " INNER JOIN {search_dataset} d ON i.sid = d.sid AND i.type = d.type";
     }
-    // The COUNT ensures that we get only nodes where "term1 AND term2"
-    // match as we demand 2 matches. Note that this doesn't work when
-    // using the partial word search patch.
-    $args[] =$query[4];
+    // The COUNT ensures that we only get nodes where "term1 AND term2" match as
+    // we demand two matches. Note that this doesn't work when using the partial
+    // word search patch.
+    $args[] = $query[4];
 
-    $query = "SELECT distinct(i.sid) FROM {search_index} i
-              INNER JOIN {node} n ON n.nid = i.sid
+    $query = "SELECT distinct(i.sid) FROM {search_index} AS i
+              INNER JOIN {node} AS n ON n.nid = i.sid
               $join
               WHERE n.status = 1 AND (n.type = 'biblio')
               AND $where
@@ -821,25 +993,21 @@ function biblio_build_search_query($keys = '') {
   return FALSE;
 }
 
-
 /**
+ * Form submission handler for biblio_search_form().
+ *
  * When we submit a search, we revoke all current filters since search
- * and filtering are considered two different concepts things* conceptually.
+ * and filtering are considered two different concepts things conceptually.
  *
  * But we store the results as a filter (which is just a list of node ids that
  * matched the search request) so that we can reorder or export the search
  * results like with any other filter.  The filter has three components:
- * ('search',<list of node ids>,<search keywords>).
- * The second component, the filter value, is empty when submitting keywords.
- * In biblio_db_search we fill the second component with the list of nids
+ * ('search', <list of node ids>, <search keywords>).
+ * The second component (the filter value) is empty when submitting keywords.
+ * In biblio_db_search, we fill the second component with the list of nids
  * matching our keywords, as returned by node_search.  We store the keywords
  * only for showing them in "Search results for <keywords>".
  */
-/**
- * @param $form
- * @param $form_state
- * @return unknown_type
- */
 function biblio_search_form_submit($form, &$form_state) {
   $keys = $form_state['values']['keys'];
   if ($keys != '')  {
@@ -856,30 +1024,56 @@ function biblio_search_form_submit($form, &$form_state) {
 }
 
 /**
- * @param $arg
- * @return unknown_type
+ * Retrieves biblio filter information from session variable.
+ *
+ * @param string $arg
+ *   (optional) A string indicating the type of filter information. Possible
+ *   values are 'keys' and 'nodelist'; the default value is 'keys'.
+ *
+ * @return mixed
+ *   If either 'keys' or 'node' are passed in as $arg, the content of
+ *   $_SESSION['biblio_filter'] will be returned.  Otherwise NULL will be
+ *   returned.
  */
 function _get_biblio_search_filter($arg = 'keys') {
-  if (variable_get('biblio_search',0) &&
-    is_array($_SESSION['biblio_filter']) &&
-    is_array($_SESSION['biblio_filter'][0]) &&
-    in_array('search',$_SESSION['biblio_filter'][0])
-  ){
+  if (variable_get('biblio_search', 0) &&
+      isset($_SESSION['biblio_filter']) &&
+      is_array($_SESSION['biblio_filter']) &&
+      isset($_SESSION['biblio_filter'][0]) &&
+      is_array($_SESSION['biblio_filter'][0]) &&
+      in_array('search', $_SESSION['biblio_filter'][0])
+    ) {
     switch ($arg) {
-      case 'keys': return $_SESSION['biblio_filter'][0][2]; break;
-      case 'nodelist': return $_SESSION['biblio_filter'][0][1]; break;
+      case 'nodelist':
+        return $_SESSION['biblio_filter'][0][1];
+        break;
+
+      case 'keys':
+      default:
+        return $_SESSION['biblio_filter'][0][2];
+        break;
     }
   }
 }
 
-
+/**
+ * Populates the various selection filters with biblio data.
+ *
+ * @return array
+ *   An associative array with the following keys:
+ *   - author:
+ *   - type:
+ *   - term_id:
+ *   - year:
+ *   - keyword:
+ */
 function _get_biblio_filters() {
-
   $pub_authors[0] = '';
   $pub_years[-1] = '';
   $pub_type[0] = '';
   $pub_taxo[0] = '';
   $pub_keywords[0] = '';
+  
   $fields = " b.biblio_year, t.name , t.tid ";
   $order = " b.biblio_year DESC";
   $taxo_fields = "td.name as termname,td.tid as taxid, v.name as vocab_name";
@@ -890,7 +1084,7 @@ function _get_biblio_filters() {
                      "left join  {term_data} as td on tn.tid= td.tid",
                      "left join  {vocabulary} as v on v.vid= td.vid");
 
-  $taxo_joins = implode(' ',$taxo_join);
+  $taxo_joins = implode(' ', $taxo_join);
 
   $result = db_query("SELECT $fields FROM $table $join ORDER BY $order");
   $authors = db_query("SELECT firstname, initials, lastname, cid FROM {biblio_contributor_data} ORDER BY lastname ASC");
@@ -906,7 +1100,7 @@ function _get_biblio_filters() {
   }
 
   while($auth = db_fetch_object($authors)) {
-    $pub_authors[$auth->cid] = $auth->lastname .((!empty($auth->firstname) || !empty($auth->initials))?', '.$auth->firstname.' '.$auth->initials :'');
+    $pub_authors[$auth->cid] = $auth->lastname . ((!empty($auth->firstname) || !empty($auth->initials)) ? ', ' . $auth->firstname . ' ' . $auth->initials : '');
   }
   while($keyword = db_fetch_object($keywords)) {
     $pub_keywords[$keyword->kid] = $keyword->word;
@@ -915,25 +1109,30 @@ function _get_biblio_filters() {
     $pub_taxo["$tax->taxid"] = "$tax->vocab_name - $tax->termname";
   }
 
-  $author_select = count($pub_authors) > 1 ? array('title' => t('Author'), 'options' => $pub_authors) : null;
-  $years_select  = count($pub_years) > 1   ? array('title' => t('Year'), 'options' => array_unique($pub_years)) : null;
-  $type_select   = count($pub_type) > 1    ? array('title' => t('Type'), 'options' => array_unique($pub_type))  : null;
-  $tax_select    = count($pub_taxo) > 1    ? array('title' => t('Term'),'options' => array_unique($pub_taxo))  : null;
-  $keyword_select = count($pub_keywords) > 1 ? array('title' => t('Keyword'), 'options' => $pub_keywords) : null;
+  $author_select = count($pub_authors) > 1 ? array('title' => t('Author'), 'options' => $pub_authors) : NULL;
+  $years_select  = count($pub_years) > 1   ? array('title' => t('Year'), 'options' => array_unique($pub_years)) : NULL;
+  $type_select   = count($pub_type) > 1    ? array('title' => t('Type'), 'options' => array_unique($pub_type))  : NULL;
+  $tax_select    = count($pub_taxo) > 1    ? array('title' => t('Term'),'options' => array_unique($pub_taxo))  : NULL;
+  $keyword_select = count($pub_keywords) > 1 ? array('title' => t('Keyword'), 'options' => $pub_keywords) : NULL;
 
   $filters = array(
-    'author'     => $author_select,
+    'author'  => $author_select,
     'type'    => $type_select,
     'term_id' => $tax_select,
     'year'    => $years_select,
-    'keyword'     => $keyword_select,
+    'keyword' => $keyword_select,
   );
-
   return $filters;
 }
 
 /**
- * @return unknown_type
+ * Form constructor for a biblio content filter.
+ *
+ * @return array $form
+ *   An assoicative array with form elements for the biblio content filter.
+ *
+ * @see biblio_form_filter_submit()
+ * @ingroup forms
  */
 function biblio_form_filter() {
   // No longer use &$_SESSION so that we can alter $session in case of the search filter.
@@ -942,7 +1141,8 @@ function biblio_form_filter() {
   $filters = _get_biblio_filters();
 
   $i = 0;
-  $form['filters'] = array('#type' => 'fieldset',
+  $form['filters'] = array(
+    '#type' => 'fieldset',
     '#title' => t('Show only items where'),
     '#theme' => 'biblio_filters',
   );
@@ -950,18 +1150,21 @@ function biblio_form_filter() {
     list($type, $value) = $filter;
     // Don't show the search filter. Reset $session because of the $count(session) below.
     if ($type == 'search') {
-      $session = array ();
+      $session = array();
       break;
     }
     if ($type == 'category') {
       // Load term name from DB rather than search and parse options array.
       $value = module_invoke('taxonomy', 'get_term', $value);
       $value = $value->name;
-    }else {
+    }
+    else {
       $value = $filters[$type]['options'][$value];
     }
-    $string = ($i++ ? '<em>and</em> where <strong>%a</strong> is <strong>%b</strong>' : '<strong>%a</strong> is <strong>%b</strong>');
-    $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'] , '%b' => $value)));
+    $string = ($i++)
+                ? '<em>and</em> where <strong>%a</strong> is <strong>%b</strong>'
+                : '<strong>%a</strong> is <strong>%b</strong>';
+    $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'], '%b' => $value)));
   }
 
   foreach ($filters as $key => $filter) {
@@ -978,13 +1181,11 @@ function biblio_form_filter() {
     $form['filters']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
   }
 
-  return  $form;
+  return $form;
 }
 
 /**
- * @param $form
- * @param $form_state
- * @return unknown_type
+ * Form submission handler for biblio_form_filter().
  */
 function biblio_form_filter_submit($form, &$form_state) {
   // If the search filter was set, remove it now.
@@ -1008,13 +1209,14 @@ function biblio_form_filter_submit($form, &$form_state) {
           $_SESSION['biblio_filter'][] = array($filter, $form_state['values'][$filter]);
           $base =  variable_get('biblio_base', 'biblio');
           drupal_goto($base);
-
         }
       }
       break;
+
     case t('Undo'):
       array_pop($_SESSION['biblio_filter']);
       break;
+
     case t('Reset'):
       $_SESSION['biblio_filter'] = array();
       break;
@@ -1022,27 +1224,40 @@ function biblio_form_filter_submit($form, &$form_state) {
 }
 
 /**
- * @param $user
+ * Retrieves the publications associated with an user ID.
+ *
+ * @param object $user
+ *   An object with user information possibly including contributor ID or the
+ *   last name of the user.  At minimum the user ID must be specified.
  * @param $profile
- * @return unknown_type
+ *   (optional)
+ * @param string $nofilter
+ *   (optional)
+ *
+ * @return array
+ *   An array of publications associated with a user.
  */
-function biblio_get_user_pubs($user, $profile='', $nofilters=''){
-  if (isset($user->biblio_contributor_id) && !empty($user->biblio_contributor_id) ){
+function biblio_get_user_pubs($user, $profile = '', $nofilters = '') {
+  if (isset($user->biblio_contributor_id) && !empty($user->biblio_contributor_id)) {
     $pubs = biblio_db_search('author', $user->biblio_contributor_id, $profile, $nofilters);
   }
   elseif (isset($user->biblio_lastname) && !empty($user->biblio_lastname)) {
     $pubs = biblio_db_search('author', $user->biblio_lastname, $profile, $nofilters);
   }
-  else{
+  else {
     $pubs = biblio_db_search('uid', $user->uid, $profile, $nofilters);
   }
-
   return $pubs;
 }
 
 /**
+ * Creates an HTML string for a node view in either tabular or long format.
+ *
  * @param $node
- * @return unknown_type
+ *
+ *
+ * @return string
+ *   An HTML formatted string for inline style of biblio content view. 
  */
 function biblio_view_inline(&$node) {
   $style = biblio_get_style();
@@ -1056,7 +1271,10 @@ function biblio_view_inline(&$node) {
 }
 
 /**
- * @return unknown_type
+ * Creates a view based upon a cititaion key.
+ * 
+ * @return string
+ *
  */
 function biblio_citekey_view() {
   $citekey = arg(2);
@@ -1064,25 +1282,32 @@ function biblio_citekey_view() {
   if ($nid->nid > 0) {
     $node = node_load($nid->nid);
     return node_page_view($node);
-  } else {
+  } 
+  else {
     return t("Sorry, citekey @cite not found", array('@cite'=>$citekey));
   }
-
 }
 
 /**
- * @param $keywords
- * @param $base
- * @return unknown_type
+ * Creates an HTML string with links to an array of biblio keywords.
+ *
+ * @param array $keywords
+ *
+ * @param string $base
+ *   (optional)
+ *
+ * @return string
+ *   An HTML formatted string with links to biblio keyswords.
  */
-function _biblio_keyword_links($keywords,$base='biblio') {
+function _biblio_keyword_links($keywords, $base = 'biblio') {
   $options = array();
   if (isset($_GET['sort'])) {
-    $options['query']  .= "sort=" . $_GET['sort'];
+    $options['query'] = "sort=" . $_GET['sort'];
   }
   if (isset($_GET['order'])) {
-    $options['query']  .= $options['query'] ? "&" : "";
-    $options['query']  .= "order=" . $_GET['order'];
+    if (!isset($options['query'])) $options['query'] = '';
+    $options['query'] .= empty($options['query']) ? "" : "?";
+    $options['query'] .= "order=" . $_GET['order'];
   }
   $html = "";
   if (!is_array($keywords)) {
@@ -1098,13 +1323,31 @@ function _biblio_keyword_links($keywords,$base='biblio') {
   return $html;
 }
 
+/**
+ *
+ *
+ * @param array $filter
+ *   (optional)
+ *
+ * @return string
+ *   An HTML formatted string with biblio author information.
+ */
 function biblio_author_page($filter = NULL) {
   $path = drupal_get_path('module', 'biblio');
   drupal_add_js($path . '/misc/biblio.highlight.js');
   $authors = _biblio_get_authors($filter);
-    return _biblio_format_author_page($filter, $authors);
+  return _biblio_format_author_page($filter, $authors);
 }
 
+/**
+ *
+ *
+ * @param array $filter
+ *   (optional)
+ *
+ * @return array
+ *
+ */
 function _biblio_get_authors($filter = NULL) {
   global $user;
   $where = array();
@@ -1138,39 +1381,47 @@ function _biblio_get_authors($filter = NULL) {
   }
 
   $suspects = array();
-  $result = db_query('SELECT lastname FROM {biblio_contributor_data} '
-                      . (isset($where['filter']) ? 'WHERE '  . $where['filter'] : '') .
-                      ' GROUP BY lastname HAVING COUNT(*) > 1', array(':filter' => $filter)
-             );
+  $result = db_query(
+              'SELECT lastname FROM {biblio_contributor_data} '
+              . (isset($where['filter']) ? 'WHERE ' . $where['filter'] : '')
+              . ' GROUP BY lastname HAVING COUNT(*) > 1', array(':filter' => $filter)
+            );
 
   while ($author = db_fetch_object($result)) {
     $suspects[] = $author->lastname;
   }
 
-  $db_result = db_query('SELECT bd.cid, bd.drupal_uid, bd.name, bd.lastname,
-                              bd.firstname, bd.prefix, bd.suffix, bd.initials,
-                              bd.affiliation, bd.md5, bd.literal, COUNT(*) AS cnt
-                            FROM {biblio_contributor} b
-                                 LEFT JOIN {biblio_contributor_data} bd ON b.cid = bd.cid
-                                 INNER JOIN {node} n on n.vid = b.vid
-                            '. $where_clause.'
-                            GROUP BY bd.cid, bd.drupal_uid, bd.name, bd.lastname,
-                                     bd.firstname, bd.prefix, bd.suffix,
-                                     bd.initials, bd.affiliation, bd.md5, bd.literal
-                            HAVING COUNT(*) > 0
-                            ORDER BY  lastname ASC, SUBSTRING(firstname,1,1) ASC,
-                            initials ASC', $filter);
-
+  $sql = 'SELECT bd.cid, bd.drupal_uid, bd.name, bd.lastname, bd.firstname, bd.prefix, ' . 
+           'bd.suffix, bd.initials, bd.affiliation, bd.md5, bd.literal, COUNT(*) AS cnt ' .
+         'FROM {biblio_contributor} b ' .
+           'LEFT JOIN {biblio_contributor_data} bd ON b.cid = bd.cid ' .
+           'INNER JOIN {node} n on n.vid = b.vid ' .
+         $where_clause . ' ' .
+         'GROUP BY bd.cid, bd.drupal_uid, bd.name, bd.lastname, bd.firstname, bd.prefix, ' .
+           'bd.suffix, bd.initials, bd.affiliation, bd.md5, bd.literal ' .
+         'HAVING COUNT(*) > 0 ' .
+         'ORDER BY lastname ASC, SUBSTRING(firstname, 1, 1) ASC, initials ASC';
+  $db_result = db_query($sql, $filter);
   while ($author = db_fetch_array($db_result)){
     if (array_search($author['lastname'], $suspects) !== FALSE) {
       $author['#suspect'] = TRUE;
     }
     $authors[] = $author;
   }
-
   return $authors;
 }
 
+/**
+ *
+ *
+ * @param array $filter
+ *
+ * @param array $authors
+ *
+ *
+ * @return
+ *
+ */
 function _biblio_format_author_page($filter, $authors) {
   $header_ext = $checkbox = '';
   $header = array();
@@ -1181,8 +1432,8 @@ function _biblio_format_author_page($filter, $authors) {
     }
     $checkbox = array(
       '#title' => t('Hightlight possible duplicates'),
-      '#type'	 => 'checkbox',
-      '#id'		 => 'biblio-highlight',
+      '#type'  => 'checkbox',
+      '#id'    => 'biblio-highlight',
     );
     $checkbox = '<div class="biblio-alpha-line">' . drupal_render($checkbox) . '</div>';
     $header = array(array('data' => t('There are a total of @count authors in the database!header_ext.', array('@count' => count($authors), '!header_ext' => $header_ext)), 'align' =>'center', 'colspan' => 3));
@@ -1200,8 +1451,17 @@ function _biblio_format_author_page($filter, $authors) {
   $output = theme('table', $header, $rows);
   return $output;
 }
+
 /*
- * Helper function to format the authors and add edit links if required
+ * Formats the authors as HTML and adds edit links if desired. 
+ *
+ * Helper function to format the authors and add edit links if required.
+ *
+ * @param array $author
+ *
+ *
+ * @return string
+ *
  */
 function _biblio_format_author($author) {
   static $author_options = array();
@@ -1217,77 +1477,140 @@ function _biblio_format_author($author) {
   return $format;
 }
 
+/**
+ *
+ *
+ * @param array $author
+ *
+ *
+ * @return string
+ *
+ */
 function _biblio_author_edit_links($author) {
   static $path = '';
   if (empty($path)){
     $path =  (ord(substr($_GET['q'],-1)) > 97) ? $_GET['q'] . "/" : substr($_GET['q'], 0, -1);
     $path = (strpos($path, 'list/')) ? str_replace('list/', '', $path) : $path;
   }
-  return l(' ['.t('edit').']', $path . $author['cid'] ."/edit/" );
+  return l(' [' . t('edit') . ']', $path . $author['cid'] . "/edit/" );
 }
 
+/**
+ *
+ *
+ * @param array $filter
+ *
+ *
+ * @return string
+ *
+ */
 function biblio_keyword_page($filter = NULL) {
   $keywords = _biblio_get_keywords($filter);
   return _biblio_format_keyword_page($filter, $keywords);
 }
 
+/**
+ *
+ *
+ * @param array $filter
+ *
+ *
+ * @return array
+ *
+ */
 function _biblio_get_keywords($filter = NULL) {
   global $user;
+  $keywords = array();
   $where = array();
   $where_clause = '';
+  
   if ($filter) {
     $filter = strtoupper($filter);
     $where[] =  "UPPER(SUBSTRING(word,1,1)) = '%s' ";
-    $header_ext = t(' (which start with the letter "@letter") ',array('@letter' => $filter ));
+    $header_ext = t(' (which start with the letter "@letter") ', array('@letter' => $filter));
   }
   else {
-    $query_ext =  NULL;
+    $query_ext = NULL;
     $header_ext = NULL;
   }
 
-  if ($user->uid != 1 ) {//show only published entries to everyone except admin
+  // Never show unpublished biblio content (except super admin user).
+  if ($user->uid != 1) {
     $where[] = 'n.status = 1 ';
   }
-
-  if (variable_get('biblio_view_only_own', 0) ) {//show only authors that belong to nodes that the user has access to
+  
+  // Possibly restrict access to biblio content one has permission to view.
+  if (variable_get('biblio_view_only_own', 0) ) {
     $where[] = "n.uid = $user->uid";
   }
   if (count($where)) {
-    $where_clause = count($where) > 1 ? 'WHERE ('. implode(') AND (', $where) .')': 'WHERE '. $where[0];
+    $where_clause = count($where) > 1 
+                      ? 'WHERE (' . implode(') AND (', $where) . ')' 
+                      : 'WHERE ' . $where[0];
   }
-
-  $db_result = db_query('SELECT bkd.kid, bkd.word, COUNT(*) AS cnt
-                         FROM {biblio_keyword} bk
-                         LEFT JOIN {biblio_keyword_data} bkd ON bkd.kid = bk.kid
-                         INNER JOIN {node} n ON n.vid = bk.vid
-                         '. $where_clause. '
-                         GROUP BY bkd.kid, bkd.word HAVING COUNT(*) > 0
-                         ORDER BY  word ASC', $filter);
-
+  $sql = 'SELECT bkd.kid, bkd.word, COUNT(*) AS cnt ' .
+         'FROM {biblio_keyword} bk ' .
+           'LEFT JOIN {biblio_keyword_data} bkd ON bkd.kid = bk.kid ' .
+           'INNER JOIN {node} n ON n.vid = bk.vid ' .
+         $where_clause . ' ' .
+         'GROUP BY bkd.kid, bkd.word HAVING COUNT(*) > 0 ' .
+         'ORDER BY word ASC';
+  $db_result = db_query($sql, $filter);
   while ($keyword = db_fetch_object($db_result)){
     $keywords[] = $keyword;
   }
   return $keywords;
 }
 
+/**
+ * Page callback: 
+ *
+ * @param array $filter
+ *
+ * @param array $keywords
+ *
+ *
+ * @return string
+ *
+ */
 function _biblio_format_keyword_page($filter, $keywords) {
-  $rows[] = array(array('data' => theme('biblio_alpha_line', 'keywords', $filter), 'colspan' => 3));
-  for ($i=0; $i < count($keywords); $i+=3) {
-    $rows[] = array( array('data' => _biblio_format_keyword($keywords[$i]) ),
-    array('data' => isset($keywords[$i+1])?_biblio_format_keyword($keywords[$i+1]):'' ),
-    array('data' => isset($keywords[$i+2])?_biblio_format_keyword($keywords[$i+2]):'' ));
+  $header = array();
+	$rows = array();
+  $output = '';
+	$alphabar = theme('biblio_alpha_line', 'keywords', $filter);
+  $rows[] = array(array('data' => $alphabar, 'colspan' => 3));
+  for ($i = 0; $i < count($keywords); $i += 3) {
+    $rows[] = array( 
+      array('data' => _biblio_format_keyword($keywords[$i]) ),
+      array('data' => isset($keywords[$i+1]) ? _biblio_format_keyword($keywords[$i+1]) : ''),
+      array('data' => isset($keywords[$i+2]) ? _biblio_format_keyword($keywords[$i+2]) : '')
+    );
   }
-  //$header = array(array('data' => t('There are a total of @count keywords !header_ext in the database',array('@count' => count($keywords), '!header_ext' => $header_ext)), 'align' =>'center', 'colspan' => 3));
+  // $header = array(
+  //             array('data' => t('There are a total of @count keywords !header_ext in the database', array(
+  //               '@count' => count($keywords), 
+  //               '!header_ext' => $header_ext
+  //             )), 'align' =>'center', 'colspan' => 3
+  //           ));
   $output .= theme('table', $header, $rows);
   return $output;
 }
-function _biblio_format_keyword($keyword) {
-  $base      = variable_get('biblio_base', 'biblio');
-  $format    = l(trim($keyword->word), "$base/keyword/$keyword->kid" );
-  $format   .= ' ('. $keyword->cnt . ') ' ;
-  $path =  (ord(substr($_GET['q'],-1)) > 97) ? $_GET['q'] . "/" : substr($_GET['q'], 0, -1);
-  $edit_link = ' ['.l(t('edit'), $path . $keyword->kid . "/edit" ).'] ';
-  $format   .= (user_access('administer biblio')) ? $edit_link: '';
 
+/**
+ *
+ *
+ * @param object $keyword
+ *
+ *
+ * @return string
+ *
+ */
+function _biblio_format_keyword($keyword) {
+  $base = variable_get('biblio_base', 'biblio');
+  $format  = l(trim($keyword->word), "$base/keyword/$keyword->kid");
+  $format .= ' (' . $keyword->cnt . ') ';
+  $path = (ord(substr($_GET['q'], -1)) > 97) ? $_GET['q'] . "/" : substr($_GET['q'], 0, -1);
+  $edit_link = ' ['. l(t('edit'), $path . $keyword->kid . "/edit" ) . '] ';
+  $format .= (user_access('administer biblio')) ? $edit_link : '';
   return $format;
 }
diff --git a/includes/biblio_theme.inc b/includes/biblio_theme.inc
index 327d5b7..5a5d81a 100644
--- a/includes/biblio_theme.inc
+++ b/includes/biblio_theme.inc
@@ -514,9 +514,11 @@ function theme_biblio_format_authors($contributors, $options, $inline = false)
         //$author['initials'] = str_replace(' ', '',  $author['initials']);
 
         // within initials, add a space after a hyphen, but only if ...
-        if (ereg(" $", $options['betweenInitialsDelim'])) // ... the delimiter that separates initials ends with a space
-        $author['initials'] = preg_replace("/-(?=[$upper])/$patternModifiers", "- ", $author['initials']);
-
+        // ... the delimiter that separates initials ends with a space
+        if (preg_match('/ $/', $options['betweenInitialsDelim'])) { 
+          $author['initials'] = preg_replace("/-(?=[$upper])/$patternModifiers", "- ", $author['initials']);
+        }
+        
         // then, separate initials with the specified delimiter:
         $delim = $options['betweenInitialsDelim'];
         $author['initials'] = preg_replace("/([$upper])(?=[^$lower]+|$)/$patternModifiers", "\\1$delim", $author['initials']);
@@ -580,10 +582,10 @@ function theme_biblio_format_authors($contributors, $options, $inline = false)
       // we'll append the string in '$customStringAfterFirstAuthors' to the number of authors given in '$includeNumberOfAuthors' if the total number of authors is greater than the number given in '$numberOfAuthorsTriggeringEtAl':
       if ((($rank + 1) == $options['includeNumberOfAuthors']) AND ($authorCount > $options['numberOfAuthorsTriggeringEtAl']))
       {
-        if (ereg("__NUMBER_OF_AUTHORS__", $options['customStringAfterFirstAuthors']))
-        $customStringAfterFirstAuthors = preg_replace("/__NUMBER_OF_AUTHORS__/", ($authorCount - $options['includeNumberOfAuthors']), $options['customStringAfterFirstAuthors']); // resolve placeholder
-
-        $includeStringAfterFirstAuthor = true;
+        if (preg_replace('/__NUMBER_OF_AUTHORS__/', $options['customStringAfterFirstAuthors'])) {
+          $customStringAfterFirstAuthors = preg_replace("/__NUMBER_OF_AUTHORS__/", ($authorCount - $options['includeNumberOfAuthors']), $options['customStringAfterFirstAuthors']); // resolve placeholder
+        }
+        $includeStringAfterFirstAuthor = TRUE;
         break;
       }
     }
@@ -606,12 +608,23 @@ function theme_biblio_format_authors($contributors, $options, $inline = false)
   return $output;
 }
 
+/**
+ * Returns HTML for an author link.
+ *
+ * @param array $author
+ *   An associative array with information about an author including elements:
+ *   - name: A string with the author's name.
+ *   - cid: An integer identifying the author in biblio module.
+ *   - drupal_uid: (optional) An integer linking to Drupal user ID.
+ *
+ * @ingroup themeable
+ */
 function theme_biblio_author_link($author) {
   $base = variable_get('biblio_base', 'biblio');
   $link_to_profile = variable_get('biblio_author_link_profile', 0);
   $link_to_profile_path = variable_get('biblio_author_link_profile_path', 'user/[uid]');
   $options = array();
-  $inline = $inline ? "/inline" : "";
+  $inline = isset($inline) ? "/inline" : "";
   $language = isset($node->language) ? $node->language : '';
 
   if (isset($_GET['sort'])) {
@@ -625,11 +638,11 @@ function theme_biblio_author_link($author) {
   if (isset($author['drupal_uid']) && $author['drupal_uid'] > 0) {
     $options['attributes']['class'] = 'biblio-local-author';
   }
-  if (variable_get('biblio_links_target_new_window', null)){
-    $options = array_merge($options, array('attributes' => array('target'=>'_blank'), 'html' => TRUE));
+  if (variable_get('biblio_links_target_new_window', NULL)){
+    $options = array_merge($options, array('attributes' => array('target' => '_blank'), 'html' => TRUE));
   }
 
-  if ($link_to_profile && $author['drupal_uid'] ) {
+  if ($link_to_profile && isset($author['drupal_uid']) && $author['drupal_uid']) {
     $data['user'] = user_load($author['drupal_uid']);
     $path = token_replace_multiple($link_to_profile_path, $data);
     $alias = drupal_get_path_alias($path, $language);
@@ -637,7 +650,7 @@ function theme_biblio_author_link($author) {
     return l(trim($author['name']), $path_profile, $options);
   }
   else {
-    return l(trim($author['name']), "$base/author/". $author['cid'] .$inline, $options );
+    return l(trim($author['name']), "$base/author/" . $author['cid'] . $inline, $options);
   }
   return $html;
 }
diff --git a/styles/biblio_style_classic.inc b/styles/biblio_style_classic.inc
index 648a961..1b2ff92 100644
--- a/styles/biblio_style_classic.inc
+++ b/styles/biblio_style_classic.inc
@@ -1,53 +1,68 @@
 <?PHP
 
 /**
- * Get the style information
+ * @file
+ * Functions for rendering biblio item information in classic style.
+ */
+
+/**
+ * Get the style information.
  *
- * @return
- *   The name of the style
+ * @return array
+ *   The name of the style.
  */
 function biblio_style_classic_info() {
   return array (
     'classic' => 'Classic - This is the original biblio style'
   );
 }
+
+/**
+ *
+ * 
+ * @return array
+ *   An array of author styling options for the classic style.
+ */
 function biblio_style_classic_author_options() {
   $author_options = array(
-    'BetweenAuthorsDelimStandard'     =>  ', ',      //4
-    'BetweenAuthorsDelimLastAuthor'   =>  ', and ',    //5
-    'AuthorsInitialsDelimFirstAuthor' =>  ', ',      //7
-    'AuthorsInitialsDelimStandard'    =>  ' ',       //8
-    'betweenInitialsDelim'            =>  '. ',      //9
-    'initialsBeforeAuthorFirstAuthor' =>  FALSE,     //10
-    'initialsBeforeAuthorStandard'    =>  FALSE,      //11
-    'shortenGivenNames'               =>  FALSE,      //12
-    'numberOfAuthorsTriggeringEtAl'   =>  10,        //13
-    'includeNumberOfAuthors'          =>  10,        //14
-    'customStringAfterFirstAuthors'   =>  ', et al.',//15
+    'BetweenAuthorsDelimStandard'     =>  ', ',        //  4
+    'BetweenAuthorsDelimLastAuthor'   =>  ', and ',    //  5
+    'AuthorsInitialsDelimFirstAuthor' =>  ', ',        //  7
+    'AuthorsInitialsDelimStandard'    =>  ' ',         //  8
+    'betweenInitialsDelim'            =>  '. ',        //  9
+    'initialsBeforeAuthorFirstAuthor' =>  FALSE,       // 10
+    'initialsBeforeAuthorStandard'    =>  FALSE,       // 11
+    'shortenGivenNames'               =>  FALSE,       // 12
+    'numberOfAuthorsTriggeringEtAl'   =>  10,          // 13
+    'includeNumberOfAuthors'          =>  10,          // 14
+    'customStringAfterFirstAuthors'   =>  ', et al.',  // 15
     'encodeHTML'                      =>  TRUE
   );
   return $author_options;
 }
 
 /**
- * Apply a bibliographic style to the node
- *
+ * Apply a bibliographic style to the biblio node.
  *
  * @param $node
- *   An object containing the node data to render
+ *   An object containing the node data to render.
  * @param $base
- *   The base URL of the biblio module (defaults to /biblio)
+ *   The base URL of the biblio module (defaults to /biblio).
  * @param $inline
  *   A logical value indicating if this is being rendered within the
- *   Drupal framwork (false) or we are just passing back the html (true)
+ *   Drupal framwork (false) or we are just passing back the html (true).
+ *
  * @return
- *   The styled biblio entry
+ *   The styled biblio entry.
  */
 function biblio_style_classic($node, $base = 'biblio', $inline = FALSE) {
   $output = '';
   $author_options = biblio_style_classic_author_options();
-  $authors = theme('biblio_format_authors', $node->biblio_contributors[1], $author_options, $inline);
-  if (!empty ($node->biblio_citekey)&&(variable_get('biblio_display_citation_key',0))) {
+  $authors = '';
+  if (isset($node->biblio_contributors[1])) {
+    $authors = theme('biblio_format_authors', $node->biblio_contributors[1], $author_options, $inline);
+  }
+  if (!empty($node->biblio_citekey) && variable_get('biblio_display_citation_key', 0)) {
     $output .= '[' . check_plain($node->biblio_citekey) . '] ';
   }
   $output .= '<span class="biblio-title">';
@@ -74,12 +89,24 @@ function biblio_style_classic($node, $base = 'biblio', $inline = FALSE) {
     $output .= ', (' . check_plain($node->biblio_year) . ")\n";
   }
   return filter_xss($output, biblio_get_allowed_tags());
-
 }
 
+/**
+ * Creates a string with the author's nname in classic format.
+ *
+ * @param array $author
+ *   An associative arry with the following keys:
+ *   - prefix:
+ *   - lastname:
+ *   - firstname: 
+ *   - initials: 
+ *
+ * @return string
+ *   A string representing the author's name in classic format.
+ */
 function _classic_format_author($author) {
   $format = $author['prefix'] . ' ' . $author['lastname'] . ' ';
   $format .= !empty ($author['firstname']) ? ' ' . drupal_substr($author['firstname'], 0, 1) : '';
   $format .= !empty ($author['initials']) ? str_replace(' ', '', $author['initials']) : '';
   return $format;
-}
\ No newline at end of file
+}
-- 
1.7.6.msysgit.0

