diff --git a/uc_sagepay_token/uc_sagepay_token.admin.inc b/uc_sagepay_token/uc_sagepay_token.admin.inc
index e69de29..965e32d 100755
--- a/uc_sagepay_token/uc_sagepay_token.admin.inc
+++ b/uc_sagepay_token/uc_sagepay_token.admin.inc
@@ -0,0 +1,192 @@
+<?php
+
+/**
+ * Display the stored credit card terminal page.
+ *
+ * @see uc_credit_terminal()
+ */
+function uc_sagepay_token_terminal($order) {
+  $output = l(t('Return to order view screen.'), 'admin/store/orders/' . $order->order_id);
+
+  $output .= '<p>' . t('Use this terminal to process payments against stored credit cards.') . '</p>';
+
+  $context = array(
+    'revision' => 'formatted-original',
+    'type' => 'order_total',
+    'subject' => array(
+      'order' => $order,
+    ),
+  );
+  $output .= '<div><strong>' . t('Order total: @total', array('@total' => uc_price($order->order_total, $context))) . '</strong></div>'
+            . '<div><strong>' . t('Balance: @balance', array('@balance' => uc_price(uc_payment_balance($order), $context))) . '</strong></div>';
+
+  $output .= drupal_get_form('uc_sagepay_token_terminal_form', $order);
+
+  return $output;
+}
+
+/**
+ * Display the stored credit card terminal form.
+ *
+ * @see uc_credit_terminal_form()
+ */
+function uc_sagepay_token_terminal_form($form, $form_state, $order) {
+  // Use the credit card terminal form as a base.
+  module_load_include('inc', 'uc_credit', 'uc_credit.admin');
+  $form = uc_credit_terminal_form($form_state, $order);
+
+  // Replace the credit card selection field with the list of tokens.
+  $form['specify_card']['cc_data'] = uc_payment_method_sagepay_token_form(array(), $order);
+  $form['specify_card']['cc_data']['#tree'] = TRUE;
+  unset($form['specify_card']['cc_data']['cc_policy']);
+  unset($form['specify_card']['cc_data']['cc_cvv']['#description']);
+
+  return $form;
+}
+
+/**
+ * Validate the stored credit card terminal form.
+ */
+function uc_sagepay_token_terminal_form_validate($form, &$form_state) {
+  if (!is_numeric($form_state['values']['amount']) || $form_state['values']['amount'] <= 0) {
+    form_set_error('amount', t('You must enter a positive number for the amount.'));
+  }
+}
+
+/**
+ * Submit handler for the stored credit card terminal form.
+ *
+ * @see uc_credit_terminal_form_submit()
+ */
+function uc_sagepay_token_terminal_form_submit($form, &$form_state) {
+  // Load the order.
+  $order = uc_order_load($form_state['values']['order_id']);
+
+  // Get the data from the form and replace masked data from the order.
+  $cc_data = $form_state['values']['cc_data'];
+
+  if ($cc_data['cc_cvv'] == str_repeat('-', strlen($cc_data['cc_cvv']))) {
+    $cc_data['cc_cvv'] = $order->payment_details['cc_cvv'];
+  }
+
+  // Cache the values for use during processing.
+  uc_credit_cache('save', $cc_data, FALSE);
+
+  // Build the data array passed on to the payment gateway.
+  $data = array();
+
+  switch ($form_state['values']['op']) {
+    case t('Charge amount'):
+      $data['txn_type'] = UC_CREDIT_AUTH_CAPTURE;
+      break;
+
+    case t('Authorize amount only'):
+      $data['txn_type'] = UC_CREDIT_AUTH_ONLY;
+      break;
+
+    case t('Capture amount to this authorization'):
+      $data['txn_type'] = UC_CREDIT_PRIOR_AUTH_CAPTURE;
+      $data['auth_id'] = $form_state['values']['select_auth'];
+      break;
+
+    case t('Credit amount to this reference'):
+      $data['txn_type'] = UC_CREDIT_REFERENCE_CREDIT;
+      $data['ref_id'] = $form_state['values']['select_ref'];
+  }
+
+  $result = uc_payment_process('credit', $form_state['values']['order_id'], $form_state['values']['amount'], $data, TRUE, NULL, FALSE);
+
+  if ($result) {
+    $crypt = new uc_encryption_class;
+
+    // Load up the existing data array.
+    $data = db_query("SELECT data FROM {uc_orders} WHERE order_id = :order_id", array(':order_id' => $form_state['values']['order_id']))->fetchField();
+    $data = unserialize($data);
+
+    $cache = uc_credit_cache('load');
+
+    $cc_data = array('cc_token' => $cache['cc_token']);
+
+    // Stuff the serialized and encrypted CC details into the array.
+    $data['cc_data'] = $crypt->encrypt(uc_credit_encryption_key(), serialize($cc_data));
+    uc_store_encryption_errors($crypt, 'uc_credit');
+
+    // Save it again.
+    // TODO Please review the conversion of this statement to the D7 database API syntax.
+    /* db_query("UPDATE {uc_orders} SET data = '%s' WHERE order_id = %d", serialize($data), $form_state['values']['order_id']) */
+    db_update('uc_orders')
+      ->fields(array(
+        'data' => serialize($data),
+      ))
+    ->condition('order_id', $form_state['values']['order_id'])
+    ->execute();
+
+    drupal_set_message(t('The credit card was processed successfully. See the admin comments for more details.'));
+  }
+  else {
+    if (variable_get('uc_credit_debug', FALSE)) {
+      _save_cc_data_to_order(uc_credit_cache('load'), $form_state['values']['order_id']);
+    }
+
+    drupal_set_message(t('There was an error processing the credit card.  See the admin comments for details.'), 'error');
+  }
+
+  $form_state['redirect'] = 'admin/store/orders/' . $form_state['values']['order_id'];
+}
+
+/**
+ * Theme function to display a list of saved cards.
+ */
+function theme_uc_sagepay_token_list_cards($variables) {
+  $tokens = $variables['tokens'];
+  if (!empty($tokens)) {
+    $header = array(
+      array('data' => t('Card')),
+      array('data' => t('Actions')),
+    );
+    $rows = array();
+
+    foreach ($tokens as $token) {
+      $rows[] = array(
+        array('data' => theme('uc_sagepay_token_description', array('token' => $token))),
+        array('data' => l(t('delete'), 'user/' . $token['uid'] . '/delete_card/' . $token['token_id'])),
+      );
+    }
+
+    return theme('table', array('header' => $header, 'rows' => $rows));
+  }
+  else {
+    return t('No cards have been saved to your account.');
+  }
+}
+
+/**
+ * Confirmation form to delete a saved card.
+ */
+function uc_sagepay_token_delete_confirm_form($form, $form_state, $account, $token) {
+  $form['uid'] = array(
+    '#type' => 'value',
+    '#value' => $account->uid,
+  );
+
+  $form['token_id'] = array(
+    '#type' => 'value',
+    '#value' => $token['token_id'],
+  );
+
+  return confirm_form($form, t('Are you sure you want to delete the saved @card?', array('@card' => theme('uc_sagepay_token_description', array('token' => $token)))), 'user/' . $account->uid, NULL, t('Delete'));
+}
+
+/**
+ * @see uc_sagepay_token_delete_confirm_form()
+ */
+function uc_sagepay_token_delete_confirm_form_submit($form, &$form_state) {
+  if (uc_sagepay_token_delete($form_state['values']['token_id'], TRUE)) {
+    drupal_set_message(t('The card details have been deleted.'));
+  }
+  else {
+    drupal_set_message(t('It was not possible to delete your card details. Please try again later.'));
+  }
+
+  $form_state['redirect'] = 'user/' . $form_state['values']['uid'];
+}
diff --git a/uc_sagepay_token/uc_sagepay_token.info b/uc_sagepay_token/uc_sagepay_token.info
index e69de29..dbebc07 100755
--- a/uc_sagepay_token/uc_sagepay_token.info
+++ b/uc_sagepay_token/uc_sagepay_token.info
@@ -0,0 +1,5 @@
+name = Sage Pay Direct token system
+description = Allows customers to store credit card details at Sage Pay for future purchases. Supports recurring payments if uc_recurring is also installed.
+dependencies[] = uc_sagepay
+package = Ubercart - payment
+core = 7.x
diff --git a/uc_sagepay_token/uc_sagepay_token.install b/uc_sagepay_token/uc_sagepay_token.install
index e69de29..f991fbc 100755
--- a/uc_sagepay_token/uc_sagepay_token.install
+++ b/uc_sagepay_token/uc_sagepay_token.install
@@ -0,0 +1,90 @@
+<?php
+/**
+ * @file
+ * Install, update and uninstall functions for the uc_sagepay_token module.
+ *
+ */
+
+
+/**
+ * Implements hook_install().
+ */
+function uc_sagepay_token_install() {
+  // TODO The drupal_(un)install_schema functions are called automatically in D7.
+  // drupal_install_schema('uc_sagepay_token')
+}
+
+/**
+ * Implements hook_uninstall().
+ */
+function uc_sagepay_token_uninstall() {
+  // TODO The drupal_(un)install_schema functions are called automatically in D7.
+  // drupal_uninstall_schema('uc_sagepay_token')
+}
+
+/**
+ * Implements hook_schema().
+ */
+function uc_sagepay_token_schema() {
+  $schema = array();
+
+  $schema['uc_sagepay_tokens'] = array(
+    'description' => 'Stores SagePay tokens for customers to use instead of credit card details in future orders.',
+    'fields' => array(
+      'token_id' => array(
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'uid' => array(
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'server' => array(
+        'type' => 'int',
+        'size' => 'tiny',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+      'token' => array(
+        'type' => 'varchar',
+        'length' => 38,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'card_type' => array(
+        'type' => 'varchar',
+        'length' => 20,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'last_4' => array(
+        'type' => 'varchar',
+        'length' => 4,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'expiry' => array(
+        'type' => 'varchar',
+        'length' => 4,
+        'not null' => TRUE,
+        'default' => '',
+      ),
+      'order_id' => array(
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+        'default' => 0,
+      ),
+    ),
+    'indexes' => array(
+      'uid' => array('uid'),
+    ),
+    'primary key' => array('token_id'),
+  );
+
+  return $schema;
+}
diff --git a/uc_sagepay_token/uc_sagepay_token.module b/uc_sagepay_token/uc_sagepay_token.module
index e69de29..d1c7ae1 100755
--- a/uc_sagepay_token/uc_sagepay_token.module
+++ b/uc_sagepay_token/uc_sagepay_token.module
@@ -0,0 +1,713 @@
+<?php
+
+/**
+ * Implements hook_init().
+ */
+function uc_sagepay_token_init() {
+  if (module_exists('uc_recurring')) {
+    require_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'uc_sagepay_token') . '/' . 'uc_sagepay_token.recurring.inc';
+  }
+}
+
+/**
+ * Implements hook_menu().
+ */
+function uc_sagepay_token_menu() {
+  $items = array();
+
+  $items['admin/store/orders/%uc_order/sagepay_token'] = array(
+    'title callback' => 'uc_sagepay_token_terminal_title',
+    'title arguments' => array(3),
+    'description' => 'Displays a form to process a credit card payment.',
+    'page callback' => 'uc_sagepay_token_terminal',
+    'page arguments' => array(3),
+    'access arguments' => array('process credit cards'),
+    'type' => MENU_CALLBACK,
+    'file' => 'uc_sagepay_token.admin.inc',
+  );
+
+  $items['user/%user/delete_card/%uc_sagepay_token'] = array(
+    'title' => 'Delete saved card',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('uc_sagepay_token_delete_confirm_form', 1, 3),
+    'access callback' => 'uc_sagepay_token_can_view_cards',
+    'access arguments' => array(1, 3),
+    'type' => MENU_CALLBACK,
+    'weight' => 1,
+    'file' => 'uc_sagepay_token.admin.inc',
+  );
+
+  return $items;
+}
+
+/**
+ * Title callback for admin/store/orders/%uc_order/sagepay_token.
+ */
+function uc_sagepay_token_terminal_title($order) {
+  // error_log ( __FUNCTION__ );
+  return t('Credit card terminal: Order @order_id', array('@order_id' => $order->order_id));
+}
+
+/**
+ * Implements hook_permission().
+ */
+function uc_sagepay_token_permission() {
+  // error_log ( __FUNCTION__ );
+  return array(
+    'use stored credit cards' => array(
+      'title' => t('use stored credit cards'),
+      'description' => t('TODO Add a description for \'use stored credit cards\''),
+    ),
+  );
+}
+
+/**
+ * Access callback for viewing saved card(s).
+ */
+function uc_sagepay_token_can_view_cards($account, $token = NULL) {
+  global $user;
+  // error_log ( __FUNCTION__ );
+  // Administrators can see all cards.
+  if (user_access('administer credit cards')) {
+    return TRUE;
+  }
+
+  // Otherwise, the user must be logged in, have permission, be viewing their own account,
+  // and if a saved card is supplied, it must belong to them.
+  return $user->uid && user_access('use stored credit cards') && $user->uid == $account->uid && (!isset($token) || $token['uid'] == $account->uid);
+}
+
+/**
+ * Implements hook_user_view().
+ */
+function uc_sagepay_token_user_view($account, $view_mode) {
+  global $user;
+  if ($user->uid && (($user->uid == $account->uid && user_access('use stored credit cards')) || user_access('administer credit cards'))) {
+    $account->content['sagepay_token'] = array(
+      '#type' => 'user_profile_category',
+      '#title' => t('Saved credit/debit cards'),
+      'cards' => array(
+        '#type' => 'user_profile_item',
+        '#value' => theme('uc_sagepay_token_list_cards', array('tokens' => uc_sagepay_token_load_tokens($account->uid))),
+      ),
+    );
+  }
+}
+
+/**
+ * Implements hook_payment_method().
+ */
+function uc_sagepay_token_payment_method() {
+  // error_log ( __FUNCTION__ );
+  if (arg(0) == 'cart') {
+    // This method can only be used at checkout if the user has permission and at least one stored card.
+    $tokens = uc_sagepay_token_load_tokens();
+    if (!user_access('use stored credit cards') || empty($tokens)) {
+      return;
+    }
+  }
+
+  return array(array(
+      'id' => 'sagepay_token',
+      'name' => t('Sage Pay stored credit card'),
+      'title' => t('Use my saved card details'),
+      'review' => t('Stored credit card'),
+      'callback' => 'uc_payment_method_sagepay_token',
+      'weight' => 1,
+      'checkout' => TRUE,
+      'no_gateway' => TRUE,
+    ));
+}
+
+/**
+ * Implements hook_theme().
+ */
+function uc_sagepay_token_theme() {
+  // error_log ( __FUNCTION__ );
+  return array(
+    'uc_sagepay_token_description' => array(
+      'variables' => array('token' => NULL),
+    ),
+    'uc_sagepay_token_list_cards' => array(
+      'variables' => array('tokens' => NULL),
+      'file' => 'uc_sagepay_token.admin.inc',
+    ),
+  );
+}
+
+/**
+ * Implements hook_theme_registry_alter().
+ *
+ * Override theme_uc_payment_method_credit_form to add our checkbox.
+ */
+function uc_sagepay_token_theme_registry_alter(&$theme_registry) {
+  global $theme;
+
+  // error_log ( __FUNCTION__ );
+  // Back up the existing theme function.
+  if ( isset ( $theme_registry['uc_payment_method_credit_form']['function'] ) ) {
+    $themes = variable_get('uc_sagepay_token_theme', array());
+    $themes[$theme] = array(
+      'uc_payment_method_credit_form' => $theme_registry['uc_payment_method_credit_form']['function'],
+    );
+    variable_set('uc_sagepay_token_theme', $themes);
+  }
+
+  // Replace with our own.
+  $theme_registry['uc_payment_method_credit_form']['function'] = 'uc_sagepay_token_theme_uc_payment_method_credit_form';
+}
+
+/**
+ * Implements hook_form_alter().
+ *
+ * Add a new checkbox to the credit card payment form.
+ */
+function uc_sagepay_token_form_uc_payment_method_credit_form_alter(&$form, $form_state) {
+  // error_log ( __FUNCTION__ );
+  if (module_exists('uc_recurring_product')) {
+    $order = new stdClass();
+    $order->products = uc_cart_get_contents();
+    if (uc_recurring_product_get_recurring_products_in_order($order)) {
+      // Orders with recurring products must create a token, so don't provide the option.
+      return;
+    }
+  }
+
+  if (user_access('use stored credit cards')) {
+    $form['create_sagepay_token'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Securely store these details for my next order.'),
+      '#default_value' => isset($_SESSION['create_sagepay_token']) ? $_SESSION['create_sagepay_token'] : FALSE,
+    );
+  }
+}
+
+/**
+ * Override theme_uc_payment_method_credit_form.
+ */
+function uc_sagepay_token_theme_uc_payment_method_credit_form($form) {
+  global $theme;
+  // error_log ( __FUNCTION__ );
+  // Call the original function to render the form.
+  $registry = variable_get('uc_sagepay_token_theme', array());
+  $function = isset($registry[$theme]) ? $registry[$theme]['uc_payment_method_credit_form'] : 'theme_uc_payment_method_credit_form';
+  $output = $function($form);
+
+  // If we're at checkout, render the additional checkbox.
+  if (arg(1) == 'checkout' && isset($form['create_sagepay_token'])) {
+    $output .= drupal_render($form['create_sagepay_token']);
+  }
+
+  return $output;
+}
+
+/**
+ * Implements hook_form_alter().
+ */
+function uc_sagepay_token_form_uc_cart_checkout_form_alter(&$form, $form_state) {
+  // error_log ( __FUNCTION__ );
+  if (user_access('use stored credit cards')) {
+    // Modify the standard "credit card" payment method title so it makes more sense.
+    if (isset($form['panes']['payment']['payment_method']['#options']['sagepay_token'])
+         && isset($form['panes']['payment']['payment_method']['#options']['credit'])) {
+      $form['panes']['payment']['payment_method']['#options']['credit'] = t('Enter details for a different card');
+    }
+  }
+
+  $form['#submit'][] = 'uc_sagepay_token_checkout_form_submit';
+}
+
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function uc_sagepay_token_checkout_form_submit($form, &$form_state) {
+  // error_log ( __FUNCTION__ );
+  $_SESSION['create_sagepay_token'] = isset($_POST['create_sagepay_token']) && $_POST['create_sagepay_token'];
+
+  // Orders with recurring products must create a token.
+  if (module_exists('uc_recurring_product')) {
+    $order = new stdClass();
+    $order->products = uc_cart_get_contents();
+    if (uc_recurring_product_get_recurring_products_in_order($order)) {
+      $_SESSION['create_sagepay_token'] = TRUE;
+    }
+  }
+}
+
+/**
+ * Implements hook_uc_sagepay_transaction_alter().
+ *
+ * If the user selected to create a token, register their card with SagePay and use it for the transaction.
+ * If this order is being processed with a stored card, load the token and the customer-supplied CVV.
+ */
+function uc_sagepay_token_uc_sagepay_transaction_alter(&$transaction, $order) {
+  // error_log ( __FUNCTION__ );
+  // error_log ( print_r ( $order,1 ) );
+  // error_log ( print_r ( $transaction, 1 ) );
+
+  global $user;
+
+  // Transaction fields that need to be removed when using tokens.
+  $fields = array('CardHolder', 'CardNumber', 'StartDate', 'ExpiryDate', 'IssueNumber', 'CV2', 'CardType');
+
+  if ($order->payment_method == 'credit' && isset($_SESSION['create_sagepay_token']) && $_SESSION['create_sagepay_token']) {
+    if (variable_get('uc_sagepay_server', 2) == 0) {
+      drupal_set_message(t('The SagePay token system is not implemented in the simulator, use the test server instead.'), 'error');
+      return;
+    }
+
+    $registration = array(
+      'VPSProtocol' => '2.23',
+      'Vendor' => variable_get('uc_sagepay_vendor', ''),
+      'TxType' => 'TOKEN',
+      'Currency' => $transaction['Currency'],
+    );
+
+    // Copy data from the transaction for the token registration.
+    foreach ($fields as $field) {
+      if (isset($transaction[$field])) {
+        $registration[$field] = $transaction[$field];
+      }
+    }
+
+    // Send token registration to SagePay.
+    uc_order_comment_save($order->order_id, $user->uid, t('Token registration sent.'));
+    $result = uc_sagepay_transaction('TOKEN', $registration, $order);
+
+    // error_log ( __FUNCTION__." ".print_r($result,1));
+    if ($result['success']) {
+      // Save the token for later, as the user may not have an account to attach it to just yet.
+      $_SESSION['sagepay_token'] = array(
+        'token' => $result['data']['Token'],
+        'card_type' => $order->payment_details['cc_type'],
+        'last_4' => substr($registration['CardNumber'], -4),
+        'expiry' => $registration['ExpiryDate'],
+      );
+
+      // Modify the actual transaction to use the token.
+      $transaction['Token'] = $result['data']['Token'];
+      $transaction['StoreToken'] = 1;
+      foreach ($fields as $field) {
+        unset($transaction[$field]);
+      }
+    }
+  }
+  elseif ($order->payment_method == 'sagepay_token') {
+    // error_log ( __FUNCTION__ . " - Processing sagepay_token payment");
+    // Load the stored tokens for this user
+    $tokens = uc_sagepay_token_load_tokens($order->uid);
+    
+    // error_log ( "Tokens: ".print_r($tokens,1));
+
+    $key = uc_credit_encryption_key();
+    $crypt = new UbercartEncryption();
+    if (isset($order->data['cc_data'])) {
+      $cc_data = $crypt->decrypt($key, $order->data['cc_data']);
+      if (strpos($cc_data, ':') === FALSE) {
+        $cc_data = base64_decode($cc_data);
+      }
+      $cc_data = unserialize($cc_data);
+      // error_log ( "CCD: ".print_r($cc_data,1));
+    }
+
+    if (!isset($tokens[$cc_data['cc_token']])) {
+      $transaction['Error'] = t('The stored credit card details are no longer available.');
+    }
+    else {
+      // Set the transaction type based on how the Sage Pay module is configured.
+      $txn_type = variable_get('uc_pg_protx_vsp_direct_cc_txn_type', UC_CREDIT_AUTH_CAPTURE);
+      $transaction['TxType'] = ($txn_type == UC_CREDIT_AUTH_CAPTURE) ? 'PAYMENT' : 'AUTHENTICATE';
+
+      // Remove the fields that we don't need.
+      foreach ($fields as $field) {
+        unset($transaction[$field]);
+      }
+
+      // Modify the transaction to use the token GUID and the supplied CVV.
+      $token = $tokens[$cc_data['cc_token']];
+      $transaction['Token'] = $token['token'];
+      $transaction['StoreToken'] = 1;
+      $transaction['CV2'] = $order->payment_details['cc_cvv'];
+
+      // For recurring orders, skip CV2 and 3D-Secure checks.
+      // This may result in failure for Maestro cards, as 3D-Secure is mandatory.
+      if (isset($order->data['recurring_fee'])) {
+        $transaction['Apply3DSecure'] = 2;
+        $transaction['ApplyAVSCV2'] = 2;
+        unset($transaction['CV2']);
+      }
+    }
+  }
+}
+
+/**
+ * Implements hook_uc_sagepay_url_alter().
+ */
+function uc_sagepay_token_uc_sagepay_url_alter(&$servers) {
+  // error_log ( __FUNCTION__ );
+  $servers['TOKEN'] = array(
+    1 => 'https://test.sagepay.com/gateway/service/directtoken.vsp',
+    2 => 'https://live.sagepay.com/gateway/service/directtoken.vsp',
+  );
+  $servers['REMOVETOKEN'] = array(
+    1 => 'https://test.sagepay.com/gateway/service/removetoken.vsp',
+    2 => 'https://live.sagepay.com/gateway/service/removetoken.vsp',
+  );
+}
+
+/**
+ * Implements hook_uc_checkout_complete().
+ *
+ * Save a created token to the database, now we have the user's account details.
+ */
+function uc_sagepay_token_uc_checkout_complete($order, $account) {
+  // error_log ( __FUNCTION__ );
+  // Double check we don't save tokens against the anonymous user.
+  if ($order->uid && isset($_SESSION['sagepay_token'])) {
+    $token = $_SESSION['sagepay_token'];
+    $token['uid'] = $order->uid;
+    $token['order_id'] = $order->order_id;
+    $token['server'] = variable_get('uc_sagepay_server', 2);
+    drupal_write_record('uc_sagepay_tokens', $token);
+  }
+
+  unset($_SESSION['sagepay_token']);
+  unset($_SESSION['create_sagepay_token']);
+}
+
+/**
+ * Load a single saved card.
+ */
+function uc_sagepay_token_load($token_ids) {
+  // error_log ( __FUNCTION__ );
+  foreach ($token_ids as $nid => &$token_id) {
+    $node_additions = db_fetch_array(db_query("SELECT * FROM {uc_sagepay_tokens} WHERE token_id = :token_id", array(':token_id' => $token_id)));
+    foreach ($node_additions as $property => &$value) {
+      $token_id->$property = $value;
+    }
+  }
+}
+
+/**
+ * Delete a single saved card.
+ */
+function uc_sagepay_token_delete($token_id, $force = FALSE) {
+  // error_log ( __FUNCTION__ );
+  if ($token = uc_sagepay_token_load($token_id)) {
+    $transaction = array(
+      'VPSProtocol' => '2.23',
+      'Vendor' => variable_get('uc_sagepay_vendor', ''),
+      'TxType' => 'REMOVETOKEN',
+      'Token' => $token['token'],
+    );
+    $result = uc_sagepay_transaction('REMOVETOKEN', $transaction);
+
+    if ($result['success'] || $force) {
+      // TODO Please review the conversion of this statement to the D7 database API syntax.
+      /* db_query("DELETE FROM {uc_sagepay_tokens} WHERE token_id = %d", $token_id) */
+      db_delete('uc_sagepay_tokens')
+        ->condition('token_id', $token_id)
+        ->execute();
+      return TRUE;
+    }
+  }
+
+  return FALSE;
+}
+
+/**
+ * Load available saved cards for the specified user.
+ */
+function uc_sagepay_token_load_tokens($uid = NULL) {
+  global $user;
+  // error_log ( __FUNCTION__ );
+  if (is_null($uid)) {
+    $uid = $user->uid;
+  }
+  $server = variable_get('uc_sagepay_server', 2);
+
+  $tokens = array();
+  $result = db_query("SELECT * FROM {uc_sagepay_tokens} WHERE uid = :uid AND server = :server ORDER BY token_id", array(':uid' => $uid, ':server' => $server));
+  foreach ($result as $token) {
+    // Don't return expired cards.
+    if (_uc_credit_valid_card_expiration(substr($token->expiry, 0, 2), 2000 + substr($token->expiry, 2))) {
+      $tokens[$token->token_id] = (array)$token;
+    }
+  }
+
+  return $tokens;
+}
+
+/**
+ * Implements hook_order().
+ */
+function uc_sagepay_token_order($op, &$arg1, $arg2) {
+  // error_log ( __FUNCTION__ ." : ".$op);
+  switch ($op) {
+    case 'submit':
+      if ($arg1->payment_method == 'sagepay_token') {
+        unset($_SESSION['cc_pay']);
+
+        // Attempt to process using the standard credit card payment method, with a custom transaction type.
+        $data = array('txn_type' => 'sagepay_token');
+        $pass = uc_payment_process('credit', $arg1->order_id, $arg1->order_total, $data, TRUE, NULL, FALSE);
+
+        if (!$pass) {
+          $message = variable_get('uc_credit_fail_message', t('We were unable to process your credit card payment. Please verify your card details and try again.  If the problem persists, contact us to complete your order.'));
+          return array(array('pass' => FALSE, 'message' => $message));
+        }
+      }
+      break;
+
+    case 'save':
+      if ($arg1->payment_method == 'sagepay_token') {
+        if (!empty($arg1->payment_details)) {
+          // Ensure we only save the token, not the CVV.
+          $cc_data = array('cc_token' => $arg1->payment_details['cc_token']);
+          _save_cc_data_to_order($cc_data, $arg1->order_id);
+        }
+      }
+      break;
+
+    case 'load':
+      if ($arg1->payment_method == 'sagepay_token') {
+        // Load the CC details from the credit cache if available.
+        $arg1->payment_details = uc_credit_cache('load');
+
+        // Otherwise load any details that might be stored in the data array.
+        if (empty($arg1->payment_details) && isset($arg1->data['cc_data'])) {
+          $arg1->payment_details = uc_credit_cache('save', $arg1->data['cc_data']);
+        }
+      }
+      break;
+  }
+}
+
+/**
+ * Payment method callback for stored credit cards.
+ */
+function uc_payment_method_sagepay_token($op, &$arg1, $silent = FALSE) {
+  // error_log ( __FUNCTION__ );
+  switch ($op) {
+    case 'cart-details':
+      return uc_strip_form(drupal_get_form('uc_payment_method_sagepay_token_form', $arg1));
+
+    case 'cart-process':
+      // Fetch the CC details from the $_POST directly.
+      $cc_data = array(
+        'cc_token' => check_plain($_POST['cc_token']),
+        'cc_cvv' => check_plain($_POST['cc_cvv']),
+      );
+
+      // Recover cached CC data in $_POST if it exists.
+      if (isset($_POST['payment_details_data'])) {
+        $cache = uc_credit_cache('save', $_POST['payment_details_data']);
+      }
+
+      // Account for masked CVV numbers.
+      if (!empty($cc_data['cc_cvv']) && $cc_data['cc_cvv'] == str_repeat('-', strlen($cc_data['cc_cvv']))) {
+        // Recover the number from the encrypted data in $_POST if truncated.
+        if (isset($cache['cc_cvv'])) {
+          $cc_data['cc_cvv'] = $cache['cc_cvv'];
+        }
+        else {
+          $cc_data['cc_cvv'] = '';
+        }
+      }
+
+      // Go ahead and put the CC data in the payment details array.
+      $arg1->payment_details = $cc_data;
+
+      // Default our value for validation.
+      $return = TRUE;
+
+      // Validate that the token belongs to this user.
+      $tokens = uc_sagepay_token_load_tokens();
+      if (!isset($tokens[$cc_data['cc_token']])) {
+        if (!$silent) {
+          drupal_set_message(t('You have selected an invalid saved card.'), 'error');
+        }
+        $return = FALSE;
+      }
+
+      // Validate the CVV number if enabled.
+      if (variable_get('uc_credit_cvv_enabled', TRUE) && !_valid_cvv($cc_data['cc_cvv'])) {
+        if (!$silent) {
+          drupal_set_message(t('You have entered an invalid CVV number.'), 'error');
+        }
+        $return = FALSE;
+      }
+
+      // Initialize the encryption key and class.
+      $key = uc_credit_encryption_key();
+      $crypt = new uc_encryption_class;
+
+      // Store the encrypted details in the session for the next pageload.
+      $_SESSION['sescrd'] = $crypt->encrypt($key, serialize($arg1->payment_details));
+
+      // Log any errors to the watchdog.
+      uc_store_encryption_errors($crypt, 'uc_credit');
+
+      // If we're going to the review screen, set a variable that lets us know
+      // we're paying by CC.
+      if ($return) {
+        $_SESSION['cc_pay'] = TRUE;
+      }
+
+      return $return;
+
+    case 'cart-review':
+      $token = uc_sagepay_token_load($arg1->payment_details['cc_token']);
+
+      $review = array();
+      if (variable_get('uc_credit_type_enabled', FALSE)) {
+        $review[] = array(
+          'title' => t('Card Type'),
+          'data' => check_plain($token['card_type']),
+        );
+      }
+      $review[] = array(
+        'title' => t('Card Number'),
+        'data' => str_repeat('-', 12) . check_plain($token['last_4']),
+      );
+      $review[] = array(
+        'title' => t('Expiration'),
+        'data' => substr($token['expiry'], 0, 2) . '/20' . substr($token['expiry'], 2),
+      );
+      if (variable_get('uc_credit_cvv_enabled', TRUE)) {
+        $review[] = array(
+          'title' => t('CVV'),
+          'data' => user_access('view cc numbers') ? $arg1->payment_details['cc_cvv'] : str_repeat('-', strlen($arg1->payment_details['cc_cvv'])),
+        );
+      }
+      return $review;
+
+    case 'order-view':
+      if (user_access('view cc details') && $token = uc_sagepay_token_load($arg1->payment_details['cc_token'])) {
+        $output = '<a href="#" onclick="$(this).hide().next().show(); return false;">' . t('View card details') . '</a>';
+        $output .= '<table style="width: auto; display: none;">';
+        $output .= '<tr><td>' . t('Card Type:') . ' </td><td>' . check_plain($token['card_type']) . '</td></tr>';
+        $output .= '<tr><td>' . t('Card Number:') . ' </td><td>' . t('(Last 4) ') . check_plain($token['last_4']) . '</td></tr>';
+        $output .= '<tr><td>' . t('Expiration:') . ' </td><td>' . substr($token['expiry'], 0, 2) . '/20' . substr($token['expiry'], 2) . '</td></tr>';
+        $output .= '</table>';
+
+        if (user_access('process credit cards')) {
+          $output .= drupal_get_form('uc_sagepay_token_order_view_form', $arg1->order_id);
+        }
+      }
+
+      return $output;
+
+    case 'customer-view':
+      if ($token = uc_sagepay_token_load($arg1->payment_details['cc_token'])) {
+        $output = t('Card Number:') . '<br />' . t('(Last 4) ') . check_plain($token['last_4']);
+        return $output;
+      }
+  }
+}
+
+/**
+ * "Process card" button for the order view.
+ *
+ * @see uc_credit_order_view_form()
+ */
+function uc_sagepay_token_order_view_form($form, $form_state, $order_id) {
+  // error_log ( __FUNCTION__ );
+  $form['#attributes'] = array('style' => 'margin: 0.5em 0 0 0;');
+  $form['order_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $order_id,
+  );
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Process card'),
+    '#attributes' => array('style' => 'margin: 0;'),
+  );
+  return $form;
+}
+
+/**
+ * @todo Please document this function.
+ * @see http://drupal.org/node/1354
+ */
+function uc_sagepay_token_order_view_form_submit($form, &$form_state) {
+  // error_log ( __FUNCTION__ );
+  $form_state['redirect'] = 'admin/store/orders/' . $form_state['values']['order_id'] . '/sagepay_token';
+}
+
+/**
+ * Stored credit card selection form.
+ *
+ * @see uc_payment_method_credit_form()
+ */
+function uc_payment_method_sagepay_token_form($form, $form_state, $order) {
+  // error_log ( __FUNCTION__ );
+  // Normally the CC data is posted in via AJAX.
+  if (!empty($_POST['payment-details-data']) && arg(0) == 'cart') {
+    $order->payment_details = uc_credit_cache('save', $_POST['payment-details-data']);
+  }
+
+  // But we have to accommodate failed checkout form validation here.
+  if (isset($_SESSION['sescrd'])) {
+    $order->payment_details = uc_credit_cache('save', $_SESSION['sescrd']);
+    unset($_SESSION['sescrd']);
+  }
+
+  $tokens = uc_sagepay_token_load_tokens($order->uid);
+  $options = array();
+  foreach ($tokens as $token) {
+    $options[$token['token_id']] = theme('uc_sagepay_token_description', array('token' => $token));
+  }
+
+  $form['cc_policy'] = array('#value' => variable_get('uc_credit_policy', t('Your billing information must match the billing address for the credit card entered below or we will be unable to process your payment.')));
+
+  $form['cc_token'] = array(
+    '#type' => 'select',
+    '#title' => 'Card',
+    '#options' => $options,
+    '#default_value' => isset($order->payment_details['cc_token']) ? $order->payment_details['cc_token'] : array_shift(array_keys($options)),
+  );
+
+  if (variable_get('uc_credit_cvv_enabled', TRUE)) {
+    // Set up the default CVV on the credit card form.
+    if (!_valid_cvv($order->payment_details['cc_cvv'])) {
+      // Display the CVV as is if it does not validate so it can be corrected.
+      $default_cvv = $order->payment_details['cc_cvv'];
+    }
+    elseif (!empty($order->payment_details['cc_cvv'])) {
+      if (user_access('view cc numbers')) {
+        // Display the full number to those with access.
+        $default_cvv = $order->payment_details['cc_cvv'];
+      }
+      else {
+        // Otherwise mask it with dashes.
+        $default_cvv = str_repeat('-', strlen($order->payment_details['cc_cvv']));
+      }
+    }
+    $form['cc_cvv'] = array(
+      '#type' => 'textfield',
+      '#title' => t('CVV'),
+      '#description' => t('To protect our customers, we do not store the CVV number.'),
+      '#field_suffix' => '<img src="' . base_path() . drupal_get_path('module', 'uc_credit') . '/images/info.png" onclick="cvv_info_popup();" style="cursor: pointer; position: relative; top: 3px;" /> <a style="cursor: pointer; font-weight: normal;" onclick="cvv_info_popup();">' . t("What's the CVV?") . '</a>',
+      '#default_value' => $_SESSION['clear_cc'] ? '' : $default_cvv,
+      '#attributes' => array('autocomplete' => 'off'),
+      '#size' => variable_get('uc_credit_amex', TRUE) ? 4 : 3,
+      '#maxlength' => variable_get('uc_credit_amex', TRUE) ? 4 : 3,
+    );
+  }
+
+  unset($_SESSION['clear_cc']);
+
+  return $form;
+}
+
+/**
+ * Theme description of a saved card.
+ */
+function theme_uc_sagepay_token_description($variables) {
+  // error_log ( __FUNCTION__ .": ".print_r($variables,1));
+  $token = $variables['token'];
+  $expiry = substr($token['expiry'], 0, 2) . '/20' . substr($token['expiry'], 2);
+  return t('!type, ending with !last-4, expires !expiry', array('!type' => $token['card_type'], '!last-4' => $token['last_4'], '!expiry' => $expiry));
+}
diff --git a/uc_sagepay_token/uc_sagepay_token.recurring.inc b/uc_sagepay_token/uc_sagepay_token.recurring.inc
index e69de29..77a0f56 100755
--- a/uc_sagepay_token/uc_sagepay_token.recurring.inc
+++ b/uc_sagepay_token/uc_sagepay_token.recurring.inc
@@ -0,0 +1,111 @@
+<?php
+
+/**
+ * Implements hook_recurring_info().
+ */
+function uc_sagepay_token_recurring_info() {
+  $items = array();
+
+  $items['sagepay_direct'] = array(
+    'name' => t('Sage Pay Direct'),
+    'payment method' => 'credit',
+    'module' => 'uc_sagepay_token',
+    'fee handler' => 'sagepay_token',
+    'process callback' => 'uc_sagepay_recurring_process',
+    //'renew callback' => 'uc_sagepay_token_recurring_renew',
+    'menu' => array(
+      'charge' => UC_RECURRING_MENU_DEFAULT,
+      'edit' => UC_RECURRING_MENU_DEFAULT,
+      'cancel' => UC_RECURRING_MENU_DEFAULT,
+    ),
+  );
+
+  $items['sagepay_token'] = array(
+    'name' => t('Sage Pay Token'),
+    'payment method' => 'sagepay_token',
+    'module' => 'uc_sagepay_token',
+    'fee handler' => 'sagepay_token',
+    'process callback' => 'uc_sagepay_token_recurring_process',
+    'renew callback' => 'uc_sagepay_token_recurring_renew',
+    'menu' => array(
+      'charge' => UC_RECURRING_MENU_DEFAULT,
+      'edit' => UC_RECURRING_MENU_DEFAULT,
+      'cancel' => UC_RECURRING_MENU_DEFAULT,
+    ),
+  );
+
+  return $items;
+}
+
+/**
+ * Set up the recurring fee when a new credit card is being stored.
+ *
+ * Recurring orders are handled by the sagepay_token handler instead.
+ */
+function uc_sagepay_recurring_process($order, &$fee) {
+  // error_log ( __FUNCTION__ );
+  $fee->fee_handler = 'sagepay_token';
+
+  return TRUE;
+}
+
+/**
+ * Set up the recurring fee when a stored credit card is used for the initial payment.
+ *
+ * The payment data is already set in the original order, so nothing needs to be done.
+ */
+function uc_sagepay_token_recurring_process($order, &$fee) {
+  // error_log ( __FUNCTION__ );
+  return TRUE;
+}
+
+/**
+ * Implements hook_recurring_renewal_pending().
+ */
+function uc_sagepay_token_recurring_renewal_pending(&$order, $fee) {
+  // error_log ( __FUNCTION__ ." for ".$order->data['old_order_id']);;
+  // error_log ( __FUNCTION__ . " " . print_r($fee->fee_handler,1));
+  // error_log ( __FUNCTION__ . " " . print_r($order->payment_method,1));
+  // If the original order was made by credit card, switch this order to the
+  // token method, using the token that was created against the original.
+  if ($fee->fee_handler == 'sagepay_token' && $order->payment_method == 'credit') {
+    $token = db_query("SELECT token_id FROM {uc_sagepay_tokens} WHERE order_id = :order_id", array(':order_id' => $order->data['old_order_id']))->fetchField();
+    $order->payment_method = 'sagepay_token';
+
+    $key = uc_credit_encryption_key();
+    $crypt = new UbercartEncryption();
+
+    if (isset($order->data['cc_data'])) {
+      $cc_data = $crypt->decrypt($key, $order->data['cc_data']);
+      if (strpos($cc_data, ':') === FALSE) {
+        $cc_data = base64_decode($cc_data);
+      }
+      $cc_data = unserialize($cc_data);
+    } else {
+      $cc_data = array();
+    }
+
+    $cc_data['cc_token'] = $token;
+    $cc_data = serialize($cc_data);
+    $order->data['cc_data'] = $crypt->encrypt($key, $cc_data);
+    //$order->payment_details['cc_token'] = $token;
+
+    // Clear the credit cache so uc_credit doesn't clobber the token.
+    uc_credit_cache('clear');
+
+  }
+
+}
+
+
+
+/**
+ * Process a renewal.
+ */
+function uc_sagepay_token_recurring_renew($order, &$fee) {
+
+  // error_log ( __FUNCTION__ );
+  $data = array('txn_type' => 'sagepay_token');
+  return uc_payment_process_payment('credit', $order->order_id, $order->order_total, $data, TRUE, NULL, FALSE);
+  
+}
