From c0c37b1598ba59bbcb2e99d8fac85cd50233802a Mon Sep 17 00:00:00 2001
From: Jason Flatt <drupal@oadaeh.net>
Date: 04.04.2012 11:04:20

work in drupal7, but not stable
Signed-off-by:b1101 <b1101@1855940.no-reply.drupal.org>

diff --git a/basic_webmail.install b/basic_webmail.install
index 8e9c76a..274196f 100644
--- a/basic_webmail.install
+++ b/basic_webmail.install
@@ -1,80 +1,80 @@
-<?php
-
-/**
- * @file
- * Install, update and uninstall functions for the Basic webmail module.
- */
-
-/**
- * Implements hook_schema().
- */
-function basic_webmail_schema() {
-  $schema['basic_webmail_messages'] = array(
-    'description' => 'This is a temporary holding place for the basic information of the e-mail messages. This is used for the message listing.',
-    'fields' => array(
-      'user_id' => array(
-        'description' => 'The user to whom this message belongs.',
-        'type' => 'int',
-        'unsigned' => TRUE,
-        'not null' => FALSE,
-      ),
-      'message_number' => array(
-        'description' => 'The message id.',
-        'type' => 'int',
-        'unsigned' => TRUE,
-        'not null' => FALSE,
-      ),
-      'message_subject' => array(
-        'description' => 'The subject of the message.',
-        'type' => 'varchar',
-        'length' => 256,
-        'not null' => FALSE,
-      ),
-      'from_address' => array(
-        'description' => 'Who the message is from.',
-        'type' => 'varchar',
-        'length' => 256,
-        'not null' => FALSE,
-      ),
-      'message_date' => array(
-        'description' => 'When the message was sent.',
-        'type' => 'varchar',
-        'length' => 64,
-        'not null' => FALSE,
-      ),
-      'message_unread' => array(
-        'description' => 'TRUE if the message is unread.',
-        'type' => 'int',
-        'size' => 'tiny',
-        'unsigned' => TRUE,
-        'not null' => FALSE,
-      ),
-      'attachment_exists' => array(
-        'description' => 'TRUE if there are any attachments.',
-        'type' => 'int',
-        'size' => 'tiny',
-        'unsigned' => TRUE,
-        'not null' => FALSE,
-      ),
-      'message_answered' => array(
-        'description' => 'TRUE if the message was replied to.',
-        'type' => 'int',
-        'size' => 'tiny',
-        'unsigned' => TRUE,
-        'not null' => FALSE,
-      ),
-    ),
-  );
-
-  return $schema;
-} // End of basic_webmail_schema().
-
-
- /**
- * Implements hook_uninstall().
- */
-function basic_webmail_uninstall() {
-  db_delete('variable')
-    ->condition('name', 'basic_webmail_%', 'LIKE')
-    ->execute();
-} // End of basic_webmail_uninstall().
+<?php
+
+/**
+ * @file
+ * Install, update and uninstall functions for the Basic webmail module.
+ */
+
+/**
+ * Implements hook_schema().
+ */
+function basic_webmail_schema() {
+  $schema['basic_webmail_messages'] = array(
+    'description' => 'This is a temporary holding place for the basic information of the e-mail messages. This is used for the message listing.',
+    'fields' => array(
+      'user_id' => array(
+        'description' => 'The user to whom this message belongs.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => FALSE,
+      ),
+      'message_number' => array(
+        'description' => 'The message id.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => FALSE,
+      ),
+      'message_subject' => array(
+        'description' => 'The subject of the message.',
+        'type' => 'varchar',
+        'length' => 256,
+        'not null' => FALSE,
+      ),
+      'from_address' => array(
+        'description' => 'Who the message is from.',
+        'type' => 'varchar',
+        'length' => 256,
+        'not null' => FALSE,
+      ),
+      'message_date' => array(
+        'description' => 'When the message was sent.',
+        'type' => 'varchar',
+        'length' => 64,
+        'not null' => FALSE,
+      ),
+      'message_unread' => array(
+        'description' => 'TRUE if the message is unread.',
+        'type' => 'int',
+        'size' => 'tiny',
+        'unsigned' => TRUE,
+        'not null' => FALSE,
+      ),
+      'attachment_exists' => array(
+        'description' => 'TRUE if there are any attachments.',
+        'type' => 'int',
+        'size' => 'tiny',
+        'unsigned' => TRUE,
+        'not null' => FALSE,
+      ),
+      'message_answered' => array(
+        'description' => 'TRUE if the message was replied to.',
+        'type' => 'int',
+        'size' => 'tiny',
+        'unsigned' => TRUE,
+        'not null' => FALSE,
+      ),
+    ),
+  );
+
+  return $schema;
+} // End of basic_webmail_schema().
+
+
+ /**
+ * Implements hook_uninstall().
+ */
+function basic_webmail_uninstall() {
+  db_delete('variable')
+    ->condition('name', 'basic_webmail_%', 'LIKE')
+    ->execute();
+} // End of basic_webmail_uninstall().
diff --git a/basic_webmail.module b/basic_webmail.module
index f71b419..b341199 100644
--- a/basic_webmail.module
+++ b/basic_webmail.module
@@ -1,4379 +1,4443 @@
-<?php
-
-/**
- * @file
- * This is the main code file for the Basic webmail module.
- *
- * This module allows users to send and receive email through an IMAP mail
- * server with a web based user interface.
- */
-
-/** *******************************************************
- *
- *  Implementation of Drupal hooks.
- *
- *  ******************************************************/
-
-/**
- * Implements hook_help().
- */
-function basic_webmail_help($path, $arg) {
-  $output = '';
-
-  switch ($path) {
-    case 'admin/config/basic_webmail':
-      $output = t('Send and receive email through an IMAP mail server.');
-      break;
-  }
-
-  return $output;
-} // End of basic_webmail_help().
-
-
-/**
- * Implements hook_permission().
- */
-function basic_webmail_permission() {
-  return array(
-    'administer basic_webmail' => array(
-      'title' => t('Administer basic_webmail'),
-      'description' => 'Perform administration tasks for Basic webmail.',
-    ),
-    'access basic_webmail' => array(
-      'title' => t('Access basic_webmail'),
-      'description' => 'Use Basic webmail',
-    ),
-  );
-} // End of basic_webmail_permission().
-
-
-/**
- * Implements hook_menu().
- */
-function basic_webmail_menu() {
-  $items = array();
-
-  // Admin settings.
-  $items['admin/config/system/basic_webmail'] = array(
-    'title' => 'Basic webmail',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('basic_webmail_admin_settings'),
-    'access arguments' => array('administer basic_webmail'),
-    'description' => 'Configure the mail server.',
-//    'file' => 'basic_webmail.admin.inc',
-  );
-
-  // The main mail listing page.
-  $items['basic_webmail'] = array(
-    'title' => 'Email',
-    'page callback' => 'drupal_get_form',
-//    'page callback' => 'basic_webmail_mail_list',
-//    'page arguments' => 'basic_webmail_mail_list',
-    'page arguments' => array('basic_webmail_mail_list_form'),
-    'description' => 'Send and/or receive email.',
-    'access arguments' => array('access basic_webmail'),
-    'type' => MENU_NORMAL_ITEM,
-//    'file' => 'basic_webmail.list.inc',
-  );
-
-  // The delete message confirmation page.
-  $items['basic_webmail/delete'] = array(
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('_basic_webmail_delete_message_form'),
-    'access arguments' => array('access basic_webmail'),
-    'type' => MENU_CALLBACK,
-//    'file' => 'basic_webmail.list.inc',
-  );
-  // The copy message page.
-  $items['basic_webmail/copy'] = array(
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('_basic_webmail_copy_message_form'),
-    'access arguments' => array('access basic_webmail'),
-    'type' => MENU_CALLBACK,
-//    'file' => 'basic_webmail.list.inc',
-  );
-  // The move message page.
-  $items['basic_webmail/move'] = array(
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('_basic_webmail_move_message_form'),
-    'access arguments' => array('access basic_webmail'),
-    'type' => MENU_CALLBACK,
-//    'file' => 'basic_webmail.list.inc',
-  );
-
-  // The message view page.
-  $items['basic_webmail/message'] = array(
-    'page callback' => '_basic_webmail_message',
-    'access arguments' => array('access basic_webmail'),
-    'type' => MENU_CALLBACK,
-//    'file' => 'basic_webmail.view.inc',
-  );
-
-  // The compose message page.
-  $items['basic_webmail/sendmail'] = array(
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('_basic_webmail_send_mail_form'),
-    'access arguments' => array('access basic_webmail'),
-    'type' => MENU_CALLBACK,
-//    'file' => 'basic_webmail.edit.inc',
-  );
-  // Show email matches when filling in the forms.
-  $items['basic_webmail/autocomplete'] = array(
-    'title' => 'Basic webmail autocomplete',
-    'page callback' => 'basic_webmail_autocomplete',
-    'access arguments' => array('access basic_webmail'),
-    'type' => MENU_CALLBACK,
-//    'file' => 'basic_webmail.edit.inc',
-  );
-
-  return $items;
-} // End of basic_webmail_menu().
-
-/** *******************************************************
- *
- *  These next hooks are what became of hook_user().
- *
- *  ******************************************************/
-
-function basic_webmail_form_alter(&$form, &$form_state, $form_id) {
-//dpm('$form');
-//dpm($form);
-//dpm('$form_state');
-//dpm($form_state);
-//dpm('$form_id = "' . $form_id . '"');
-}
-
-/**
- * Implements hook_form_FORM_ID_alter().
- *
- * Modifies the user profile page to add the login ID and password fields.
- */
-function basic_webmail_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
-  // If this is the user's account form, they are allowed to access Basic
-  // webmail, and the administrator has chosen to collect the login ID and
-  // password, then add the fields to the form.
-  if ($form['#user_category'] == 'account' && user_access('access basic_webmail') && !variable_get('basic_webmail_account_info', 1)) {
-    _basic_webmail_form_user_form($form);
-  }
-} // End of basic_webmail_form_user_profile_form_alter() {
-
-/**
- * Implements hook_form_FORM_ID_alter().
- *
- * Modifies the user registration page to add the login ID and password fields.
- */
-function basic_webmail_form_user_register_form_alter(&$form, &$form_state, $form_id) {
-  // If the user is allowed to access Basic webmail, and the administrator has
-  // chosen to collect the login ID and password, then add the fields to the
-  // form.
-  if (user_access('access basic_webmail') && !variable_get('basic_webmail_account_info', 1)) {
-    _basic_webmail_form_user_form($form);
-  }
-} // End of basic_webmail_form_user_profile_form_alter() {
-
-/**
- * The form parts to add to the user forms above.
- */
-function _basic_webmail_form_user_form(&$form) {
-  $basic_webmail_username = '';
-
-  if (!empty($form['#user']->data['basic_webmail_username'])) {
-    $basic_webmail_username = $form['#user']->data['basic_webmail_username'];
-  }
-
-  $form['basic_webmail_email_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Basic webmail account settings'),
-    '#collapsible' => TRUE,
-    '#weight' => 1,
-  );
-  $form['basic_webmail_email_settings']['basic_webmail_username'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Email account login'),
-    '#default_value' => $basic_webmail_username,
-    '#description' => 'The login ID of your email account.',
-    '#required' => TRUE,
-  );
-  $form['basic_webmail_email_settings']['basic_webmail_password'] = array(
-    '#type' => 'password_confirm',
-    '#description' => 'The login password of your email account.',
-  );
-} // End of basic_webmail_form_user_register_form_form_alter() {
-
-
-/**
- * Implements hook_user_insert().
- * /
-function basic_webmail_user_insert(&$edit, $account, $category) {
-  if (variable_get('basic_webmail_account_info', 1)) {
-    $edit['data']['basic_webmail_username'] = $edit['mail'];
-    $edit['data']['basic_webmail_password'] = $edit['pass'];
-  }
-
-  $basic_webmail_common_inc = drupal_get_path('module', 'basic_webmail') . 'basic_webmail.common.inc';
-  include_once($basic_webmail_common_inc);
-
-  _basic_webmail_subscribe_to_mailboxes();
-} // End of basic_webmail_user().
-
-
-/**
- * Implements hook_user_update().
- * /
-function basic_webmail_user_update(&$edit, $account, $category) {
-  if ($category == 'account' && variable_get('basic_webmail_account_info', 1)) {
-    if ($edit['mail'] != $account->mail) {
-      $edit['data']['basic_webmail_username'] = $edit['mail'];
-    }
-    else {
-      $edit['data']['basic_webmail_username'] = $account->mail;
-    }
-
-    if ($edit['pass'] != '') {
-      $edit['data']['basic_webmail_password'] = $edit['pass'];
-    }
-    else {
-      $edit['data']['basic_webmail_password'] = $account->basic_webmail_password;
-    }
-  }
-
-  $basic_webmail_common_inc = drupal_get_path('module', 'basic_webmail') . '/basic_webmail.common.inc';
-  require($basic_webmail_common_inc);
-
-  _basic_webmail_subscribe_to_mailboxes();
-
-dpm('$edit:');
-dpm($edit);
-dpm('$account:');
-dpm($account);
-dpm('$category: '. $category);
-} // End of basic_webmail_user_update().
-
-
-/**
- * Implements hook_user_presave().
- */
-function basic_webmail_user_presave(&$edit, $account, $category) {
-//dpm('$edit:');
-//dpm($edit);
-//dpm('$account:');
-//dpm($account);
-  // Remove the incorrectly named password variable.
-  if (!empty($edit['basic_webmail_passsword'])) {
-    unset($edit['basic_webmail_passsword']);
-  }
-  if (!empty($edit['data']['basic_webmail_passsword'])) {
-    unset($edit['data']['basic_webmail_passsword']);
-  }
-
-  // Check to see if we need to save any information.
-  if ($category == 'account') {
-    // Initialize the variable to keep track of changes, so we don't access the
-    // mail server unnecessarily.
-    $changed = 0;
-
-    // We're providing our own fields to collect the login ID and password.
-    if (variable_get('basic_webmail_account_info', 1) == 0) {
-      // If the email address has changed, save it as the login id.
-      if (($account->data['basic_webmail_username'] != $edit['basic_webmail_username']) && !empty($edit['basic_webmail_username'])) {
-        $edit['data']['basic_webmail_username'] = $edit['basic_webmail_username'];
-        $changed++;
-      }
-
-      if (!empty($edit['basic_webmail_password'])) {
-        $edit['data']['basic_webmail_password'] = $edit['basic_webmail_password'];
-        $changed++;
-      }
-    }
-    // We're using the system provided fields for the login ID and password.
-    elseif (variable_get('basic_webmail_account_info', 1) == 1) {
-      // If the email address has changed, save it as the login id.
-      if (($account->data['basic_webmail_username'] != $edit['basic_webmail_username']) && !empty($edit['basic_webmail_username'])) {
-        $edit['data']['basic_webmail_username'] = $edit['basic_webmail_username'];
-        $changed++;
-      }
-
-      // If the password has changed, save it.
-      if (!empty($edit['basic_webmail_password'])) {
-        $edit['data']['basic_webmail_password'] = $edit['basic_webmail_password'];
-        $changed++;
-      }
-    }
-     // We're using the system provided fields for the login ID and password.
-   else {
-      // If the username has changed, save it as the login id.
-      if (($account->data['basic_webmail_username'] != $edit['basic_webmail_username']) && !empty($edit['basic_webmail_username'])) {
-        $edit['data']['basic_webmail_username'] = $edit['basic_webmail_username'];
-        $changed++;
-      }
-
-      // If the password has changed, save it.
-      if (!empty($edit['basic_webmail_password'])) {
-        $edit['data']['basic_webmail_password'] = $edit['basic_webmail_password'];
-        $changed++;
-      }
-    }
-
-//include_once('includes/password.inc');
-//dpm(user_hash_password($edit['basic_webmail_password']));
-
-    if ($changed > 0) {
-//      $basic_webmail_common_inc = drupal_get_path('module', 'basic_webmail') . '/basic_webmail.common.inc';
-//      include_once($basic_webmail_common_inc);
-      _basic_webmail_subscribe_to_mailboxes($account->uid);
-    }
-  }
-} // End of basic_webmail_user_presave().
-
-/** *******************************************************
- *
- *  End of hook_user() hooks.
- *
- *  ******************************************************/
-
-/**
- * Implements hook_mail().
- */
-function basic_webmail_mail($key, &$message, $params) {
-  if (!empty($params['headers'])) {
-    foreach ($params['headers'] as $key => $value) {
-      $message['headers'][$key] = $params['headers'][$key];
-    }
-  }
-  $message['subject'] = $params['subject'];
-  $message['body'] = $params['body'];
-} // End of basic_webmail_mail().
-
-
-/**
- * Implements hook_theme().
- * /
-function basic_webmail_theme() {
-  return array(
-    'basic_webmail_mail_list_form' => array(
-      'render element' => 'form',
-    ),
-  );
-} // End of basic_webmail_theme().
-
-
-/** *******************************************************
- *
- *  Administrative functions.
- *
- *  ******************************************************/
-
-
-/**
- * Administration settings form.
- *
- * @return
- *   The completed form definition.
- */
-function basic_webmail_admin_settings($form, &$form_state) {
-  $form = array();
-
-  $form['basic_webmail_general_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('General settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-  $options = array(
-    0 => "Add Basic webmail specific fields to collect the login ID and password",
-    1 => "Use the user's account email address and password for checking email",
-    2 => "Use the user's account name and password for checking email",
-  );
-  $form['basic_webmail_general_settings']['basic_webmail_account_info'] = array(
-    '#type' => 'radios',
-    '#title' => t("How shoud the account login ID and password be collected?"),
-    '#options' => $options,
-    '#default_value' => variable_get('basic_webmail_account_info', 1),
-    '#description' => t("Instead of providing additional form fields to get the user's email address and password, just use what is provided within the account settings."),
-  );
-  $max_file_uploads = ini_get ('max_file_uploads');
-  if (!empty($max_file_uploads)) {
-    $description = t("The number of attachments to allow on the contact form. The maximum number of allowed uploads may be limited by PHP. Your system's php.ini file has it set to @max_file_uploads. To change it, alter the max_file_uploads directive.", array('@max_file_uploads' => $max_file_uploads));
-  }
-  else {
-    $description = t("The number of attachments to allow on the contact form. The maximum number of allowed uploads may be limited by PHP. If necessary, check your system's PHP php.ini file for a max_file_uploads directive to change.");
-  }
-  $form['basic_webmail_general_settings']['basic_webmail_number_attachments'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Number of attachments'),
-    '#size' => 10,
-    '#default_value' => variable_get('basic_webmail_number_attachments', 3),
-    '#description' => $description,
-  );
-  $form['basic_webmail_general_settings']['basic_webmail_attachment_location'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Attachment location'),
-    '#default_value' => variable_get('basic_webmail_attachment_location', file_directory_path() . '/attachments'),
-    '#description' => t('The file path where to save message attachments.'),
-  );
-
-  $form['basic_webmail_listing_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Message listing settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-  $form['basic_webmail_listing_settings']['basic_webmail_messages_per_page'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Messages per page'),
-    '#size' => 10,
-    '#default_value' => variable_get('basic_webmail_messages_per_page', 25),
-    '#description' => t('The number of messages to show per page when viewing the listing.'),
-  );
-  $form['basic_webmail_listing_settings']['basic_webmail_subject_characters'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Number of characters to display'),
-    '#size' => 10,
-    '#default_value' => variable_get('basic_webmail_subject_characters', 40),
-    '#description' => t('This is the number of characters of the subject that are displayed in the message list before being truncated. Entering a zero (0) here will cause the listing to display all characters of the subject line, no matter how long it is.'),
-  );
-  $timestamp = REQUEST_TIME;
-  $small_date = format_date($timestamp, 'short');
-  $medium_date = format_date($timestamp);
-  $large_date = format_date($timestamp, $type = 'long');
-  $options = array(
-    'small' => t('Small (!small_date)', array('!small_date' => $small_date)),
-    'medium' => t('Medium (!medium_date)', array('!medium_date' => $medium_date)),
-    'large' => t('Long (!large_date)', array('!large_date' => $large_date)),
-    'custom' => t('Custom'),
-  );
-  $form['basic_webmail_listing_settings']['basic_webmail_format_option'] = array(
-    '#type' => 'radios',
-    '#title' => t('Date format option'),
-    '#options' => $options,
-    '#default_value' => variable_get('basic_webmail_format_option', 'small'),
-    '#description' => t('Specify how you want the date of the message displayed.'),
-  );
-  $form['basic_webmail_listing_settings']['basic_webmail_custom_format'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Custom format'),
-    '#default_value' => variable_get('basic_webmail_custom_format', 'D, M j, Y - g:i:s a'),
-    '#description' => t('Specify how you want the Custom date format configured, using the format options of the PHP !date function.',
-      array(
-        '!date' => l(t('date()', array(), array('langcode' => 'en')), 'http://php.net/manual/en/function.date.php')
-      ),
-      array(
-        'langcode' => 'en',
-      )
-    ),
-  );
-
-  $form['basic_webmail_server_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Server settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => FALSE,
-  );
-  $form['basic_webmail_server_settings']['basic_webmail_server_address'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Server address'),
-    '#default_value' => variable_get('basic_webmail_server_address', ''),
-    '#description' => t('The address to the server you wish to connect to.'),
-  );
-  $form['basic_webmail_server_settings']['basic_webmail_server_port'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Connection port'),
-    '#size' => 10,
-    '#default_value' => variable_get('basic_webmail_server_port', 143),
-    '#description' => t('The default IMAP port is 143, if one is not specified. If you are using SSL, the default port number is 993. If you are using TLS, the default port number is 143.'),
-  );
-  $form['basic_webmail_server_settings']['basic_webmail_secure_log_in'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Secure login'),
-    '#default_value' => variable_get('basic_webmail_secure_log_in', 0),
-    '#description' => t('Check to make a secure connection to your IMAP Server.'),
-  );
-  $form['basic_webmail_server_settings']['basic_webmail_use_ssl'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Encrypt session using SSL'),
-    '#default_value' => variable_get('basic_webmail_use_ssl', 0),
-    '#description' => t('Use SSL to connect to the server.'),
-  );
-  $form['basic_webmail_server_settings']['basic_webmail_validate_cert'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Validate certificate'),
-    '#default_value' => variable_get('basic_webmail_validate_cert', 0),
-    '#description' => t('When using a secure connection, validate the certificate.'),
-  );
-  $form['basic_webmail_server_settings']['basic_webmail_use_tls'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Encrypt session using TLS'),
-    '#default_value' => variable_get('basic_webmail_use_tls', 0),
-    '#description' => t('Use TLS to connect to the server.'),
-  );
-
-  return system_settings_form($form);
-} // End of basic_webmail_admin_settings().
-
-
-/**
- * Additional vaidation for the administration settings form.
- *
- * @param form_id
- *   The form ID of the passed form.
- * @param $form_state
- *   The form values which you may perform validation on.
- */
-function basic_webmail_admin_settings_validate($form, &$form_state) {
-  if ($form_state['values']['basic_webmail_format_option'] == 'custom' && $form_state['values']['basic_webmail_custom_format'] == '') {
-    form_set_error('basic_webmail_custom_format', t('You have specified Custom as your Format option for your Date format, but you have not specified the configuration of the Cuatom format. Either choose a different Format option, or specify the configuration of the Custom format.'));
-  }
-
-  if (!file_prepare_directory($form_state['values']['basic_webmail_attachment_location'], FILE_CREATE_DIRECTORY)) {
-    form_set_error('basic_webmail_attachment_location', t('The directory does not exist or is not writable, and there was a problem creating the path.'));
-  }
-
-  if ($form_state['values']['basic_webmail_use_ssl'] == 1 && $form_state['values']['basic_webmail_server_port'] == '143') {
-    form_set_error('basic_webmail_server_port', t('The normal port for secure IMAP is 993.'));
-  }
-} // End of basic_webmail_admin_settings_validate().
-
-
-/** *******************************************************
- *
- *  The main functions of the module.
- *
- *  ******************************************************/
-
-/**
- * Display the listing of messages.
- *
- * @param folder
- *   The name of the folder to open. If no folder is specified, the default
- *   of 'INBOX' is used.
- *
- * @return
- *   The formatted message listing.
- * /
-function basic_webmail_mail_list($folder = 'INBOX') {
-  $output = '';
-  $form = array();
-
-  // Set the title of the page to the current mailbox, if there is one.
-  if (arg(1)) {
-    drupal_set_title(t('!title', array('!title' => arg(1))));
-  }
-
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  $mailboxes = imap_getsubscribed($imap_resource, _basic_webmail_get_server_string(), '*');
-  if (!$mailboxes[4]) {
-    _basic_webmail_subscribe_to_mailboxes();
-  }
-
-  // Retrieve and display the list of folders.
-  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
-  if ($folders) {
-    /*
-    $output .= '<br />';
-
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
-    }
-
-    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
-    $output .= '<hr>';
-     *
-     * /
-    $output = '<br />';
-
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
-    }
-
-    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
-    $output .= '<hr>';
-    $form['folders'] = $output;
-  }
-  else {
-//    $output .= '<br />';
-    $form['folders'] = '<br />';
-  }
-
-  if (imap_num_msg($imap_resource) > 0) {
-    // Retrieve and display the mail in the current folder.
-    $threads = imap_thread($imap_resource);
-    if ($threads === FALSE) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error getting the list of messages: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-      return '<br />' . t('There was an error getting the list of messages: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
-    }
-    else {
-      // TODO Please review the conversion of this statement to the D7 database API syntax.
-      /* db_query('DELETE FROM {basic_webmail_messages} WHERE user_id = %d', $user->uid) * /
-      db_delete('basic_webmail_messages')
-        ->condition('user_id', $user->uid)
-        ->execute();
-
-      $total_messages = 0;
-      $new_messages = 0;
-
-      // Save the message information in a temporary table.
-      foreach ($threads as $key => $message_number) {
-        $tree = explode('.', $key);
-        if ($tree[1] == 'num' && $message_number > 0) {
-          $message_header = imap_headerinfo($imap_resource, $message_number);
-
-          if ($message_header->Deleted == ' ') {
-            $total_messages++;
-
-            // Check for attachments.
-            // Get the message parts list.
-            $parts_list = _basic_webmail_get_parts_list($imap_resource, $message_number);
-            // Iterate over the parts list.
-            foreach ($parts_list as $part_id => $part_array) {
-              if (!empty($part_array[0]) && !empty($part_array[1])) {
-                $attachment_exists = 1;
-                continue;
-              }
-              else {
-                $attachment_exists = 0;
-              }
-            }
-
-            // Check if message was answered.
-            if ($message_header->Answered == 'A') {
-              $message_answered = 1;
-            }
-            else {
-              $message_answered = 0;
-            }
-
-            $number_characters = variable_get('basic_webmail_subject_characters', 40);
-            if (empty($number_characters)) {
-              $message_subject_link = l(_basic_webmail_decode_mime_str($message_header->subject), 'basic_webmail/message/' . $message_number . '/' . $folder);
-            }
-            else {
-              $message_subject_link = l(truncate_utf8(_basic_webmail_decode_mime_str($message_header->subject), $number_characters, TRUE, TRUE), 'basic_webmail/message/' . $message_number . '/' . $folder);
-            }
-
-            if ($message_header->Recent == 'N' || $message_header->Unseen == 'U') {
-              $new_messages++;
-              $message_unread = 1;
-
-              if (empty($message_header->subject)) {
-                $message_subject = '<strong>' . l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder) . '</strong>';
-              }
-              else {
-                $message_subject = '<strong>' . $message_subject_link . '</strong>';
-              }
-            }
-            else {
-              $message_unread = 0;
-
-              if (empty($message_header->subject)) {
-                $message_subject = l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder);
-              }
-              else {
-                $message_subject = $message_subject_link;
-              }
-            }
-
-//            if ($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host == '@') {
-            if (empty($message_header->from[0]->mailbox) && empty($message_header->from[0]->host)) {
-              $from_address = '(Unknown)';
-            }
-            elseif (!empty($message_header->from[0]->personal)) {
-              $from_address = l(_basic_webmail_decode_mime_str($message_header->from[0]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>');
-            }
-            else {
-              $from_address = l($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host, 'basic_webmail/sendmail/' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host);
-            }
-
-            if (empty($message_header->date)) {
-              $message_date = 0;
-            }
-            else {
-              $message_date = _basic_webmail_mail_list_process_message_date($message_header->date);
-            }
-
-            // imap_uid($imap_resource, $message_number)
-            // TODO Please review the conversion of this statement to the D7 database API syntax.
-            /* db_query('INSERT INTO {basic_webmail_messages} (user_id, message_number, message_subject, from_address, message_date, message_unread, message_answered, attachment_exists) VALUES (%d, %d, "%s", "%s", "%s", %d, %d, %d)', $user->uid, $message_number, $message_subject, $from_address, $message_date, $message_unread, $message_answered, $attachment_exists) * /
-            $id = db_insert('basic_webmail_messages')
-              ->fields(array(
-                'user_id' => $user->uid,
-                'message_number' => $message_number,
-                'message_subject' => $message_subject,
-                'from_address' => $from_address,
-                'message_date' => $message_date,
-                'message_unread' => $message_unread,
-                'message_answered' => $message_answered,
-                'attachment_exists' => $attachment_exists,
-              ))
-              ->execute();
-            if (!$id) {
-              watchdog('basic_webmail', 'There was an error inserting message records into the basic_webmail_messages table.', array(), WATCHDOG_ERROR);
-            }
-          }
-        }
-
-        // Set the title of the page to the current mailbox, if there is one.
-        if (arg(1)) {
-          if ($new_messages) {
-            drupal_set_title(t('!mail_box (!total_messages total, !new_messages unread)', array('!mail_box' => arg(1), '!total_messages' => $total_messages, '!new_messages' => $new_messages)));
-          }
-          else {
-            drupal_set_title(t('!mail_box (!total_messages total)', array('!mail_box' => arg(1), '!total_messages' => $total_messages)));
-          }
-        }
-        else {
-          if ($new_messages) {
-            drupal_set_title(t('Email (!total_messages total, !new_messages unread)', array('!total_messages' => $total_messages, '!new_messages' => $new_messages)));
-          }
-          else {
-            drupal_set_title(t('Email (!total_messages total)', array('!total_messages' => $total_messages)));
-          }
-        }
-      }
-
-      // Add a link to a blank composition form.
-//      $output .= l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
-      $form['comoposition'] = l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
-
-      // Create the form and add it to the output.
-//      $output .= drupal_get_form('basic_webmail_mail_list_form', $folder);
-      // From http://drupal.org/node/224333#menu_callback_array:
-      // "If you find yourself calling render() or drupal_render(), you're
-      // probably making a mistake."
-      // See also http://drupal.org/node/224333#unrendered.
-      $form['messages'] = drupal_get_form('basic_webmail_mail_list_form', $folder);
-//dpm('$message_list_form_array');
-//dpm($message_list_form_array);
-      //$message_list_form_rendered = drupal_render($message_list_form_array);
-//dpm('$message_list_form_rendered');
-//dpm($message_list_form_rendered);
-      //$output .= $message_list_form_rendered;
-
-      // Add the page numbers at the bottom of the table.
-//      $output .= '<br />' . theme('pager', array('tags' => NULL, 'element' => 0));
-    }
-  }
-  else {
-    /*
-    $output .= 'You have no email in this mailbox.';
-    // Add a link to a blank composition form.
-    $output .= '<hr />' . l(t('Compose new message'), 'basic_webmail/sendmail');
-     *
-     * /
-
-    $form['empty'] = 'You have no email in this mailbox.';
-    // Add a link to a blank composition form.
-    $form['comoposition'] = '<hr />' . l(t('Compose new message'), 'basic_webmail/sendmail');
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-//dpm('$output');
-//dpm($output);
-//  return $output;
-  return $form;
-} // End of basic_webmail_mail_list().
-
-
-/**
- * Construct the form for the message listing w/checkboxes.
- *
- * @return
- *   The completed form definition.
- * /
-function basic_webmail_mail_list_form($form, &$form_state, $folder = 'INBOX') {
-  // Load the custom CSS file.
-  drupal_add_css(drupal_get_path('module', 'basic_webmail') . '/basic_webmail.css');
-
-  // Set the path to the icons.
-//  $icon_path = drupal_get_path('module', 'basic_webmail') . '/icons/';
-
-  // Display the message information in a sortable table.
-  $header = array(
-    array(),
-//    array('data' => t('No.'),    'field' => 'message_number'),
-    array('data' => t('Unread'), 'field' => 'message_unread'),
-//    array('data' => t('U'), 'field' => 'message_unread'),
-//    array('data' => theme_image($icon_path . 'mini-mail.png'), 'field' => 'message_unread'),
-    array('data' => t('Att.'), 'field' => 'attachment_exists'),
-//    array('data' => t('A'), 'field' => 'attachment_exists'),
-//    array('data' => theme_image($icon_path . 'mini-doc.png'), 'field' => 'attachment_exists'),
-    array('data' => t('Ans.'), 'field' => 'message_answered'),
-//    array('data' => t('R'), 'field' => 'message_answered'),
-//    array('data' => theme_image($icon_path . 'mini-edit.png'), 'field' => 'message_answered'),
-    array('data' => t('Subject'), 'field' => 'message_subject'),
-    array('data' => t('From'), 'field' => 'from_address'),
-    array('data' => t('Date/Time'), 'field' => 'message_date', 'sort' => 'desc'),
-  );
-
-//  $query = 'SELECT message_number, message_unread, attachment_exists, message_answered, message_subject, from_address, message_date FROM {basic_webmail_messages} WHERE user_id = %d';
-  $row_limit = variable_get('basic_webmail_messages_per_page', 25);
-  $result = db_select('basic_webmail_messages', 'm')
-    ->fields('m', array('message_number', 'message_unread', 'attachment_exists', 'message_answered', 'message_subject', 'from_address', 'message_date'))
-    ->extend('PagerDefault')
-    ->limit($row_limit)
-    ->extend('TableSort')
-    ->orderByHeader($header)
-    ->execute();
-//  $tablesort = tablesort_sql($header);
-//  $result = pager_query($query . $tablesort, variable_get('basic_webmail_messages_per_page', 25), 0, NULL, $user->uid);
-
-//  $rows = array();
-
-//  while ($message = db_fetch_object($result)) {
-  foreach ($result as $message) {
-    // Checkbox for actions.
-    $messages[$message->message_number] = '';
-//    $form['message_number'][$message->message_number] = array('#value' => $message->message_number);
-
-    // If the message is unread, show an icon indentifing that, otherwise, show
-    // nothing.
-    $message_unread = '';
-    if ($message->message_unread) {
-      $message_unread = theme_image(array(
-        'path' => 'misc/menu-leaf.png',
-        //'path' => $icon_path . 'mini-mail.png',
-        'alt' => 'Generic icon indicating message is unread.',
-        'title' => t('You have not read this message.'),
-        'attributes' => array(),
-       ));
-    }
-    $form['message_unread'][$message->message_number] = array(
-      '#value' => $message_unread,
-      '#prefix' => '<div class="column-center">',
-      '#suffix' => '</div>',
-    );
-
-    // If the message has an attachment, show an icon indentifing that,
-    // otherwise, show nothing.
-    $message_attachment = '';
-    if ($message->attachment_exists) {
-      $message_attachment = theme_image(array(
-        'path' => 'misc/menu-leaf.png',
-        //'path' => $icon_path . 'mini-doc.png',
-        'alt' => 'Generic icon indicating message has an attachment.',
-        'title' => t('This message has one or more attachments.'),
-        'attributes' => array(),
-      ));
-    }
-    $form['attachment_exists'][$message->message_number] = array(
-      '#value' => $message_attachment,
-      '#prefix' => '<div class="column-center">',
-      '#suffix' => '</div>',
-    );
-
-    // If the message has been answered, show an icon indentifing that,
-    // otherwise, show nothing.
-    $message_answered = '';
-    if ($message->message_answered) {
-      $message_answered = theme_image(array(
-        'path' => 'misc/menu-leaf.png',
-        //'path' => $icon_path . 'misc/mini-edit.png',
-        'alt' => 'Generic icon indicating message has been answered.',
-        'title' => t('You have replied to this message.'),
-        'attributes' => array(),
-      ));
-    }
-    $form['message_answered'][$message->message_number] = array(
-      '#value' => $message_answered,
-      '#prefix' => '<div class="column-center">',
-      '#suffix' => '</div>',
-    );
-
-    // Show the message subject.
-    $form['message_subject'][$message->message_number] = array('#value' => $message->message_subject);
-
-    // Show the address of the party who the message is from.
-    $form['from_address'][$message->message_number] = array('#value' => $message->from_address);
-
-    // Show the date the message was sent.
-    if ($message->message_date == 0) {
-      $form['message_date'][$message->message_number] = array('#value' => '(Invalid date.)');
-    }
-    else {
-      $format_option = variable_get('basic_webmail_format_option', 'small');
-
-      if ($format_option == 'custom') {
-        $custom_format = variable_get('basic_webmail_custom_format', 'D, M j, Y - g:i:s a');
-        $message->message_date = format_date($message->message_date, $format_option, $custom_format);
-      }
-      else {
-        $message->message_date = format_date($message->message_date, $format_option);
-      }
-
-      $form['message_date'][$message->message_number] = array('#value' => $message->message_date);
-    }
-  }
-
-  $form['messages'] = array(
-    '#type' => 'checkboxes',
-    '#options' => $messages,
-  );
-
-  $form['operation'] = array(
-    '#type' => 'select',
-    '#title' => t('With checked'),
-    '#default_value' => 'read',
-    '#options' => array(
-      'delete' => t('Delete'),
-      'read' => t('Mark read'),
-      'unread' => t('Mark unread'),
-      'copy_to' => t('Copy'),
-      'move_to' => t('Move'),
-    ),
-    '#prefix' => '<div class="container-inline">',
-  );
-
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Get the list of folders from the server.
-  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
-  if ($folders) {
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-
-      if ($brief_folder_name != $folder) {
-        $folder_names[$brief_folder_name] = $brief_folder_name;
-      }
-    }
-  }
-
-  $form['folder_name'] = array(
-    '#type' => 'select',
-    '#title' => t('The folder to copy or move to'),
-    '#options' => $folder_names,
-  );
-
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Update'),
-    '#suffix' => '</div>',
-  );
-
-  $form['folder'] = array(
-    '#type' => 'hidden',
-    '#value' => $folder,
-  );
-
-  $form['pager'] = array('#markup' => theme('pager'));
-
-  return $form;
-} // End of basic_webmail_mail_list_form().
-
-
-/**
- * Display the listing of messages.
- *
- * @param folder
- *   The name of the folder to open. If no folder is specified, the default
- *   of 'INBOX' is used.
- *
- * @return
- *   The formatted message listing.
- */
-function basic_webmail_mail_list_form($folder = 'INBOX') {
-
-
-  /**
-   * @TODO: Add the page title.
-   *
-  // Set the title of the page to the current mailbox, if there is one.
-  if (arg(1)) {
-    drupal_set_title(t('!title', array('!title' => arg(1))));
-  }
-   */
-
-
-  /**
-   * @TODO: Add the custom CSS?:
-   *
-  // Load the custom CSS file.
-  drupal_add_css(drupal_get_path('module', 'basic_webmail') . '/basic_webmail.css');
-   */
-
-
-  $form = array();
-
-  // Create the table header for the message listing.
-  $header = _basic_webmail_create_message_list_header();
-
-  // Update the saved message information.
-  _basic_webmail_update_stored_message_list($folder);
-
-  // Get the message list.
-  $message_list = _basic_webmail_get_message_list_data($header);
-
-  $folder_list = _basic_webmail_get_folder_list($folder);
-
-
-  /**
-   * @TODO: Add the folder list to the top of the page:
-   *
-  if ($folder_list) {
-    /*
-    $output .= '<br />';
-
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
-    }
-
-    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
-    $output .= '<hr>';
-     *
-     * /
-    $output = '<br />';
-
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
-    }
-
-    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
-    $output .= '<hr>';
-    $form['folders'] = $output;
-  }
-
-   */
-
-
-  /**
-   * @TODO: Add the compisition link:
-   *
-      // Add a link to a blank composition form.
-//      $output .= l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
-      $form['comoposition'] = l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
-   */
-
-
-  // Create the table/form.
-  $form['message_list'] = array (
-    '#type' => 'tableselect',
-    '#header' => $header,
-    '#options' => $message_list,
-    '#empty' => t('You have no email in this mailbox.'),
-  );
-
-
-  // Add the operation select list.
-  $form['operation'] = array(
-    '#type' => 'select',
-    '#title' => t('With checked'),
-    '#default_value' => 'read',
-    '#options' => array(
-      'delete' => t('Delete'),
-      'read' => t('Mark read'),
-      'unread' => t('Mark unread'),
-      'copy_to' => t('Copy'),
-      'move_to' => t('Move'),
-    ),
-    '#prefix' => '<div class="container-inline">',
-  );
-
-  // Add the select list with the list of folders.
-  $form['folder_name'] = array(
-    '#type' => 'select',
-    '#title' => t('The folder to copy or move to'),
-    '#options' => $folder_list,
-  );
-
-  // Add the button.
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Update'),
-    '#suffix' => '</div>',
-  );
-
-  // Save the current folder name for later use.
-  $form['folder'] = array(
-    '#type' => 'hidden',
-    '#value' => $folder,
-  );
-
-  // Add the pager at the bottom of the form.
-  $form['pager'] = array('#markup' => theme('pager'));
-
-  return $form;
-} // End of basic_webmail_mail_list_form().
-
-
-/**
- * Create the table header for the message listing.
- *
- * @return
- *   An array containing the table header.
- */
-function _basic_webmail_create_message_list_header() {
-  // Set the path to the icons.
-//  $icon_path = drupal_get_path('module', 'basic_webmail') . '/icons/';
-
-  // Specify the header information for the message list.
-  return array(
-    'message_unread' => array('data' => t('Unread'), 'field' => 'message_unread'),
-//    'message_unread' => array('data' => t('U'), 'field' => 'message_unread'),
-//    'message_unread' => array('data' => theme_image($icon_path . 'mini-mail.png'), 'field' => 'message_unread'),
-    'attachment_exists' => array('data' => t('Att.'), 'field' => 'attachment_exists'),
-//    'attachment_exists' => array('data' => t('A'), 'field' => 'attachment_exists'),
-//    'attachment_exists' => array('data' => theme_image($icon_path . 'mini-doc.png'), 'field' => 'attachment_exists'),
-    'message_answered' => array('data' => t('Ans.'), 'field' => 'message_answered'),
-//    'message_answered' => array('data' => t('R'), 'field' => 'message_answered'),
-//    'message_answered' => array('data' => theme_image($icon_path . 'mini-edit.png'), 'field' => 'message_answered'),
-    'message_subject' => array('data' => t('Subject'), 'field' => 'message_subject'),
-    'from_address' => array('data' => t('From'), 'field' => 'from_address'),
-    'message_date' => array('data' => t('Date/Time'), 'field' => 'message_date', 'sort' => 'desc'),
-  );
-} // End of _basic_webmail_create_message_list_header().
-
-
-/**
- * Updates the saved message list information.
- *
- * @param folder
- *   The name of the folder to open. If no folder is specified, the default
- *   of 'INBOX' is used.
- */
-function _basic_webmail_update_stored_message_list($folder = 'INBOX') {
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  $mailboxes = imap_getsubscribed($imap_resource, _basic_webmail_get_server_string(), '*');
-  if (!$mailboxes[4]) {
-    _basic_webmail_subscribe_to_mailboxes();
-  }
-
-  if (imap_num_msg($imap_resource) > 0) {
-    // Retrieve and display the mail in the current folder.
-    $threads = imap_thread($imap_resource);
-    if ($threads === FALSE) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error getting the list of messages: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-      return '<br />' . t('There was an error getting the list of messages: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
-    }
-    else {
-      db_delete('basic_webmail_messages')
-        ->condition('user_id', $user->uid)
-        ->execute();
-
-      // Save the message information in a temporary table.
-      foreach ($threads as $key => $message_number) {
-        $tree = explode('.', $key);
-        if ($tree[1] == 'num' && $message_number > 0) {
-          $message_header = imap_headerinfo($imap_resource, $message_number);
-
-          if ($message_header->Deleted == ' ') {
-            // Check for attachments.
-            // Get the message parts list.
-            $parts_list = _basic_webmail_get_parts_list($imap_resource, $message_number);
-            // Iterate over the parts list.
-            foreach ($parts_list as $part_id => $part_array) {
-              if (!empty($part_array[0]) && !empty($part_array[1])) {
-                $attachment_exists = 1;
-                continue;
-              }
-              else {
-                $attachment_exists = 0;
-              }
-            }
-
-            // Check if message was answered.
-            if ($message_header->Answered == 'A') {
-              $message_answered = 1;
-            }
-            else {
-              $message_answered = 0;
-            }
-
-            // Create a link to the message.
-            $number_characters = variable_get('basic_webmail_subject_characters', 40);
-            if (empty($number_characters)) {
-              $message_subject_link = l(_basic_webmail_decode_mime_str($message_header->subject), 'basic_webmail/message/' . $message_number . '/' . $folder);
-            }
-            else {
-              $message_subject_link = l(truncate_utf8(_basic_webmail_decode_mime_str($message_header->subject), $number_characters, TRUE, TRUE), 'basic_webmail/message/' . $message_number . '/' . $folder);
-            }
-
-            // Save the message's subject and read status.
-            if ($message_header->Recent == 'N' || $message_header->Unseen == 'U') {
-              $message_unread = 1;
-
-              if (empty($message_header->subject)) {
-                $message_subject = '<strong>' . l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder) . '</strong>';
-              }
-              else {
-                $message_subject = '<strong>' . $message_subject_link . '</strong>';
-              }
-            }
-            else {
-              $message_unread = 0;
-
-              if (empty($message_header->subject)) {
-                $message_subject = l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder);
-              }
-              else {
-                $message_subject = $message_subject_link;
-              }
-            }
-
-            // Save the sender's information.
-            if (empty($message_header->from[0]->mailbox) && empty($message_header->from[0]->host)) {
-              $from_address = '(Unknown)';
-            }
-            elseif (!empty($message_header->from[0]->personal)) {
-              $from_address = l(_basic_webmail_decode_mime_str($message_header->from[0]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>');
-            }
-            else {
-              $from_address = l($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host, 'basic_webmail/sendmail/' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host);
-            }
-
-            // Save the message's date.
-            if (empty($message_header->date)) {
-              $message_date = 0;
-            }
-            else {
-              $message_date = _basic_webmail_message_list_process_message_date($message_header->date);
-            }
-
-            // imap_uid($imap_resource, $message_number)
-            $id = db_insert('basic_webmail_messages')
-              ->fields(array(
-                'user_id' => $user->uid,
-                'message_number' => $message_number,
-                'message_subject' => $message_subject,
-                'from_address' => $from_address,
-                'message_date' => $message_date,
-                'message_unread' => $message_unread,
-                'message_answered' => $message_answered,
-                'attachment_exists' => $attachment_exists,
-              ))
-              ->execute();
-            if (!$id) {
-              watchdog('basic_webmail', 'There was an error inserting message records into the basic_webmail_messages table.', array(), WATCHDOG_ERROR);
-            }
-          }
-        }
-      }
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-} // End of _basic_webmail_update_stored_message_list().
-
-/**
- * Format the date for the message listing.
- *
- * @param $message_header_date
- *   The original date from the header of the message.
- *
- * @return
- *   The reformatted date.
- */
-function _basic_webmail_message_list_process_message_date($message_header_date) {
-  // Format the date so we can sort on it.
-  $message_hour = (int) drupal_substr($message_header_date, strpos($message_header_date, ':') - 2, 2);
-  $message_minute = (int) drupal_substr($message_header_date, strpos($message_header_date, ':') + 1, 2);
-  $message_second = (int) drupal_substr($message_header_date, strpos($message_header_date, ':') + 4, 2);
-
-  if (strpos($message_header_date, ',') === FALSE) {
-    // The day is the first item in the date string.
-    $message_day_start = 0;
-    $message_day_length = (int) strpos($message_header_date, ' ', $message_day_start) - $message_day_start;
-    $message_day = (int) drupal_substr($message_header_date, $message_day_start, $message_day_length);
-
-    // Start at the first space.
-    $message_month_start = (int) strpos($message_header_date, ' ') + 1;
-    $message_month_length = (int) strpos($message_header_date, ' ', $message_month_start) - $message_month_start;
-
-    // Start at the second space.
-    $message_year_start = (int) strpos($message_header_date, ' ', strpos($message_header_date, ' ') + 1) + 1;
-    $message_year_length = (int) strpos($message_header_date, ' ', $message_year_start) - $message_year_start;
-    $message_year = (int) drupal_substr($message_header_date, $message_year_start, $message_year_length);
-  }
-  else {
-    // Start at the first space.
-    $message_day_start = (int) strpos($message_header_date, ' ') + 1;
-    $message_day_length = (int) strpos($message_header_date, ' ', $message_day_start) - $message_day_start;
-    $message_day = (int) drupal_substr($message_header_date, $message_day_start, $message_day_length);
-
-    // Start at the second space.
-    $message_month_start = (int) strpos($message_header_date, ' ', strpos($message_header_date, ' ') + 1) + 1;
-    $message_month_length = (int) strpos($message_header_date, ' ', $message_month_start) - $message_month_start;
-
-    // Start at the third space.
-    $message_year_start = (int) strpos($message_header_date, ' ', strpos($message_header_date, ' ', strpos($message_header_date, ' ') + 1) + 1) + 1;
-    $message_year_length = (int) strpos($message_header_date, ' ', $message_year_start) - $message_year_start;
-    $message_year = (int) drupal_substr($message_header_date, $message_year_start, $message_year_length);
-  }
-
-  switch (drupal_substr($message_header_date, $message_month_start, $message_month_length)) {
-    case 'Jan':
-      $message_month = 1;
-      break;
-    case 'Feb':
-      $message_month = 2;
-      break;
-    case 'Mar':
-      $message_month = 3;
-      break;
-    case 'Apr':
-      $message_month = 4;
-      break;
-    case 'May':
-      $message_month = 5;
-      break;
-    case 'Jun':
-      $message_month = 6;
-      break;
-    case 'Jul':
-      $message_month = 7;
-      break;
-    case 'Aug':
-      $message_month = 8;
-      break;
-    case 'Sep':
-      $message_month = 9;
-      break;
-    case 'Oct':
-      $message_month = 10;
-      break;
-    case 'Nov':
-      $message_month = 11;
-      break;
-    case 'Dec':
-      $message_month = 12;
-      break;
-  }
-
-  $message_date = mktime($message_hour, $message_minute, $message_second, $message_month, $message_day, $message_year);
-
-  return $message_date;
-} // End of _basic_webmail_message_list_process_message_date().
-
-
-/**
- * Retrieves the list of messages.
- *
- * @param $header
- *   The original header that was created in
- *   _basic_webmail_create_message_list_header().
- *
- * @return
- *   The list of messages.
- */
-function _basic_webmail_get_message_list_data($header) {
-  // Initialize variables.
-  $message_unread = '';
-  $message_attachment = '';
-  $message_answered = '';
-  $message_date = '(Invalid date.)';
-  $message_list = array();
-
-  // Specifiy the number of messages to display on a page.
-  $row_limit = variable_get('basic_webmail_messages_per_page', 25);
-
-  // Construct and execute the database query.
-  $result = db_select('basic_webmail_messages', 'm')
-    ->fields('m', array('message_number', 'message_unread', 'attachment_exists', 'message_answered', 'message_subject', 'from_address', 'message_date'))
-    ->extend('PagerDefault')
-    ->limit($row_limit)
-    ->extend('TableSort')
-    ->orderByHeader($header)
-    ->execute();
-
-  // Iterate through the messages.
-  foreach ($result as $message) {
-    // If the message is unread, show the icon.
-    if ($message->message_unread) {
-      $message_unread = theme_image(array(
-        'path' => 'misc/menu-leaf.png',
-        //'path' => $icon_path . 'mini-mail.png',
-        'alt' => 'Generic icon indicating message is unread.',
-        'title' => t('You have not read this message.'),
-        'attributes' => array(),
-       ));
-    }
-
-    // If the message has an attachment, show the icon.
-    if ($message->attachment_exists) {
-      $message_attachment = theme_image(array(
-        'path' => 'misc/menu-leaf.png',
-        //'path' => $icon_path . 'mini-doc.png',
-        'alt' => 'Generic icon indicating message has an attachment.',
-        'title' => t('This message has one or more attachments.'),
-        'attributes' => array(),
-      ));
-    }
-
-    // If the message has been answered, show the icon.
-    if ($message->message_answered) {
-      $message_answered = theme_image(array(
-        'path' => 'misc/menu-leaf.png',
-        //'path' => $icon_path . 'misc/mini-edit.png',
-        'alt' => 'Generic icon indicating message has been answered.',
-        'title' => t('You have replied to this message.'),
-        'attributes' => array(),
-      ));
-    }
-
-    // The date the message was sent.
-    if ($message->message_date != 0) {
-      $format_option = variable_get('basic_webmail_format_option', 'small');
-
-      if ($format_option == 'custom') {
-        $custom_format = variable_get('basic_webmail_custom_format', 'D, M j, Y - g:i:s a');
-        $message->message_date = format_date($message->message_date, $format_option, $custom_format);
-      }
-      else {
-        $message->message_date = format_date($message->message_date, $format_option);
-      }
-
-      $message_date = $message->message_date;
-    }
-
-    $message_list[$message->message_number] = array(
-      'message_unread' => $message_unread,
-      'attachment_exists' => $message_attachment,
-      'message_answered' => $message_answered,
-      'message_subject' => $message->message_subject,
-      'from_address' => $message->from_address,
-      'message_date' => $message_date,
-    );
-  }
-
-  return $message_list;
-} // End of _basic_webmail_message_list_process_message_date().
-
-
-/**
- * Retrieves the list of folders.
- *
- * @param folder
- *   The name of the folder to open. If no folder is specified, the default
- *   of 'INBOX' is used.
- *
- * @return
- *   The folder listing.
- */
-function _basic_webmail_get_folder_list($folder = 'INBOX') {
-  global $user;
-  // Connect to the server and retrieve a connection to the mailbox.
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Get the list of folders from the server.
-  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
-  if ($folders) {
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-
-      if ($brief_folder_name != $folder) {
-        $folder_list[$brief_folder_name] = $brief_folder_name;
-      }
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  return $folder_list;
-} // End of _basic_webmail_get_folder_list().
-
-
-/**
- * Perform an action on a group of messages.
- *
- * @param form_id
- *   The form ID of the passed form.
- * @param $form_state
- *   The form values of the passed form.
- */
-function basic_webmail_mail_list_form_submit($form, &$form_state) {
-  $operation = $form_state['values']['operation'];
-  // Filter out unselected messages.
-  $messages = array_filter($form_state['values']['messages']);
-
-  if (isset($messages) && is_array($messages)) {
-    // Connect to the server and retrieve a connection to the mailbox.
-    global $user;
-    $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['folder']);
-    if (!$imap_resource) {
-      drupal_set_title(t('Error'));
-      $output .= '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-      $form_state['redirect'] = $output;
-    }
-
-    switch ($operation) {
-      case 'delete':
-        _basic_webmail_mail_list_form_submit_delete($form_state, $messages, $imap_resource);
-        break;
-
-      case 'read':
-        _basic_webmail_mail_list_form_submit_mark_read($form_state, $messages, $imap_resource);
-        break;
-
-      case 'unread':
-        _basic_webmail_mail_list_form_submit_mark_unread($form_state, $messages, $imap_resource);
-        break;
-
-      case 'copy_to':
-        _basic_webmail_mail_list_form_submit_copy_to($form_state, $messages, $imap_resource);
-        break;
-
-      case 'move_to':
-        _basic_webmail_mail_list_form_submit_move_to($form_state, $messages, $imap_resource);
-        break;
-    }
-
-    // Clean up.
-    if (!imap_close($imap_resource)) {
-      watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    }
-  }
-
-  // Send the user back to the page they were looking at.
-  $orig_path = drupal_get_destination();
-  $orig_length = drupal_strlen($orig_path);
-  $orig_start = strpos($orig_path, '=');
-  $new_path = drupal_substr($orig_path, $orig_start + 1, $orig_length);
-
-  // Clean up the converted characters.
-  $new_path = str_replace('%25', '%', $new_path);
-  $new_path = str_replace('%2F', '/', $new_path);
-  $new_path = str_replace('%3F', '?', $new_path);
-  $new_path = str_replace('%3D', '=', $new_path);
-  $new_path = str_replace('%26', '&', $new_path);
-
-  // Setup the return parameters.
-  $query_point = strpos($new_path, '?');
-  if ($query_point === FALSE) {
-    $dest_path = $new_path;
-    $dest_query = NULL;
-  }
-  else {
-    $dest_path = drupal_substr($new_path, 0, strpos($new_path, '?'));
-    $dest_query = drupal_substr($new_path, strpos($new_path, '?') + 1, drupal_strlen($new_path));
-  }
-
-  // Bye, bye, baby.
-  $form_state['redirect'] = array($dest_path, $dest_query);
-} // End of basic_webmail_mail_list_form_submit().
-
-
-/** *******************************************************
- *
- *  Themeing functions.
- *
- *  ******************************************************/
-
-
-/**
- * Theme the message listing page.
- *
- * @param form
- *   The form to theme.
- *
- * @return
- *   The themed listing.
- * /
-function theme_basic_webmail_mail_list_form($variables) {
-  $form = $variables['form'];
-  // Set the path to the icons.
-//  $icon_path = drupal_get_path('module', 'basic_webmail') . '/icons/';
-
-  // Overview table:
-  // TODO Please change this theme call to use an associative array for the $variables parameter.
-  $header = array(
-    theme('table_select_header_cell'),
-    //    array('data' => t('No.'),    'field' => 'message_number'),
-    array(
-      'data' => t('Unread'),
-      'field' => 'message_unread',
-    ),
-    //    array('data' => t('U'),    'field' => 'message_unread'), //    array('data' => theme_image($icon_path . 'mini-mail.png'),    'field' => 'message_unread'),
-    array(
-      'data' => t('Att.'),
-      'field' => 'attachment_exists',
-    ),
-    //    array('data' => t('A'),   'field' => 'attachment_exists'), //    array('data' => theme_image($icon_path . 'mini-doc.png'),   'field' => 'attachment_exists'),
-    array(
-      'data' => t('Ans.'),
-      'field' => 'message_answered',
-    ),
-    //    array('data' => t('R'),  'field' => 'message_answered'), //    array('data' => theme_image($icon_path . 'mini-edit.png'),  'field' => 'message_answered'),
-    array(
-      'data' => t('Subject'),
-      'field' => 'message_subject',
-    ),
-    array(
-      'data' => t('From'),
-      'field' => 'from_address',
-    ),
-    array(
-      'data' => t('Date/Time'),
-      'field' => 'message_date',
-      'sort' => 'desc',
-    ),
-  );
-
-  $output = drupal_render($form['options']);
-
-  if (isset($form['message_subject']) && is_array($form['message_subject'])) {
-    foreach (element_children($form['message_subject']) as $key) {
-      $rows[] = array(
-        drupal_render($form['messages'][$key]),
-        //        drupal_render($form['message_number'][$key]),
-        drupal_render($form['message_unread'][$key]),
-        drupal_render($form['attachment_exists'][$key]),
-        drupal_render($form['message_answered'][$key]),
-        drupal_render($form['message_subject'][$key]),
-        drupal_render($form['from_address'][$key]),
-        drupal_render($form['message_date'][$key]),
-      );
-    }
-  }
-  else {
-    $rows[] = array(array(
-        'data' => t('You have no email.'),
-        'colspan' => '6',
-      ));
-  }
-
-  $output .= theme('table', array('header' => $header, 'rows' => $rows));
-  $output .= drupal_render_children($form);
-
-  return $output;
-} // End of theme_basic_webmail_mail_list_form().
-
-
-/** *******************************************************
- *
- *  Private helper functions that do the main work of the module.
- *
- *  ******************************************************/
-
-
-/**
- * Reports error messages.
- *
- * @param message
- *   The additional text to be saved and/or displayed.
- * @param display
- *   A boolean value to indicate whether to display the error message to the
- *   user or not.
- * @param log
- *   A boolean value to indicate whether to save the error message to the logs
- *   or not.
- * @param severity
- *   The severity of the message, as per RFC 3164. See
- *   http://api.drupal.org/api/drupal/includes--bootstrap.inc/group/logging_severity_levels/7
- *   for more information.
- */
-function _basic_webmail_report_error($message = '', $display = TRUE, $log = TRUE, $severity = WATCHDOG_ERROR) {
-/*
-      $last_error = imap_last_error();
-      if ($last_error === FALSE) {
-        $last_error = t('There was no additional information returned by the system.');
-      }
-      drupal_set_message($last_error);
-*/
-  $last_error = imap_last_error();
-  if ($last_error === FALSE) {
-    $last_error = 'There was no additional information provided by the system.';
-  }
-
-  if ($display) {
-    if (!empty($message)) {
-
-    }
-    else {
-      drupal_set_message(t('There was an error connecting to the server: @last_error', array('@last_error' => $last_error)), 'error');
-    }
-  }
-
-  if ($log) {
-    if (!empty($message)) {
-      watchdog('basic_webmail', $message . ': @last_error', array('@last_error' => $last_error), $severity);
-    }
-    else {
-      watchdog('basic_webmail', 'There was an error connecting to the server: @last_error', array('@last_error' => $last_error), $severity);
-    }
-  }
-} // End of _basic_webmail_report_error().
-
-
-/**
- * Deletes a group of messages.
- *
- * @param $form_state
- *   The form values of the passed form.
- * @param $messages
- *   The messasges to delete.
- * @param $imap_resource
- *   A connection to the mailbox on the server.
- */
-function _basic_webmail_mail_list_form_submit_delete($form_state, $messages, $imap_resource) {
-  $error = 0;
-  $message_count = 0;
-
-  foreach ($messages as $message_number) {
-    if ($form_state['values']['folder'] != 'INBOX.Trash') {
-      if (!imap_mail_move($imap_resource, $message_number, 'INBOX.Trash')) {
-        // Report the error.
-        $last_error = imap_last_error();
-        watchdog('basic_webmail', 'There was an error deleting message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-        drupal_set_message(t('There was an error deleting message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-        $error++;
-      }
-      else {
-        $message_count++;
-      }
-    }
-    else {
-      if (!imap_delete($imap_resource, $message_number)) {
-        // Report the error.
-        $last_error = imap_last_error();
-        watchdog('basic_webmail', 'There was an error deleting message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-        drupal_set_message(t('There was an error deleting message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-        $error++;
-      }
-      else {
-        $message_count++;
-      }
-    }
-  }
-
-  if (!imap_expunge($imap_resource)) {
-    // Report the error.
-    watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    $error++;
-  }
-
-  if (!$error) {
-    drupal_set_message(t('@message_count messages were successfully deleted.', array('@message_count' => $message_count)));
-  }
-} // End of _basic_webmail_mail_list_form_submit_delete().
-
-
-/**
- * Marks a group of messages as read.
- *
- * @param $form_state
- *   The form values of the passed form.
- * @param $messages
- *   The messasges to .
- * @param $imap_resource
- *   A connection to the mailbox on the server.
- */
-function _basic_webmail_mail_list_form_submit_mark_read($form_state, $messages, $imap_resource) {
-  $error = 0;
-  $message_count = 0;
-
-  foreach ($messages as $message_number) {
-    if (!imap_setflag_full($imap_resource, $message_number, '\\Seen')) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error setting the flag of message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-      drupal_set_message(t('There was an error setting the flag of message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-      $error++;
-    }
-    else {
-      $message_count++;
-    }
-  }
-
-  if (!$error) {
-    drupal_set_message(t('@message_count messages were successfully marked as read.', array('@message_count' => $message_count)));
-  }
-} // End of _basic_webmail_mail_list_form_submit_mark_read().
-
-
-/**
- * Marks a group of messages as unread.
- *
- * @param $form_state['values']
- *   The form values of the passed form.
- * @param $messages
- *   The messasges to .
- * @param $imap_resource
- *   A connection to the mailbox on the server.
- */
-function _basic_webmail_mail_list_form_submit_mark_unread($form_state, $messages, $imap_resource) {
-  $error = 0;
-  $message_count = 0;
-
-  foreach ($messages as $message_number) {
-    if (!imap_clearflag_full($imap_resource, $message_number, '\\Seen')) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error clearing the flag of message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-      drupal_set_message(t('There was an error clearing the flag of message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-      $error++;
-    }
-    else {
-      $message_count++;
-    }
-  }
-
-  if (!$error) {
-    drupal_set_message(t('@message_count messages were successfully marked as unread.', array('@message_count' => $message_count)));
-  }
-} // End of _basic_webmail_mail_list_form_submit_mark_unread().
-
-
-/**
- * Copies a group of messages to another folder.
- *
- * @param $form_state['values']
- *   The form values of the passed form.
- * @param $messages
- *   The messasges to .
- * @param $imap_resource
- *   A connection to the mailbox on the server.
- */
-function _basic_webmail_mail_list_form_submit_copy_to($form_state, $messages, $imap_resource) {
-  $error = 0;
-  $message_count = 0;
-
-  foreach ($messages as $message_number) {
-    if (!imap_mail_copy($imap_resource, $message_number, $form_state['values']['folder_name'])) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-      drupal_set_message(t('There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-      $error++;
-    }
-    else {
-      $message_count++;
-    }
-  }
-
-  if (!imap_expunge($imap_resource)) {
-    // Report the error.
-    watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    $error++;
-  }
-
-  if (!$error) {
-    drupal_set_message(t('@message_count messages were successfully copied to @folder_name.', array('@message_count' => $message_count, '@folder_name' => $form_state['values']['folder_name'])));
-  }
-} // End of _basic_webmail_mail_list_form_submit_copy_to().
-
-
-/**
- * Moves a group of messages to another folder.
- *
- * @param $form_state['values']
- *   The form values of the passed form.
- * @param $messages
- *   The messasges to .
- * @param $imap_resource
- *   A connection to the mailbox on the server.
- */
-function _basic_webmail_mail_list_form_submit_move_to($form_state, $messages, $imap_resource) {
-  $error = 0;
-  $message_count = 0;
-
-  foreach ($messages as $message_number) {
-    if (!imap_mail_move($imap_resource, $message_number, $form_state['values']['folder_name'])) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-      drupal_set_message(t('There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-      $error++;
-    }
-    else {
-      $message_count++;
-    }
-  }
-
-  if (!imap_expunge($imap_resource)) {
-    // Report the error.
-    watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    $error++;
-  }
-
-  if (!$error) {
-    drupal_set_message(t('@message_count messages were successfully moved to @folder_name.', array('@message_count' => $message_count, '@folder_name' => $form_state['values']['folder_name'])));
-  }
-} // End of _basic_webmail_mail_list_form_submit_move_to().
-
-
-/**
- * Display the message.
- *
- * @TODO: Consider a feature to allow or not the displaying of remote content.
- *
- * @param message_number
- *   The ID of the message to delete.
- * @param folder
- *   The name of the folder the message is in. If no folder is specified, it
- *   defaults to 'INBOX'.
- *
- * @return
- *   The formatted message.
- */
-function _basic_webmail_message($message_number, $folder = 'INBOX') {
-  $output = '';
-
-  // Sanity check -- make sure we have an actual message to display.
-  if (arg(0) == 'basic_webmail' && arg(1) == 'message' && $message_number == '') {
-    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('No message_number was given when attempting to view a message.') . '<br /><br />';
-  }
-
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Show the message.
-
-  // Start with the the message header.
-  $message_header = imap_headerinfo($imap_resource, $message_number);
-  if (!$message_header) {
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
-  }
-
-  // Set the title of the page.
-  drupal_set_title(t('!title', array('!title' => _basic_webmail_decode_mime_str($message_header->subject))));
-
-  // Offer a link back to where we came from.
-  $output .= '<br />';
-  $output .= l(t('Return to message listing'), 'basic_webmail/' . $folder);
-  $output .= '<hr>';
-  $output .= '<table>';
-
-  // Start processing the header of the message.
-
-  // Retrieve and display who the message is from.
-  if (!empty($message_header->from[0]->personal)) {
-    $output .= '<tr><td>From:</td><td>' . l(_basic_webmail_decode_mime_str($message_header->from[0]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>') . '</td></tr>';
-  }
-  else {
-    $output .= '<tr><td>From:</td><td>' . l($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host, 'basic_webmail/sendmail/' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host) . '</td></tr>';
-  }
-
-  // Retrieve and display who the message is to.
-  $toaddresses = '';
-  for ($i = 0; $i < count($message_header->to); $i++) {
-    if (!empty($message_header->to[$i]->personal)) {
-      $toaddresses .= l(_basic_webmail_decode_mime_str($message_header->to[$i]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->to[0]->personal) . ' <' . $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host . '>') . ', ';
-    }
-    else {
-      $toaddresses .= l($message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host, 'basic_webmail/sendmail/' . $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host) . ', ';
-    }
-  }
-  // Drop the final comma and space.
-  $output .= '<tr><td>To:</td><td>' . drupal_substr($toaddresses, 0, drupal_strlen($toaddresses) - 2) . '</td></tr>';
-
-  // Retrieve and display who the message was CC'd to.
-  if (!empty($message_header->ccaddress)) {
-    $ccaddresses = '';
-    for ($i = 0; $i < count($message_header->cc); $i++) {
-      if ($message_header->cc[$i]->personal) {
-        $ccaddresses .= l(_basic_webmail_decode_mime_str($message_header->cc[$i]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->cc[0]->personal) . ' <' . $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host . '>') . ', ';
-      }
-      else {
-        $ccaddresses .= l($message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host, 'basic_webmail/sendmail/' . $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host) . ', ';
-      }
-    }
-    // Drop the final comma and space.
-    $output .= '<tr><td>CC:</td><td>' . drupal_substr($ccaddresses, 0, drupal_strlen($ccaddresses) - 2) . '</td></tr>';
-  }
-
-  // Retrieve and display the date of the message.
-  $output .= '<tr><td>Date:</td><td>' . $message_header->date . '</td></tr>';
-
-  // Close out the header.
-  $output .= '</table>';
-  $output .= '<hr>';
-
-
-  // Start processing the body of the message.
-
-  // Get the message parts list.
-  $parts_list = _basic_webmail_get_parts_list($imap_resource, $message_number);
-
-  // Initialize variable.
-  $message_body = '';
-  $message_self_link = '';
-  $attachment_links = '';
-  $reply_part = '';
-
-  // Iterate over the parts list.
-  foreach ($parts_list as $part_id => $part_array) {
-    // Process an HTML part.
-    if (arg(4) == 'html' && $part_array[0] == drupal_strtoupper('HTML')) {
-      if (arg(5)) {
-        if ($message_body) {
-          // Add a separator between message parts, but only if there is at
-          // least one other part.
-          $message_body .= '<hr width="75%">';
-        }
-
-        $message_body .= _basic_webmail_decode_body_part($imap_resource, $message_number, arg(5));
-      }
-      else {
-        if ($message_body) {
-          // Add a separator between message parts, but only if there is at
-          // least one other part.
-          $message_body .= '<hr width="75%">';
-        }
-
-        $message_body .= _basic_webmail_decode_body_part($imap_resource, $message_number, $part_id);
-      }
-
-      if (!$reply_part) {
-        $reply_part = $part_id;
-      }
-
-      $message_self_link .= '<hr>' . l(t('View the original message.'), 'basic_webmail/message/' . $message_number . '/' . $folder);
-    }
-
-    // Process a plain text part.
-    elseif (arg(4) != 'html' && $part_array[0] == drupal_strtoupper('PLAIN')) {
-      if ($message_body) {
-        // Add a separator between message parts, but only if there is at
-        // least one other part.
-        $message_body .= '<hr width="75%">';
-      }
-
-      $message_body .= check_markup(_basic_webmail_decode_body_part($imap_resource, $message_number, $part_id));
-
-      if (!$reply_part) {
-        $reply_part = $part_id;
-      }
-    }
-
-    // Create a link to an HTML parts.
-    elseif (arg(4) != 'html' && $part_array[0] == drupal_strtoupper('HTML')) {
-      $message_self_link .= '<hr>' . l(t('View this message as a web page.'), 'basic_webmail/message/' . $message_number . '/' . $folder . '/html/' . $part_id);
-    }
-
-    // Everything else?
-    // For attachments we really want them available whether the part being
-    // viewed is HTML or plain text.
-    elseif (!empty($part_array[0]) && !empty($part_array[1])) {
-      $attachment = _basic_webmail_process_attachment($imap_resource, $message_number, $part_id, $part_array[1]);
-      $attachment_links .= l($attachment[1], $attachment[2]) . '&nbsp; -- &nbsp;';
-    }
-  }
-
-
-  // Add the formatted message body to the output string.
-  $output .= $message_body;
-
-  // Add links to the attachments.
-  if ($attachment_links) {
-    $output .= '<hr>Attachment(s):<br /><br />';
-    $output .= drupal_substr($attachment_links, 0, drupal_strlen($attachment_links) - 16);
-  }
-
-  // Add the link to the other part.
-  $output .= $message_self_link;
-
-  // Add a separator.
-  $output .= '<hr>';
-
-  // Add some action links for this message.
-  // Links for all folders.
-  $delete_link = l(t('Delete'), 'basic_webmail/delete/' . $message_number . '/' . $folder);
-  $copy_link = l(t('Copy'), 'basic_webmail/copy/' . $message_number . '/' . $folder);
-  $move_link = l(t('Move'), 'basic_webmail/move/' . $message_number . '/' . $folder);
-  if ($folder == 'INBOX.Drafts') {
-    // Links for the Drafts folder.
-    $continue_link = l(t('Continue composition'), 'basic_webmail/sendmail/continue/' . $folder . '/' . $message_number . '/' . $reply_part);
-    $output .= $continue_link . '&nbsp; -- &nbsp;' . $copy_link . '&nbsp; -- &nbsp;' . $move_link . '&nbsp; -- &nbsp;' . $delete_link;
-  }
-  else {
-    // Links for the other folders.
-    $reply_link = l(t('Reply'), 'basic_webmail/sendmail/reply/' . $folder . '/' . $message_number . '/' . $reply_part);
-    $reply_to_all_link = l(t('Reply to all'), 'basic_webmail/sendmail/replytoall/' . $folder . '/' . $message_number . '/' . $reply_part);
-    $forward_link = l(t('Forward'), 'basic_webmail/sendmail/forward/' . $folder . '/' . $message_number . '/' . $reply_part);
-    $output .= $reply_link . '&nbsp; -- &nbsp;' . $reply_to_all_link . '&nbsp; -- &nbsp;' . $forward_link . '&nbsp; -- &nbsp;' . $copy_link . '&nbsp; -- &nbsp;' . $move_link . '&nbsp; -- &nbsp;' . $delete_link;
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  return $output;
-} // End of _basic_webmail_message().
-
-
-/**
- * Construct the form for conposing an email message.
- *
- * @param send_mail_type
- *   Whether the message is new, a reply or a forward. Possible values:
- *   - "new": All form fields are left blank.
- *   - "reply": The To form field is filled in with the from address of the
- *     original message. The Subject and Body form fields are filled in with
- *     the corresponding fields from the original message.
- *   - "replytoall": The To form field is filled in with the from address of
- *     the original message. The CC form field is filled in with all of the
- *     addresses in the to and cc fields of the original message. The Subject
- *     and Body form fields are filled in with the corresponding fields from
- *     the original message.
- *   - "forward": The To, CC and BCC form fields are blank. The Subject and
- *     Body form fields are filled in with the corresponding fields from the
- *     original message.
- *   - "continue": The contents of the form are filled in by the message in
- *     the Drafts folder that is being continued.
- *   - An email address: The To form field gets filled in with the value in
- *     $send_mail_type, and all other form fields are left blank.
- * @param send_mail_message_number
- *   The ID of the message being replied to or forwarded, blank otherwise.
- *
- * @return
- *   The completed form definition.
- */
-//function _basic_webmail_send_mail_form(&$form_state, $send_mail_type = 'new', $send_mail_folder = '', $send_mail_message_number = '') {
-function _basic_webmail_send_mail_form($send_mail_type = 'new', $send_mail_folder = '', $send_mail_message_number = '') {
-  $form = array();
-
-  // Initialize variables.
-  $send_mail_to = '';
-  $send_mail_cc = '';
-  $send_mail_bcc = '';
-  $send_mail_subject = '';
-  $send_mail_body = '';
-  $attachments = array();
-
-  // Check to see if this is a reply or forward.
-  if ($send_mail_type == 'reply' || $send_mail_type == 'replytoall' || $send_mail_type == 'forward' || $send_mail_type == 'continue') {
-    // Make sure we have a message id.
-    if (!$send_mail_message_number) {
-      watchdog('basic_webmail', 'There was an attempt to reply to or forward a message w/o including the message id.', array(), WATCHDOG_ERROR);
-    }
-    // Get the message information for use in filling the form.
-    else {
-      // Connect to the server and retrieve a connection to the mailbox.
-      global $user;
-      $imap_resource = _basic_webmail_connect_to_server($user->uid, $send_mail_folder);
-      if (!$imap_resource) {
-        drupal_set_title(t('Error'));
-        return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-      }
-
-      // Show the message.
-
-      // Get the message header.
-      $message_header = imap_headerinfo($imap_resource, $send_mail_message_number);
-      if (!$message_header) {
-        watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
-      }
-
-      // Get the message body.
-      $message_body = imap_fetchbody($imap_resource, $send_mail_message_number, arg(5));
-      if (!$message_body) {
-        watchdog('basic_webmail', 'There was an error retrieving the message body: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
-      }
-
-      // Set the title of the page.
-      drupal_set_title(t('!title', array('!title' => _basic_webmail_decode_mime_str($message_header->subject))));
-
-      // Add a link back to the listing.
-      if (!$send_mail_message_number) {
-        $form['basic_webmail_send_mail_list_link'] = array(
-          '#value' => l(t('Return to message listing'), 'basic_webmail/' . $send_mail_folder) . '<hr>',
-        );
-      }
-      else {
-        $form['basic_webmail_send_mail_list_link'] = array(
-          '#value' => l(t('Return to message listing'), 'basic_webmail/' . $send_mail_folder) . '&nbsp; -- &nbsp;' . l(t('Return to message'), 'basic_webmail/message/' . $send_mail_message_number . '/' . $send_mail_folder) . '<hr>',
-        );
-      }
-
-
-      // Set defaults based on $send_mail_type.
-      if ($send_mail_type == 'reply' || $send_mail_type == 'replytoall' || $send_mail_type == 'forward' || $send_mail_type == 'continue') {
-        // Get the message parts list.
-        $parts_list = _basic_webmail_get_parts_list($imap_resource, $send_mail_message_number);
-
-        // Initialize variables.
-        $message_self_link = '';
-        $attachment_links = '';
-
-        // Iterate over the parts list.
-        foreach ($parts_list as $part_id => $part_array) {
-          // If there's an attachment, allow the user to send it.
-          if ($part_array[0] && $part_array[1]) {
-            $attachment = _basic_webmail_process_attachment($imap_resource, $send_mail_message_number, $part_id, $part_array[1]);
-            $attachments[$attachment[0]] = $attachment[1];
-          }
-        }
-      }
-
-      // Set defaults based on $send_mail_type.
-      if ($send_mail_type == 'reply' || $send_mail_type == 'replytoall') {
-        $form['basic_webmail_message_number'] = array(
-          '#type' => 'hidden',
-          '#value' => $message_header->Msgno,
-        );
-        $form['basic_webmail_in_reply_to'] = array(
-          '#type' => 'hidden',
-          '#value' => $message_header->message_id,
-        );
-
-        // Set the subject of the message.
-        $send_mail_subject = 'Re: ' . _basic_webmail_decode_mime_str($message_header->subject);
-
-        // Set the "To" of the message.
-        if ($message_header->from[0]->personal) {
-          $send_mail_to = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
-        }
-        else {
-          $send_mail_to = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
-        }
-
-        // Set the body of the message.
-        if ($send_mail_type == 'reply') {
-          $send_mail_body = "\n\n\nOn " . $message_header->date . ", you wrote:\n";
-        }
-        else {
-          $send_mail_body = "\n\n\nOn " . $message_header->date . ', ' . $send_mail_to . " wrote:\n";
-        }
-
-        $temp_send_mail_body = explode("\n", utf8_encode(quoted_printable_decode($message_body)));
-        $send_mail_body .= '> ' . implode("\n> ", $temp_send_mail_body);
-        $send_mail_body .= "\n";
-
-        // Add the sender's signature, if one exists.
-        global $user;
-        if ($user->signature) {
-          $send_mail_body .= "\n-- \n" . $user->signature;
-        }
-      }
-
-
-      // Set defaults based on $send_mail_type.
-      if ($send_mail_type == 'replytoall') {
-        // Set the cc of the message.
-        // Make sure we don't have any bad information by setting it to an empty string first.
-        $send_mail_cc = '';
-
-        // Add all addresses in the to field.
-        for ($i = 0; $i < count($message_header->to); $i++) {
-          if ($message_header->to[$i]->personal) {
-            $send_mail_cc .= _basic_webmail_decode_mime_str($message_header->to[$i]->personal) . ' <' . $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host . '>, ';
-          }
-          else {
-            $send_mail_cc .= $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host . ', ';
-          }
-        }
-
-        // Add all addresses in the cc field.
-        if ($message_header->ccaddress) {
-          for ($i = 0; $i < count($message_header->cc); $i++) {
-            if ($message_header->cc[$i]->personal) {
-              $send_mail_cc .= _basic_webmail_decode_mime_str($message_header->cc[$i]->personal) . ' <' . $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host . '>, ';
-            }
-            else {
-              $send_mail_cc .= $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host . ', ';
-            }
-          }
-        }
-
-        $send_mail_cc = drupal_substr($send_mail_cc, 0, drupal_strlen($send_mail_cc) - 2);
-      }
-
-
-      // Set defaults based on $send_mail_type.
-      if ($send_mail_type == 'forward') {
-        // Set the subject of the message.
-        $send_mail_subject = 'Fw: ' . _basic_webmail_decode_mime_str($message_header->subject);
-
-        // Set the body of the message.
-        $send_mail_body = "\n\n\n------- Forwarded Message\n\n";
-        $send_mail_body .= $message_body;
-        $send_mail_body .= "\n\n------- End of Forwarded Message\n\n";
-
-        // Add the sender's signature, if one exists.
-        global $user;
-        if ($user->signature) {
-          $send_mail_body .= "\n-- \n" . $user->signature;
-        }
-      }
-
-
-      // Set defaults based on $send_mail_type.
-      if ($send_mail_type == 'continue') {
-        $form['basic_webmail_message_number'] = array(
-          '#type' => 'hidden',
-          '#value' => $message_header->Msgno,
-        );
-
-        // Set the "To" of the message.
-        $send_mail_to = $message_header->toaddress;
-        // Set the cc of the message.
-        $send_mail_cc = $message_header->ccaddress;
-        // Set the bcc of the message.
-        $send_mail_bcc = $message_header->bccaddress;
-        // Set the subject of the message.
-        $send_mail_subject = _basic_webmail_decode_mime_str($message_header->subject);
-        // Fill in the body of the message.
-        $send_mail_body = $message_body;
-      }
-
-
-      // Clean up.
-      if (!imap_close($imap_resource)) {
-        watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-      }
-    }
-  }
-  else {
-    // Set the title of the page.
-    drupal_set_title(t('New mail message'));
-
-    // If this is true, $send_mail_type holds the email address to send the
-    // message to.
-    if ($send_mail_type != 'new') {
-      // Set the to field.
-      $send_mail_to = $send_mail_type;
-    }
-  }
-
-  $form['basic_webmail_send_mail_to'] = array(
-    '#type' => 'textfield',
-    '#title' => t('To'),
-    '#default_value' => $send_mail_to,
-    //    '#size' => 96,
-    '#maxlength' => 1024,
-    '#autocomplete_path' => 'basic_webmail/autocomplete',
-    '#description' => t('One or more recepients of this message. Separate the addresses with a comma (,).'),
-    '#required' => TRUE,
-  );
-
-  $form['basic_webmail_send_mail_cc'] = array(
-    '#type' => 'textfield',
-    '#title' => t('CC'),
-    '#default_value' => $send_mail_cc,
-    //    '#size' => 96,
-    '#maxlength' => 1024,
-    '#autocomplete_path' => 'basic_webmail/autocomplete',
-    '#description' => t('One or more email addresses to receive a carbon copy. Separate the addresses with a comma (,).'),
-  );
-  $form['basic_webmail_send_mail_bcc'] = array(
-    '#type' => 'textfield',
-    '#title' => t('BCC'),
-    '#default_value' => $send_mail_bcc,
-    //    '#size' => 96,
-    '#maxlength' => 1024,
-    '#autocomplete_path' => 'basic_webmail/autocomplete',
-    '#description' => t('One or more email addresses to receive a blind carbon copy. These email addresses will not be visible in the message. Separate the addresses with a comma (,).'),
-  );
-
-  $form['basic_webmail_send_mail_subject'] = array(
-    '#type' => 'textfield',
-    '#title' => t('Subject'),
-    '#default_value' => $send_mail_subject,
-    //    '#size' => 96,
-    '#maxlength' => 1024,
-  );
-  $form['basic_webmail_send_mail_body'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Message'),
-    '#default_value' => $send_mail_body,
-    '#rows' => 15,
-  );
-
-  // If any exists, include attachments from message as checkboxes here.
-  if ($attachments) {
-    $form['basic_webmail_attachments'] = array(
-      '#type' => 'checkboxes',
-      '#title' => t('Attachments from original message'),
-      '#options' => $attachments,
-      '#description' => t('Check any attachments from the original you want to include in this message.'),
-    );
-  }
-
-  for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', 3); $i++) {
-    $form['basic_webmail_attachment_' . $i] = array(
-      '#type' => 'file',
-      '#title' => t('Attachment #!number', array('!number' => $i)),
-    );
-  }
-
-  $form['basic_webmail_send_mail_self'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Send a copy to myself.'),
-  );
-
-//  $form['_basic_webmail_send_mail_form_preview'] = array(
-//    '#type' => 'button',
-//    '#value' => t('Preview'),
-//    '#submit' => array('_basic_webmail_send_mail_form_preview'),
-//  );
-  $form['_basic_webmail_send_mail_form_save'] = array(
-    '#type' => 'submit',
-    '#value' => t('Save in INBOX.Drafts'),
-    '#submit' => array('_basic_webmail_send_mail_form_save'),
-  );
-  $form['_basic_webmail_send_mail_form_send'] = array(
-    '#type' => 'submit',
-    '#value' => t('Send'),
-    '#submit' => array('_basic_webmail_send_mail_form_send'),
-  );
-
-  $form['#attributes']['enctype'] = 'multipart/form-data';
-
-  return $form;
-} // End of _basic_webmail_send_mail_form().
-
-
-
-/**
- * Send the message.
- *
- * @param form_id
- *   The form ID of the passed form.
- * @param $form_state
- *   The form values of the passed form.
- */
-function _basic_webmail_send_mail_form_send($form, &$form_state) {
-  global $user;
-
-  // Initialize variables.
-  $sent_envelope = array();
-  $sent_part = array();
-  $sent_body = array();
-  $send_mail_headers = array();
-  $send_mail_body = '';
-
-
-  // Set the From email address.
-  if (variable_get('basic_webmail_account_info', 1)) {
-    $sent_envelope['from'] = $user->mail;
-  }
-  else {
-    $sent_envelope['from'] = $user->data['basic_webmail_username'];
-  }
-  // This ends up creating saved messages with email addresses that look like admin@"NO HOST".
-//  $from_name_address = addslashes(mime_header_encode($user->name)) .' <'. $user->mail .'>';
-
-
-  // Set some other header parts.
-  $sent_envelope['return_path'] = $sent_envelope['from'];
-  $sent_envelope['reply_to'] = $sent_envelope['from'];
-  $send_mail_headers['Return-Path'] = $sent_envelope['from'];
-  $send_mail_headers['Sender'] = $sent_envelope['from'];
-
-  if ($form_state['values']['basic_webmail_in_reply_to']) {
-    $sent_envelope['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
-    $send_mail_headers['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
-  }
-
-
-  // Set the CC and BCC fields, if they exist.
-  if ($form_state['values']['basic_webmail_send_mail_cc']) {
-    if ($form_state['values']['basic_webmail_send_mail_bcc']) {
-      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
-      $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
-      $send_mail_headers['Cc'] = $sent_envelope['cc'];
-      $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
-    }
-    else {
-      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
-      $send_mail_headers['Cc'] = $sent_envelope['cc'];
-    }
-  }
-  elseif ($form_state['values']['basic_webmail_send_mail_bcc']) {
-    $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
-    $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
-  }
-
-
-  // Check for the exsistance of added attachments.
-  for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
-    if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
-      $has_attachments = 1;
-      break;
-    }
-  }
-
-  // Check for the exsistance of forwarded attachments.
-  if ($form_state['values']['basic_webmail_attachments']) {
-    foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
-      if ($attachment) {
-        $has_attachments = 1;
-        break;
-      }
-    }
-  }
-
-  // Create headers based on presence or absence of attachment.
-  if ($has_attachments) {
-    $sent_part['type'] = TYPEMULTIPART;
-    $sent_part['subtype'] = 'mixed';
-    $sent_body[] = $sent_part;
-    $sent_part = array();
-
-    $uid = md5(uniqid(REQUEST_TIME));
-    $send_mail_headers['Content-Type'] = 'multipart/mixed; boundary="' . $uid . '"';
-
-    $sent_part['type'] = TYPETEXT;
-    $sent_part['subtype'] = 'plain';
-    $sent_part['description'] = 'message';
-
-    $send_mail_body = "\n--$uid\n";
-    $send_mail_body .= "Content-Type: text/plain; charset=UTF-8; format=flowed\n\n";
-
-
-    // Add in the actual message
-    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n\n";
-    $send_mail_body .= $sent_part['contents.data'];
-    $sent_body[] = $sent_part;
-    $sent_part = array();
-
-
-    // Add any forwarded attachments.
-    if ($form_state['values']['basic_webmail_attachments']) {
-      foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
-        if ($attachment) {
-          $sent_part = array();
-          $content_type = mime_content_type($attachment);
-
-          switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
-            case 'audio':
-              $sent_part['type'] = TYPEAUDIO;
-              break;
-            case 'image':
-              $sent_part['type'] = TYPEIMAGE;
-              break;
-            case 'text':
-              $sent_part['type'] = TYPETEXT;
-              break;
-            case 'video':
-              $sent_part['type'] = TYPEVIDEO;
-              break;
-            default:
-              $sent_part['type'] = TYPEAPPLICATION;
-              break;
-          }
-
-          $sent_part['encoding'] = ENCBASE64;
-          $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
-          $sent_part['description'] = basename($attachment);
-          $sent_part['disposition.type'] = 'attachment';
-          $sent_part['disposition'] = array('filename' => $sent_part['description']);
-          $sent_part['type.parameters'] = array('name' => $sent_part['description']);
-          $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($attachment)));
-
-          $sent_body[] = $sent_part;
-
-          $send_mail_body .= "--$uid\n";
-          $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
-          $send_mail_body .= "Content-Transfer-Encoding: base64\n";
-          $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
-          $send_mail_body .= $sent_part['contents.data'];
-          $send_mail_body .= "\n\n";
-        }
-      }
-    }
-
-    // Add any added attachments.
-    for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
-      if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
-        $sent_part = array();
-        $content_type = $_FILES['files']['type']['basic_webmail_attachment_' . $i];
-
-        switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
-          case 'audio':
-            $sent_part['type'] = TYPEAUDIO;
-            break;
-          case 'image':
-            $sent_part['type'] = TYPEIMAGE;
-            break;
-          case 'text':
-            $sent_part['type'] = TYPETEXT;
-            break;
-          case 'video':
-            $sent_part['type'] = TYPEVIDEO;
-            break;
-          default:
-            $sent_part['type'] = TYPEAPPLICATION;
-            break;
-        }
-
-        $sent_part['encoding'] = ENCBASE64;
-        $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
-        $sent_part['description'] = basename($_FILES['files']['name']['basic_webmail_attachment_' . $i]);
-        $sent_part['disposition.type'] = 'attachment';
-        $sent_part['disposition'] = array('filename' => $sent_part['description']);
-        $sent_part['type.parameters'] = array('name' => $sent_part['description']);
-        $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($_FILES['files']['tmp_name']['basic_webmail_attachment_' . $i])));
-
-        $sent_body[] = $sent_part;
-
-        $send_mail_body .= "--$uid\n";
-        $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
-        $send_mail_body .= "Content-Transfer-Encoding: base64\n";
-        $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
-        $send_mail_body .= $sent_part['contents.data'];
-        $send_mail_body .= "\n\n";
-      }
-    }
-
-    // Add the final boundary to the body.
-    $send_mail_body .= "--$uid--\n\n";
-  }
-  // No attachments exist.
-  else {
-    // Add in the actual message
-    $sent_part = array();
-    $sent_part['type'] = TYPETEXT;
-    $sent_part['subtype'] = 'plain';
-    $sent_part['description'] = 'message';
-    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n";
-    $send_mail_body .= $sent_part['contents.data'];
-    $sent_body[] = $sent_part;
-    $sent_part = array();
-  }
-
-
-  // Prepare the message for sending.
-  $module = 'basic_webmail';
-  $key = 'message';
-  $to = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_to']);
-  $language = language_default();
-  $from = $sent_envelope['from'];
-
-  $params['subject'] = $form_state['values']['basic_webmail_send_mail_subject'];
-  $params['body'] = $send_mail_body;
-  if ($send_mail_headers) {
-    $params['headers'] = $send_mail_headers;
-  }
-
-  // Send the message.
-  $completed_message = drupal_mail($module, $key, $to, $language, $params, $from);
-  if ($completed_message) {
-    // If a copy to self was requested, send it.
-    if ($form_state['values']['basic_webmail_send_mail_self']) {
-      $key = 'copy_to_self';
-      global $language;
-      drupal_mail($module, $key, $to, $language, $params, $from);
-    }
-
-    // Copy the message to the INBOX.Sent folder, marked as read.
-
-    // Connect to the server and retrieve a connection to the mailbox.
-    global $user;
-    $imap_resource = _basic_webmail_connect_to_server($user->uid);
-    if (!$imap_resource) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error connecting to the server: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-      drupal_set_message(t('There was an error connecting to the server: @last_error', array('@last_error' => $last_error)), 'error');
-    }
-
-    // If this is a reply, mark the replied to message as answered.
-    if ($form_state['values']['basic_webmail_in_reply_to']) {
-      if (!imap_setflag_full($imap_resource, $form_state['values']['basic_webmail_message_number'], '\\Answered')) {
-        // Report the error.
-        watchdog('basic_webmail', 'There was an error marking the replied to message as answered: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
-      }
-    }
-
-    // Complete the envelope for the copy for the Sent folder.
-    $sent_envelope['to'] = $to;
-    $sent_envelope['subject'] = $params['subject'];
-    $sent_envelope['date'] = date('r');
-
-    // Create the message string to store.
-    $sent_message = imap_mail_compose($sent_envelope, $sent_body);
-    if (!$sent_message) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error creating the copy of the message for the sent folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-      drupal_set_message(t('There was an error creating the copy of the message for the sent folder: @last_error', array('@last_error' => $last_error)), 'error');
-    }
-    else {
-      // Place the message in the Sent folder.
-      if (!imap_append($imap_resource, _basic_webmail_get_server_string() . 'INBOX.Sent', $sent_message, '\\Seen')) {
-        // Report the error.
-        $last_error = imap_last_error();
-        watchdog('basic_webmail', 'There was an error saving a copy of the message to the sent folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-        drupal_set_message(t('There was an error saving a copy of the message to the sent folder: @last_error', array('@last_error' => $last_error)), 'error');
-      }
-    }
-
-    // Clean up.
-    if (!imap_close($imap_resource)) {
-      watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    }
-
-    // Report to the user.
-    drupal_set_message(t('Your message was successfully sent.'));
-
-    // Where we go after the message is sent.
-    if (arg(3) && arg(4)) {
-      // The original message, if there was one.
-      drupal_goto('/basic_webmail/message/' . arg(4) . '/' . arg(3));
-    }
-    else {
-      // The message list otherwise.
-      drupal_goto('/basic_webmail');
-    }
-  }
-  else {
-    // Report to the user.
-    drupal_set_message(t('There was an error sending your message.'), 'error');
-  }
-} // End of _basic_webmail_send_mail_form_send().
-
-
-/**
- * Save the message.
- *
- * @param form_id
- *   The form ID of the passed form.
- * @param $form_state
- *   The form values of the passed form.
- */
-function _basic_webmail_send_mail_form_save($form, &$form_state) {
-  global $user;
-
-  // Initialize variables.
-  $sent_envelope = array();
-  $sent_part = array();
-  $sent_body = array();
-  $send_mail_headers = array();
-  $send_mail_body = '';
-
-
-  // Set the From email address.
-  if (variable_get('basic_webmail_account_info', 1)) {
-    $sent_envelope['from'] = $user->mail;
-  }
-  else {
-    $sent_envelope['from'] = $user->data['basic_webmail_username'];
-  }
-  // This ends up creating saved messages with email addresses that look like admin@"NO HOST".
-//  $from_name_address = addslashes(mime_header_encode($user->name)) .' <'. $user->mail .'>';
-
-
-  // Set some other header parts.
-  $sent_envelope['return_path'] = $sent_envelope['from'];
-  $sent_envelope['reply_to'] = $sent_envelope['from'];
-  $send_mail_headers['Return-Path'] = $sent_envelope['from'];
-  $send_mail_headers['Sender'] = $sent_envelope['from'];
-
-  if ($form_state['values']['basic_webmail_in_reply_to']) {
-    $sent_envelope['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
-    $send_mail_headers['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
-  }
-
-
-  // Set the CC and BCC fields, if they exist.
-  if ($form_state['values']['basic_webmail_send_mail_cc']) {
-    if ($form_state['values']['basic_webmail_send_mail_bcc']) {
-      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
-      $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
-      $send_mail_headers['Cc'] = $sent_envelope['cc'];
-      $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
-    }
-    else {
-      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
-      $send_mail_headers['Cc'] = $sent_envelope['cc'];
-    }
-  }
-  elseif ($form_state['values']['basic_webmail_send_mail_bcc']) {
-    $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
-    $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
-  }
-
-
-  // Check for the exsistance of added attachments.
-  for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
-    if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
-      $has_attachments = 1;
-      break;
-    }
-  }
-
-  // Check for the exsistance of forwarded attachments.
-  if ($form_state['values']['basic_webmail_attachments']) {
-    foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
-      if ($attachment) {
-        $has_attachments = 1;
-        break;
-      }
-    }
-  }
-
-  // Create headers based on presence or absence of attachment.
-  if ($has_attachments) {
-    $sent_part['type'] = TYPEMULTIPART;
-    $sent_part['subtype'] = 'mixed';
-    $sent_body[] = $sent_part;
-    $sent_part = array();
-
-    $uid = md5(uniqid(REQUEST_TIME));
-    $send_mail_headers['Content-Type'] = 'multipart/mixed; boundary="' . $uid . '"';
-
-    $sent_part['type'] = TYPETEXT;
-    $sent_part['subtype'] = 'plain';
-    $sent_part['description'] = 'message';
-
-    $send_mail_body = "\n--$uid\n";
-    $send_mail_body .= "Content-Type: text/plain; charset=UTF-8; format=flowed\n\n";
-
-
-    // Add in the actual message
-    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n\n";
-    $send_mail_body .= $sent_part['contents.data'];
-    $sent_body[] = $sent_part;
-    $sent_part = array();
-
-
-    // Add any forwarded attachments.
-    if ($form_state['values']['basic_webmail_attachments']) {
-      foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
-        if ($attachment) {
-          $sent_part = array();
-          $content_type = mime_content_type($attachment);
-
-          switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
-            case 'audio':
-              $sent_part['type'] = TYPEAUDIO;
-              break;
-            case 'image':
-              $sent_part['type'] = TYPEIMAGE;
-              break;
-            case 'text':
-              $sent_part['type'] = TYPETEXT;
-              break;
-            case 'video':
-              $sent_part['type'] = TYPEVIDEO;
-              break;
-            default:
-              $sent_part['type'] = TYPEAPPLICATION;
-              break;
-          }
-
-          $sent_part['encoding'] = ENCBASE64;
-          $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
-          $sent_part['description'] = basename($attachment);
-          $sent_part['disposition.type'] = 'attachment';
-          $sent_part['disposition'] = array('filename' => $sent_part['description']);
-          $sent_part['type.parameters'] = array('name' => $sent_part['description']);
-          $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($attachment)));
-
-          $sent_body[] = $sent_part;
-
-          $send_mail_body .= "--$uid\n";
-          $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
-          $send_mail_body .= "Content-Transfer-Encoding: base64\n";
-          $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
-          $send_mail_body .= $sent_part['contents.data'];
-          $send_mail_body .= "\n\n";
-        }
-      }
-    }
-
-    // Add any added attachments.
-    for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
-      if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
-        $sent_part = array();
-        $content_type = $_FILES['files']['type']['basic_webmail_attachment_' . $i];
-
-        switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
-          case 'audio':
-            $sent_part['type'] = TYPEAUDIO;
-            break;
-          case 'image':
-            $sent_part['type'] = TYPEIMAGE;
-            break;
-          case 'text':
-            $sent_part['type'] = TYPETEXT;
-            break;
-          case 'video':
-            $sent_part['type'] = TYPEVIDEO;
-            break;
-          default:
-            $sent_part['type'] = TYPEAPPLICATION;
-            break;
-        }
-
-        $sent_part['encoding'] = ENCBASE64;
-        $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
-        $sent_part['description'] = basename($_FILES['files']['name']['basic_webmail_attachment_' . $i]);
-        $sent_part['disposition.type'] = 'attachment';
-        $sent_part['disposition'] = array('filename' => $sent_part['description']);
-        $sent_part['type.parameters'] = array('name' => $sent_part['description']);
-        $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($_FILES['files']['tmp_name']['basic_webmail_attachment_' . $i])));
-
-        $sent_body[] = $sent_part;
-
-        $send_mail_body .= "--$uid\n";
-        $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
-        $send_mail_body .= "Content-Transfer-Encoding: base64\n";
-        $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
-        $send_mail_body .= $sent_part['contents.data'];
-        $send_mail_body .= "\n\n";
-      }
-    }
-
-    // Add the final boundary to the body.
-    $send_mail_body .= "--$uid--\n\n";
-  }
-  // No attachments exist.
-  else {
-    // Add in the actual message
-    $sent_part = array();
-    $sent_part['type'] = TYPETEXT;
-    $sent_part['subtype'] = 'plain';
-    $sent_part['description'] = 'message';
-    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n";
-    $send_mail_body .= $sent_part['contents.data'];
-    $sent_body[] = $sent_part;
-    $sent_part = array();
-  }
-
-
-  // Complete the envelope for the copy to the Drafts folder.
-  $sent_envelope['to'] = $form_state['values']['basic_webmail_send_mail_to'];
-  $sent_envelope['subject'] = $form_state['values']['basic_webmail_send_mail_subject'];
-  $sent_envelope['date'] = date('r');
-
-  // Connect to the server and retrieve a connection to the mailbox.
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, 'INBOX.Drafts');
-  if (!$imap_resource) {
-    // Report the error.
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error connecting to the server: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    drupal_set_message(t('There was an error connecting to the server: @last_error', array('@last_error' => $last_error)), 'error');
-  }
-
-  // Copy message to INBOX.Drafts, marked as unread.
-  // Create the message string to store.
-  $draft_message = imap_mail_compose($sent_envelope, $sent_body);
-  if (!$draft_message) {
-    // Report the error.
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error creating the message for the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    drupal_set_message(t('There was an error creating the message for the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error)), 'error');
-  }
-  else {
-    // Place the message in the Drafts folder.
-    // First make sure this isn't a re-saving of a previously saved
-    // message.
-    if (imap_num_msg($imap_resource) > 0) {
-      $threads = imap_thread($imap_resource);
-      if ($threads) {
-        foreach ($threads as $message_number) {
-          if ($message_number == $form_state['values']['basic_webmail_message_number']) {
-            // Remove the old copy.
-            if (!imap_delete($imap_resource, $message_number)) {
-              // Report the error.
-              watchdog('basic_webmail', 'There was an error deleting message #@message_number from the INBOX.Drafts folder: @last_error', array('@message_number' => $message_number, '@last_error' => imap_last_error()), WATCHDOG_ERROR);
-            }
-
-            if (!imap_expunge($imap_resource)) {
-              // Report the error.
-              watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-            }
-          }
-        }
-      }
-    }
-
-    if (!imap_append($imap_resource, _basic_webmail_get_server_string() . 'INBOX.Drafts', $draft_message)) {
-      // Report the error.
-      $last_error = imap_last_error();
-      watchdog('basic_webmail', 'There was an error saving the message in the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-      drupal_set_message(t('There was an error saving the message in the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error)), 'error');
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  // Report to the user.
-  drupal_set_message(t('Your message was successfully saved in the INBOX.Drafts folder.'));
-
-  // Where we go after the message is saved.
-  if (arg(3)) {
-    // The INBOX.Drafts message listing.
-    drupal_goto('/basic_webmail/' . arg(3));
-  }
-  else {
-    // The INBOX message listing, otherwise.
-    drupal_goto('/basic_webmail/');
-  }
-} // End of _basic_webmail_send_mail_form_save().
-
-
-/**
- * Pre-process the message.
- *
- * @param form_id
- *   The form ID of the passed form.
- * @param $form_state
- *   The form values of the passed form.
- * /
- function _basic_webmail_send_mail_form_preprocess($form, &$form_state) {
- global $user;
-
- // Initialize variables.
- $sent_envelope = array();
- $sent_part = array();
- $sent_body = array();
- $send_mail_headers = array();
- $send_mail_body = '';
- $message = array();
-
-
- // Set the From email address.
- if (variable_get('basic_webmail_account_info', 1)) {
- $sent_envelope['from'] = $user->mail;
- }
- else {
- $sent_envelope['from'] = $user->data['basic_webmail_username'];
- }
-
-
- // Set some other header parts.
- $sent_envelope['return_path'] = $sent_envelope['from'];
- $sent_envelope['reply_to'] = $sent_envelope['from'];
- $send_mail_headers['Return-Path'] = $sent_envelope['from'];
- $send_mail_headers['Sender'] = $sent_envelope['from'];
-
- if ($form_state['values']['basic_webmail_in_reply_to']) {
- $sent_envelope['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
- $send_mail_headers['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
- }
-
- // Set the CC and BCC fields, if they exist.
- if ($form_state['values']['basic_webmail_send_mail_cc']) {
- if ($form_state['values']['basic_webmail_send_mail_bcc']) {
- $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
- $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
- $send_mail_headers['Cc'] = $sent_envelope['cc'];
- $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
- }
- else {
- $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
- $send_mail_headers['Cc'] = $sent_envelope['cc'];
- }
- }
- elseif ($form_state['values']['basic_webmail_send_mail_bcc']) {
- $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
- $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
- }
-
- // Check for the exsistance of added attachments.
- for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
- if ($_FILES['files']['error']['basic_webmail_attachment_'. $i] == 0) {
- $has_attachments = 1;
- // Process the attachments.
- $message = _basic_webmail_send_mail_form_process_attachments($form_state, $message);
- break;
- }
- }
-
- // Check for the exsistance of forwarded attachments.
- if (!$has_attachments && $form_state['values']['basic_webmail_attachments']) {
- $has_attachments = 1;
- // Process the attachment(s).
- $message = _basic_webmail_send_mail_form_process_attachments($form_state, $message);
- }
-
- // No attachments exist.
- if (!$has_attachments) {
- // Add in the actual message
- $sent_part = array();
- $sent_part['type'] = TYPETEXT;
- $sent_part['subtype'] = 'plain';
- $sent_part['description'] = 'message';
- $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) ."\n\n";
- $send_mail_body .= $sent_part['contents.data'];
- $sent_body[] = $sent_part;
- $sent_part = array();
- }
-
- $message['sent_envelope'] = $sent_envelope;
- $message['sent_part'] = $sent_part;
- $message['sent_body'] = $sent_body;
- $message['send_mail_headers'] = $send_mail_headers;
- $message['send_mail_body'] = $send_mail_body;
-
- return $message;
- } // End of _basic_webmail_send_mail_form_preprocess().
-
-
- /**
- * Takes given email addresses and adds the user name, if it exists, to them.
- *
- * @param email_addresses
- *   A string containing one or more email addresses, separated by commas.
- *
- * @return
- *   A string contaning those email address with their corresponding user
- *   name, if one exists.
- */
-function _basic_webmail_send_mail_form_process_addresses($email_addresses) {
-  $addresses = array();
-  $results = '';
-
-  // Check to see if there are multiple addresses in the string.
-  if (strpos($email_addresses, ',')) {
-    // Seperate the multiple addresses into an array of individual items.
-    $addresses = explode(',', $email_addresses);
-
-    foreach ($addresses as $address) {
-      // For each item in the list, attempt to add the user's name.
-      $results .= _basic_webmail_send_mail_form_get_user_from_mail(trim($address)) . ', ';
-    }
-  }
-  else {
-    // There is only one address. Attempt to add the user's name to it.
-    $results = _basic_webmail_send_mail_form_get_user_from_mail(trim($email_addresses)) . ', ';
-  }
-
-  // Remove any extra white space.
-  $results = trim($results);
-
-  // If there is a trailing comma, remove it.
-  if (drupal_substr($results, drupal_strlen($results) - 1, 1) == ',') {
-    $results = drupal_substr($results, 0, drupal_strlen($results) - 1);
-  }
-
-  return $results;
-} // End of _basic_webmail_send_mail_form_process_addresses().
-
-
-/**
- * Takes a given email address and adds the user name, if it exists, to it.
- *
- * @param email_addresses
- *   A string containing the email address.
- *
- * @return
- *   A string contaning the email address with its corresponding user name,
- *   if one exists.
- */
-function _basic_webmail_send_mail_form_get_user_from_mail($address) {
-  // Search the user list for anyone with the given email address.
-  $user_name = db_query("SELECT name FROM {users} WHERE mail = :mail", array(':mail' => $address))->fetchField();
-
-  // If something was found...
-  if ($user_name) {
-    // Return the new email address, including the user's name.
-    return '"' . addslashes(mime_header_encode($user_name)) . '" <' . $address . '>';
-  }
-  else {
-    // Otherwise, return the supplied email address.
-    return $address;
-  }
-} // End of _basic_webmail_send_mail_form_get_user_from_mail().
-
-
-/**
- * Process the attachments of the message.
- *
- * @param form_id
- *   The form ID of the passed form.
- * @param $form_state
- *   The form values of the passed form.
- * /
- function _basic_webmail_send_mail_form_process_attachments($form_state, $message) {
- $message['sent_part']['type'] = TYPEMULTIPART;
- $message['sent_part']['subtype'] = 'mixed';
- $message['sent_body'][] = $message['sent_part'];
- $message['sent_part'] = array();
-
- $uid = md5(uniqid(REQUEST_TIME));
- $message['send_mail_headers']['Content-Type'] = 'multipart/mixed; boundary="'. $uid .'"';
-
- $message['sent_part']['type'] = TYPETEXT;
- $message['sent_part']['subtype'] = 'plain';
- $message['sent_part']['description'] = 'message';
-
- $message['send_mail_body'] = "\n--$uid\n";
- $message['send_mail_body'] .= "Content-Type: text/plain; charset=UTF-8; format=flowed\n\n";
-
- // Add in the actual message
- $message['sent_part']['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) ."\n\n\n";
- $message['send_mail_body'] .= $message['sent_part']['contents.data'];
- $message['sent_body'][] = $message['sent_part'];
- $message['sent_part'] = array();
-
- // Add attachment(s).
- if ($form_state['values']['basic_webmail_attachments']) {
- foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
- if ($attachment) {
- $message = _basic_webmail_send_mail_form_process_an_attachment($form_state, $message, $attachment);
- }
- }
- }
-
- for ($i; $i <= variable_get('basic_webmail_number_attachments', 3); $i++) {
- if ($_FILES['files']['error']['basic_webmail_attachment_'. $i] == 0) {
- $message = _basic_webmail_send_mail_form_process_an_attachment($form_state, $message);
- }
- }
-
- $message['send_mail_body'] .= "--$uid--\n\n";
-
- return $message;
- }  //  End of _basic_webmail_send_mail_form_process_attachments().
-
-
- /**
- * Process an individual attachment.
- *
- * @param form_id
- *   The form ID of the passed form.
- * @param $form_state
- *   The form values of the passed form.
- * /
- function basic_webmail_send_mail_form_process_an_attachment($form_state, $message, $attachment) {
- $sent_part = array();
- $content_type = mime_content_type($attachment);
-
- switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
- case 'audio':
- $message['sent_part']['type'] = TYPEAUDIO;
- break;
- case 'image':
- $message['sent_part']['type'] = TYPEIMAGE;
- break;
- case 'text':
- $message['sent_part']['type'] = TYPETEXT;
- break;
- case 'video':
- $message['sent_part']['type'] = TYPEVIDEO;
- break;
- default:
- $message['sent_part']['type'] = TYPEAPPLICATION;
- break;
- }
-
- $message['sent_part']['encoding'] = ENCBASE64;
- $message['sent_part']['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
- $message['sent_part']['description'] = basename($attachment);
- $message['sent_part']['disposition.type'] = 'attachment';
- $message['sent_part']['disposition'] = array('filename' => $message['sent_part']['description']);
- $message['sent_part']['type.parameters'] = array('name' => $message['sent_part']['description']);
- $message['sent_part']['contents.data'] = chunk_split(base64_encode(file_get_contents($attachment)));
-
- $message['sent_body'][] = $sent_part;
-
- $message['send_mail_body'] .= "--$uid\n";
- $message['send_mail_body'] .= "Content-Type: ". $content_type ."; name=\"". $sent_part['description'] ."\"\n";
- $message['send_mail_body'] .= "Content-Transfer-Encoding: base64\n";
- $message['send_mail_body'] .= "Content-Disposition: attachment; filename=\"". $sent_part['description'] ."\"\n\n";
- $message['send_mail_body'] .= $sent_part['contents.data'];
- $message['send_mail_body'] .= "\n\n";
-
- return $message;
- } // End of _basic_webmail_send_mail_form_process_an_attachment().
-
-
-
- /**
- * Connect to the mail server.
- *
- * @param user_id
- *   The user ID of the mailbox to subscribe to.
- * @param folder
- *   The name of the folder to open. If no folder is specified, the default
- *   of INBOX is used.
- *
- * @return
- *   The mailbox connection, if successful, or FALSE, if not.
- */
-function _basic_webmail_connect_to_server($user_id, $folder = 'INBOX') {
-  // Retrieve the user object for the user accessing the mail server.
-  $user = user_load($user_id);
-  if (!$user->data['basic_webmail_username'] || !$user->data['basic_webmail_password']) {
-    user_access('administer basic_webmail') ?
-      watchdog('basic_webmail', 'Your !admin_settings_link have not yet been configured. Please do that before checking your email.', array('!admin_settings_link' => l(t('mail settings'), 'user/' . $user->uid . '/edit')), WATCHDOG_ERROR) :
-      watchdog('basic_webmail', 'Your mail settings have not been configured yet. Please do that before checking your email.', WATCHDOG_ERROR);
-    return FALSE;
-  }
-
-  // Get the users email login and password.
-  $username = $user->data['basic_webmail_username'];
-  $password = $user->data['basic_webmail_password'];
-
-  $mailbox = _basic_webmail_get_server_string() . $folder;
-
-  // Make the actual connection.
-  if (version_compare(phpversion(), '5.2.0', '>=')) {
-    $imap_resource = imap_open($mailbox, $username, $password, 0, 1);
-    if (empty($imap_resource)) {
-      watchdog('basic_webmail', 'There was an error accessing the remote server: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
-      return FALSE;
-    }
-  }
-  else {
-    $imap_resource = imap_open($mailbox, $username, $password, 0);
-    if ($imap_resource == FALSE) {
-      watchdog('basic_webmail', 'There was an error accessing the remote server: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
-      return FALSE;
-    }
-  }
-
-  return $imap_resource;
-} // End of _basic_webmail_connect_to_server().
-
-
-/**
- * Create the server connection string.
- *
- * @return
- *   The string representing the server connection information.
- */
-function _basic_webmail_get_server_string() {
-  // Sanity check -- make sure the admin has done the configuration.
-  if (variable_get('basic_webmail_server_address', '') == '' || variable_get('basic_webmail_server_port', '') == '') {
-    user_access('administer basic_webmail') ?
-      watchdog('basic_webmail', 'The !server_settings for Basic webmail have not yet been configured. Please do that before checking your email.', array('!server_settings' => l(t('server settings'), 'admin/config/basic_webmail')), WATCHDOG_ERROR) :
-      watchdog('basic_webmail', 'The server settings for Basic webmail have not yet been configured. Please do that before checking your email.', WATCHDOG_ERROR);
-    return FALSE;
-  }
-
-  // Prepare the flags for connecting to the server with.
-  $imap_flags = '';
-  if (variable_get('basic_webmail_secure_log_in', 0) == 1) {
-    $imap_flags .= '/secure';
-  }
-  if (variable_get('basic_webmail_use_ssl', 0) == 1) {
-    $imap_flags .= '/ssl';
-  }
-  if (variable_get('basic_webmail_validate_cert', 0) == 1) {
-    $imap_flags .= '/validate-cert';
-  }
-  else {
-    $imap_flags .= '/novalidate-cert';
-  }
-  if (variable_get('basic_webmail_use_tls', 0) == 1) {
-    $imap_flags .= '/tls';
-  }
-  else {
-    $imap_flags .= '/notls';
-  }
-
-  if (variable_get('basic_webmail_server_port', '') == '143') {
-    $server_string = '{' . variable_get('basic_webmail_server_address', '') . $imap_flags . '}';
-  }
-  else {
-    $server_string = '{' . variable_get('basic_webmail_server_address', '') . ':' . variable_get('basic_webmail_server_port', '') . $imap_flags . '}';
-  }
-
-  // Return the configured settings and create a connection string.
-  return $server_string;
-} // End of _basic_webmail_get_server_string().
-
-
-/**
- * Post a message delete confirmation form.
- *
- * @param message_number
- *   The ID of the message to delete.
- * @param folder
- *   The name of the folder the message is in. If no folder is specified, the
- *   default of 'INBOX' is used.
- *
- * @return
- *   The results of the confirmation question.
- */
-function _basic_webmail_delete_message_form($form_state, $message_number, $folder = 'INBOX') {
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Get the message header.
-  $message_header = imap_headerinfo($imap_resource, $message_number);
-  if (!$message_header) {
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
-  }
-
-  // Retrieve who the message is from.
-  if ($message_header->from[0]->personal) {
-    $from_address = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
-  }
-  else {
-    $from_address = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
-  }
-
-  // Retrieve the message date.
-  if (!$message_header->date) {
-    $message_date = 0;
-  }
-  else {
-    $message_date = $message_header->date;
-  }
-
-  // Retrieve the message subject.
-  if (!$message_header->subject) {
-    $message_subject = '(No subject given.)';
-  }
-  else {
-    $message_subject = _basic_webmail_decode_mime_str($message_header->subject);
-  }
-
-  // Fill in the form fields.
-  $form['message_number'] = array(
-    '#type' => 'hidden',
-    '#value' => $message_number,
-  );
-
-  $form['folder'] = array(
-    '#type' => 'hidden',
-    '#value' => $folder,
-  );
-
-  // Fill in the rest of the confirm_form() variables.
-  $question = t('Delete message?');
-  $path = 'basic_webmail/message/' . $message_number . '/' . $folder;
-  $description = t("Are you sure you want to delete the message from !from_address, sent on !message_date with the subject of '!message_subject'?", array('!from_address' => $from_address, '!message_date' => $message_date, '!message_subject' => $message_subject));
-  $yes = 'Yes';
-  $no = 'No';
-  $name = 'confirm_message_deletion';
-
-  // Call the function with the data.
-  $confirmation_result = confirm_form(
-    $form,         // Additional elements to inject into the form, for example hidden elements.
-    $question,     // The question to ask the user (e.g. "Are you sure you want to delete the block <em>foo</em>?").
-    $path,         // The page to go to if the user denies the action. Can be either a drupal path, or an array with the keys 'path', 'query', 'fragment'.
-    $description, // Additional text to display (defaults to "This action cannot be undone.").
-    $yes,          // A caption for the button which confirms the action (e.g. "Delete", "Replace", ...).
-    $no,           // A caption for the link which denies the action (e.g. "Cancel").
-    $name         // The internal name used to refer to the confirmation item.
-  );
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  return $confirmation_result;
-} // End of _basic_webmail_delete_message_form().
-
-
-/**
- * Delete a specified message.
- *
- * @param form_id
- *   The ID of the form created in the form generation function.
- * @param form_values
- *   The contents of the form fields.
- */
-function _basic_webmail_delete_message_form_submit($form, &$form_state) {
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['folder']);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  if ($form_state['values']['folder'] != 'INBOX.Trash') {
-    // If the message is located in a folder other than INBOX.Trash, move it to INBOX.Trash.
-    $result = imap_mail_move($imap_resource, $form_state['values']['message_number'], 'INBOX.Trash');
-  }
-  else {
-    // Otherwise, delete the message.
-    $result = imap_delete($imap_resource, $form_state['values']['message_number']);
-  }
-
-  if (!$result) {
-    // Report the error.
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error deleting the message: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    drupal_set_message(t('There was an error deleting the message: @last_error', array('@last_error' => $last_error)), 'error');
-  }
-  else {
-    drupal_set_message(t('The message was deleted.'));
-    if (!imap_expunge($imap_resource)) {
-      // Report the error.
-      watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => $last_error), WATCHDOG_WARNING);
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => $last_error), WATCHDOG_WARNING);
-  }
-
-  $form_state['redirect'] = 'basic_webmail/' . $form_state['values']['folder'];
-} // End of _basic_webmail_delete_message_form_submit().
-
-
-/**
- * Post a message copy form.
- *
- * @param message_number
- *   The ID of the message to delete.
- * @param folder
- *   The name of the folder the message is in. If no folder is specified, the
- *   default of 'INBOX' is used.
- *
- * @return
- *   The results of the confirmation question.
- */
-function _basic_webmail_copy_message_form($form_state, $message_number, $folder = 'INBOX') {
-  $form = array();
-
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Get the message header.
-  $message_header = imap_headerinfo($imap_resource, $message_number);
-  if (!$message_header) {
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
-  }
-
-  // Retrieve who the message is from.
-  if ($message_header->from[0]->personal) {
-    $from_address = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
-  }
-  else {
-    $from_address = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
-  }
-
-  // Retrieve the message date.
-  if (!$message_header->date) {
-    $message_date = 0;
-  }
-  else {
-    $message_date = $message_header->date;
-  }
-
-  // Retrieve the message subject.
-  if (!$message_header->subject) {
-    $message_subject = '(No subject given.)';
-  }
-  else {
-    $message_subject = _basic_webmail_decode_mime_str($message_header->subject);
-  }
-
-  // Get the list of folders from the server.
-  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
-  if ($folders) {
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-
-      if ($brief_folder_name != $folder) {
-        $folder_names[$brief_folder_name] = $brief_folder_name;
-      }
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  $form['basic_webmail_to_folder'] = array(
-    '#type' => 'select',
-    '#title' => t('The folder to which you want to copy the message'),
-    '#options' => $folder_names,
-  );
-
-  // Fill in the form fields.
-  $form['basic_webmail_message_number'] = array(
-    '#type' => 'hidden',
-    '#value' => $message_number,
-  );
-
-  $form['basic_webmail_from_folder'] = array(
-    '#type' => 'hidden',
-    '#value' => $folder,
-  );
-
-  // Fill in the rest of the confirm_form() variables.
-  $question = t('Copy message?');
-  $path = 'basic_webmail/message/' . $message_number . '/' . $folder;
-  $description = t("Copy message from !from_address, sent on !message_date with the subject of '!message_subject'?", array('!from_address' => $from_address, '!message_date' => $message_date, '!message_subject' => $message_subject));
-  $yes = 'Copy';
-  $no = 'Cancel';
-  $name = 'confirm_message_copy';
-
-  // Call the function with the data.
-  $confirmation_result = confirm_form($form, $question, $path, $description, $yes, $no, $name);
-
-  return $confirmation_result;
-} // End of _basic_webmail_copy_message_form().
-
-
-/**
- * Copy a specified message.
- *
- * @param form_id
- *   The ID of the form created in the form generation function.
- * @param form_values
- *   The contents of the form fields.
- */
-function _basic_webmail_copy_message_form_submit($form, &$form_state) {
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['basic_webmail_from_folder']);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Copy the message.
-  if (!imap_mail_copy($imap_resource, $form_state['values']['basic_webmail_message_number'], $form_state['values']['basic_webmail_to_folder'])) {
-    // Report the error.
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-    drupal_set_message(t('There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-  }
-  else {
-    drupal_set_message(t('The message was copied.'));
-    if (!imap_expunge($imap_resource)) {
-      // Report the error.
-      watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  return 'basic_webmail/' . $form_state['values']['basic_webmail_from_folder'];
-} // End of _basic_webmail_copy_message_form_submit().
-
-
-/**
- * Post a message move form.
- *
- * @param message_number
- *   The ID of the message to delete.
- * @param folder
- *   The name of the folder the message is in. If no folder is specified, the
- *   default of 'INBOX' is used.
- *
- * @return
- *   The results of the confirmation question.
- */
-function _basic_webmail_move_message_form($form_state, $message_number, $folder = 'INBOX') {
-  $form = array();
-
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Get the message header.
-  $message_header = imap_headerinfo($imap_resource, $message_number);
-  if (!$message_header) {
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
-  }
-
-  // Retrieve who the message is from.
-  if ($message_header->from[0]->personal) {
-    $from_address = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
-  }
-  else {
-    $from_address = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
-  }
-
-  // Retrieve the message date.
-  if (!$message_header->date) {
-    $message_date = 0;
-  }
-  else {
-    $message_date = $message_header->date;
-  }
-
-  // Retrieve the message subject.
-  if (!$message_header->subject) {
-    $message_subject = '(No subject given.)';
-  }
-  else {
-    $message_subject = _basic_webmail_decode_mime_str($message_header->subject);
-  }
-
-  // Get the list of folders from the server.
-  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
-  if ($folders) {
-    natsort($folders);
-    foreach ($folders as $folder_name) {
-      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
-
-      if ($brief_folder_name != $folder) {
-        $folder_names[$brief_folder_name] = $brief_folder_name;
-      }
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  $form['basic_webmail_to_folder'] = array(
-    '#type' => 'select',
-    '#title' => t('The folder to which you want to move the message'),
-    '#options' => $folder_names,
-  );
-
-  // Fill in the form fields.
-  $form['basic_webmail_message_number'] = array(
-    '#type' => 'hidden',
-    '#value' => $message_number,
-  );
-
-  $form['basic_webmail_from_folder'] = array(
-    '#type' => 'hidden',
-    '#value' => $folder,
-  );
-
-  // Fill in the rest of the confirm_form() variables.
-  $question = t('Move message?');
-  $path = 'basic_webmail/message/' . $message_number . '/' . $folder;
-  $description = t("Move message from !from_address, sent on !message_date with the subject of '!message_subject'?", array('!from_address' => $from_address, '!message_date' => $message_date, '!message_subject' => $message_subject));
-  $yes = 'Move';
-  $no = 'Cancel';
-  $name = 'confirm_message_move';
-
-  // Call the function with the data.
-  $confirmation_result = confirm_form($form, $question, $path, $description, $yes, $no, $name);
-
-  return $confirmation_result;
-} // End of _basic_webmail_move_message_form().
-
-
-/**
- * Move a specified message.
- *
- * @param form_id
- *   The ID of the form created in the form generation function.
- * @param form_values
- *   The contents of the form fields.
- */
-function _basic_webmail_move_message_form_submit($form, &$form_state) {
-  // Connect to the server and retrieve a connection to the mailbox.
-  global $user;
-  $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['basic_webmail_from_folder']);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  // Move the message.
-  if (!imap_mail_move($imap_resource, $form_state['values']['basic_webmail_message_number'], $form_state['values']['basic_webmail_to_folder'])) {
-    // Report the error.
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
-    drupal_set_message(t('There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
-  }
-  else {
-    drupal_set_message(t('The message was moved.'));
-    if (!imap_expunge($imap_resource)) {
-      // Report the error.
-      watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-
-  $form_state['redirect'] = 'basic_webmail/' . $form_state['values']['basic_webmail_from_folder'];
-} // End of _basic_webmail_move_message_form_submit().
-
-
-/*
- Much of the following function was taken from http://us2.php.net/manual/en/function.imap-fetchstructure.php#51497
- */
-
-/**
- * Get a list of all the possible parts.
- *
- * @param imap_resource
- *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
- * @param message_number
- *   The number of the message to get the information for.
- *
- * @return
- *   An array containing all of the available message parts, or FALSE if
- *   there is an error.
- */
-function _basic_webmail_get_parts_list($imap_resource, $message_number) {
-  /*
-    $parts_list = array(
-      [$part_id] => array(
-        '$part_type',
-        '$part_structure'
-      ),
-    );
-  */
-
-  /*
-   * @TODO: This function needs to be rethought through and done better.
-   *        It works for now, so I'm leaving it until later.
-   */
-
-  // Initialize the return value.
-  $parts_list = FALSE;
-
-  // Retrieve the message structure.
-  $message_structure = imap_fetchstructure($imap_resource, $message_number);
-  if (!$message_structure) {
-    $last_error = imap_last_error();
-    watchdog('basic_webmail', 'There was an error retrieving the message structure: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
-    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message structure: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
-  }
-
-  if ($message_structure->type == 0) {
-    // Simple message -- only 1 part.
-    $parts_list[1] = array($message_structure->subtype);
-  }
-  else {
-    // Pull the parts from the message structure.
-    $parts = $message_structure->parts;
-    // Complex message -- multiple parts.
-    $endwhile = FALSE;
-    // Stack while parsing message.
-    $stack = array();
-    // Incrementer.
-    $i = 0;
-
-    // Do while the marker is false.
-    while (!$endwhile) {
-      // If there is no part for this item...
-      if (empty($parts[$i])) {
-        // If the number of items on the stack are one or more...
-        if (count($stack) > 0) {
-          // Process the subparts.
-          // Decrement the stack count by one.
-          $stack_count = count($stack) - 1;
-          // Overwrite the parts list with what is on the stack.
-          $parts = $stack[$stack_count]['p'];
-          // Set the incrementer.
-          $i = $stack[$stack_count]['i'] + 1;
-          // Remove the last item from the stack.
-          array_pop($stack);
-        }
-        else {
-          // End the process.
-          $endwhile = TRUE;
-        }
-      }
-
-      if (!$endwhile) {
-        // Create message part first (example '1.2.3').
-        $partstring = '';
-
-        // Fill in the parts string.
-        foreach ($stack as $s) {
-          $partstring .= ($s['i'] + 1) . '.';
-        }
-
-        // Finish it.
-        $partstring .= ($i + 1);
-
-        // Determine attachment status.
-        // If ifdisposition == 1, then there's one or more attachments. If
-        // type > 2 (0 = text (plain), 1 = multipart (html), 2 = message (rfc?))
-        // then it's not a message attachment.
-        if (!empty($parts[$i])) {
-          if ($parts[$i]->type > 2 && $parts[$i]->ifdisposition) {
-            // One or more attachments exists.
-            $parts_list[$partstring] = array(drupal_strtoupper($parts[$i]->subtype), $parts[$i]);
-          }
-          else {
-            // No attachments exist.
-            $parts_list[$partstring] = array(drupal_strtoupper($parts[$i]->subtype));
-          }
-        }
-      }
-
-      // If there are subparts.
-      if (!empty($parts[$i]->parts)) {
-        // Add to the stack, filling it with the subparts and the increment
-        // number.
-        $stack[] = array(
-          'p' => $parts,
-          'i' => $i,
-        );
-        // Reset the parts array with the subparts for continued processing.
-        $parts = $parts[$i]->parts;
-        // Reset the incrementer.
-        $i = 0;
-      }
-      else {
-        // Bump the incrementer.
-        $i++;
-      }
-    }
-  }
-
-  return $parts_list;
-} // End of _basic_webmail_get_parts_list().
-
-
-/**
- * Decode the body part for the specified message number and message part ID.
- *
- * @param imap_resource
- *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
- * @param message_number
- *   The number of the message to get the information for.
- * @param part_id
- *   The ID of the part to get the information for.
- *
- * @return
- *   The message body, decoded if necessary.
- */
-function _basic_webmail_decode_body_part($imap_resource, $message_number, $part_id) {
-  $message_body_structure = imap_bodystruct($imap_resource, $message_number, $part_id);
-  switch ($message_body_structure->encoding) {
-    case 3:
-      return imap_base64(_basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id));
-      break;
-
-    case 4:
-      return utf8_encode(quoted_printable_decode(_basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id)));
-      break;
-
-    default:
-      return _basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id);
-      break;
-  }
-} // End of _basic_webmail_decode_body_part().
-
-
-/**
- * Process the attachment for the specified message number and message part ID.
- *
- * @param imap_resource
- *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
- * @param message_number
- *   The number of the message to get the information for.
- * @param part_id
- *   The ID of the part to get the information for.
- * @param part_structure
- *   An object with the structure definitaion of the part of the message that
- *   represents the attachment.
- *
- * @return
- *   An array containing all of the available message parts, or FALSE if
- *   there is an error.
- */
-function _basic_webmail_process_attachment($imap_resource, $message_number, $part_id, $part_structure) {
-  $attachment = '';
-  $file_name = $part_structure->dparameters[0]->value;
-  $file_data = _basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id);
-
-  if ($part_structure->encoding == 3) {
-    // Decode if base64.
-    $file_data = base64_decode($file_data);
-  }
-  elseif ($part_structure->encoding == 4) {
-    $file_data = quoted_printable_decode($file_data);
-  }
-
-  // Create the destination path variable, along with creating any necessary
-  // directories.
-  $file_dest = variable_get('basic_webmail_attachment_location', file_directory_path() . '/attachments');
-  $file_dest .= '/';
-
-  global $user;
-  $file_dest .= $user->name;
-  file_prepare_directory($file_dest, FILE_CREATE_DIRECTORY);
-  $file_dest .= '/';
-
-  $message_overview = imap_fetch_overview($imap_resource, arg(2));
-  $file_dest .= drupal_substr($message_overview[0]->message_id, 1, drupal_strlen($message_overview[0]->message_id) - 2);
-  file_prepare_directory($file_dest, FILE_CREATE_DIRECTORY);
-
-  if (isset($_SESSION['messages']) && isset($_SESSION['messages']['status'])) {
-    foreach ($_SESSION['messages']['status'] as $key => $drupal_message) {
-      if (drupal_substr($drupal_message, 0, 13) == 'The directory' && drupal_substr($drupal_message, drupal_strlen($drupal_message) - 17, 17) == 'has been created.') {
-        unset($_SESSION['messages']['status'][$key]);
-      }
-    }
-  }
-
-  $file_path = file_save_data($file_data, $file_dest . '/' . $file_name, FILE_EXISTS_REPLACE);
-  $file_url = file_create_url($file_path);
-  $attachment = array($file_path, $file_name, $file_url);
-
-  return $attachment;
-} // End of _basic_webmail_process_attachment().
-
-
-/** *******************************************************
- *
- *  The next four functions are from
- *  http://us3.php.net/manual/en/function.imap-fetchbody.php#31685
- *  with modifications for Drupal Coding Standards:
- *  http://drupal.org/coding-standards
- *  and what is already here in this module.
- *
- *  ******************************************************/
-
-
-// Get the body of a part of a message according to the string in $part.
-/**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
- */
-function _basic_webmail_mail_fetchpart($imap_resource, $message_number, $part) {
-  $parts = _basic_webmail_mail_fetchparts($imap_resource, $message_number);
-  $part_numbers = explode(".", $part);
-  $current_part = $parts;
-
-  while (list($key, $val) = each($part_numbers)) {
-    $current_part = $current_part[$val];
-  }
-
-  if ($current_part != "") {
-    return $current_part;
-  }
-  else {
-    return FALSE;
-  }
-} // End of _basic_webmail_mail_fetchpart().
-
-
-// Get an array with the bodies of all parts of an email.
-// The structure of the array corresponds to the structure that is available
-// with imap_fetchstructure.
-/**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
- */
-function _basic_webmail_mail_fetchparts($imap_resource, $message_number) {
-  $parts = array();
-  $header = imap_fetchheader($imap_resource, $message_number);
-  $body = imap_body($imap_resource, $message_number, FT_INTERNAL);
-  $i = 1;
-
-  $new_parts = _basic_webmail_mail_mimesplit($header, $body);
-  if ($new_parts) {
-    while (list($key, $val) = each($new_parts)) {
-      $parts[$i] = _basic_webmail_mail_mimesub($val);
-      $i++;
-    }
-  }
-  else {
-    $parts[$i] = $body;
-  }
-
-  return $parts;
-} // End of _basic_webmail_mail_fetchparts().
-
-
-/**
- * Splits a mulitpart mime message body into its respective parts.
- *
- * If the message body is a mulitpart mime message, this function slits the
- * body out into the various parts.
- *
- * @param header
- *   A string containing the header of the message.
- * @param body
- *   A string containing the body of the message.
- *
- * @return
- *   An array containing the message body's parts, or FALSE, if no parts are
- *   found.
- */
-function _basic_webmail_mail_mimesplit($header, $body) {
-  // Initialize the message parts variable.
-  $parts = array();
-  // Matches 'Content-Type:', followed by any character zero or more times,
-  // followed by 'boundary="', followed by any character other than '"' one or
-  // more times, followed by '"'.
-  $pattern = '~.*boundary="[^"]+"~';
-  // Search the message header for the message part boundary definition, which
-  // is what $pattern describes, and save the results in $regs.
-  if (preg_match($pattern, $header, $regs)) {
-    // I can't seem to figure out how to get the previous match to work 100%
-    // with PCRE as it was originally intended to work in POSIX, so I've
-    // created this interim step, which ends up producing the desired results.
-    $interim_pattern = '~"[^"]+"~';
-    preg_match($interim_pattern, $regs[0], $interim_results);
-    // Save the actual boundary from the results.
-    $boundary = drupal_substr($interim_results[0], 1, drupal_strlen($interim_results[0]) - 2);
-
-    // Matches zero or more characters that are not '\r\n' before and after
-    // what is in '$boundary'.
-    $delimiter_reg = '~[^\r\n]*' . $boundary . '[^\r\n]*~';
-
-    // Search $body for any instance of the boundary, which is what
-    // $delimiter_reg describes, and save the results in $results.
-    if (preg_match($delimiter_reg, $body, $results)) {
-      // Break out the results into the relevant pieces.
-      $delimiter = $results[0];
-      $parts = explode($delimiter, $body);
-      $parts = array_slice($parts, 1, -1);
-    }
-
-    // Deliver the payload.
-    return $parts;
-  }
-  // No parts were found, so return FALSE.
-  else {
-    return FALSE;
-  }
-} // End of _basic_webmail_mail_mimesplit().
-
-
-// Returns an array with all parts that are subparts of the given part.
-// If no subparts are found, returns the body of the current part.
-/**
- * @todo Please document this function.
- * @see http://drupal.org/node/1354
- */
-function _basic_webmail_mail_mimesub($part) {
-  $i = 1;
-  $head_delimiter = "\r\n\r\n";
-  $del_length = drupal_strlen($head_delimiter);
-
-  // get head & body of the current part
-  $end_of_head = strpos($part, $head_delimiter);
-  $head = drupal_substr($part, 0, $end_of_head);
-  $body = drupal_substr($part, $end_of_head + $del_length, drupal_strlen($part));
-
-  // check whether it is a message according to rfc822
-  if (stristr($head, "Content-Type: message/rfc822")) {
-    $part = drupal_substr($part, $end_of_head + $del_length, drupal_strlen($part));
-    $return_parts[1] = _basic_webmail_mail_mimesub($part);
-    return $return_parts;
-  }
-  // if no message, get subparts and call function recursively
-  elseif ($sub_parts = _basic_webmail_mail_mimesplit($head, $body)) {
-    // got more subparts
-    while (list($key, $val) = each($sub_parts)) {
-      $return_parts[$i] = _basic_webmail_mail_mimesub($val);
-      $i++;
-    }
-
-    return $return_parts;
-  }
-  else {
-    return $body;
-  }
-} // End of _basic_webmail_mail_mimesub().
-/*
- End of four imap_fetchbody functions.
- */
-
-
-/**
- * Checks for the existence of a specified mailbox.
- *
- * @param imap_resource
- *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
- * @param mailbox
- *   The name of the mailbox to check for.
- *
- * @return
- *   Returns TRUE if the mailbox exists, and FALSE if it does not exist.
- */
-function _basic_webmail_mailbox_exists($imap_resource, $mailbox) {
-  $mailbox_exists = FALSE;
-
-  $mailboxes = imap_getmailboxes($imap_resource, _basic_webmail_get_server_string(), '*');
-  foreach ($mailboxes as $mailbox_object) {
-    if (drupal_substr($mailbox_object->name, strpos($mailbox_object->name, '}') + 1, drupal_strlen($mailbox_object->name)) == $mailbox) {
-      $mailbox_exists = TRUE;
-    }
-  }
-
-  return $mailbox_exists;
-} // End of _basic_webmail_mailbox_exists().
-
-
-/**
- * Checks if the standard mailboxes exist and creates them, if necessary.
- *
- * This function checks to see if the standard mailboxes exit or not. If they
- * do not exist, this function will also create them. This fucntion will then
- * subscribe to the mailboxes.
- *
- * @param user_id
- *   The user ID of the mailbox to subscribe to.
- */
-function _basic_webmail_subscribe_to_mailboxes($user_id) {
-  // Connect to the server and retrieve a connection to the mailbox.
-  $imap_resource = _basic_webmail_connect_to_server($user_id);
-  if (!$imap_resource) {
-    drupal_set_title(t('Error'));
-    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
-  }
-
-  $mailboxes = array('INBOX', 'INBOX.Drafts', 'INBOX.Junk', 'INBOX.Sent', 'INBOX.Trash');
-  foreach ($mailboxes as $mailbox) {
-    if (!imap_status($imap_resource, _basic_webmail_get_server_string() . $mailbox, SA_ALL)) {
-      if (!imap_createmailbox($imap_resource, _basic_webmail_get_server_string() . $mailbox)) {
-        watchdog('basic_webmail', 'There was an error subscribing to the INBOX mailbox: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-      }
-    }
-
-    if (!imap_subscribe($imap_resource, _basic_webmail_get_server_string() . $mailbox)) {
-      watchdog('basic_webmail', 'There was an error subscribing to the !mailbox mailbox: @last_error', array('!mailbox' => $mailbox, '@last_error' => imap_last_error()), WATCHDOG_WARNING);
-    }
-  }
-
-  // Clean up.
-  if (!imap_close($imap_resource)) {
-    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
-  }
-} // End of _basic_webmail_subscribe_to_mailboxes().
-
-
-/**
- * Converts UTF8 encoded strings.
- *
- * This function is necessary, because there is a bug in some versions of PHP
- * that returns strings converted with the imap_utf8() function in all upper
- * case letters.  http://bugs.php.net/bug.php?id=44098
- *
- * This function was taken from here and modified:
- * http://us2.php.net/manual/en/function.imap-utf8.php#92026
- */
-function _basic_webmail_decode_mime_str($string, $char_set = 'UTF-8') {
-  $new_string = '';
-  $elements = imap_mime_header_decode($string);
-
-  for ($i = 0; $i < count($elements); $i++) {
-    if ($elements[$i]->charset == 'default') {
-      $elements[$i]->charset = 'iso-8859-1';
-    }
-
-    $new_string .= iconv($elements[$i]->charset, $char_set, $elements[$i]->text);
-  }
-
-  return $new_string;
-} // End of _basic_webmail_decode_mime_str().
-
-
-/** *******************************************************
- *
- *  Administrative functions.
- *
- *  ******************************************************/
-
-
-/**
- * Automatically fills in email addresses of the current users.
- *
- * Copied and modified from taxonomy_autocomplete() in
- * modules/taxonomy/taxonomy.pages.inc
- */
-function basic_webmail_autocomplete($field_name, $addresses = '') {
-  // Get the field definition.
-  $field = field_info_field($field_name);
-
-  // The user enters a comma-separated list of email addresses. We only
-  // autocomplete the last address.
-  $address_array = drupal_explode_tags($addresses);
-
-  // Get the last address.
-  $last_address = trim(drupal_strtolower(array_pop($address_array)));
-
-  $matches = array();
-
-  if ($last_address != '') {
-    // Search the users table for all email addresses which are similar to
-    // the last item in the list.
-//    $query = "SELECT mail FROM {users} WHERE LOWER(mail) LIKE LOWER('%%%s%%') AND status = 1";
-    $query = db_select('users', 'u')
-      ->fields('u', array(mail))
-      ->condition('u.status', 1)
-      ->condition('u.mail', '%' . db_like($last_address) . '%', 'LIKE')
-      ->range(0, 10);
-
-    // Do not select any addresses that are already entered.
-    if (!empty($address_array)) {
-      $query->condition('t.mail', $address_array, 'NOT IN');
-    }
-
-    // Execute the query and get the results.
-    $results = $query
-      ->execute()
-      ->fetchAllKeyed();
-
-    // Convert what's left of the array to a string.
-    $prefix = count($address_array) ? drupal_implode_tags($address_array) . ', ' : '';
-
-    // Iterate through the list of similar email addresses.
-    foreach ($results as $mail) {
-      $n = $mail;
-      // Add the email address to the list of possible matches.
-      $matches[$prefix . $n] = $mail;
-    }
-  }
-
-  // Send the results back.
-  drupal_json_output($matches);
-} // End of basic_webmail_autocomplete().
+<?php
+
+/**
+ * @file
+ * This is the main code file for the Basic webmail module.
+ *
+ * This module allows users to send and receive email through an IMAP mail
+ * server with a web based user interface.
+ */
+
+/** *******************************************************
+ *
+ *  Implementation of Drupal hooks.
+ *
+ *  ******************************************************/
+
+/**
+ * Implements hook_help().
+ */
+function basic_webmail_help($path, $arg) {
+  $output = '';
+
+  switch ($path) {
+    case 'admin/config/basic_webmail':
+      $output = t('Send and receive email through an IMAP mail server.');
+      break;
+  }
+
+  return $output;
+} // End of basic_webmail_help().
+
+
+/**
+ * Implements hook_permission().
+ */
+function basic_webmail_permission() {
+  return array(
+    'administer basic_webmail' => array(
+      'title' => t('Administer basic_webmail'),
+      'description' => 'Perform administration tasks for Basic webmail.',
+    ),
+    'access basic_webmail' => array(
+      'title' => t('Access basic_webmail'),
+      'description' => 'Use Basic webmail',
+    ),
+  );
+} // End of basic_webmail_permission().
+
+
+/**
+ * Implements hook_menu().
+ */
+function basic_webmail_menu() {
+  $items = array();
+
+  // Admin settings.
+  $items['admin/config/system/basic_webmail'] = array(
+    'title' => 'Basic webmail',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('basic_webmail_admin_settings'),
+    'access arguments' => array('administer basic_webmail'),
+    'description' => 'Configure the mail server.',
+//    'file' => 'basic_webmail.admin.inc',
+  );
+
+  // The main mail listing page. +
+  $items['basic_webmail'] = array(
+    'title' => 'Email',
+    'page callback' => 'drupal_get_form',
+//    'page callback' => 'basic_webmail_mail_list',
+//    'page arguments' => 'basic_webmail_mail_list',
+    'page arguments' => array('basic_webmail_mail_list_form'),
+    'description' => 'Send and/or receive email.',
+    'access arguments' => array('access basic_webmail'),
+    'type' => MENU_NORMAL_ITEM,
+//    'file' => 'basic_webmail.list.inc',
+  );
+
+  // The delete message confirmation page. +
+  $items['basic_webmail/delete'] = array(
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('_basic_webmail_delete_message_form'),
+    'access arguments' => array('access basic_webmail'),
+    'type' => MENU_CALLBACK,
+//    'file' => 'basic_webmail.list.inc',
+  );
+  // The copy message page. +
+  $items['basic_webmail/copy'] = array(
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('_basic_webmail_copy_message_form'),
+    'access arguments' => array('access basic_webmail'),
+    'type' => MENU_CALLBACK,
+//    'file' => 'basic_webmail.list.inc',
+  );
+  // The move message page. +
+  $items['basic_webmail/move'] = array(
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('_basic_webmail_move_message_form'),
+    'access arguments' => array('access basic_webmail'),
+    'type' => MENU_CALLBACK,
+//    'file' => 'basic_webmail.list.inc',
+  );
+
+  // The message view page.
+  $items['basic_webmail/message'] = array(
+    'page callback' => '_basic_webmail_message',
+    'access arguments' => array('access basic_webmail'),
+    'type' => MENU_CALLBACK,
+//    'file' => 'basic_webmail.view.inc',
+  );
+
+  // The compose message page. +
+  $items['basic_webmail/sendmail'] = array(
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('_basic_webmail_send_mail_form'),
+    'access arguments' => array('access basic_webmail'),
+    'type' => MENU_CALLBACK,
+//    'file' => 'basic_webmail.edit.inc',
+  );
+  // Show email matches when filling in the forms.
+  $items['basic_webmail/autocomplete'] = array(
+    'title' => 'Basic webmail autocomplete',
+    'page callback' => 'basic_webmail_autocomplete',
+    'access arguments' => array('access basic_webmail'),
+    'type' => MENU_CALLBACK,
+//    'file' => 'basic_webmail.edit.inc',
+  );
+
+  return $items;
+} // End of basic_webmail_menu().
+
+/** *******************************************************
+ *
+ *  These next hooks are what became of hook_user().
+ *
+ *  ******************************************************/
+
+function basic_webmail_form_alter(&$form, &$form_state, $form_id) {
+//dpm('$form');
+//dpm($form);
+//dpm('$form_state');
+//dpm($form_state);
+//dpm('$form_id = "' . $form_id . '"');
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ *
+ * Modifies the user profile page to add the login ID and password fields.
+ */
+function basic_webmail_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
+  // If this is the user's account form, they are allowed to access Basic
+  // webmail, and the administrator has chosen to collect the login ID and
+  // password, then add the fields to the form.
+  if ($form['#user_category'] == 'account' && user_access('access basic_webmail') && !variable_get('basic_webmail_account_info', 1)) {
+    _basic_webmail_form_user_form($form);
+  }
+} // End of basic_webmail_form_user_profile_form_alter() {
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ *
+ * Modifies the user registration page to add the login ID and password fields.
+ */
+function basic_webmail_form_user_register_form_alter(&$form, &$form_state, $form_id) {
+  // If the user is allowed to access Basic webmail, and the administrator has
+  // chosen to collect the login ID and password, then add the fields to the
+  // form.
+  if (user_access('access basic_webmail') && !variable_get('basic_webmail_account_info', 1)) {
+    _basic_webmail_form_user_form($form);
+  }
+} // End of basic_webmail_form_user_profile_form_alter() {
+
+/**
+ * The form parts to add to the user forms above.
+ */
+function _basic_webmail_form_user_form(&$form) {
+  $basic_webmail_username = '';
+
+  if (!empty($form['#user']->data['basic_webmail_username'])) {
+    $basic_webmail_username = $form['#user']->data['basic_webmail_username'];
+  }
+
+  $form['basic_webmail_email_settings'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Basic webmail account settings'),
+    '#collapsible' => TRUE,
+    '#weight' => 1,
+  );
+  $form['basic_webmail_email_settings']['basic_webmail_username'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Email account login'),
+    '#default_value' => $basic_webmail_username,
+    '#description' => 'The login ID of your email account.',
+    '#required' => TRUE,
+  );
+  $form['basic_webmail_email_settings']['basic_webmail_password'] = array(
+    '#type' => 'password_confirm',
+    '#description' => 'The login password of your email account.',
+  );
+} // End of basic_webmail_form_user_register_form_form_alter() {
+
+
+/**
+ * Implements hook_user_insert().
+ * /
+function basic_webmail_user_insert(&$edit, $account, $category) {
+  if (variable_get('basic_webmail_account_info', 1)) {
+    $edit['data']['basic_webmail_username'] = $edit['mail'];
+    $edit['data']['basic_webmail_password'] = $edit['pass'];
+  }
+
+  $basic_webmail_common_inc = drupal_get_path('module', 'basic_webmail') . 'basic_webmail.common.inc';
+  include_once($basic_webmail_common_inc);
+
+  _basic_webmail_subscribe_to_mailboxes();
+} // End of basic_webmail_user().
+
+
+/**
+ * Implements hook_user_update().
+ * /
+function basic_webmail_user_update(&$edit, $account, $category) {
+  if ($category == 'account' && variable_get('basic_webmail_account_info', 1)) {
+    if ($edit['mail'] != $account->mail) {
+      $edit['data']['basic_webmail_username'] = $edit['mail'];
+    }
+    else {
+      $edit['data']['basic_webmail_username'] = $account->mail;
+    }
+
+    if ($edit['pass'] != '') {
+      $edit['data']['basic_webmail_password'] = $edit['pass'];
+    }
+    else {
+      $edit['data']['basic_webmail_password'] = $account->basic_webmail_password;
+    }
+  }
+
+  $basic_webmail_common_inc = drupal_get_path('module', 'basic_webmail') . '/basic_webmail.common.inc';
+  require($basic_webmail_common_inc);
+
+  _basic_webmail_subscribe_to_mailboxes();
+
+dpm('$edit:');
+dpm($edit);
+dpm('$account:');
+dpm($account);
+dpm('$category: '. $category);
+} // End of basic_webmail_user_update().
+
+
+/**
+ * Implements hook_user_presave().
+ */
+function basic_webmail_user_presave(&$edit, $account, $category) {
+//dpm('$edit:');
+//dpm($edit);
+//dpm('$account:');
+//dpm($account);
+  // Remove the incorrectly named password variable.
+  if (!empty($edit['basic_webmail_passsword'])) {
+    unset($edit['basic_webmail_passsword']);
+  }
+  if (!empty($edit['data']['basic_webmail_passsword'])) {
+    unset($edit['data']['basic_webmail_passsword']);
+  }
+
+  // Check to see if we need to save any information.
+  if ($category == 'account') {
+    // Initialize the variable to keep track of changes, so we don't access the
+    // mail server unnecessarily.
+    $changed = 0;
+
+    // We're providing our own fields to collect the login ID and password.
+    if (variable_get('basic_webmail_account_info', 1) == 0) {
+      // If the email address has changed, save it as the login id.
+      if (($account->data['basic_webmail_username'] != $edit['basic_webmail_username']) && !empty($edit['basic_webmail_username'])) {
+        $edit['data']['basic_webmail_username'] = $edit['basic_webmail_username'];
+        $changed++;
+      }
+
+      if (!empty($edit['basic_webmail_password'])) {
+        $edit['data']['basic_webmail_password'] = $edit['basic_webmail_password'];
+        $changed++;
+      }
+    }
+    // We're using the system provided fields for the login ID and password.
+    elseif (variable_get('basic_webmail_account_info', 1) == 1) {
+      // If the email address has changed, save it as the login id.
+      if (($account->data['basic_webmail_username'] != $edit['basic_webmail_username']) && !empty($edit['basic_webmail_username'])) {
+        $edit['data']['basic_webmail_username'] = $edit['basic_webmail_username'];
+        $changed++;
+      }
+
+      // If the password has changed, save it.
+      if (!empty($edit['basic_webmail_password'])) {
+        $edit['data']['basic_webmail_password'] = $edit['basic_webmail_password'];
+        $changed++;
+      }
+    }
+     // We're using the system provided fields for the login ID and password.
+   else {
+      // If the username has changed, save it as the login id.
+      if (($account->data['basic_webmail_username'] != $edit['basic_webmail_username']) && !empty($edit['basic_webmail_username'])) {
+        $edit['data']['basic_webmail_username'] = $edit['basic_webmail_username'];
+        $changed++;
+      }
+
+      // If the password has changed, save it.
+      if (!empty($edit['basic_webmail_password'])) {
+        $edit['data']['basic_webmail_password'] = $edit['basic_webmail_password'];
+        $changed++;
+      }
+    }
+
+//include_once('includes/password.inc');
+//dpm(user_hash_password($edit['basic_webmail_password']));
+
+    if ($changed > 0) {
+//      $basic_webmail_common_inc = drupal_get_path('module', 'basic_webmail') . '/basic_webmail.common.inc';
+//      include_once($basic_webmail_common_inc);
+      _basic_webmail_subscribe_to_mailboxes($account->uid);
+    }
+  }
+} // End of basic_webmail_user_presave().
+
+/** *******************************************************
+ *
+ *  End of hook_user() hooks.
+ *
+ *  ******************************************************/
+
+/**
+ * Implements hook_mail().
+ */
+function basic_webmail_mail($key, &$message, $params) {
+  if (!empty($params['headers'])) {
+    foreach ($params['headers'] as $key => $value) {
+      $message['headers'][$key] = $params['headers'][$key];
+    }
+  }
+  $message['subject'] = $params['subject'];
+  $message['body'] = $params['body'];
+} // End of basic_webmail_mail().
+
+
+/**
+ * Implements hook_theme().
+ * /
+function basic_webmail_theme() {
+  return array(
+    'basic_webmail_mail_list_form' => array(
+      'render element' => 'form',
+    ),
+  );
+} // End of basic_webmail_theme().
+
+
+/** *******************************************************
+ *
+ *  Administrative functions.
+ *
+ *  ******************************************************/
+
+
+/**
+ * Administration settings form.
+ *
+ * @return
+ *   The completed form definition.
+ */
+function basic_webmail_admin_settings($form, &$form_state) {
+  $form = array();
+
+  $form['basic_webmail_general_settings'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('General settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+  $options = array(
+    0 => "Add Basic webmail specific fields to collect the login ID and password",
+    1 => "Use the user's account email address and password for checking email",
+    2 => "Use the user's account name and password for checking email",
+  );
+  $form['basic_webmail_general_settings']['basic_webmail_account_info'] = array(
+    '#type' => 'radios',
+    '#title' => t("How shoud the account login ID and password be collected?"),
+    '#options' => $options,
+    '#default_value' => variable_get('basic_webmail_account_info', 1),
+    '#description' => t("Instead of providing additional form fields to get the user's email address and password, just use what is provided within the account settings."),
+  );
+  $max_file_uploads = ini_get ('max_file_uploads');
+  if (!empty($max_file_uploads)) {
+    $description = t("The number of attachments to allow on the contact form. The maximum number of allowed uploads may be limited by PHP. Your system's php.ini file has it set to @max_file_uploads. To change it, alter the max_file_uploads directive.", array('@max_file_uploads' => $max_file_uploads));
+  }
+  else {
+    $description = t("The number of attachments to allow on the contact form. The maximum number of allowed uploads may be limited by PHP. If necessary, check your system's PHP php.ini file for a max_file_uploads directive to change.");
+  }
+  $form['basic_webmail_general_settings']['basic_webmail_number_attachments'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Number of attachments'),
+    '#size' => 10,
+    '#default_value' => variable_get('basic_webmail_number_attachments', 3),
+    '#description' => $description,
+  );
+  $form['basic_webmail_general_settings']['basic_webmail_attachment_location'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Attachment location'),
+    '#default_value' => variable_get('basic_webmail_attachment_location', file_default_scheme() . '/attachments'),
+    '#description' => t('The file path where to save message attachments.'),
+  );
+
+  $form['basic_webmail_listing_settings'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Message listing settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+  $form['basic_webmail_listing_settings']['basic_webmail_messages_per_page'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Messages per page'),
+    '#size' => 10,
+    '#default_value' => variable_get('basic_webmail_messages_per_page', 25),
+    '#description' => t('The number of messages to show per page when viewing the listing.'),
+  );
+  $form['basic_webmail_listing_settings']['basic_webmail_subject_characters'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Number of characters to display'),
+    '#size' => 10,
+    '#default_value' => variable_get('basic_webmail_subject_characters', 40),
+    '#description' => t('This is the number of characters of the subject that are displayed in the message list before being truncated. Entering a zero (0) here will cause the listing to display all characters of the subject line, no matter how long it is.'),
+  );
+  $timestamp = REQUEST_TIME;
+  $small_date = format_date($timestamp, 'short');
+  $medium_date = format_date($timestamp);
+  $large_date = format_date($timestamp, $type = 'long');
+  $options = array(
+    'small' => t('Small (!small_date)', array('!small_date' => $small_date)),
+    'medium' => t('Medium (!medium_date)', array('!medium_date' => $medium_date)),
+    'large' => t('Long (!large_date)', array('!large_date' => $large_date)),
+    'custom' => t('Custom'),
+  );
+  $form['basic_webmail_listing_settings']['basic_webmail_format_option'] = array(
+    '#type' => 'radios',
+    '#title' => t('Date format option'),
+    '#options' => $options,
+    '#default_value' => variable_get('basic_webmail_format_option', 'small'),
+    '#description' => t('Specify how you want the date of the message displayed.'),
+  );
+  $form['basic_webmail_listing_settings']['basic_webmail_custom_format'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Custom format'),
+    '#default_value' => variable_get('basic_webmail_custom_format', 'D, M j, Y - g:i:s a'),
+    '#description' => t('Specify how you want the Custom date format configured, using the format options of the PHP !date function.',
+      array(
+        '!date' => l(t('date()', array(), array('langcode' => 'en')), 'http://php.net/manual/en/function.date.php')
+      ),
+      array(
+        'langcode' => 'en',
+      )
+    ),
+  );
+
+  $form['basic_webmail_server_settings'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Server settings'),
+    '#collapsible' => TRUE,
+    '#collapsed' => FALSE,
+  );
+  $form['basic_webmail_server_settings']['basic_webmail_server_address'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Server address'),
+    '#default_value' => variable_get('basic_webmail_server_address', ''),
+    '#description' => t('The address to the server you wish to connect to.'),
+  );
+  $form['basic_webmail_server_settings']['basic_webmail_server_port'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Connection port'),
+    '#size' => 10,
+    '#default_value' => variable_get('basic_webmail_server_port', 143),
+    '#description' => t('The default IMAP port is 143, if one is not specified. If you are using SSL, the default port number is 993. If you are using TLS, the default port number is 143.'),
+  );
+  $form['basic_webmail_server_settings']['basic_webmail_secure_log_in'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Secure login'),
+    '#default_value' => variable_get('basic_webmail_secure_log_in', 0),
+    '#description' => t('Check to make a secure connection to your IMAP Server.'),
+  );
+  $form['basic_webmail_server_settings']['basic_webmail_use_ssl'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Encrypt session using SSL'),
+    '#default_value' => variable_get('basic_webmail_use_ssl', 0),
+    '#description' => t('Use SSL to connect to the server.'),
+  );
+  $form['basic_webmail_server_settings']['basic_webmail_validate_cert'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Validate certificate'),
+    '#default_value' => variable_get('basic_webmail_validate_cert', 0),
+    '#description' => t('When using a secure connection, validate the certificate.'),
+  );
+  $form['basic_webmail_server_settings']['basic_webmail_use_tls'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Encrypt session using TLS'),
+    '#default_value' => variable_get('basic_webmail_use_tls', 0),
+    '#description' => t('Use TLS to connect to the server.'),
+  );
+
+  return system_settings_form($form);
+} // End of basic_webmail_admin_settings().
+
+
+/**
+ * Additional vaidation for the administration settings form.
+ *
+ * @param form_id
+ *   The form ID of the passed form.
+ * @param $form_state
+ *   The form values which you may perform validation on.
+ */
+function basic_webmail_admin_settings_validate($form, &$form_state) {
+  if ($form_state['values']['basic_webmail_format_option'] == 'custom' && $form_state['values']['basic_webmail_custom_format'] == '') {
+    form_set_error('basic_webmail_custom_format', t('You have specified Custom as your Format option for your Date format, but you have not specified the configuration of the Cuatom format. Either choose a different Format option, or specify the configuration of the Custom format.'));
+  }
+
+  if (!file_prepare_directory($form_state['values']['basic_webmail_attachment_location'], FILE_CREATE_DIRECTORY)) {
+    form_set_error('basic_webmail_attachment_location', t('The directory does not exist or is not writable, and there was a problem creating the path.'));
+  }
+
+  if ($form_state['values']['basic_webmail_use_ssl'] == 1 && $form_state['values']['basic_webmail_server_port'] == '143') {
+    form_set_error('basic_webmail_server_port', t('The normal port for secure IMAP is 993.'));
+  }
+} // End of basic_webmail_admin_settings_validate().
+
+
+/** *******************************************************
+ *
+ *  The main functions of the module.
+ *
+ *  ******************************************************/
+
+/**
+ * Display the listing of messages.
+ *
+ * @param folder
+ *   The name of the folder to open. If no folder is specified, the default
+ *   of 'INBOX' is used.
+ *
+ * @return
+ *   The formatted message listing.
+ * /
+function basic_webmail_mail_list($folder = 'INBOX') {
+  $output = '';
+  $form = array();
+
+  // Set the title of the page to the current mailbox, if there is one.
+  if (arg(1)) {
+    drupal_set_title(t('!title', array('!title' => arg(1))));
+  }
+
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  $mailboxes = imap_getsubscribed($imap_resource, _basic_webmail_get_server_string(), '*');
+  if (!$mailboxes[4]) {
+    _basic_webmail_subscribe_to_mailboxes();
+  }
+
+  // Retrieve and display the list of folders.
+  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
+  if ($folders) {
+    /*
+    $output .= '<br />';
+
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
+    }
+
+    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
+    $output .= '<hr>';
+     *
+     * /
+    $output = '<br />';
+
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
+    }
+
+    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
+    $output .= '<hr>';
+    $form['folders'] = $output;
+  }
+  else {
+//    $output .= '<br />';
+    $form['folders'] = '<br />';
+  }
+
+  if (imap_num_msg($imap_resource) > 0) {
+    // Retrieve and display the mail in the current folder.
+    $threads = imap_thread($imap_resource);
+    if ($threads === FALSE) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', 'There was an error getting the list of messages: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+      return '<br />' . t('There was an error getting the list of messages: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
+    }
+    else {
+      // TODO Please review the conversion of this statement to the D7 database API syntax.
+      /* db_query('DELETE FROM {basic_webmail_messages} WHERE user_id = %d', $user->uid) * /
+      db_delete('basic_webmail_messages')
+        ->condition('user_id', $user->uid)
+        ->execute();
+
+      $total_messages = 0;
+      $new_messages = 0;
+
+      // Save the message information in a temporary table.
+      foreach ($threads as $key => $message_number) {
+        $tree = explode('.', $key);
+        if ($tree[1] == 'num' && $message_number > 0) {
+          $message_header = imap_headerinfo($imap_resource, $message_number);
+
+          if ($message_header->Deleted == ' ') {
+            $total_messages++;
+
+            // Check for attachments.
+            // Get the message parts list.
+            $parts_list = _basic_webmail_get_parts_list($imap_resource, $message_number);
+            // Iterate over the parts list.
+            foreach ($parts_list as $part_id => $part_array) {
+              if (!empty($part_array[0]) && !empty($part_array[1])) {
+                $attachment_exists = 1;
+                continue;
+              }
+              else {
+                $attachment_exists = 0;
+              }
+            }
+
+            // Check if message was answered.
+            if ($message_header->Answered == 'A') {
+              $message_answered = 1;
+            }
+            else {
+              $message_answered = 0;
+            }
+
+            $number_characters = variable_get('basic_webmail_subject_characters', 40);
+            if (empty($number_characters)) {
+              $message_subject_link = l(_basic_webmail_decode_mime_str($message_header->subject), 'basic_webmail/message/' . $message_number . '/' . $folder);
+            }
+            else {
+              $message_subject_link = l(truncate_utf8(_basic_webmail_decode_mime_str($message_header->subject), $number_characters, TRUE, TRUE), 'basic_webmail/message/' . $message_number . '/' . $folder);
+            }
+
+            if ($message_header->Recent == 'N' || $message_header->Unseen == 'U') {
+              $new_messages++;
+              $message_unread = 1;
+
+              if (empty($message_header->subject)) {
+                $message_subject = '<strong>' . l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder) . '</strong>';
+              }
+              else {
+                $message_subject = '<strong>' . $message_subject_link . '</strong>';
+              }
+            }
+            else {
+              $message_unread = 0;
+
+              if (empty($message_header->subject)) {
+                $message_subject = l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder);
+              }
+              else {
+                $message_subject = $message_subject_link;
+              }
+            }
+
+//            if ($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host == '@') {
+            if (empty($message_header->from[0]->mailbox) && empty($message_header->from[0]->host)) {
+              $from_address = '(Unknown)';
+            }
+            elseif (!empty($message_header->from[0]->personal)) {
+              $from_address = l(_basic_webmail_decode_mime_str($message_header->from[0]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>');
+            }
+            else {
+              $from_address = l($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host, 'basic_webmail/sendmail/' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host);
+            }
+
+            if (empty($message_header->date)) {
+              $message_date = 0;
+            }
+            else {
+              $message_date = _basic_webmail_mail_list_process_message_date($message_header->date);
+            }
+
+            // imap_uid($imap_resource, $message_number)
+            // TODO Please review the conversion of this statement to the D7 database API syntax.
+            /* db_query('INSERT INTO {basic_webmail_messages} (user_id, message_number, message_subject, from_address, message_date, message_unread, message_answered, attachment_exists) VALUES (%d, %d, "%s", "%s", "%s", %d, %d, %d)', $user->uid, $message_number, $message_subject, $from_address, $message_date, $message_unread, $message_answered, $attachment_exists) * /
+            $id = db_insert('basic_webmail_messages')
+              ->fields(array(
+                'user_id' => $user->uid,
+                'message_number' => $message_number,
+                'message_subject' => $message_subject,
+                'from_address' => $from_address,
+                'message_date' => $message_date,
+                'message_unread' => $message_unread,
+                'message_answered' => $message_answered,
+                'attachment_exists' => $attachment_exists,
+              ))
+              ->execute();
+            if (!$id) {
+              watchdog('basic_webmail', 'There was an error inserting message records into the basic_webmail_messages table.', array(), WATCHDOG_ERROR);
+            }
+          }
+        }
+
+        // Set the title of the page to the current mailbox, if there is one.
+        if (arg(1)) {
+          if ($new_messages) {
+            drupal_set_title(t('!mail_box (!total_messages total, !new_messages unread)', array('!mail_box' => arg(1), '!total_messages' => $total_messages, '!new_messages' => $new_messages)));
+          }
+          else {
+            drupal_set_title(t('!mail_box (!total_messages total)', array('!mail_box' => arg(1), '!total_messages' => $total_messages)));
+          }
+        }
+        else {
+          if ($new_messages) {
+            drupal_set_title(t('Email (!total_messages total, !new_messages unread)', array('!total_messages' => $total_messages, '!new_messages' => $new_messages)));
+          }
+          else {
+            drupal_set_title(t('Email (!total_messages total)', array('!total_messages' => $total_messages)));
+          }
+        }
+      }
+
+      // Add a link to a blank composition form.
+//      $output .= l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
+      $form['comoposition'] = l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
+
+      // Create the form and add it to the output.
+//      $output .= drupal_get_form('basic_webmail_mail_list_form', $folder);
+      // From http://drupal.org/node/224333#menu_callback_array:
+      // "If you find yourself calling render() or drupal_render(), you're
+      // probably making a mistake."
+      // See also http://drupal.org/node/224333#unrendered.
+      $form['messages'] = drupal_get_form('basic_webmail_mail_list_form', $folder);
+//dpm('$message_list_form_array');
+//dpm($message_list_form_array);
+      //$message_list_form_rendered = drupal_render($message_list_form_array);
+//dpm('$message_list_form_rendered');
+//dpm($message_list_form_rendered);
+      //$output .= $message_list_form_rendered;
+
+      // Add the page numbers at the bottom of the table.
+//      $output .= '<br />' . theme('pager', array('tags' => NULL, 'element' => 0));
+    }
+  }
+  else {
+    /*
+    $output .= 'You have no email in this mailbox.';
+    // Add a link to a blank composition form.
+    $output .= '<hr />' . l(t('Compose new message'), 'basic_webmail/sendmail');
+     *
+     * /
+
+    $form['empty'] = 'You have no email in this mailbox.';
+    // Add a link to a blank composition form.
+    $form['comoposition'] = '<hr />' . l(t('Compose new message'), 'basic_webmail/sendmail');
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+//dpm('$output');
+//dpm($output);
+//  return $output;
+  return $form;
+} // End of basic_webmail_mail_list().
+
+
+/**
+ * Construct the form for the message listing w/checkboxes.
+ *
+ * @return
+ *   The completed form definition.
+ * /
+function basic_webmail_mail_list_form($form, &$form_state, $folder = 'INBOX') {
+  // Load the custom CSS file.
+  drupal_add_css(drupal_get_path('module', 'basic_webmail') . '/basic_webmail.css');
+
+  // Set the path to the icons.
+//  $icon_path = drupal_get_path('module', 'basic_webmail') . '/icons/';
+
+  // Display the message information in a sortable table.
+  $header = array(
+    array(),
+//    array('data' => t('No.'),    'field' => 'message_number'),
+    array('data' => t('Unread'), 'field' => 'message_unread'),
+//    array('data' => t('U'), 'field' => 'message_unread'),
+//    array('data' => theme_image($icon_path . 'mini-mail.png'), 'field' => 'message_unread'),
+    array('data' => t('Att.'), 'field' => 'attachment_exists'),
+//    array('data' => t('A'), 'field' => 'attachment_exists'),
+//    array('data' => theme_image($icon_path . 'mini-doc.png'), 'field' => 'attachment_exists'),
+    array('data' => t('Ans.'), 'field' => 'message_answered'),
+//    array('data' => t('R'), 'field' => 'message_answered'),
+//    array('data' => theme_image($icon_path . 'mini-edit.png'), 'field' => 'message_answered'),
+    array('data' => t('Subject'), 'field' => 'message_subject'),
+    array('data' => t('From'), 'field' => 'from_address'),
+    array('data' => t('Date/Time'), 'field' => 'message_date', 'sort' => 'desc'),
+  );
+
+//  $query = 'SELECT message_number, message_unread, attachment_exists, message_answered, message_subject, from_address, message_date FROM {basic_webmail_messages} WHERE user_id = %d';
+  $row_limit = variable_get('basic_webmail_messages_per_page', 25);
+  $result = db_select('basic_webmail_messages', 'm')
+    ->fields('m', array('message_number', 'message_unread', 'attachment_exists', 'message_answered', 'message_subject', 'from_address', 'message_date'))
+    ->extend('PagerDefault')
+    ->limit($row_limit)
+    ->extend('TableSort')
+    ->orderByHeader($header)
+    ->execute();
+//  $tablesort = tablesort_sql($header);
+//  $result = pager_query($query . $tablesort, variable_get('basic_webmail_messages_per_page', 25), 0, NULL, $user->uid);
+
+//  $rows = array();
+
+//  while ($message = db_fetch_object($result)) {
+  foreach ($result as $message) {
+    // Checkbox for actions.
+    $messages[$message->message_number] = '';
+//    $form['message_number'][$message->message_number] = array('#value' => $message->message_number);
+
+    // If the message is unread, show an icon indentifing that, otherwise, show
+    // nothing.
+    $message_unread = '';
+    if ($message->message_unread) {
+      $message_unread = theme_image(array(
+        'path' => 'misc/menu-leaf.png',
+        //'path' => $icon_path . 'mini-mail.png',
+        'alt' => 'Generic icon indicating message is unread.',
+        'title' => t('You have not read this message.'),
+        'attributes' => array(),
+       ));
+    }
+    $form['message_unread'][$message->message_number] = array(
+      '#value' => $message_unread,
+      '#prefix' => '<div class="column-center">',
+      '#suffix' => '</div>',
+    );
+
+    // If the message has an attachment, show an icon indentifing that,
+    // otherwise, show nothing.
+    $message_attachment = '';
+    if ($message->attachment_exists) {
+      $message_attachment = theme_image(array(
+        'path' => 'misc/menu-leaf.png',
+        //'path' => $icon_path . 'mini-doc.png',
+        'alt' => 'Generic icon indicating message has an attachment.',
+        'title' => t('This message has one or more attachments.'),
+        'attributes' => array(),
+      ));
+    }
+    $form['attachment_exists'][$message->message_number] = array(
+      '#value' => $message_attachment,
+      '#prefix' => '<div class="column-center">',
+      '#suffix' => '</div>',
+    );
+
+    // If the message has been answered, show an icon indentifing that,
+    // otherwise, show nothing.
+    $message_answered = '';
+    if ($message->message_answered) {
+      $message_answered = theme_image(array(
+        'path' => 'misc/menu-leaf.png',
+        //'path' => $icon_path . 'misc/mini-edit.png',
+        'alt' => 'Generic icon indicating message has been answered.',
+        'title' => t('You have replied to this message.'),
+        'attributes' => array(),
+      ));
+    }
+    $form['message_answered'][$message->message_number] = array(
+      '#value' => $message_answered,
+      '#prefix' => '<div class="column-center">',
+      '#suffix' => '</div>',
+    );
+
+    // Show the message subject.
+    $form['message_subject'][$message->message_number] = array('#value' => $message->message_subject);
+
+    // Show the address of the party who the message is from.
+    $form['from_address'][$message->message_number] = array('#value' => $message->from_address);
+
+    // Show the date the message was sent.
+    if ($message->message_date == 0) {
+      $form['message_date'][$message->message_number] = array('#value' => '(Invalid date.)');
+    }
+    else {
+      $format_option = variable_get('basic_webmail_format_option', 'small');
+
+      if ($format_option == 'custom') {
+        $custom_format = variable_get('basic_webmail_custom_format', 'D, M j, Y - g:i:s a');
+        $message->message_date = format_date($message->message_date, $format_option, $custom_format);
+      }
+      else {
+        $message->message_date = format_date($message->message_date, $format_option);
+      }
+
+      $form['message_date'][$message->message_number] = array('#value' => $message->message_date);
+    }
+  }
+
+  $form['messages'] = array(
+    '#type' => 'checkboxes',
+    '#options' => $messages,
+  );
+
+  $form['operation'] = array(
+    '#type' => 'select',
+    '#title' => t('With checked'),
+    '#default_value' => 'read',
+    '#options' => array(
+      'delete' => t('Delete'),
+      'read' => t('Mark read'),
+      'unread' => t('Mark unread'),
+      'copy_to' => t('Copy'),
+      'move_to' => t('Move'),
+    ),
+    '#prefix' => '<div class="container-inline">',
+  );
+
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Get the list of folders from the server.
+  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
+  if ($folders) {
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+
+      if ($brief_folder_name != $folder) {
+        $folder_names[$brief_folder_name] = $brief_folder_name;
+      }
+    }
+  }
+
+  $form['folder_name'] = array(
+    '#type' => 'select',
+    '#title' => t('The folder to copy or move to'),
+    '#options' => $folder_names,
+  );
+
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Update'),
+    '#suffix' => '</div>',
+  );
+
+  $form['folder'] = array(
+    '#type' => 'hidden',
+    '#value' => $folder,
+  );
+
+  $form['pager'] = array('#markup' => theme('pager'));
+
+  return $form;
+} // End of basic_webmail_mail_list_form().
+
+
+/**
+ * Display the listing of messages.
+ *
+ * @param folder
+ *   The name of the folder to open. If no folder is specified, the default
+ *   of 'INBOX' is used.
+ *
+ * @return
+ *   The formatted message listing.
+ */
+function basic_webmail_mail_list_form($form, &$form_state) {
+
+    
+  /**
+   * @TODO: Add the page title.
+   *
+  // Set the title of the page to the current mailbox, if there is one.
+  if (arg(1)) {
+    drupal_set_title(t('!title', array('!title' => arg(1))));
+  }
+   */
+
+
+  /**
+   * @TODO: Add the custom CSS?:
+   *
+  // Load the custom CSS file.
+  drupal_add_css(drupal_get_path('module', 'basic_webmail') . '/basic_webmail.css');
+   */
+
+  if (isset($form_state['build_info']['args'][0])) {
+      $folder = $form_state['build_info']['args'][0];
+  }
+  else{
+      $folder = 'INBOX';
+  };
+  //$form = array();
+  //dpm($folder);
+
+  // Create the table header for the message listing.
+  $header = _basic_webmail_create_message_list_header();
+
+  // Update the saved message information.
+  _basic_webmail_update_stored_message_list($folder);
+
+  // Get the message list.
+  $message_list = _basic_webmail_get_message_list_data($header);
+
+  $folder_list = _basic_webmail_get_folder_list($folder);
+
+
+  /**
+   * @TODO: Add the folder list to the top of the page:
+   *
+  if ($folder_list) {
+    /*
+    $output .= '<br />';
+
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
+    }
+
+    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
+    $output .= '<hr>';
+     *
+     * /
+    $output = '<br />';
+
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+      $output .= l($brief_folder_name, 'basic_webmail/' . $brief_folder_name) . '&nbsp; -- &nbsp;';
+    }
+
+    $output = drupal_substr($output, 0, drupal_strlen($output) - 16);
+    $output .= '<hr>';
+    $form['folders'] = $output;
+  }
+
+   */
+
+
+  /**
+   * @TODO: Add the compisition link:
+   *
+      // Add a link to a blank composition form.
+//      $output .= l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
+      $form['comoposition'] = l(t('Compose new message'), 'basic_webmail/sendmail') . '<hr />';
+   */
+
+
+  // Create the table/form.
+  $form['message_list'] = array (
+    '#type' => 'tableselect',
+    '#header' => $header,
+    '#options' => $message_list,
+    '#empty' => t('You have no email in this mailbox.'),
+  );
+
+
+  // Add the operation select list.
+  $form['operation'] = array(
+    '#type' => 'select',
+    '#title' => t('With checked'),
+    '#default_value' => 'read',
+    '#options' => array(
+      'delete' => t('Delete'),
+      'read' => t('Mark read'),
+      'unread' => t('Mark unread'),
+      'copy_to' => t('Copy'),
+      'move_to' => t('Move'),
+    ),
+    '#prefix' => '<div class="container-inline">',
+  );
+
+  // Add the select list with the list of folders.
+  $form['folder_name'] = array(
+    '#type' => 'select',
+    '#title' => t('The folder to copy or move to'),
+    '#options' => $folder_list,
+  );
+
+  // Add the button.
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Update'),
+    '#suffix' => '</div>',
+  );
+
+  // Save the current folder name for later use.
+  $form['folder'] = array(
+    '#type' => 'hidden',
+    '#value' => $folder,
+  );
+
+  // Add the pager at the bottom of the form.
+  $form['pager'] = array('#markup' => theme('pager'));
+
+  return $form;
+} // End of basic_webmail_mail_list_form().
+
+
+/**
+ * Create the table header for the message listing.
+ *
+ * @return
+ *   An array containing the table header.
+ */
+function _basic_webmail_create_message_list_header() {
+  // Set the path to the icons.
+//  $icon_path = drupal_get_path('module', 'basic_webmail') . '/icons/';
+
+  // Specify the header information for the message list.
+  return array(
+    'message_unread' => array('data' => t('Unread'), 'field' => 'message_unread'),
+//    'message_unread' => array('data' => t('U'), 'field' => 'message_unread'),
+//    'message_unread' => array('data' => theme_image($icon_path . 'mini-mail.png'), 'field' => 'message_unread'),
+    'attachment_exists' => array('data' => t('Att.'), 'field' => 'attachment_exists'),
+//    'attachment_exists' => array('data' => t('A'), 'field' => 'attachment_exists'),
+//    'attachment_exists' => array('data' => theme_image($icon_path . 'mini-doc.png'), 'field' => 'attachment_exists'),
+    'message_answered' => array('data' => t('Ans.'), 'field' => 'message_answered'),
+//    'message_answered' => array('data' => t('R'), 'field' => 'message_answered'),
+//    'message_answered' => array('data' => theme_image($icon_path . 'mini-edit.png'), 'field' => 'message_answered'),
+    'message_subject' => array('data' => t('Subject'), 'field' => 'message_subject'),
+    'from_address' => array('data' => t('From'), 'field' => 'from_address'),
+    'message_date' => array('data' => t('Date/Time'), 'field' => 'message_date', 'sort' => 'desc'),
+  );
+} // End of _basic_webmail_create_message_list_header().
+
+
+/**
+ * Updates the saved message list information.
+ *
+ * @param folder
+ *   The name of the folder to open. If no folder is specified, the default
+ *   of 'INBOX' is used.
+ */
+function _basic_webmail_update_stored_message_list($folder = 'INBOX') {
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  $mailboxes = imap_getsubscribed($imap_resource, _basic_webmail_get_server_string(), '*');
+  if (!$mailboxes[4]) {
+    _basic_webmail_subscribe_to_mailboxes($user->uid);
+  }
+
+  if (imap_num_msg($imap_resource) > 0) {
+    // Retrieve and display the mail in the current folder.
+    $threads = imap_thread($imap_resource);
+    if ($threads === FALSE) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', t('There was an error getting the list of messages: %last_error'), array('%last_error' => $last_error), WATCHDOG_ERROR);
+      return '<br />' . t('There was an error getting the list of messages: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
+    }
+    else {
+      db_delete('basic_webmail_messages')
+        ->condition('user_id', $user->uid)
+        ->execute();
+
+      // Save the message information in a temporary table.
+      foreach ($threads as $key => $message_number) {
+        $tree = explode('.', $key);
+        if ($tree[1] == 'num' && $message_number > 0) {
+          $message_header = imap_headerinfo($imap_resource, $message_number);
+
+          if ($message_header->Deleted == ' ') {
+            // Check for attachments.
+            // Get the message parts list.
+            $parts_list = _basic_webmail_get_parts_list($imap_resource, $message_number);
+            // Iterate over the parts list.
+            foreach ($parts_list as $part_id => $part_array) {
+              if (!empty($part_array[0]) && !empty($part_array[1])) {
+                $attachment_exists = 1;
+                continue;
+              }
+              else {
+                $attachment_exists = 0;
+              }
+            }
+
+            // Check if message was answered.
+            if ($message_header->Answered == 'A') {
+              $message_answered = 1;
+            }
+            else {
+              $message_answered = 0;
+            }
+
+            // Create a link to the message.
+            $number_characters = variable_get('basic_webmail_subject_characters', 40);
+            if (empty($number_characters)) {
+              $message_subject_link = l(_basic_webmail_decode_mime_str($message_header->subject), 'basic_webmail/message/' . $message_number . '/' . $folder);
+            }
+            else {
+              $message_subject_link = l(truncate_utf8(_basic_webmail_decode_mime_str($message_header->subject), $number_characters, TRUE, TRUE), 'basic_webmail/message/' . $message_number . '/' . $folder);
+            }
+
+            // Save the message's subject and read status.
+            if ($message_header->Recent == 'N' || $message_header->Unseen == 'U') {
+              $message_unread = 1;
+
+              if (empty($message_header->subject)) {
+                $message_subject = '<strong>' . l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder) . '</strong>';
+              }
+              else {
+                $message_subject = '<strong>' . $message_subject_link . '</strong>';
+              }
+            }
+            else {
+              $message_unread = 0;
+
+              if (empty($message_header->subject)) {
+                $message_subject = l(t('(No subject specified)'), 'basic_webmail/message/' . $message_number . '/' . $folder);
+              }
+              else {
+                $message_subject = $message_subject_link;
+              }
+            }
+
+            // Save the sender's information.
+            if (empty($message_header->from[0]->mailbox) && empty($message_header->from[0]->host)) {
+              $from_address = '(Unknown)';
+            }
+            elseif (!empty($message_header->from[0]->personal)) {
+              $from_address = l(_basic_webmail_decode_mime_str($message_header->from[0]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>');
+            }
+            else {
+              $from_address = l($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host, 'basic_webmail/sendmail/' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host);
+            }
+
+            // Save the message's date.
+            if (empty($message_header->date)) {
+              $message_date = 0;
+            }
+            else {
+              $message_date = _basic_webmail_message_list_process_message_date($message_header->date);
+            }
+
+            // imap_uid($imap_resource, $message_number)
+            $id = db_insert('basic_webmail_messages')
+              ->fields(array(
+                'user_id' => $user->uid,
+                'message_number' => $message_number,
+                'message_subject' => $message_subject,
+                'from_address' => $from_address,
+                'message_date' => $message_date,
+                'message_unread' => $message_unread,
+                'message_answered' => $message_answered,
+                'attachment_exists' => $attachment_exists,
+              ))
+              ->execute();
+            if (!$id) {
+              watchdog('basic_webmail', t('There was an error inserting message records into the basic_webmail_messages table.'), array(), WATCHDOG_ERROR);
+            }
+          }
+        }
+      }
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', t('There was an error closing the IMAP stream: %last_error'), array('%last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+} // End of _basic_webmail_update_stored_message_list().
+
+/**
+ * Format the date for the message listing.
+ *
+ * @param $message_header_date
+ *   The original date from the header of the message.
+ *
+ * @return
+ *   The reformatted date.
+ */
+function _basic_webmail_message_list_process_message_date($message_header_date) {
+  // Format the date so we can sort on it.
+  $message_hour = (int) drupal_substr($message_header_date, strpos($message_header_date, ':') - 2, 2);
+  $message_minute = (int) drupal_substr($message_header_date, strpos($message_header_date, ':') + 1, 2);
+  $message_second = (int) drupal_substr($message_header_date, strpos($message_header_date, ':') + 4, 2);
+
+  if (strpos($message_header_date, ',') === FALSE) {
+    // The day is the first item in the date string.
+    $message_day_start = 0;
+    $message_day_length = (int) strpos($message_header_date, ' ', $message_day_start) - $message_day_start;
+    $message_day = (int) drupal_substr($message_header_date, $message_day_start, $message_day_length);
+
+    // Start at the first space.
+    $message_month_start = (int) strpos($message_header_date, ' ') + 1;
+    $message_month_length = (int) strpos($message_header_date, ' ', $message_month_start) - $message_month_start;
+
+    // Start at the second space.
+    $message_year_start = (int) strpos($message_header_date, ' ', strpos($message_header_date, ' ') + 1) + 1;
+    $message_year_length = (int) strpos($message_header_date, ' ', $message_year_start) - $message_year_start;
+    $message_year = (int) drupal_substr($message_header_date, $message_year_start, $message_year_length);
+  }
+  else {
+    // Start at the first space.
+    $message_day_start = (int) strpos($message_header_date, ' ') + 1;
+    $message_day_length = (int) strpos($message_header_date, ' ', $message_day_start) - $message_day_start;
+    $message_day = (int) drupal_substr($message_header_date, $message_day_start, $message_day_length);
+
+    // Start at the second space.
+    $message_month_start = (int) strpos($message_header_date, ' ', strpos($message_header_date, ' ') + 1) + 1;
+    $message_month_length = (int) strpos($message_header_date, ' ', $message_month_start) - $message_month_start;
+
+    // Start at the third space.
+    $message_year_start = (int) strpos($message_header_date, ' ', strpos($message_header_date, ' ', strpos($message_header_date, ' ') + 1) + 1) + 1;
+    $message_year_length = (int) strpos($message_header_date, ' ', $message_year_start) - $message_year_start;
+    $message_year = (int) drupal_substr($message_header_date, $message_year_start, $message_year_length);
+  }
+
+  switch (drupal_substr($message_header_date, $message_month_start, $message_month_length)) {
+    case 'Jan':
+      $message_month = 1;
+      break;
+    case 'Feb':
+      $message_month = 2;
+      break;
+    case 'Mar':
+      $message_month = 3;
+      break;
+    case 'Apr':
+      $message_month = 4;
+      break;
+    case 'May':
+      $message_month = 5;
+      break;
+    case 'Jun':
+      $message_month = 6;
+      break;
+    case 'Jul':
+      $message_month = 7;
+      break;
+    case 'Aug':
+      $message_month = 8;
+      break;
+    case 'Sep':
+      $message_month = 9;
+      break;
+    case 'Oct':
+      $message_month = 10;
+      break;
+    case 'Nov':
+      $message_month = 11;
+      break;
+    case 'Dec':
+      $message_month = 12;
+      break;
+  }
+
+  $message_date = mktime($message_hour, $message_minute, $message_second, $message_month, $message_day, $message_year);
+
+  return $message_date;
+} // End of _basic_webmail_message_list_process_message_date().
+
+
+/**
+ * Retrieves the list of messages.
+ *
+ * @param $header
+ *   The original header that was created in
+ *   _basic_webmail_create_message_list_header().
+ *
+ * @return
+ *   The list of messages.
+ */
+function _basic_webmail_get_message_list_data($header) {
+  // Initialize variables.
+  $message_unread = '';
+  $message_attachment = '';
+  $message_answered = '';
+  $message_date = '(Invalid date.)';
+  $message_list = array();
+
+  // Specifiy the number of messages to display on a page.
+  $row_limit = variable_get('basic_webmail_messages_per_page', 25);
+
+  // Construct and execute the database query.
+  $result = db_select('basic_webmail_messages', 'm')
+    ->fields('m', array('message_number', 'message_unread', 'attachment_exists', 'message_answered', 'message_subject', 'from_address', 'message_date'))
+    ->extend('PagerDefault')
+    ->limit($row_limit)
+    ->extend('TableSort')
+    ->orderByHeader($header)
+    ->execute();
+
+  // Iterate through the messages.
+  foreach ($result as $message) {
+    // If the message is unread, show the icon.
+    if ($message->message_unread) {
+      $message_unread = theme_image(array(
+        'path' => 'misc/menu-leaf.png',
+        //'path' => $icon_path . 'mini-mail.png',
+        'alt' => 'Generic icon indicating message is unread.',
+        'title' => t('You have not read this message.'),
+        'attributes' => array(),
+       ));
+    }
+
+    // If the message has an attachment, show the icon.
+    if ($message->attachment_exists) {
+      $message_attachment = theme_image(array(
+        'path' => 'misc/menu-leaf.png',
+        //'path' => $icon_path . 'mini-doc.png',
+        'alt' => 'Generic icon indicating message has an attachment.',
+        'title' => t('This message has one or more attachments.'),
+        'attributes' => array(),
+      ));
+    }
+
+    // If the message has been answered, show the icon.
+    if ($message->message_answered) {
+      $message_answered = theme_image(array(
+        'path' => 'misc/menu-leaf.png',
+        //'path' => $icon_path . 'misc/mini-edit.png',
+        'alt' => 'Generic icon indicating message has been answered.',
+        'title' => t('You have replied to this message.'),
+        'attributes' => array(),
+      ));
+    }
+
+    // The date the message was sent.
+    if ($message->message_date != 0) {
+      $format_option = variable_get('basic_webmail_format_option', 'small');
+
+      if ($format_option == 'custom') {
+        $custom_format = variable_get('basic_webmail_custom_format', 'D, M j, Y - g:i:s a');
+        $message->message_date = format_date($message->message_date, $format_option, $custom_format);
+      }
+      else {
+        $message->message_date = format_date($message->message_date, $format_option);
+      }
+
+      $message_date = $message->message_date;
+    }
+
+    $message_list[$message->message_number] = array(
+      'message_unread' => $message_unread,
+      'attachment_exists' => $message_attachment,
+      'message_answered' => $message_answered,
+      'message_subject' => $message->message_subject,
+      'from_address' => $message->from_address,
+      'message_date' => $message_date,
+    );
+  }
+
+  return $message_list;
+} // End of _basic_webmail_message_list_process_message_date().
+
+
+/**
+ * Retrieves the list of folders.
+ *
+ * @param folder
+ *   The name of the folder to open. If no folder is specified, the default
+ *   of 'INBOX' is used.
+ *
+ * @return
+ *   The folder listing.
+ */
+function _basic_webmail_get_folder_list($folder = 'INBOX') {
+  global $user;
+  // Connect to the server and retrieve a connection to the mailbox.
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Get the list of folders from the server.
+  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
+  if ($folders) {
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+
+      if ($brief_folder_name != $folder) {
+        $folder_list[$brief_folder_name] = $brief_folder_name;
+      }
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', t('There was an error closing the IMAP stream: %last_error'), array('%last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  return $folder_list;
+} // End of _basic_webmail_get_folder_list().
+
+
+/**
+ * Perform an action on a group of messages.
+ *
+ * @param form_id
+ *   The form ID of the passed form.
+ * @param $form_state
+ *   The form values of the passed form.
+ */
+function basic_webmail_mail_list_form_submit($form, &$form_state) {
+  $operation = $form_state['values']['operation'];
+  // Filter out unselected messages.
+  $messages = array_filter($form_state['values']['message_list']);
+
+  if (isset($messages) && is_array($messages)) {
+    // Connect to the server and retrieve a connection to the mailbox.
+    global $user;
+    $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['folder']);
+    if (!$imap_resource) {
+      drupal_set_title(t('Error'));
+      $output .= '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+      $form_state['redirect'] = $output;
+    }
+
+    switch ($operation) {
+      case 'delete':
+        _basic_webmail_mail_list_form_submit_delete($form_state, $messages, $imap_resource);
+        break;
+
+      case 'read':
+        _basic_webmail_mail_list_form_submit_mark_read($form_state, $messages, $imap_resource);
+        break;
+
+      case 'unread':
+        _basic_webmail_mail_list_form_submit_mark_unread($form_state, $messages, $imap_resource);
+        break;
+
+      case 'copy_to':
+        _basic_webmail_mail_list_form_submit_copy_to($form_state, $messages, $imap_resource);
+        break;
+
+      case 'move_to':
+        _basic_webmail_mail_list_form_submit_move_to($form_state, $messages, $imap_resource);
+        break;
+    }
+
+    // Clean up.
+    if (!imap_close($imap_resource)) {
+      watchdog('basic_webmail', t('There was an error closing the IMAP stream: %last_error'), array('%last_error' => imap_last_error()), WATCHDOG_WARNING);
+    }
+  }
+
+  // Send the user back to the page they were looking at.
+  //$orig_path = drupal_get_destination();
+  $orig_path_a = drupal_get_destination();
+  $orig_path = $orig_path_a['destination'];
+  $orig_length = drupal_strlen($orig_path);
+  $orig_start = strpos($orig_path, '=');
+  $new_path = ($orig_start>0) ? drupal_substr($orig_path, $orig_start + 1, $orig_length) : $orig_path;
+
+  // Clean up the converted characters.
+  $new_path = str_replace('%25', '%', $new_path);
+  $new_path = str_replace('%2F', '/', $new_path);
+  $new_path = str_replace('%3F', '?', $new_path);
+  $new_path = str_replace('%3D', '=', $new_path);
+  $new_path = str_replace('%26', '&', $new_path);
+
+  // Setup the return parameters.
+  $query_point = strpos($new_path, '?');
+  if ($query_point === FALSE) {
+    $dest_path = $new_path;
+    $dest_query = NULL;
+  }
+  else {
+    $dest_path = drupal_substr($new_path, 0, strpos($new_path, '?'));
+    $dest_query = drupal_substr($new_path, strpos($new_path, '?') + 1, drupal_strlen($new_path));
+  }
+
+  // Bye, bye, baby.
+  //$form_state['redirect'] = array($dest_path, $dest_query);
+} // End of basic_webmail_mail_list_form_submit().
+
+
+/** *******************************************************
+ *
+ *  Themeing functions.
+ *
+ *  ******************************************************/
+
+
+/**
+ * Theme the message listing page.
+ *
+ * @param form
+ *   The form to theme.
+ *
+ * @return
+ *   The themed listing.
+ * /
+function theme_basic_webmail_mail_list_form($variables) {
+  $form = $variables['form'];
+  // Set the path to the icons.
+//  $icon_path = drupal_get_path('module', 'basic_webmail') . '/icons/';
+
+  // Overview table:
+  // TODO Please change this theme call to use an associative array for the $variables parameter.
+  $header = array(
+    theme('table_select_header_cell'),
+    //    array('data' => t('No.'),    'field' => 'message_number'),
+    array(
+      'data' => t('Unread'),
+      'field' => 'message_unread',
+    ),
+    //    array('data' => t('U'),    'field' => 'message_unread'), //    array('data' => theme_image($icon_path . 'mini-mail.png'),    'field' => 'message_unread'),
+    array(
+      'data' => t('Att.'),
+      'field' => 'attachment_exists',
+    ),
+    //    array('data' => t('A'),   'field' => 'attachment_exists'), //    array('data' => theme_image($icon_path . 'mini-doc.png'),   'field' => 'attachment_exists'),
+    array(
+      'data' => t('Ans.'),
+      'field' => 'message_answered',
+    ),
+    //    array('data' => t('R'),  'field' => 'message_answered'), //    array('data' => theme_image($icon_path . 'mini-edit.png'),  'field' => 'message_answered'),
+    array(
+      'data' => t('Subject'),
+      'field' => 'message_subject',
+    ),
+    array(
+      'data' => t('From'),
+      'field' => 'from_address',
+    ),
+    array(
+      'data' => t('Date/Time'),
+      'field' => 'message_date',
+      'sort' => 'desc',
+    ),
+  );
+
+  $output = drupal_render($form['options']);
+
+  if (isset($form['message_subject']) && is_array($form['message_subject'])) {
+    foreach (element_children($form['message_subject']) as $key) {
+      $rows[] = array(
+        drupal_render($form['messages'][$key]),
+        //        drupal_render($form['message_number'][$key]),
+        drupal_render($form['message_unread'][$key]),
+        drupal_render($form['attachment_exists'][$key]),
+        drupal_render($form['message_answered'][$key]),
+        drupal_render($form['message_subject'][$key]),
+        drupal_render($form['from_address'][$key]),
+        drupal_render($form['message_date'][$key]),
+      );
+    }
+  }
+  else {
+    $rows[] = array(array(
+        'data' => t('You have no email.'),
+        'colspan' => '6',
+      ));
+  }
+
+  $output .= theme('table', array('header' => $header, 'rows' => $rows));
+  $output .= drupal_render_children($form);
+
+  return $output;
+} // End of theme_basic_webmail_mail_list_form().
+
+
+/** *******************************************************
+ *
+ *  Private helper functions that do the main work of the module.
+ *
+ *  ******************************************************/
+
+
+/**
+ * Reports error messages.
+ *
+ * @param message
+ *   The additional text to be saved and/or displayed.
+ * @param display
+ *   A boolean value to indicate whether to display the error message to the
+ *   user or not.
+ * @param log
+ *   A boolean value to indicate whether to save the error message to the logs
+ *   or not.
+ * @param severity
+ *   The severity of the message, as per RFC 3164. See
+ *   http://api.drupal.org/api/drupal/includes--bootstrap.inc/group/logging_severity_levels/7
+ *   for more information.
+ */
+function _basic_webmail_report_error($message = '', $display = TRUE, $log = TRUE, $severity = WATCHDOG_ERROR) {
+/*
+      $last_error = imap_last_error();
+      if ($last_error === FALSE) {
+        $last_error = t('There was no additional information returned by the system.');
+      }
+      drupal_set_message($last_error);
+*/
+  $last_error = imap_last_error();
+  if ($last_error === FALSE) {
+    $last_error = 'There was no additional information provided by the system.';
+  }
+
+  if ($display) {
+    if (!empty($message)) {
+
+    }
+    else {
+      drupal_set_message(t('There was an error connecting to the server: @last_error', array('@last_error' => $last_error)), 'error');
+    }
+  }
+
+  if ($log) {
+    if (!empty($message)) {
+      watchdog('basic_webmail', t($message . ': @last_error'), array('@last_error' => $last_error), $severity);
+    }
+    else {
+      watchdog('basic_webmail', t('There was an error connecting to the server: %last_error'), array('%last_error' => $last_error), $severity);
+    }
+  }
+} // End of _basic_webmail_report_error().
+
+
+/**
+ * Deletes a group of messages.
+ *
+ * @param $form_state
+ *   The form values of the passed form.
+ * @param $messages
+ *   The messasges to delete.
+ * @param $imap_resource
+ *   A connection to the mailbox on the server.
+ */
+function _basic_webmail_mail_list_form_submit_delete($form_state, $messages, $imap_resource) {
+  $error = 0;
+  $message_count = 0;
+
+  foreach ($messages as $message_number) {
+    if ($form_state['values']['folder'] != 'INBOX.Trash') {
+      if (!imap_mail_move($imap_resource, $message_number, 'INBOX.Trash')) {
+        // Report the error.
+        $last_error = imap_last_error();
+        watchdog('basic_webmail', t('There was an error deleting message #%message_number: %last_error'), array('%message_number' => $message_number, '%last_error' => $last_error), WATCHDOG_ERROR);
+        drupal_set_message(t('There was an error deleting message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+        $error++;
+      }
+      else {
+        $message_count++;
+      }
+    }
+    else {
+      if (!imap_delete($imap_resource, $message_number)) {
+        // Report the error.
+        $last_error = imap_last_error();
+        watchdog('basic_webmail', t('There was an error deleting message #%message_number: %last_error'), array('%message_number' => $message_number, '%last_error' => $last_error), WATCHDOG_ERROR);
+        drupal_set_message(t('There was an error deleting message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+        $error++;
+      }
+      else {
+        $message_count++;
+      }
+    }
+  }
+
+  if (!imap_expunge($imap_resource)) {
+    // Report the error.
+    watchdog('basic_webmail', t('There was an error expunging the mailboxes: %last_error'), array('%last_error' => imap_last_error()), WATCHDOG_WARNING);
+    $error++;
+  }
+
+  if (!$error) {
+    drupal_set_message(t('@message_count messages were successfully deleted.', array('@message_count' => $message_count)));
+  }
+} // End of _basic_webmail_mail_list_form_submit_delete().
+
+
+/**
+ * Marks a group of messages as read.
+ *
+ * @param $form_state
+ *   The form values of the passed form.
+ * @param $messages
+ *   The messasges to .
+ * @param $imap_resource
+ *   A connection to the mailbox on the server.
+ */
+function _basic_webmail_mail_list_form_submit_mark_read($form_state, $messages, $imap_resource) {
+  $error = 0;
+  $message_count = 0;
+
+  foreach ($messages as $message_number) {
+    if (!imap_setflag_full($imap_resource, $message_number, '\\Seen')) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', t('There was an error setting the flag of message #%message_number: %last_error'), array('%message_number' => $message_number, '%last_error' => $last_error), WATCHDOG_ERROR);
+      drupal_set_message(t('There was an error setting the flag of message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+      $error++;
+    }
+    else {
+      $message_count++;
+    }
+  }
+
+  if (!$error) {
+    drupal_set_message(t('@message_count messages were successfully marked as read.', array('@message_count' => $message_count)));
+  }
+} // End of _basic_webmail_mail_list_form_submit_mark_read().
+
+
+/**
+ * Marks a group of messages as unread.
+ *
+ * @param $form_state['values']
+ *   The form values of the passed form.
+ * @param $messages
+ *   The messasges to .
+ * @param $imap_resource
+ *   A connection to the mailbox on the server.
+ */
+function _basic_webmail_mail_list_form_submit_mark_unread($form_state, $messages, $imap_resource) {
+  $error = 0;
+  $message_count = 0;
+
+  foreach ($messages as $message_number) {
+    if (!imap_clearflag_full($imap_resource, $message_number, '\\Seen')) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', t('There was an error clearing the flag of message #%message_number: %last_error'), array('%message_number' => $message_number, '%last_error' => $last_error), WATCHDOG_ERROR);
+      drupal_set_message(t('There was an error clearing the flag of message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+      $error++;
+    }
+    else {
+      $message_count++;
+    }
+  }
+
+  if (!$error) {
+    drupal_set_message(t('@message_count messages were successfully marked as unread.', array('@message_count' => $message_count)));
+  }
+} // End of _basic_webmail_mail_list_form_submit_mark_unread().
+
+
+/**
+ * Copies a group of messages to another folder.
+ *
+ * @param $form_state['values']
+ *   The form values of the passed form.
+ * @param $messages
+ *   The messasges to .
+ * @param $imap_resource
+ *   A connection to the mailbox on the server.
+ */
+function _basic_webmail_mail_list_form_submit_copy_to($form_state, $messages, $imap_resource) {
+  $error = 0;
+  $message_count = 0;
+
+  foreach ($messages as $message_number) {
+    if (!imap_mail_copy($imap_resource, $message_number, $form_state['values']['folder_name'])) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', 'There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
+      drupal_set_message(t('There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+      $error++;
+    }
+    else {
+      $message_count++;
+    }
+  }
+
+  if (!imap_expunge($imap_resource)) {
+    // Report the error.
+    watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+    $error++;
+  }
+
+  if (!$error) {
+    drupal_set_message(t('@message_count messages were successfully copied to @folder_name.', array('@message_count' => $message_count, '@folder_name' => $form_state['values']['folder_name'])));
+  }
+} // End of _basic_webmail_mail_list_form_submit_copy_to().
+
+
+/**
+ * Moves a group of messages to another folder.
+ *
+ * @param $form_state['values']
+ *   The form values of the passed form.
+ * @param $messages
+ *   The messasges to .
+ * @param $imap_resource
+ *   A connection to the mailbox on the server.
+ */
+function _basic_webmail_mail_list_form_submit_move_to($form_state, $messages, $imap_resource) {
+  $error = 0;
+  $message_count = 0;
+
+  foreach ($messages as $message_number) {
+    if (!imap_mail_move($imap_resource, $message_number, $form_state['values']['folder_name'])) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', 'There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
+      drupal_set_message(t('There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+      $error++;
+    }
+    else {
+      $message_count++;
+    }
+  }
+
+  if (!imap_expunge($imap_resource)) {
+    // Report the error.
+    watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+    $error++;
+  }
+
+  if (!$error) {
+    drupal_set_message(t('@message_count messages were successfully moved to @folder_name.', array('@message_count' => $message_count, '@folder_name' => $form_state['values']['folder_name'])));
+  }
+} // End of _basic_webmail_mail_list_form_submit_move_to().
+
+
+/**
+ * Display the message.
+ *
+ * @TODO: Consider a feature to allow or not the displaying of remote content.
+ *
+ * @param message_number
+ *   The ID of the message to delete.
+ * @param folder
+ *   The name of the folder the message is in. If no folder is specified, it
+ *   defaults to 'INBOX'.
+ *
+ * @return
+ *   The formatted message.
+ */
+function _basic_webmail_message($message_number, $folder = 'INBOX') {
+  $output = '';
+
+  // Sanity check -- make sure we have an actual message to display.
+  if (arg(0) == 'basic_webmail' && arg(1) == 'message' && $message_number == '') {
+    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('No message_number was given when attempting to view a message.') . '<br /><br />';
+  }
+
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Show the message.
+
+  // Start with the the message header.
+  $message_header = imap_headerinfo($imap_resource, $message_number);
+  if (!$message_header) {
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
+  }
+
+  // Set the title of the page.
+  drupal_set_title(t('!title', array('!title' => _basic_webmail_decode_mime_str($message_header->subject))));
+
+  // Offer a link back to where we came from.
+  $output .= '<br />';
+  $output .= l('Return to message listing', 'basic_webmail/' . $folder);
+  $output .= '<hr>';
+  $output .= '<table>';
+
+  // Start processing the header of the message.
+
+  // Retrieve and display who the message is from.
+  if (!empty($message_header->from[0]->personal)) {
+    $output .= '<tr><td>From:</td><td>' . l(_basic_webmail_decode_mime_str($message_header->from[0]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>') . '</td></tr>';
+  }
+  else {
+    $output .= '<tr><td>From:</td><td>' . l($message_header->from[0]->mailbox . '@' . $message_header->from[0]->host, 'basic_webmail/sendmail/' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host) . '</td></tr>';
+  }
+
+  // Retrieve and display who the message is to.
+  $toaddresses = '';
+  for ($i = 0; $i < count($message_header->to); $i++) {
+    if (!empty($message_header->to[$i]->personal)) {
+      $toaddresses .= l(_basic_webmail_decode_mime_str($message_header->to[$i]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->to[0]->personal) . ' <' . $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host . '>') . ', ';
+    }
+    else {
+      $toaddresses .= l($message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host, 'basic_webmail/sendmail/' . $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host) . ', ';
+    }
+  }
+  // Drop the final comma and space.
+  $output .= '<tr><td>To:</td><td>' . drupal_substr($toaddresses, 0, drupal_strlen($toaddresses) - 2) . '</td></tr>';
+
+  // Retrieve and display who the message was CC'd to.
+  if (!empty($message_header->ccaddress)) {
+    $ccaddresses = '';
+    for ($i = 0; $i < count($message_header->cc); $i++) {
+      if ($message_header->cc[$i]->personal) {
+        $ccaddresses .= l(_basic_webmail_decode_mime_str($message_header->cc[$i]->personal), 'basic_webmail/sendmail/' . _basic_webmail_decode_mime_str($message_header->cc[0]->personal) . ' <' . $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host . '>') . ', ';
+      }
+      else {
+        $ccaddresses .= l($message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host, 'basic_webmail/sendmail/' . $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host) . ', ';
+      }
+    }
+    // Drop the final comma and space.
+    $output .= '<tr><td>CC:</td><td>' . drupal_substr($ccaddresses, 0, drupal_strlen($ccaddresses) - 2) . '</td></tr>';
+  }
+
+  // Retrieve and display the date of the message.
+  $output .= '<tr><td>Date:</td><td>' . $message_header->date . '</td></tr>';
+
+  // Close out the header.
+  $output .= '</table>';
+  $output .= '<hr>';
+
+
+  // Start processing the body of the message.
+
+  // Get the message parts list.
+  $parts_list = _basic_webmail_get_parts_list($imap_resource, $message_number);
+
+  // Initialize variable.
+  $message_body = '';
+  $message_self_link = '';
+  $attachment_links = '';
+  $reply_part = '';
+
+  // Iterate over the parts list.
+  foreach ($parts_list as $part_id => $part_array) {
+    // Process an HTML part.
+    if (arg(4) == 'html' && $part_array[0] == drupal_strtoupper('HTML')) {
+      if (arg(5)) {
+        if ($message_body) {
+          // Add a separator between message parts, but only if there is at
+          // least one other part.
+          $message_body .= '<hr width="75%">';
+        }
+
+        $message_body .= _basic_webmail_decode_body_part($imap_resource, $message_number, arg(5));
+      }
+      else {
+        if ($message_body) {
+          // Add a separator between message parts, but only if there is at
+          // least one other part.
+          $message_body .= '<hr width="75%">';
+        }
+
+        $message_body .= _basic_webmail_decode_body_part($imap_resource, $message_number, $part_id);
+      }
+
+      if (!$reply_part) {
+        $reply_part = $part_id;
+      }
+
+      $message_self_link .= '<hr>' . l(t('View the original message.'), 'basic_webmail/message/' . $message_number . '/' . $folder);
+    }
+
+    // Process a plain text part.
+    elseif (arg(4) != 'html' && $part_array[0] == drupal_strtoupper('PLAIN')) {
+      if ($message_body) {
+        // Add a separator between message parts, but only if there is at
+        // least one other part.
+        $message_body .= '<hr width="75%">';
+      }
+
+      $message_body .= check_markup(_basic_webmail_decode_body_part($imap_resource, $message_number, $part_id));
+
+      if (!$reply_part) {
+        $reply_part = $part_id;
+      }
+    }
+
+    // Create a link to an HTML parts.
+    elseif (arg(4) != 'html' && $part_array[0] == drupal_strtoupper('HTML')) {
+      $message_self_link .= '<hr>' . l(t('View this message as a web page.'), 'basic_webmail/message/' . $message_number . '/' . $folder . '/html/' . $part_id);
+    }
+
+    // Everything else?
+    // For attachments we really want them available whether the part being
+    // viewed is HTML or plain text.
+    elseif (!empty($part_array[0]) && !empty($part_array[1])) {
+      $attachment = _basic_webmail_process_attachment($imap_resource, $message_number, $part_id, $part_array[1]);
+      $attachment_links .= l($attachment[1], $attachment[2]) . '&nbsp; -- &nbsp;';
+    }
+  }
+
+
+  // Add the formatted message body to the output string.
+  $output .= $message_body;
+
+  // Add links to the attachments.
+  if ($attachment_links) {
+    $output .= '<hr>Attachment(s):<br /><br />';
+    $output .= drupal_substr($attachment_links, 0, drupal_strlen($attachment_links) - 16);
+  }
+
+  // Add the link to the other part.
+  $output .= $message_self_link;
+
+  // Add a separator.
+  $output .= '<hr>';
+
+  // Add some action links for this message.
+  // Links for all folders.
+  $delete_link = l(t('Delete'), 'basic_webmail/delete/' . $message_number . '/' . $folder);
+  $copy_link = l(t('Copy'), 'basic_webmail/copy/' . $message_number . '/' . $folder);
+  $move_link = l(t('Move'), 'basic_webmail/move/' . $message_number . '/' . $folder);
+  if ($folder == 'INBOX.Drafts') {
+    // Links for the Drafts folder.
+    $continue_link = l(t('Continue composition'), 'basic_webmail/sendmail/continue/' . $folder . '/' . $message_number . '/' . $reply_part);
+    $output .= $continue_link . '&nbsp; -- &nbsp;' . $copy_link . '&nbsp; -- &nbsp;' . $move_link . '&nbsp; -- &nbsp;' . $delete_link;
+  }
+  else {
+    // Links for the other folders.
+    $reply_link = l(t('Reply'), 'basic_webmail/sendmail/reply/' . $folder . '/' . $message_number . '/' . $reply_part);
+    $reply_to_all_link = l(t('Reply to all'), 'basic_webmail/sendmail/replytoall/' . $folder . '/' . $message_number . '/' . $reply_part);
+    $forward_link = l(t('Forward'), 'basic_webmail/sendmail/forward/' . $folder . '/' . $message_number . '/' . $reply_part);
+    $output .= $reply_link . '&nbsp; -- &nbsp;' . $reply_to_all_link . '&nbsp; -- &nbsp;' . $forward_link . '&nbsp; -- &nbsp;' . $copy_link . '&nbsp; -- &nbsp;' . $move_link . '&nbsp; -- &nbsp;' . $delete_link;
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  return $output;
+} // End of _basic_webmail_message().
+
+
+/**
+ * Construct the form for conposing an email message.
+ *
+ * @param send_mail_type
+ *   Whether the message is new, a reply or a forward. Possible values:
+ *   - "new": All form fields are left blank.
+ *   - "reply": The To form field is filled in with the from address of the
+ *     original message. The Subject and Body form fields are filled in with
+ *     the corresponding fields from the original message.
+ *   - "replytoall": The To form field is filled in with the from address of
+ *     the original message. The CC form field is filled in with all of the
+ *     addresses in the to and cc fields of the original message. The Subject
+ *     and Body form fields are filled in with the corresponding fields from
+ *     the original message.
+ *   - "forward": The To, CC and BCC form fields are blank. The Subject and
+ *     Body form fields are filled in with the corresponding fields from the
+ *     original message.
+ *   - "continue": The contents of the form are filled in by the message in
+ *     the Drafts folder that is being continued.
+ *   - An email address: The To form field gets filled in with the value in
+ *     $send_mail_type, and all other form fields are left blank.
+ * @param send_mail_message_number
+ *   The ID of the message being replied to or forwarded, blank otherwise.
+ *
+ * @return
+ *   The completed form definition.
+ */
+//function _basic_webmail_send_mail_form(&$form_state, $send_mail_type = 'new', $send_mail_folder = '', $send_mail_message_number = '') {
+function _basic_webmail_send_mail_form($form, &$form_state) {
+  if (isset($form_state['build_info']['args'][0])) {
+      $send_mail_type = $form_state['build_info']['args'][0];
+  }
+  else {
+      $send_mail_type = 'new';
+  };
+  
+  if (isset($form_state['build_info']['args'][1])) {
+      $send_mail_folder = $form_state['build_info']['args'][1];
+  }
+  else{
+      $send_mail_folder = '';
+  };
+  
+  if (isset($form_state['build_info']['args'][2])) {
+      $send_mail_message_number = $form_state['build_info']['args'][2];
+  }
+  else{
+      $send_mail_message_number = '';
+  };
+
+  // Initialize variables.
+  $send_mail_to = '';
+  $send_mail_cc = '';
+  $send_mail_bcc = '';
+  $send_mail_subject = '';
+  $send_mail_body = '';
+  $attachments = array();
+
+  // Check to see if this is a reply or forward.
+  if ($send_mail_type == 'reply' || $send_mail_type == 'replytoall' || $send_mail_type == 'forward' || $send_mail_type == 'continue') {
+    // Make sure we have a message id.
+    if (!$send_mail_message_number) {
+      watchdog('basic_webmail', 'There was an attempt to reply to or forward a message w/o including the message id.', array(), WATCHDOG_ERROR);
+    }
+    // Get the message information for use in filling the form.
+    else {
+      // Connect to the server and retrieve a connection to the mailbox.
+      global $user;
+      $imap_resource = _basic_webmail_connect_to_server($user->uid, $send_mail_folder);
+      if (!$imap_resource) {
+        drupal_set_title(t('Error'));
+        return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+      }
+
+      // Show the message.
+
+      // Get the message header.
+      $message_header = imap_headerinfo($imap_resource, $send_mail_message_number);
+      if (!$message_header) {
+        watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
+      }
+
+      // Get the message body.
+      $message_body = imap_fetchbody($imap_resource, $send_mail_message_number, arg(5));
+      if (!$message_body) {
+        watchdog('basic_webmail', 'There was an error retrieving the message body: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
+      }
+
+      // Set the title of the page.
+      drupal_set_title(t('!title', array('!title' => _basic_webmail_decode_mime_str($message_header->subject))));
+
+      // Add a link back to the listing.
+      if (!$send_mail_message_number) {
+        $form['basic_webmail_send_mail_list_link'] = array(
+          '#value' => l(t('Return to message listing'), 'basic_webmail/' . $send_mail_folder) . '<hr>',
+        );
+      }
+      else {
+        $form['basic_webmail_send_mail_list_link'] = array(
+          '#value' => l(t('Return to message listing'), 'basic_webmail/' . $send_mail_folder) . '&nbsp; -- &nbsp;' . l(t('Return to message'), 'basic_webmail/message/' . $send_mail_message_number . '/' . $send_mail_folder) . '<hr>',
+        );
+      }
+
+
+      // Set defaults based on $send_mail_type.
+      if ($send_mail_type == 'reply' || $send_mail_type == 'replytoall' || $send_mail_type == 'forward' || $send_mail_type == 'continue') {
+        // Get the message parts list.
+        $parts_list = _basic_webmail_get_parts_list($imap_resource, $send_mail_message_number);
+
+        // Initialize variables.
+        $message_self_link = '';
+        $attachment_links = '';
+
+        // Iterate over the parts list.
+        foreach ($parts_list as $part_id => $part_array) {
+          // If there's an attachment, allow the user to send it.
+          if ($part_array[0] && $part_array[1]) {
+            $attachment = _basic_webmail_process_attachment($imap_resource, $send_mail_message_number, $part_id, $part_array[1]);
+            $attachments[$attachment[0]] = $attachment[1];
+          }
+        }
+      }
+
+      // Set defaults based on $send_mail_type.
+      if ($send_mail_type == 'reply' || $send_mail_type == 'replytoall') {
+        $form['basic_webmail_message_number'] = array(
+          '#type' => 'hidden',
+          '#value' => $message_header->Msgno,
+        );
+        $form['basic_webmail_in_reply_to'] = array(
+          '#type' => 'hidden',
+          '#value' => $message_header->message_id,
+        );
+
+        // Set the subject of the message.
+        $send_mail_subject = 'Re: ' . _basic_webmail_decode_mime_str($message_header->subject);
+
+        // Set the "To" of the message.
+        if ($message_header->from[0]->personal) {
+          $send_mail_to = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
+        }
+        else {
+          $send_mail_to = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
+        }
+
+        // Set the body of the message.
+        if ($send_mail_type == 'reply') {
+          $send_mail_body = "\n\n\nOn " . $message_header->date . ", you wrote:\n";
+        }
+        else {
+          $send_mail_body = "\n\n\nOn " . $message_header->date . ', ' . $send_mail_to . " wrote:\n";
+        }
+
+        $temp_send_mail_body = explode("\n", utf8_encode(quoted_printable_decode($message_body)));
+        $send_mail_body .= '> ' . implode("\n> ", $temp_send_mail_body);
+        $send_mail_body .= "\n";
+
+        // Add the sender's signature, if one exists.
+        global $user;
+        if ($user->signature) {
+          $send_mail_body .= "\n-- \n" . $user->signature;
+        }
+      }
+
+
+      // Set defaults based on $send_mail_type.
+      if ($send_mail_type == 'replytoall') {
+        // Set the cc of the message.
+        // Make sure we don't have any bad information by setting it to an empty string first.
+        $send_mail_cc = '';
+
+        // Add all addresses in the to field.
+        for ($i = 0; $i < count($message_header->to); $i++) {
+          if ($message_header->to[$i]->personal) {
+            $send_mail_cc .= _basic_webmail_decode_mime_str($message_header->to[$i]->personal) . ' <' . $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host . '>, ';
+          }
+          else {
+            $send_mail_cc .= $message_header->to[$i]->mailbox . '@' . $message_header->to[$i]->host . ', ';
+          }
+        }
+
+        // Add all addresses in the cc field.
+        if ($message_header->ccaddress) {
+          for ($i = 0; $i < count($message_header->cc); $i++) {
+            if ($message_header->cc[$i]->personal) {
+              $send_mail_cc .= _basic_webmail_decode_mime_str($message_header->cc[$i]->personal) . ' <' . $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host . '>, ';
+            }
+            else {
+              $send_mail_cc .= $message_header->cc[$i]->mailbox . '@' . $message_header->cc[$i]->host . ', ';
+            }
+          }
+        }
+
+        $send_mail_cc = drupal_substr($send_mail_cc, 0, drupal_strlen($send_mail_cc) - 2);
+      }
+
+
+      // Set defaults based on $send_mail_type.
+      if ($send_mail_type == 'forward') {
+        // Set the subject of the message.
+        $send_mail_subject = 'Fw: ' . _basic_webmail_decode_mime_str($message_header->subject);
+
+        // Set the body of the message.
+        $send_mail_body = "\n\n\n------- Forwarded Message\n\n";
+        $send_mail_body .= $message_body;
+        $send_mail_body .= "\n\n------- End of Forwarded Message\n\n";
+
+        // Add the sender's signature, if one exists.
+        global $user;
+        if ($user->signature) {
+          $send_mail_body .= "\n-- \n" . $user->signature;
+        }
+      }
+
+
+      // Set defaults based on $send_mail_type.
+      if ($send_mail_type == 'continue') {
+        $form['basic_webmail_message_number'] = array(
+          '#type' => 'hidden',
+          '#value' => $message_header->Msgno,
+        );
+
+        // Set the "To" of the message.
+        $send_mail_to = $message_header->toaddress;
+        // Set the cc of the message.
+        $send_mail_cc = $message_header->ccaddress;
+        // Set the bcc of the message.
+        $send_mail_bcc = $message_header->bccaddress;
+        // Set the subject of the message.
+        $send_mail_subject = _basic_webmail_decode_mime_str($message_header->subject);
+        // Fill in the body of the message.
+        $send_mail_body = $message_body;
+      }
+
+
+      // Clean up.
+      if (!imap_close($imap_resource)) {
+        watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+      }
+    }
+  }
+  else {
+    // Set the title of the page.
+    drupal_set_title(t('New mail message'));
+
+    // If this is true, $send_mail_type holds the email address to send the
+    // message to.
+    if ($send_mail_type != 'new') {
+      // Set the to field.
+      $send_mail_to = $send_mail_type;
+    }
+  }
+
+  $form['basic_webmail_send_mail_to'] = array(
+    '#type' => 'textfield',
+    '#title' => t('To'),
+    '#default_value' => $send_mail_to,
+    //    '#size' => 96,
+    '#maxlength' => 1024,
+    '#autocomplete_path' => 'basic_webmail/autocomplete',
+    '#description' => t('One or more recepients of this message. Separate the addresses with a comma (,).'),
+    '#required' => TRUE,
+  );
+
+  $form['basic_webmail_send_mail_cc'] = array(
+    '#type' => 'textfield',
+    '#title' => t('CC'),
+    '#default_value' => $send_mail_cc,
+    //    '#size' => 96,
+    '#maxlength' => 1024,
+    '#autocomplete_path' => 'basic_webmail/autocomplete',
+    '#description' => t('One or more email addresses to receive a carbon copy. Separate the addresses with a comma (,).'),
+  );
+  $form['basic_webmail_send_mail_bcc'] = array(
+    '#type' => 'textfield',
+    '#title' => t('BCC'),
+    '#default_value' => $send_mail_bcc,
+    //    '#size' => 96,
+    '#maxlength' => 1024,
+    '#autocomplete_path' => 'basic_webmail/autocomplete',
+    '#description' => t('One or more email addresses to receive a blind carbon copy. These email addresses will not be visible in the message. Separate the addresses with a comma (,).'),
+  );
+
+  $form['basic_webmail_send_mail_subject'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Subject'),
+    '#default_value' => $send_mail_subject,
+    //    '#size' => 96,
+    '#maxlength' => 1024,
+  );
+  $form['basic_webmail_send_mail_body'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Message'),
+    '#default_value' => $send_mail_body,
+    '#rows' => 15,
+  );
+
+  // If any exists, include attachments from message as checkboxes here.
+  if ($attachments) {
+    $form['basic_webmail_attachments'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Attachments from original message'),
+      '#options' => $attachments,
+      '#description' => t('Check any attachments from the original you want to include in this message.'),
+    );
+  }
+
+  for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', 3); $i++) {
+    $form['basic_webmail_attachment_' . $i] = array(
+      '#type' => 'file',
+      '#title' => t('Attachment #!number', array('!number' => $i)),
+    );
+  }
+
+  $form['basic_webmail_send_mail_self'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Send a copy to myself.'),
+  );
+
+//  $form['_basic_webmail_send_mail_form_preview'] = array(
+//    '#type' => 'button',
+//    '#value' => t('Preview'),
+//    '#submit' => array('_basic_webmail_send_mail_form_preview'),
+//  );
+  $form['_basic_webmail_send_mail_form_save'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save in INBOX.Drafts'),
+    '#submit' => array('_basic_webmail_send_mail_form_save'),
+  );
+  $form['_basic_webmail_send_mail_form_send'] = array(
+    '#type' => 'submit',
+    '#value' => t('Send'),
+    '#submit' => array('_basic_webmail_send_mail_form_send'),
+  );
+
+  $form['#attributes']['enctype'] = 'multipart/form-data';
+
+  return $form;
+} // End of _basic_webmail_send_mail_form().
+
+
+
+/**
+ * Send the message.
+ *
+ * @param form_id
+ *   The form ID of the passed form.
+ * @param $form_state
+ *   The form values of the passed form.
+ */
+function _basic_webmail_send_mail_form_send($form, &$form_state) {
+  global $user;
+
+  // Initialize variables.
+  $sent_envelope = array();
+  $sent_part = array();
+  $sent_body = array();
+  $send_mail_headers = array();
+  $send_mail_body = '';
+
+
+  // Set the From email address.
+  if (variable_get('basic_webmail_account_info', 1)) {
+    $sent_envelope['from'] = $user->mail;
+  }
+  else {
+    $sent_envelope['from'] = $user->data['basic_webmail_username'];
+  }
+  // This ends up creating saved messages with email addresses that look like admin@"NO HOST".
+//  $from_name_address = addslashes(mime_header_encode($user->name)) .' <'. $user->mail .'>';
+
+
+  // Set some other header parts.
+  $sent_envelope['return_path'] = $sent_envelope['from'];
+  $sent_envelope['reply_to'] = $sent_envelope['from'];
+  $send_mail_headers['Return-Path'] = $sent_envelope['from'];
+  $send_mail_headers['Sender'] = $sent_envelope['from'];
+
+  if ($form_state['values']['basic_webmail_in_reply_to']) {
+    $sent_envelope['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
+    $send_mail_headers['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
+  }
+
+
+  // Set the CC and BCC fields, if they exist.
+  if ($form_state['values']['basic_webmail_send_mail_cc']) {
+    if ($form_state['values']['basic_webmail_send_mail_bcc']) {
+      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
+      $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
+      $send_mail_headers['Cc'] = $sent_envelope['cc'];
+      $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
+    }
+    else {
+      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
+      $send_mail_headers['Cc'] = $sent_envelope['cc'];
+    }
+  }
+  elseif ($form_state['values']['basic_webmail_send_mail_bcc']) {
+    $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
+    $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
+  }
+
+
+  // Check for the exsistance of added attachments.
+  for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
+    if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
+      $has_attachments = 1;
+      break;
+    }
+  }
+
+  // Check for the exsistance of forwarded attachments.
+  if ($form_state['values']['basic_webmail_attachments']) {
+    foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
+      if ($attachment) {
+        $has_attachments = 1;
+        break;
+      }
+    }
+  }
+
+  // Create headers based on presence or absence of attachment.
+  if ($has_attachments) {
+    $sent_part['type'] = TYPEMULTIPART;
+    $sent_part['subtype'] = 'mixed';
+    $sent_body[] = $sent_part;
+    $sent_part = array();
+
+    $uid = md5(uniqid(REQUEST_TIME));
+    $send_mail_headers['Content-Type'] = 'multipart/mixed; boundary="' . $uid . '"';
+
+    $sent_part['type'] = TYPETEXT;
+    $sent_part['subtype'] = 'plain';
+    $sent_part['description'] = 'message';
+
+    $send_mail_body = "\n--$uid\n";
+    $send_mail_body .= "Content-Type: text/plain; charset=UTF-8; format=flowed\n\n";
+
+
+    // Add in the actual message
+    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n\n";
+    $send_mail_body .= $sent_part['contents.data'];
+    $sent_body[] = $sent_part;
+    $sent_part = array();
+
+
+    // Add any forwarded attachments.
+    if ($form_state['values']['basic_webmail_attachments']) {
+      foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
+        if ($attachment) {
+          $sent_part = array();
+          $content_type = mime_content_type($attachment);
+
+          switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
+            case 'audio':
+              $sent_part['type'] = TYPEAUDIO;
+              break;
+            case 'image':
+              $sent_part['type'] = TYPEIMAGE;
+              break;
+            case 'text':
+              $sent_part['type'] = TYPETEXT;
+              break;
+            case 'video':
+              $sent_part['type'] = TYPEVIDEO;
+              break;
+            default:
+              $sent_part['type'] = TYPEAPPLICATION;
+              break;
+          }
+
+          $sent_part['encoding'] = ENCBASE64;
+          $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
+          $sent_part['description'] = basename($attachment);
+          $sent_part['disposition.type'] = 'attachment';
+          $sent_part['disposition'] = array('filename' => $sent_part['description']);
+          $sent_part['type.parameters'] = array('name' => $sent_part['description']);
+          $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($attachment)));
+
+          $sent_body[] = $sent_part;
+
+          $send_mail_body .= "--$uid\n";
+          $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
+          $send_mail_body .= "Content-Transfer-Encoding: base64\n";
+          $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
+          $send_mail_body .= $sent_part['contents.data'];
+          $send_mail_body .= "\n\n";
+        }
+      }
+    }
+
+    // Add any added attachments.
+    for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
+      if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
+        $sent_part = array();
+        $content_type = $_FILES['files']['type']['basic_webmail_attachment_' . $i];
+
+        switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
+          case 'audio':
+            $sent_part['type'] = TYPEAUDIO;
+            break;
+          case 'image':
+            $sent_part['type'] = TYPEIMAGE;
+            break;
+          case 'text':
+            $sent_part['type'] = TYPETEXT;
+            break;
+          case 'video':
+            $sent_part['type'] = TYPEVIDEO;
+            break;
+          default:
+            $sent_part['type'] = TYPEAPPLICATION;
+            break;
+        }
+
+        $sent_part['encoding'] = ENCBASE64;
+        $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
+        $sent_part['description'] = basename($_FILES['files']['name']['basic_webmail_attachment_' . $i]);
+        $sent_part['disposition.type'] = 'attachment';
+        $sent_part['disposition'] = array('filename' => $sent_part['description']);
+        $sent_part['type.parameters'] = array('name' => $sent_part['description']);
+        $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($_FILES['files']['tmp_name']['basic_webmail_attachment_' . $i])));
+
+        $sent_body[] = $sent_part;
+
+        $send_mail_body .= "--$uid\n";
+        $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
+        $send_mail_body .= "Content-Transfer-Encoding: base64\n";
+        $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
+        $send_mail_body .= $sent_part['contents.data'];
+        $send_mail_body .= "\n\n";
+      }
+    }
+
+    // Add the final boundary to the body.
+    $send_mail_body .= "--$uid--\n\n";
+  }
+  // No attachments exist.
+  else {
+    // Add in the actual message
+    $sent_part = array();
+    $sent_part['type'] = TYPETEXT;
+    $sent_part['subtype'] = 'plain';
+    $sent_part['description'] = 'message';
+    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n";
+    $send_mail_body .= $sent_part['contents.data'];
+    $sent_body[] = $sent_part;
+    $sent_part = array();
+  }
+
+
+  // Prepare the message for sending.
+  $module = 'basic_webmail';
+  $key = 'message';
+  $to = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_to']);
+  $language = language_default();
+  $from = $sent_envelope['from'];
+
+  $params['subject'] = $form_state['values']['basic_webmail_send_mail_subject'];
+  $params['body'] = $send_mail_body;
+  if ($send_mail_headers) {
+    $params['headers'] = $send_mail_headers;
+  }
+
+  // Send the message.
+  $completed_message = drupal_mail($module, $key, $to, $language, $params, $from);
+  if ($completed_message) {
+    // If a copy to self was requested, send it.
+    if ($form_state['values']['basic_webmail_send_mail_self']) {
+      $key = 'copy_to_self';
+      global $language;
+      drupal_mail($module, $key, $to, $language, $params, $from);
+    }
+
+    // Copy the message to the INBOX.Sent folder, marked as read.
+
+    // Connect to the server and retrieve a connection to the mailbox.
+    global $user;
+    $imap_resource = _basic_webmail_connect_to_server($user->uid);
+    if (!$imap_resource) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', 'There was an error connecting to the server: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+      drupal_set_message(t('There was an error connecting to the server: @last_error', array('@last_error' => $last_error)), 'error');
+    }
+
+    // If this is a reply, mark the replied to message as answered.
+    if ($form_state['values']['basic_webmail_in_reply_to']) {
+      if (!imap_setflag_full($imap_resource, $form_state['values']['basic_webmail_message_number'], '\\Answered')) {
+        // Report the error.
+        watchdog('basic_webmail', 'There was an error marking the replied to message as answered: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
+      }
+    }
+
+    // Complete the envelope for the copy for the Sent folder.
+    $sent_envelope['to'] = $to;
+    $sent_envelope['subject'] = $params['subject'];
+    $sent_envelope['date'] = date('r');
+
+    // Create the message string to store.
+    $sent_message = imap_mail_compose($sent_envelope, $sent_body);
+    if (!$sent_message) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', 'There was an error creating the copy of the message for the sent folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+      drupal_set_message(t('There was an error creating the copy of the message for the sent folder: @last_error', array('@last_error' => $last_error)), 'error');
+    }
+    else {
+      // Place the message in the Sent folder.
+      if (!imap_append($imap_resource, _basic_webmail_get_server_string() . 'INBOX.Sent', $sent_message, '\\Seen')) {
+        // Report the error.
+        $last_error = imap_last_error();
+        watchdog('basic_webmail', 'There was an error saving a copy of the message to the sent folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+        drupal_set_message(t('There was an error saving a copy of the message to the sent folder: @last_error', array('@last_error' => $last_error)), 'error');
+      }
+    }
+
+    // Clean up.
+    if (!imap_close($imap_resource)) {
+      watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+    }
+
+    // Report to the user.
+    drupal_set_message(t('Your message was successfully sent.'));
+
+    // Where we go after the message is sent.
+    if (arg(3) && arg(4)) {
+      // The original message, if there was one.
+      drupal_goto('/basic_webmail/message/' . arg(4) . '/' . arg(3));
+    }
+    else {
+      // The message list otherwise.
+      drupal_goto('/basic_webmail');
+    }
+  }
+  else {
+    // Report to the user.
+    drupal_set_message(t('There was an error sending your message.'), 'error');
+  }
+} // End of _basic_webmail_send_mail_form_send().
+
+
+/**
+ * Save the message.
+ *
+ * @param form_id
+ *   The form ID of the passed form.
+ * @param $form_state
+ *   The form values of the passed form.
+ */
+function _basic_webmail_send_mail_form_save($form, &$form_state) {
+  global $user;
+
+  // Initialize variables.
+  $sent_envelope = array();
+  $sent_part = array();
+  $sent_body = array();
+  $send_mail_headers = array();
+  $send_mail_body = '';
+
+
+  // Set the From email address.
+  if (variable_get('basic_webmail_account_info', 1)) {
+    $sent_envelope['from'] = $user->mail;
+  }
+  else {
+    $sent_envelope['from'] = $user->data['basic_webmail_username'];
+  }
+  // This ends up creating saved messages with email addresses that look like admin@"NO HOST".
+//  $from_name_address = addslashes(mime_header_encode($user->name)) .' <'. $user->mail .'>';
+
+
+  // Set some other header parts.
+  $sent_envelope['return_path'] = $sent_envelope['from'];
+  $sent_envelope['reply_to'] = $sent_envelope['from'];
+  $send_mail_headers['Return-Path'] = $sent_envelope['from'];
+  $send_mail_headers['Sender'] = $sent_envelope['from'];
+
+  if ($form_state['values']['basic_webmail_in_reply_to']) {
+    $sent_envelope['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
+    $send_mail_headers['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
+  }
+
+
+  // Set the CC and BCC fields, if they exist.
+  if ($form_state['values']['basic_webmail_send_mail_cc']) {
+    if ($form_state['values']['basic_webmail_send_mail_bcc']) {
+      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
+      $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
+      $send_mail_headers['Cc'] = $sent_envelope['cc'];
+      $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
+    }
+    else {
+      $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
+      $send_mail_headers['Cc'] = $sent_envelope['cc'];
+    }
+  }
+  elseif ($form_state['values']['basic_webmail_send_mail_bcc']) {
+    $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
+    $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
+  }
+
+
+  // Check for the exsistance of added attachments.
+  for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
+    if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
+      $has_attachments = 1;
+      break;
+    }
+  }
+
+  // Check for the exsistance of forwarded attachments.
+  if ($form_state['values']['basic_webmail_attachments']) {
+    foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
+      if ($attachment) {
+        $has_attachments = 1;
+        break;
+      }
+    }
+  }
+
+  // Create headers based on presence or absence of attachment.
+  if ($has_attachments) {
+    $sent_part['type'] = TYPEMULTIPART;
+    $sent_part['subtype'] = 'mixed';
+    $sent_body[] = $sent_part;
+    $sent_part = array();
+
+    $uid = md5(uniqid(REQUEST_TIME));
+    $send_mail_headers['Content-Type'] = 'multipart/mixed; boundary="' . $uid . '"';
+
+    $sent_part['type'] = TYPETEXT;
+    $sent_part['subtype'] = 'plain';
+    $sent_part['description'] = 'message';
+
+    $send_mail_body = "\n--$uid\n";
+    $send_mail_body .= "Content-Type: text/plain; charset=UTF-8; format=flowed\n\n";
+
+
+    // Add in the actual message
+    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n\n";
+    $send_mail_body .= $sent_part['contents.data'];
+    $sent_body[] = $sent_part;
+    $sent_part = array();
+
+
+    // Add any forwarded attachments.
+    if ($form_state['values']['basic_webmail_attachments']) {
+      foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
+        if ($attachment) {
+          $sent_part = array();
+          $content_type = mime_content_type($attachment);
+
+          switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
+            case 'audio':
+              $sent_part['type'] = TYPEAUDIO;
+              break;
+            case 'image':
+              $sent_part['type'] = TYPEIMAGE;
+              break;
+            case 'text':
+              $sent_part['type'] = TYPETEXT;
+              break;
+            case 'video':
+              $sent_part['type'] = TYPEVIDEO;
+              break;
+            default:
+              $sent_part['type'] = TYPEAPPLICATION;
+              break;
+          }
+
+          $sent_part['encoding'] = ENCBASE64;
+          $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
+          $sent_part['description'] = basename($attachment);
+          $sent_part['disposition.type'] = 'attachment';
+          $sent_part['disposition'] = array('filename' => $sent_part['description']);
+          $sent_part['type.parameters'] = array('name' => $sent_part['description']);
+          $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($attachment)));
+
+          $sent_body[] = $sent_part;
+
+          $send_mail_body .= "--$uid\n";
+          $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
+          $send_mail_body .= "Content-Transfer-Encoding: base64\n";
+          $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
+          $send_mail_body .= $sent_part['contents.data'];
+          $send_mail_body .= "\n\n";
+        }
+      }
+    }
+
+    // Add any added attachments.
+    for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
+      if ($_FILES['files']['error']['basic_webmail_attachment_' . $i] == 0) {
+        $sent_part = array();
+        $content_type = $_FILES['files']['type']['basic_webmail_attachment_' . $i];
+
+        switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
+          case 'audio':
+            $sent_part['type'] = TYPEAUDIO;
+            break;
+          case 'image':
+            $sent_part['type'] = TYPEIMAGE;
+            break;
+          case 'text':
+            $sent_part['type'] = TYPETEXT;
+            break;
+          case 'video':
+            $sent_part['type'] = TYPEVIDEO;
+            break;
+          default:
+            $sent_part['type'] = TYPEAPPLICATION;
+            break;
+        }
+
+        $sent_part['encoding'] = ENCBASE64;
+        $sent_part['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
+        $sent_part['description'] = basename($_FILES['files']['name']['basic_webmail_attachment_' . $i]);
+        $sent_part['disposition.type'] = 'attachment';
+        $sent_part['disposition'] = array('filename' => $sent_part['description']);
+        $sent_part['type.parameters'] = array('name' => $sent_part['description']);
+        $sent_part['contents.data'] = chunk_split(base64_encode(file_get_contents($_FILES['files']['tmp_name']['basic_webmail_attachment_' . $i])));
+
+        $sent_body[] = $sent_part;
+
+        $send_mail_body .= "--$uid\n";
+        $send_mail_body .= "Content-Type: " . $content_type . "; name=\"" . $sent_part['description'] . "\"\n";
+        $send_mail_body .= "Content-Transfer-Encoding: base64\n";
+        $send_mail_body .= "Content-Disposition: attachment; filename=\"" . $sent_part['description'] . "\"\n\n";
+        $send_mail_body .= $sent_part['contents.data'];
+        $send_mail_body .= "\n\n";
+      }
+    }
+
+    // Add the final boundary to the body.
+    $send_mail_body .= "--$uid--\n\n";
+  }
+  // No attachments exist.
+  else {
+    // Add in the actual message
+    $sent_part = array();
+    $sent_part['type'] = TYPETEXT;
+    $sent_part['subtype'] = 'plain';
+    $sent_part['description'] = 'message';
+    $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) . "\n\n";
+    $send_mail_body .= $sent_part['contents.data'];
+    $sent_body[] = $sent_part;
+    $sent_part = array();
+  }
+
+
+  // Complete the envelope for the copy to the Drafts folder.
+  $sent_envelope['to'] = $form_state['values']['basic_webmail_send_mail_to'];
+  $sent_envelope['subject'] = $form_state['values']['basic_webmail_send_mail_subject'];
+  $sent_envelope['date'] = date('r');
+
+  // Connect to the server and retrieve a connection to the mailbox.
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, 'INBOX.Drafts');
+  if (!$imap_resource) {
+    // Report the error.
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error connecting to the server: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    drupal_set_message(t('There was an error connecting to the server: @last_error', array('@last_error' => $last_error)), 'error');
+  }
+
+  // Copy message to INBOX.Drafts, marked as unread.
+  // Create the message string to store.
+  $draft_message = imap_mail_compose($sent_envelope, $sent_body);
+  if (!$draft_message) {
+    // Report the error.
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error creating the message for the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    drupal_set_message(t('There was an error creating the message for the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error)), 'error');
+  }
+  else {
+    // Place the message in the Drafts folder.
+    // First make sure this isn't a re-saving of a previously saved
+    // message.
+    if (imap_num_msg($imap_resource) > 0) {
+      $threads = imap_thread($imap_resource);
+      if ($threads) {
+        foreach ($threads as $message_number) {
+          if ($message_number == $form_state['values']['basic_webmail_message_number']) {
+            // Remove the old copy.
+            if (!imap_delete($imap_resource, $message_number)) {
+              // Report the error.
+              watchdog('basic_webmail', 'There was an error deleting message #@message_number from the INBOX.Drafts folder: @last_error', array('@message_number' => $message_number, '@last_error' => imap_last_error()), WATCHDOG_ERROR);
+            }
+
+            if (!imap_expunge($imap_resource)) {
+              // Report the error.
+              watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+            }
+          }
+        }
+      }
+    }
+
+    if (!imap_append($imap_resource, _basic_webmail_get_server_string() . 'INBOX.Drafts', $draft_message)) {
+      // Report the error.
+      $last_error = imap_last_error();
+      watchdog('basic_webmail', 'There was an error saving the message in the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+      drupal_set_message(t('There was an error saving the message in the INBOX.Drafts folder: @last_error', array('@last_error' => $last_error)), 'error');
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  // Report to the user.
+  drupal_set_message(t('Your message was successfully saved in the INBOX.Drafts folder.'));
+
+  // Where we go after the message is saved.
+  if (arg(3)) {
+    // The INBOX.Drafts message listing.
+    drupal_goto('/basic_webmail/' . arg(3));
+  }
+  else {
+    // The INBOX message listing, otherwise.
+    drupal_goto('/basic_webmail/');
+  }
+} // End of _basic_webmail_send_mail_form_save().
+
+
+/**
+ * Pre-process the message.
+ *
+ * @param form_id
+ *   The form ID of the passed form.
+ * @param $form_state
+ *   The form values of the passed form.
+ * /
+ function _basic_webmail_send_mail_form_preprocess($form, &$form_state) {
+ global $user;
+
+ // Initialize variables.
+ $sent_envelope = array();
+ $sent_part = array();
+ $sent_body = array();
+ $send_mail_headers = array();
+ $send_mail_body = '';
+ $message = array();
+
+
+ // Set the From email address.
+ if (variable_get('basic_webmail_account_info', 1)) {
+ $sent_envelope['from'] = $user->mail;
+ }
+ else {
+ $sent_envelope['from'] = $user->data['basic_webmail_username'];
+ }
+
+
+ // Set some other header parts.
+ $sent_envelope['return_path'] = $sent_envelope['from'];
+ $sent_envelope['reply_to'] = $sent_envelope['from'];
+ $send_mail_headers['Return-Path'] = $sent_envelope['from'];
+ $send_mail_headers['Sender'] = $sent_envelope['from'];
+
+ if ($form_state['values']['basic_webmail_in_reply_to']) {
+ $sent_envelope['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
+ $send_mail_headers['in_reply_to'] = $form_state['values']['basic_webmail_in_reply_to'];
+ }
+
+ // Set the CC and BCC fields, if they exist.
+ if ($form_state['values']['basic_webmail_send_mail_cc']) {
+ if ($form_state['values']['basic_webmail_send_mail_bcc']) {
+ $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
+ $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
+ $send_mail_headers['Cc'] = $sent_envelope['cc'];
+ $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
+ }
+ else {
+ $sent_envelope['cc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_cc']);
+ $send_mail_headers['Cc'] = $sent_envelope['cc'];
+ }
+ }
+ elseif ($form_state['values']['basic_webmail_send_mail_bcc']) {
+ $sent_envelope['bcc'] = _basic_webmail_send_mail_form_process_addresses($form_state['values']['basic_webmail_send_mail_bcc']);
+ $send_mail_headers['Bcc'] = $sent_envelope['bcc'];
+ }
+
+ // Check for the exsistance of added attachments.
+ for ($i = 1; $i <= variable_get('basic_webmail_number_attachments', '3'); $i++) {
+ if ($_FILES['files']['error']['basic_webmail_attachment_'. $i] == 0) {
+ $has_attachments = 1;
+ // Process the attachments.
+ $message = _basic_webmail_send_mail_form_process_attachments($form_state, $message);
+ break;
+ }
+ }
+
+ // Check for the exsistance of forwarded attachments.
+ if (!$has_attachments && $form_state['values']['basic_webmail_attachments']) {
+ $has_attachments = 1;
+ // Process the attachment(s).
+ $message = _basic_webmail_send_mail_form_process_attachments($form_state, $message);
+ }
+
+ // No attachments exist.
+ if (!$has_attachments) {
+ // Add in the actual message
+ $sent_part = array();
+ $sent_part['type'] = TYPETEXT;
+ $sent_part['subtype'] = 'plain';
+ $sent_part['description'] = 'message';
+ $sent_part['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) ."\n\n";
+ $send_mail_body .= $sent_part['contents.data'];
+ $sent_body[] = $sent_part;
+ $sent_part = array();
+ }
+
+ $message['sent_envelope'] = $sent_envelope;
+ $message['sent_part'] = $sent_part;
+ $message['sent_body'] = $sent_body;
+ $message['send_mail_headers'] = $send_mail_headers;
+ $message['send_mail_body'] = $send_mail_body;
+
+ return $message;
+ } // End of _basic_webmail_send_mail_form_preprocess().
+
+
+ /**
+ * Takes given email addresses and adds the user name, if it exists, to them.
+ *
+ * @param email_addresses
+ *   A string containing one or more email addresses, separated by commas.
+ *
+ * @return
+ *   A string contaning those email address with their corresponding user
+ *   name, if one exists.
+ */
+function _basic_webmail_send_mail_form_process_addresses($email_addresses) {
+  $addresses = array();
+  $results = '';
+
+  // Check to see if there are multiple addresses in the string.
+  if (strpos($email_addresses, ',')) {
+    // Seperate the multiple addresses into an array of individual items.
+    $addresses = explode(',', $email_addresses);
+
+    foreach ($addresses as $address) {
+      // For each item in the list, attempt to add the user's name.
+      $results .= _basic_webmail_send_mail_form_get_user_from_mail(trim($address)) . ', ';
+    }
+  }
+  else {
+    // There is only one address. Attempt to add the user's name to it.
+    $results = _basic_webmail_send_mail_form_get_user_from_mail(trim($email_addresses)) . ', ';
+  }
+
+  // Remove any extra white space.
+  $results = trim($results);
+
+  // If there is a trailing comma, remove it.
+  if (drupal_substr($results, drupal_strlen($results) - 1, 1) == ',') {
+    $results = drupal_substr($results, 0, drupal_strlen($results) - 1);
+  }
+
+  return $results;
+} // End of _basic_webmail_send_mail_form_process_addresses().
+
+
+/**
+ * Takes a given email address and adds the user name, if it exists, to it.
+ *
+ * @param email_addresses
+ *   A string containing the email address.
+ *
+ * @return
+ *   A string contaning the email address with its corresponding user name,
+ *   if one exists.
+ */
+function _basic_webmail_send_mail_form_get_user_from_mail($address) {
+  // Search the user list for anyone with the given email address.
+  $user_name = db_query("SELECT name FROM {users} WHERE mail = :mail", array(':mail' => $address))->fetchField();
+
+  // If something was found...
+  if ($user_name) {
+    // Return the new email address, including the user's name.
+    return '"' . addslashes(mime_header_encode($user_name)) . '" <' . $address . '>';
+  }
+  else {
+    // Otherwise, return the supplied email address.
+    return $address;
+  }
+} // End of _basic_webmail_send_mail_form_get_user_from_mail().
+
+
+/**
+ * Process the attachments of the message.
+ *
+ * @param form_id
+ *   The form ID of the passed form.
+ * @param $form_state
+ *   The form values of the passed form.
+ * /
+ function _basic_webmail_send_mail_form_process_attachments($form_state, $message) {
+ $message['sent_part']['type'] = TYPEMULTIPART;
+ $message['sent_part']['subtype'] = 'mixed';
+ $message['sent_body'][] = $message['sent_part'];
+ $message['sent_part'] = array();
+
+ $uid = md5(uniqid(REQUEST_TIME));
+ $message['send_mail_headers']['Content-Type'] = 'multipart/mixed; boundary="'. $uid .'"';
+
+ $message['sent_part']['type'] = TYPETEXT;
+ $message['sent_part']['subtype'] = 'plain';
+ $message['sent_part']['description'] = 'message';
+
+ $message['send_mail_body'] = "\n--$uid\n";
+ $message['send_mail_body'] .= "Content-Type: text/plain; charset=UTF-8; format=flowed\n\n";
+
+ // Add in the actual message
+ $message['sent_part']['contents.data'] = wordwrap($form_state['values']['basic_webmail_send_mail_body']) ."\n\n\n";
+ $message['send_mail_body'] .= $message['sent_part']['contents.data'];
+ $message['sent_body'][] = $message['sent_part'];
+ $message['sent_part'] = array();
+
+ // Add attachment(s).
+ if ($form_state['values']['basic_webmail_attachments']) {
+ foreach ($form_state['values']['basic_webmail_attachments'] as $key => $attachment) {
+ if ($attachment) {
+ $message = _basic_webmail_send_mail_form_process_an_attachment($form_state, $message, $attachment);
+ }
+ }
+ }
+
+ for ($i; $i <= variable_get('basic_webmail_number_attachments', 3); $i++) {
+ if ($_FILES['files']['error']['basic_webmail_attachment_'. $i] == 0) {
+ $message = _basic_webmail_send_mail_form_process_an_attachment($form_state, $message);
+ }
+ }
+
+ $message['send_mail_body'] .= "--$uid--\n\n";
+
+ return $message;
+ }  //  End of _basic_webmail_send_mail_form_process_attachments().
+
+
+ /**
+ * Process an individual attachment.
+ *
+ * @param form_id
+ *   The form ID of the passed form.
+ * @param $form_state
+ *   The form values of the passed form.
+ * /
+ function basic_webmail_send_mail_form_process_an_attachment($form_state, $message, $attachment) {
+ $sent_part = array();
+ $content_type = mime_content_type($attachment);
+
+ switch (drupal_substr($content_type, 0, strpos($content_type, '/'))) {
+ case 'audio':
+ $message['sent_part']['type'] = TYPEAUDIO;
+ break;
+ case 'image':
+ $message['sent_part']['type'] = TYPEIMAGE;
+ break;
+ case 'text':
+ $message['sent_part']['type'] = TYPETEXT;
+ break;
+ case 'video':
+ $message['sent_part']['type'] = TYPEVIDEO;
+ break;
+ default:
+ $message['sent_part']['type'] = TYPEAPPLICATION;
+ break;
+ }
+
+ $message['sent_part']['encoding'] = ENCBASE64;
+ $message['sent_part']['subtype'] = drupal_substr($content_type, strpos($content_type, '/') + 1);
+ $message['sent_part']['description'] = basename($attachment);
+ $message['sent_part']['disposition.type'] = 'attachment';
+ $message['sent_part']['disposition'] = array('filename' => $message['sent_part']['description']);
+ $message['sent_part']['type.parameters'] = array('name' => $message['sent_part']['description']);
+ $message['sent_part']['contents.data'] = chunk_split(base64_encode(file_get_contents($attachment)));
+
+ $message['sent_body'][] = $sent_part;
+
+ $message['send_mail_body'] .= "--$uid\n";
+ $message['send_mail_body'] .= "Content-Type: ". $content_type ."; name=\"". $sent_part['description'] ."\"\n";
+ $message['send_mail_body'] .= "Content-Transfer-Encoding: base64\n";
+ $message['send_mail_body'] .= "Content-Disposition: attachment; filename=\"". $sent_part['description'] ."\"\n\n";
+ $message['send_mail_body'] .= $sent_part['contents.data'];
+ $message['send_mail_body'] .= "\n\n";
+
+ return $message;
+ } // End of _basic_webmail_send_mail_form_process_an_attachment().
+
+
+
+ /**
+ * Connect to the mail server.
+ *
+ * @param user_id
+ *   The user ID of the mailbox to subscribe to.
+ * @param folder
+ *   The name of the folder to open. If no folder is specified, the default
+ *   of INBOX is used.
+ *
+ * @return
+ *   The mailbox connection, if successful, or FALSE, if not.
+ */
+function _basic_webmail_connect_to_server($user_id, $folder = 'INBOX') {
+  // Retrieve the user object for the user accessing the mail server.
+  $user = user_load($user_id);
+  if (!$user->data['basic_webmail_username'] || !$user->data['basic_webmail_password']) {
+    user_access('administer basic_webmail') ?
+      watchdog('basic_webmail', 'Your @admin_settings_link have not yet been configured. Please do that before checking your email.', array('@admin_settings_link' => l(t('mail settings'), 'user/' . $user->uid . '/edit')), WATCHDOG_ERROR) :
+      watchdog('basic_webmail', 'Your mail settings have not been configured yet. Please do that before checking your email.', array(), WATCHDOG_ERROR);
+    return FALSE;
+  }
+
+  // Get the users email login and password.
+  $username = $user->data['basic_webmail_username'];
+  $password = $user->data['basic_webmail_password'];
+  
+  $mailbox = _basic_webmail_get_server_string() . $folder;
+  //$mailbox = _basic_webmail_get_server_string() . 'INBOX';
+  //
+  // Make the actual connection.
+  if (version_compare(phpversion(), '5.2.0', '>=')) {
+    $imap_resource = imap_open($mailbox, $username, $password, 0, 1);
+    if (empty($imap_resource)) {
+      watchdog('basic_webmail', 'There was an error accessing the remote server: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
+      return FALSE;
+    }
+  }
+  else {
+    $imap_resource = imap_open($mailbox, $username, $password, 0);
+    if ($imap_resource == FALSE) {
+      watchdog('basic_webmail', 'There was an error accessing the remote server: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_ERROR);
+      return FALSE;
+    }
+  }
+
+  return $imap_resource;
+} // End of _basic_webmail_connect_to_server().
+
+
+/**
+ * Create the server connection string.
+ *
+ * @return
+ *   The string representing the server connection information.
+ */
+function _basic_webmail_get_server_string() {
+  // Sanity check -- make sure the admin has done the configuration.
+  if (variable_get('basic_webmail_server_address', '') == '' || variable_get('basic_webmail_server_port', '') == '') {
+    user_access('administer basic_webmail') ?
+      watchdog('basic_webmail', 'The @server_settings for Basic webmail have not yet been configured. Please do that before checking your email.', array('@server_settings' => l(t('server settings'), 'admin/config/basic_webmail')), WATCHDOG_ERROR) :
+      watchdog('basic_webmail', 'The server settings for Basic webmail have not yet been configured. Please do that before checking your email.', array(),WATCHDOG_ERROR);
+    return FALSE;
+  }
+
+  // Prepare the flags for connecting to the server with.
+  $imap_flags = '';
+  if (variable_get('basic_webmail_secure_log_in', 0) == 1) {
+    $imap_flags .= '/secure';
+  }
+  if (variable_get('basic_webmail_use_ssl', 0) == 1) {
+    $imap_flags .= '/ssl';
+  }
+  if (variable_get('basic_webmail_validate_cert', 0) == 1) {
+    $imap_flags .= '/validate-cert';
+  }
+  else {
+    $imap_flags .= '/novalidate-cert';
+  }
+  if (variable_get('basic_webmail_use_tls', 0) == 1) {
+    $imap_flags .= '/tls';
+  }
+  else {
+    $imap_flags .= '/notls';
+  }
+
+  if (variable_get('basic_webmail_server_port', '') == '143') {
+    $server_string = '{' . variable_get('basic_webmail_server_address', '') . $imap_flags . '}';
+  }
+  else {
+    $server_string = '{' . variable_get('basic_webmail_server_address', '') . ':' . variable_get('basic_webmail_server_port', '') . $imap_flags . '}';
+  }
+
+  // Return the configured settings and create a connection string.
+  return $server_string;
+} // End of _basic_webmail_get_server_string().
+
+
+/**
+ * Post a message delete confirmation form.
+ *
+ * @param message_number
+ *   The ID of the message to delete.
+ * @param folder
+ *   The name of the folder the message is in. If no folder is specified, the
+ *   default of 'INBOX' is used.
+ *
+ * @return
+ *   The results of the confirmation question.
+ */
+function _basic_webmail_delete_message_form($form, &$form_state) {
+    
+  if (isset($form_state['build_info']['args'][0])) {
+      $message_number = $form_state['build_info']['args'][0];
+  }
+  
+  if (isset($form_state['build_info']['args'][1])) {
+      $message_number = $form_state['build_info']['args'][1];
+  }
+  else{
+      $folder = 'INBOX';
+  };
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Get the message header.
+  $message_header = imap_headerinfo($imap_resource, $message_number);
+  if (!$message_header) {
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
+  }
+
+  // Retrieve who the message is from.
+  if ($message_header->from[0]->personal) {
+    $from_address = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
+  }
+  else {
+    $from_address = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
+  }
+
+  // Retrieve the message date.
+  if (!$message_header->date) {
+    $message_date = 0;
+  }
+  else {
+    $message_date = $message_header->date;
+  }
+
+  // Retrieve the message subject.
+  if (!$message_header->subject) {
+    $message_subject = '(No subject given.)';
+  }
+  else {
+    $message_subject = _basic_webmail_decode_mime_str($message_header->subject);
+  }
+
+  // Fill in the form fields.
+  $form['message_number'] = array(
+    '#type' => 'hidden',
+    '#value' => $message_number,
+  );
+
+  $form['folder'] = array(
+    '#type' => 'hidden',
+    '#value' => $folder,
+  );
+
+  // Fill in the rest of the confirm_form() variables.
+  $question = t('Delete message?');
+  $path = 'basic_webmail/message/' . $message_number . '/' . $folder;
+  $description = t("Are you sure you want to delete the message from !from_address, sent on !message_date with the subject of '!message_subject'?", array('!from_address' => $from_address, '!message_date' => $message_date, '!message_subject' => $message_subject));
+  $yes = 'Yes';
+  $no = 'No';
+  $name = 'confirm_message_deletion';
+
+  // Call the function with the data.
+  $confirmation_result = confirm_form(
+    $form,         // Additional elements to inject into the form, for example hidden elements.
+    $question,     // The question to ask the user (e.g. "Are you sure you want to delete the block <em>foo</em>?").
+    $path,         // The page to go to if the user denies the action. Can be either a drupal path, or an array with the keys 'path', 'query', 'fragment'.
+    $description, // Additional text to display (defaults to "This action cannot be undone.").
+    $yes,          // A caption for the button which confirms the action (e.g. "Delete", "Replace", ...).
+    $no,           // A caption for the link which denies the action (e.g. "Cancel").
+    $name         // The internal name used to refer to the confirmation item.
+  );
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  return $confirmation_result;
+} // End of _basic_webmail_delete_message_form().
+
+
+/**
+ * Delete a specified message.
+ *
+ * @param form_id
+ *   The ID of the form created in the form generation function.
+ * @param form_values
+ *   The contents of the form fields.
+ */
+function _basic_webmail_delete_message_form_submit($form, &$form_state) {
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['folder']);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  if ($form_state['values']['folder'] != 'INBOX.Trash') {
+    // If the message is located in a folder other than INBOX.Trash, move it to INBOX.Trash.
+    $result = imap_mail_move($imap_resource, $form_state['values']['message_number'], 'INBOX.Trash');
+  }
+  else {
+    // Otherwise, delete the message.
+    $result = imap_delete($imap_resource, $form_state['values']['message_number']);
+  }
+
+  if (!$result) {
+    // Report the error.
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error deleting the message: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    drupal_set_message(t('There was an error deleting the message: @last_error', array('@last_error' => $last_error)), 'error');
+  }
+  else {
+    drupal_set_message(t('The message was deleted.'));
+    if (!imap_expunge($imap_resource)) {
+      // Report the error.
+      watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => $last_error), WATCHDOG_WARNING);
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => $last_error), WATCHDOG_WARNING);
+  }
+
+  $form_state['redirect'] = 'basic_webmail/' . $form_state['values']['folder'];
+} // End of _basic_webmail_delete_message_form_submit().
+
+
+/**
+ * Post a message copy form.
+ *
+ * @param message_number
+ *   The ID of the message to delete.
+ * @param folder
+ *   The name of the folder the message is in. If no folder is specified, the
+ *   default of 'INBOX' is used.
+ *
+ * @return
+ *   The results of the confirmation question.
+ */
+function _basic_webmail_copy_message_form($form, &$form_state) {
+  if (isset($form_state['build_info']['args'][0])) {
+      $message_number = $form_state['build_info']['args'][0];
+  }
+  
+  if (isset($form_state['build_info']['args'][1])) {
+      $message_number = $form_state['build_info']['args'][1];
+  }
+  else{
+      $folder = 'INBOX';
+  };
+
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Get the message header.
+  $message_header = imap_headerinfo($imap_resource, $message_number);
+  if (!$message_header) {
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
+  }
+
+  // Retrieve who the message is from.
+  if ($message_header->from[0]->personal) {
+    $from_address = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
+  }
+  else {
+    $from_address = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
+  }
+
+  // Retrieve the message date.
+  if (!$message_header->date) {
+    $message_date = 0;
+  }
+  else {
+    $message_date = $message_header->date;
+  }
+
+  // Retrieve the message subject.
+  if (!$message_header->subject) {
+    $message_subject = '(No subject given.)';
+  }
+  else {
+    $message_subject = _basic_webmail_decode_mime_str($message_header->subject);
+  }
+
+  // Get the list of folders from the server.
+  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
+  if ($folders) {
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+
+      if ($brief_folder_name != $folder) {
+        $folder_names[$brief_folder_name] = $brief_folder_name;
+      }
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  $form['basic_webmail_to_folder'] = array(
+    '#type' => 'select',
+    '#title' => t('The folder to which you want to copy the message'),
+    '#options' => $folder_names,
+  );
+
+  // Fill in the form fields.
+  $form['basic_webmail_message_number'] = array(
+    '#type' => 'hidden',
+    '#value' => $message_number,
+  );
+
+  $form['basic_webmail_from_folder'] = array(
+    '#type' => 'hidden',
+    '#value' => $folder,
+  );
+
+  // Fill in the rest of the confirm_form() variables.
+  $question = t('Copy message?');
+  $path = 'basic_webmail/message/' . $message_number . '/' . $folder;
+  $description = t("Copy message from !from_address, sent on !message_date with the subject of '!message_subject'?", array('!from_address' => $from_address, '!message_date' => $message_date, '!message_subject' => $message_subject));
+  $yes = 'Copy';
+  $no = 'Cancel';
+  $name = 'confirm_message_copy';
+
+  // Call the function with the data.
+  $confirmation_result = confirm_form($form, $question, $path, $description, $yes, $no, $name);
+
+  return $confirmation_result;
+} // End of _basic_webmail_copy_message_form().
+
+
+/**
+ * Copy a specified message.
+ *
+ * @param form_id
+ *   The ID of the form created in the form generation function.
+ * @param form_values
+ *   The contents of the form fields.
+ */
+function _basic_webmail_copy_message_form_submit($form, &$form_state) {
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['basic_webmail_from_folder']);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Copy the message.
+  if (!imap_mail_copy($imap_resource, $form_state['values']['basic_webmail_message_number'], $form_state['values']['basic_webmail_to_folder'])) {
+    // Report the error.
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
+    drupal_set_message(t('There was an error copying message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+  }
+  else {
+    drupal_set_message(t('The message was copied.'));
+    if (!imap_expunge($imap_resource)) {
+      // Report the error.
+      watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  return 'basic_webmail/' . $form_state['values']['basic_webmail_from_folder'];
+} // End of _basic_webmail_copy_message_form_submit().
+
+
+/**
+ * Post a message move form.
+ *
+ * @param message_number
+ *   The ID of the message to delete.
+ * @param folder
+ *   The name of the folder the message is in. If no folder is specified, the
+ *   default of 'INBOX' is used.
+ *
+ * @return
+ *   The results of the confirmation question.
+ */
+function _basic_webmail_move_message_form($form, &$form_state) {
+  if (isset($form_state['build_info']['args'][0])) {
+      $message_number = $form_state['build_info']['args'][0];
+  }
+  
+  if (isset($form_state['build_info']['args'][1])) {
+      $message_number = $form_state['build_info']['args'][1];
+  }
+  else{
+      $folder = 'INBOX';
+  };
+
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $folder);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Get the message header.
+  $message_header = imap_headerinfo($imap_resource, $message_number);
+  if (!$message_header) {
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error retrieving the message header: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message header: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
+  }
+
+  // Retrieve who the message is from.
+  if ($message_header->from[0]->personal) {
+    $from_address = _basic_webmail_decode_mime_str($message_header->from[0]->personal) . ' <' . $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host . '>';
+  }
+  else {
+    $from_address = $message_header->from[0]->mailbox . '@' . $message_header->from[0]->host;
+  }
+
+  // Retrieve the message date.
+  if (!$message_header->date) {
+    $message_date = 0;
+  }
+  else {
+    $message_date = $message_header->date;
+  }
+
+  // Retrieve the message subject.
+  if (!$message_header->subject) {
+    $message_subject = '(No subject given.)';
+  }
+  else {
+    $message_subject = _basic_webmail_decode_mime_str($message_header->subject);
+  }
+
+  // Get the list of folders from the server.
+  $folders = imap_list($imap_resource, _basic_webmail_get_server_string(), '*');
+  if ($folders) {
+    natsort($folders);
+    foreach ($folders as $folder_name) {
+      $brief_folder_name = imap_utf7_decode(drupal_substr($folder_name, strpos($folder_name, '}') + 1, drupal_strlen($folder_name)));
+
+      if ($brief_folder_name != $folder) {
+        $folder_names[$brief_folder_name] = $brief_folder_name;
+      }
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  $form['basic_webmail_to_folder'] = array(
+    '#type' => 'select',
+    '#title' => t('The folder to which you want to move the message'),
+    '#options' => $folder_names,
+  );
+
+  // Fill in the form fields.
+  $form['basic_webmail_message_number'] = array(
+    '#type' => 'hidden',
+    '#value' => $message_number,
+  );
+
+  $form['basic_webmail_from_folder'] = array(
+    '#type' => 'hidden',
+    '#value' => $folder,
+  );
+
+  // Fill in the rest of the confirm_form() variables.
+  $question = t('Move message?');
+  $path = 'basic_webmail/message/' . $message_number . '/' . $folder;
+  $description = t("Move message from !from_address, sent on !message_date with the subject of '!message_subject'?", array('!from_address' => $from_address, '!message_date' => $message_date, '!message_subject' => $message_subject));
+  $yes = 'Move';
+  $no = 'Cancel';
+  $name = 'confirm_message_move';
+
+  // Call the function with the data.
+  $confirmation_result = confirm_form($form, $question, $path, $description, $yes, $no, $name);
+
+  return $confirmation_result;
+} // End of _basic_webmail_move_message_form().
+
+
+/**
+ * Move a specified message.
+ *
+ * @param form_id
+ *   The ID of the form created in the form generation function.
+ * @param form_values
+ *   The contents of the form fields.
+ */
+function _basic_webmail_move_message_form_submit($form, &$form_state) {
+  // Connect to the server and retrieve a connection to the mailbox.
+  global $user;
+  $imap_resource = _basic_webmail_connect_to_server($user->uid, $form_state['values']['basic_webmail_from_folder']);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  // Move the message.
+  if (!imap_mail_move($imap_resource, $form_state['values']['basic_webmail_message_number'], $form_state['values']['basic_webmail_to_folder'])) {
+    // Report the error.
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error), WATCHDOG_ERROR);
+    drupal_set_message(t('There was an error moving message #@message_number: @last_error', array('@message_number' => $message_number, '@last_error' => $last_error)), 'error');
+  }
+  else {
+    drupal_set_message(t('The message was moved.'));
+    if (!imap_expunge($imap_resource)) {
+      // Report the error.
+      watchdog('basic_webmail', 'There was an error expunging the mailboxes: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+
+  $form_state['redirect'] = 'basic_webmail/' . $form_state['values']['basic_webmail_from_folder'];
+} // End of _basic_webmail_move_message_form_submit().
+
+
+/*
+ Much of the following function was taken from http://us2.php.net/manual/en/function.imap-fetchstructure.php#51497
+ */
+
+/**
+ * Get a list of all the possible parts.
+ *
+ * @param imap_resource
+ *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
+ * @param message_number
+ *   The number of the message to get the information for.
+ *
+ * @return
+ *   An array containing all of the available message parts, or FALSE if
+ *   there is an error.
+ */
+function _basic_webmail_get_parts_list($imap_resource, $message_number) {
+  /*
+    $parts_list = array(
+      [$part_id] => array(
+        '$part_type',
+        '$part_structure'
+      ),
+    );
+  */
+
+  /*
+   * @TODO: This function needs to be rethought through and done better.
+   *        It works for now, so I'm leaving it until later.
+   */
+
+  // Initialize the return value.
+  $parts_list = FALSE;
+
+  // Retrieve the message structure.
+  $message_structure = imap_fetchstructure($imap_resource, $message_number);
+  if (!$message_structure) {
+    $last_error = imap_last_error();
+    watchdog('basic_webmail', 'There was an error retrieving the message structure: @last_error', array('@last_error' => $last_error), WATCHDOG_ERROR);
+    return '<h2 class="title">' . t('Error') . '</h2><br />' . t('There was an error retrieving the message structure: @last_error', array('@last_error' => $last_error)) . '<br /><br />';
+  }
+
+  if ($message_structure->type == 0) {
+    // Simple message -- only 1 part.
+    $parts_list[1] = array($message_structure->subtype);
+  }
+  else {
+    // Pull the parts from the message structure.
+    $parts = $message_structure->parts;
+    // Complex message -- multiple parts.
+    $endwhile = FALSE;
+    // Stack while parsing message.
+    $stack = array();
+    // Incrementer.
+    $i = 0;
+
+    // Do while the marker is false.
+    while (!$endwhile) {
+      // If there is no part for this item...
+      if (empty($parts[$i])) {
+        // If the number of items on the stack are one or more...
+        if (count($stack) > 0) {
+          // Process the subparts.
+          // Decrement the stack count by one.
+          $stack_count = count($stack) - 1;
+          // Overwrite the parts list with what is on the stack.
+          $parts = $stack[$stack_count]['p'];
+          // Set the incrementer.
+          $i = $stack[$stack_count]['i'] + 1;
+          // Remove the last item from the stack.
+          array_pop($stack);
+        }
+        else {
+          // End the process.
+          $endwhile = TRUE;
+        }
+      }
+
+      if (!$endwhile) {
+        // Create message part first (example '1.2.3').
+        $partstring = '';
+
+        // Fill in the parts string.
+        foreach ($stack as $s) {
+          $partstring .= ($s['i'] + 1) . '.';
+        }
+
+        // Finish it.
+        $partstring .= ($i + 1);
+
+        // Determine attachment status.
+        // If ifdisposition == 1, then there's one or more attachments. If
+        // type > 2 (0 = text (plain), 1 = multipart (html), 2 = message (rfc?))
+        // then it's not a message attachment.
+        if (!empty($parts[$i])) {
+          if ($parts[$i]->type > 2 && $parts[$i]->ifdisposition) {
+            // One or more attachments exists.
+            $parts_list[$partstring] = array(drupal_strtoupper($parts[$i]->subtype), $parts[$i]);
+          }
+          else {
+            // No attachments exist.
+            $parts_list[$partstring] = array(drupal_strtoupper($parts[$i]->subtype));
+          }
+        }
+      }
+
+      // If there are subparts.
+      if (!empty($parts[$i]->parts)) {
+        // Add to the stack, filling it with the subparts and the increment
+        // number.
+        $stack[] = array(
+          'p' => $parts,
+          'i' => $i,
+        );
+        // Reset the parts array with the subparts for continued processing.
+        $parts = $parts[$i]->parts;
+        // Reset the incrementer.
+        $i = 0;
+      }
+      else {
+        // Bump the incrementer.
+        $i++;
+      }
+    }
+  }
+
+  return $parts_list;
+} // End of _basic_webmail_get_parts_list().
+
+
+/**
+ * Decode the body part for the specified message number and message part ID.
+ *
+ * @param imap_resource
+ *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
+ * @param message_number
+ *   The number of the message to get the information for.
+ * @param part_id
+ *   The ID of the part to get the information for.
+ *
+ * @return
+ *   The message body, decoded if necessary.
+ */
+function _basic_webmail_decode_body_part($imap_resource, $message_number, $part_id) {
+  $message_body_structure = imap_bodystruct($imap_resource, $message_number, $part_id);
+  switch ($message_body_structure->encoding) {
+    case 3:
+      return imap_base64(_basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id));
+      break;
+
+    case 4:
+        $message_header = strstr(imap_fetchheader($imap_resource, $message_number), 'charset=');
+        $message_header = substr($message_header, $aiw2 = strcspn($message_header, "=")+1, strcspn($message_header, ";\n\r ")-$aiw2);
+        $str_ret = imap_qprint(_basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id));
+        $str_ret = mb_convert_encoding($str_ret, "UTF-8", $message_header);
+      return $str_ret;
+      //return utf8_encode(quoted_printable_decode(_basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id)));
+      //return quoted_printable_decode(_basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id));
+      //return imap_qprint(_basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id));
+      break;
+
+    default:
+      return _basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id);
+      break;
+  }
+} // End of _basic_webmail_decode_body_part().
+
+
+/**
+ * Process the attachment for the specified message number and message part ID.
+ *
+ * @param imap_resource
+ *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
+ * @param message_number
+ *   The number of the message to get the information for.
+ * @param part_id
+ *   The ID of the part to get the information for.
+ * @param part_structure
+ *   An object with the structure definitaion of the part of the message that
+ *   represents the attachment.
+ *
+ * @return
+ *   An array containing all of the available message parts, or FALSE if
+ *   there is an error.
+ */
+function _basic_webmail_process_attachment($imap_resource, $message_number, $part_id, $part_structure) {
+  $attachment = '';
+  $file_name = $part_structure->dparameters[0]->value;
+  $file_data = _basic_webmail_mail_fetchpart($imap_resource, $message_number, $part_id);
+
+  if ($part_structure->encoding == 3) {
+    // Decode if base64.
+    $file_data = base64_decode($file_data);
+  }
+  elseif ($part_structure->encoding == 4) {
+    $file_data = quoted_printable_decode($file_data);
+  }
+
+  // Create the destination path variable, along with creating any necessary
+  // directories.
+  $file_dest = variable_get('basic_webmail_attachment_location', file_directory_path() . '/attachments');
+  $file_dest .= '/';
+
+  global $user;
+  $file_dest .= $user->name;
+  file_prepare_directory($file_dest, FILE_CREATE_DIRECTORY);
+  $file_dest .= '/';
+
+  $message_overview = imap_fetch_overview($imap_resource, arg(2));
+  $file_dest .= drupal_substr($message_overview[0]->message_id, 1, drupal_strlen($message_overview[0]->message_id) - 2);
+  file_prepare_directory($file_dest, FILE_CREATE_DIRECTORY);
+
+  if (isset($_SESSION['messages']) && isset($_SESSION['messages']['status'])) {
+    foreach ($_SESSION['messages']['status'] as $key => $drupal_message) {
+      if (drupal_substr($drupal_message, 0, 13) == 'The directory' && drupal_substr($drupal_message, drupal_strlen($drupal_message) - 17, 17) == 'has been created.') {
+        unset($_SESSION['messages']['status'][$key]);
+      }
+    }
+  }
+
+  $file_path = file_save_data($file_data, $file_dest . '/' . $file_name, FILE_EXISTS_REPLACE);
+  $file_url = file_create_url($file_path);
+  $attachment = array($file_path, $file_name, $file_url);
+
+  return $attachment;
+} // End of _basic_webmail_process_attachment().
+
+
+/** *******************************************************
+ *
+ *  The next four functions are from
+ *  http://us3.php.net/manual/en/function.imap-fetchbody.php#31685
+ *  with modifications for Drupal Coding Standards:
+ *  http://drupal.org/coding-standards
+ *  and what is already here in this module.
+ *
+ *  ******************************************************/
+
+
+// Get the body of a part of a message according to the string in $part.
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function _basic_webmail_mail_fetchpart($imap_resource, $message_number, $part) {
+  $parts = _basic_webmail_mail_fetchparts($imap_resource, $message_number);
+  $part_numbers = explode(".", $part);
+  $current_part = $parts;
+
+  while (list($key, $val) = each($part_numbers)) {
+    $current_part = $current_part[$val];
+  }
+
+  if ($current_part != "") {
+    return $current_part;
+  }
+  else {
+    return FALSE;
+  }
+} // End of _basic_webmail_mail_fetchpart().
+
+
+// Get an array with the bodies of all parts of an email.
+// The structure of the array corresponds to the structure that is available
+// with imap_fetchstructure.
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function _basic_webmail_mail_fetchparts($imap_resource, $message_number) {
+  $parts = array();
+  $header = imap_fetchheader($imap_resource, $message_number);
+  $body = imap_body($imap_resource, $message_number, FT_INTERNAL);
+  $i = 1;
+
+  $new_parts = _basic_webmail_mail_mimesplit($header, $body);
+  if ($new_parts) {
+    while (list($key, $val) = each($new_parts)) {
+      $parts[$i] = _basic_webmail_mail_mimesub($val);
+      $i++;
+    }
+  }
+  else {
+    $parts[$i] = $body;
+  }
+
+  return $parts;
+} // End of _basic_webmail_mail_fetchparts().
+
+
+/**
+ * Splits a mulitpart mime message body into its respective parts.
+ *
+ * If the message body is a mulitpart mime message, this function slits the
+ * body out into the various parts.
+ *
+ * @param header
+ *   A string containing the header of the message.
+ * @param body
+ *   A string containing the body of the message.
+ *
+ * @return
+ *   An array containing the message body's parts, or FALSE, if no parts are
+ *   found.
+ */
+function _basic_webmail_mail_mimesplit($header, $body) {
+  // Initialize the message parts variable.
+  $parts = array();
+  // Matches 'Content-Type:', followed by any character zero or more times,
+  // followed by 'boundary="', followed by any character other than '"' one or
+  // more times, followed by '"'.
+  $pattern = '~.*boundary="[^"]+"~';
+  // Search the message header for the message part boundary definition, which
+  // is what $pattern describes, and save the results in $regs.
+  if (preg_match($pattern, $header, $regs)) {
+    // I can't seem to figure out how to get the previous match to work 100%
+    // with PCRE as it was originally intended to work in POSIX, so I've
+    // created this interim step, which ends up producing the desired results.
+    $interim_pattern = '~"[^"]+"~';
+    preg_match($interim_pattern, $regs[0], $interim_results);
+    // Save the actual boundary from the results.
+    $boundary = drupal_substr($interim_results[0], 1, drupal_strlen($interim_results[0]) - 2);
+
+    // Matches zero or more characters that are not '\r\n' before and after
+    // what is in '$boundary'.
+    $delimiter_reg = '~[^\r\n]*' . $boundary . '[^\r\n]*~';
+
+    // Search $body for any instance of the boundary, which is what
+    // $delimiter_reg describes, and save the results in $results.
+    if (preg_match($delimiter_reg, $body, $results)) {
+      // Break out the results into the relevant pieces.
+      $delimiter = $results[0];
+      $parts = explode($delimiter, $body);
+      $parts = array_slice($parts, 1, -1);
+    }
+
+    // Deliver the payload.
+    return $parts;
+  }
+  // No parts were found, so return FALSE.
+  else {
+    return FALSE;
+  }
+} // End of _basic_webmail_mail_mimesplit().
+
+
+// Returns an array with all parts that are subparts of the given part.
+// If no subparts are found, returns the body of the current part.
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function _basic_webmail_mail_mimesub($part) {
+  $i = 1;
+  $head_delimiter = "\r\n\r\n";
+  $del_length = drupal_strlen($head_delimiter);
+
+  // get head & body of the current part
+  $end_of_head = strpos($part, $head_delimiter);
+  $head = drupal_substr($part, 0, $end_of_head);
+  $body = drupal_substr($part, $end_of_head + $del_length, drupal_strlen($part));
+
+  // check whether it is a message according to rfc822
+  if (stristr($head, "Content-Type: message/rfc822")) {
+    $part = drupal_substr($part, $end_of_head + $del_length, drupal_strlen($part));
+    $return_parts[1] = _basic_webmail_mail_mimesub($part);
+    return $return_parts;
+  }
+  // if no message, get subparts and call function recursively
+  elseif ($sub_parts = _basic_webmail_mail_mimesplit($head, $body)) {
+    // got more subparts
+    while (list($key, $val) = each($sub_parts)) {
+      $return_parts[$i] = _basic_webmail_mail_mimesub($val);
+      $i++;
+    }
+
+    return $return_parts;
+  }
+  else {
+    return $body;
+  }
+} // End of _basic_webmail_mail_mimesub().
+/*
+ End of four imap_fetchbody functions.
+ */
+
+
+/**
+ * Checks for the existence of a specified mailbox.
+ *
+ * @param imap_resource
+ *   The IMAP stream, created by calling _basic_webmail_connect_to_server.
+ * @param mailbox
+ *   The name of the mailbox to check for.
+ *
+ * @return
+ *   Returns TRUE if the mailbox exists, and FALSE if it does not exist.
+ */
+function _basic_webmail_mailbox_exists($imap_resource, $mailbox) {
+  $mailbox_exists = FALSE;
+
+  $mailboxes = imap_getmailboxes($imap_resource, _basic_webmail_get_server_string(), '*');
+  foreach ($mailboxes as $mailbox_object) {
+    if (drupal_substr($mailbox_object->name, strpos($mailbox_object->name, '}') + 1, drupal_strlen($mailbox_object->name)) == $mailbox) {
+      $mailbox_exists = TRUE;
+    }
+  }
+
+  return $mailbox_exists;
+} // End of _basic_webmail_mailbox_exists().
+
+
+/**
+ * Checks if the standard mailboxes exist and creates them, if necessary.
+ *
+ * This function checks to see if the standard mailboxes exit or not. If they
+ * do not exist, this function will also create them. This fucntion will then
+ * subscribe to the mailboxes.
+ *
+ * @param user_id
+ *   The user ID of the mailbox to subscribe to.
+ */
+function _basic_webmail_subscribe_to_mailboxes($user_id) {
+  // Connect to the server and retrieve a connection to the mailbox.
+  $imap_resource = _basic_webmail_connect_to_server($user_id);
+  if (!$imap_resource) {
+    drupal_set_title(t('Error'));
+    return '<br />' . t('There was an error connecting to the mail server. Contact the system administrator and/or check the logs for more information.') . '<br /><br />';
+  }
+
+  $mailboxes = array('INBOX', 'INBOX.Drafts', 'INBOX.Junk', 'INBOX.Sent', 'INBOX.Trash');
+  foreach ($mailboxes as $mailbox) {
+    if (!imap_status($imap_resource, _basic_webmail_get_server_string() . $mailbox, SA_ALL)) {
+      if (!imap_createmailbox($imap_resource, _basic_webmail_get_server_string() . $mailbox)) {
+        watchdog('basic_webmail', 'There was an error subscribing to the INBOX mailbox: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+      }
+    }
+
+    if (!imap_subscribe($imap_resource, _basic_webmail_get_server_string() . $mailbox)) {
+      watchdog('basic_webmail', 'There was an error subscribing to the !mailbox mailbox: @last_error', array('!mailbox' => $mailbox, '@last_error' => imap_last_error()), WATCHDOG_WARNING);
+    }
+  }
+
+  // Clean up.
+  if (!imap_close($imap_resource)) {
+    watchdog('basic_webmail', 'There was an error closing the IMAP stream: @last_error', array('@last_error' => imap_last_error()), WATCHDOG_WARNING);
+  }
+} // End of _basic_webmail_subscribe_to_mailboxes().
+
+
+/**
+ * Converts UTF8 encoded strings.
+ *
+ * This function is necessary, because there is a bug in some versions of PHP
+ * that returns strings converted with the imap_utf8() function in all upper
+ * case letters.  http://bugs.php.net/bug.php?id=44098
+ *
+ * This function was taken from here and modified:
+ * http://us2.php.net/manual/en/function.imap-utf8.php#92026
+ */
+function _basic_webmail_decode_mime_str($string, $char_set = 'UTF-8') {
+  $new_string = '';
+  $elements = imap_mime_header_decode($string);
+
+  for ($i = 0; $i < count($elements); $i++) {
+    if ($elements[$i]->charset == 'default') {
+      $elements[$i]->charset = 'iso-8859-1';
+    }
+
+    $new_string .= iconv($elements[$i]->charset, $char_set, $elements[$i]->text);
+  }
+
+  return $new_string;
+} // End of _basic_webmail_decode_mime_str().
+
+
+/** *******************************************************
+ *
+ *  Administrative functions.
+ *
+ *  ******************************************************/
+
+
+/**
+ * Automatically fills in email addresses of the current users.
+ *
+ * Copied and modified from taxonomy_autocomplete() in
+ * modules/taxonomy/taxonomy.pages.inc
+ */
+function basic_webmail_autocomplete($field_name, $addresses = '') {
+  // Get the field definition.
+  $field = field_info_field($field_name);
+
+  // The user enters a comma-separated list of email addresses. We only
+  // autocomplete the last address.
+  $address_array = drupal_explode_tags($addresses);
+
+  // Get the last address.
+  $last_address = trim(drupal_strtolower(array_pop($address_array)));
+
+  $matches = array();
+
+  if ($last_address != '') {
+    // Search the users table for all email addresses which are similar to
+    // the last item in the list.
+//    $query = "SELECT mail FROM {users} WHERE LOWER(mail) LIKE LOWER('%%%s%%') AND status = 1";
+    $query = db_select('users', 'u')
+      ->fields('u', array(mail))
+      ->condition('u.status', 1)
+      ->condition('u.mail', '%' . db_like($last_address) . '%', 'LIKE')
+      ->range(0, 10);
+
+    // Do not select any addresses that are already entered.
+    if (!empty($address_array)) {
+      $query->condition('t.mail', $address_array, 'NOT IN');
+    }
+
+    // Execute the query and get the results.
+    $results = $query
+      ->execute()
+      ->fetchAllKeyed();
+
+    // Convert what's left of the array to a string.
+    $prefix = count($address_array) ? drupal_implode_tags($address_array) . ', ' : '';
+
+    // Iterate through the list of similar email addresses.
+    foreach ($results as $mail) {
+      $n = $mail;
+      // Add the email address to the list of possible matches.
+      $matches[$prefix . $n] = $mail;
+    }
+  }
+
+  // Send the results back.
+  drupal_json_output($matches);
+} // End of basic_webmail_autocomplete().
