diff --git a/README.txt b/README.txt
index e46a013..aebc920 100644
--- a/README.txt
+++ b/README.txt
@@ -2,13 +2,16 @@
                      D R U P A L    M O D U L E
 ********************************************************************
 Name: Webform Clear Module
-Author: Robert Castelo <www.codepositive.com>
 Drupal: 7.x
 ********************************************************************
 DESCRIPTION:
 
-Removes Webform submissions from the database once they have been emailed.
+Removes Webform submissions from the database after they have been emailed.
+Any uploaded files associated to the Webform will also be deleted.
 
+This can happen either never, immediately, or after a specified period. A
+default value for the clearing period can be set on a system-wide basis.
+This value can be overridden on a per-Webform basis.
 
 
 ********************************************************************
@@ -30,7 +33,20 @@ check the Drupal web site if you need assistance.
 2. Enable the module by navigating to:
 
    administer > build > modules
-     
-  Click the 'Save configuration' button at the bottom to commit your
-  changes. 
 
+   Click the "Save configuration" button at the bottom to commit your
+   changes.
+
+3. Go to "admin/config/content/webform_clear" if you want to change the default
+   storage period for Webforms to something other than "Do not delete".
+
+   Submissions to any Webforms created/edited before changing this default value
+   will not be affected. Submissions to any Webforms created after changing this
+   default value will be affected.
+
+4. In the "Form settings" for a Webform (at "node/NODE ID/webform/configure"),
+   this value can be overriden by users with the "Set up Webform submission
+   storage periods" permission.
+
+   For other users, this dropdown will be disabled (grayed out) and be set to
+   whatever some other user set it to, or alternatively to the default value.
diff --git a/webform_clear.info b/webform_clear.info
index fd9bd42..60d7367 100644
--- a/webform_clear.info
+++ b/webform_clear.info
@@ -1,10 +1,7 @@
 name = Webform Clear
-description = Removes Webform submissions from the database once they have been emailed.
+description = Clears specific Webforms from the database after a specified period (or immediately upon submission).
 core = 7.x
-dependencies[] = webform
+version = 7.x-1.2
 package = Webform
-
-
-
-
-
+dependencies[] = webform
+files[] = webform_clear.test
diff --git a/webform_clear.install b/webform_clear.install
new file mode 100644
index 0000000..9a02932
--- /dev/null
+++ b/webform_clear.install
@@ -0,0 +1,61 @@
+<?php
+
+/**
+ * Implements hook_schema().
+ */
+function webform_clear_schema() {
+  $schema['webform_clear'] = array(
+    'description' => t('Webform Clear data'),
+    'fields' => array(
+      'nid' => array(
+        'description' => t('The node id'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'clear_time' => array(
+        'description' => t('How many seconds after a webform submission to clear it (0 = clear immediately; -1 or no entry = do not clear).'),
+        'type' => 'int',
+        'unsigned' => FALSE,
+        'not null' => TRUE,
+      ),
+    ),
+    'primary key' => array('nid'),
+  );
+
+  return $schema;
+}
+
+/**
+ * Set up new webform_clear table.
+ */
+function webform_clear_update_7200() {
+  $schema['webform_clear'] = array(
+    'description' => t('Webform Clear data'),
+    'fields' => array(
+      'nid' => array(
+        'description' => t('The node id'),
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'clear_time' => array(
+        'description' => t('How many seconds after a webform submission to clear it (0 = clear immediately; -1 or no entry = do not clear).'),
+        'type' => 'int',
+        'unsigned' => FALSE,
+        'not null' => TRUE,
+      ),
+    ),
+    'primary key' => array('nid'),
+  );
+
+  db_create_table('webform_clear', $schema['webform_clear']);
+}
+
+/**
+ * Change the default value to "delete immediately" for people upgrading from
+ * version 1.1 in order to maintain backwards compatibility.
+ */
+function webform_clear_update_7201() {
+  variable_set('webform_clear_default_time', WEBFORM_CLEAR_DELETE_IMMEDIATELY);
+}
diff --git a/webform_clear.module b/webform_clear.module
index b4bcf19..cc1ea35 100644
--- a/webform_clear.module
+++ b/webform_clear.module
@@ -1,27 +1,201 @@
 <?php
 
+/**
+ * @file
+ * Removes Webform submissions from the database after they have been emailed.
+ *
+ * This can happen either never, immediately, or after a specified period. A
+ * default value for the clearing period can be set on a system-wide basis.
+ * This value can be overridden on a per-Webform basis.
+ */
+
+/**
+ * Defines the value of the the "Do not delete" option in the "Clear time"
+ * dropdown.
+ */
+define('WEBFORM_CLEAR_DO_NOT_DELETE', -1);
+define('WEBFORM_CLEAR_DELETE_IMMEDIATELY', 0);
+
+/**
+ * Implements hook_permission().
+ */
+function webform_clear_permission() {
+  return array(
+    'set up webform_clear times' => array(
+      'title' => t('Set up Webform submission storage periods'),
+      'description' => t('Allows the user to override the default Webform submission storage period for any webform the the user can edit, overriding the default value on a per-form basis.'),
+    ),
+  );
+}
+
+/**
+ * Implements hook_menu().
+ */
+function webform_clear_menu() {
+  $items = array();
+  $items['admin/config/content/webform_clear'] = array(
+    'title' => 'Webform Clear',
+    'description' => 'Set up default Webform submission storage.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('webform_clear_admin_settings'),
+    'access callback' => 'user_access',
+    'access arguments' => array('administer site configuration'),
+    'type' => MENU_NORMAL_ITEM,
+  );
+  return $items;
+}
+
+/**
+ * Form callback for "admin/config/content/webform_clear"
+ */
+function webform_clear_admin_settings($form, &$form_state) {
+  $form = array();
+  $form['webform_clear_default_time'] = array(
+    '#type' => 'select',
+    '#title' => t('Webform submission storage period (default)'),
+    '#description' => t('Select how long to store Webform submissions in the database by default. This default value will only apply to any future Webforms and can be overridden on a per-form basis by users with the "Set up Webform submission storage periods" permission. Please note any uploaded files associated to a submission will also be deleted. Email notifications will not be affected.'),
+    '#options' => _webform_clear_get_clear_time_options(),
+    '#default_value' => variable_get('webform_clear_default_time', WEBFORM_CLEAR_DO_NOT_DELETE),
+  );
+  return system_settings_form($form);
+}
+
+/**
+ * Implements hook_node_delete().
+ */
+function webform_clear_node_delete($node) {
+  db_delete('webform_clear')->condition('nid', $node->nid)->execute();
+}
 
 /**
  * Implements hook_form_alter().
  */
 function webform_clear_form_alter(&$form, &$form_state, $form_id) {
+  switch ($form_id) {
+    // Configuration form for the individual webforms.
+    case 'webform_configure_form':
+      $clear_time = db_query("SELECT clear_time FROM {webform_clear} WHERE nid = :nid", array(':nid' => $form['nid']['#value']))->fetchField();
+      if ($clear_time === FALSE) {
+        $default = variable_get('webform_clear_default_time', WEBFORM_CLEAR_DO_NOT_DELETE);
+      }
+      else {
+        $default = $clear_time;
+      }
+      $form['#submit'][] = 'webform_clear_configure_save';
+      $options = _webform_clear_get_clear_time_options();
+      $form['submission']['clear_time'] = array(
+        '#type' => 'select',
+        '#title' => t('Webform submission storage period'),
+        '#description' => t('Select for how long to store submissions for this Webform in the database. This setting will affect both past and future submissions for this webform. Please note any uploaded files associated to a submission will also be deleted. Email notifications will not be affected.'),
+        '#options' => $options,
+        '#default_value' => $default,
+      );
+      if (!user_access('set up webform_clear times')) {
+        $form['submission']['clear_time']['#disabled'] = TRUE;
+        $form['submission']['clear_time']['#value'] = $default;
+      }
+      break;
 
-  // Webform is being presented to visitor.
-  if (isset($form['#node']->webform) && in_array('webform_client_form_submit', $form['#submit'])) {
-    $form['#submit'][] = 'webform_clear_client_submit';
+    case strstr($form_id, 'webform_client_form'):
+      $form['#submit'][] = 'webform_clear_delete_result';
+      break;
   }
 }
 
 /**
- * Submit callback for the client form.
- * Fetch node field value and insert it in Webform field.
- *
- * @param $form
- * @param $form_state
+ * Saves webform configuration.
+ */
+function webform_clear_configure_save($form, &$form_state) {
+  $clear_time = $form_state['values']['clear_time'];
+  $nid = $form_state['values']['nid'];
+
+  // Delete entry from db
+  db_delete('webform_clear')->condition('nid', $nid)->execute();
+
+  // Add if selected
+  db_insert('webform_clear')->fields(array('nid' => $nid, 'clear_time' => $clear_time))->execute();
+}
+
+/**
+ * Deletes the webform submission immediately if selected (including files).
  */
-function webform_clear_client_submit($form, &$form_state) {
+function webform_clear_delete_result($form, &$form_state) {
+  $sid = $form_state['values']['details']['sid'];
+  $is_new = $form_state['values']['details']['is_new'];
   $nid = $form_state['values']['details']['nid'];
-  module_load_include('inc', 'webform', 'includes/webform.report');
-  webform_results_clear($nid);
-  return;
+
+  $clear = db_query("SELECT COUNT(nid) FROM {webform_clear} WHERE nid = :nid AND clear_time = :delete_immediately", array(
+    ':nid' => $nid,
+    ':delete_immediately' => WEBFORM_CLEAR_DELETE_IMMEDIATELY,
+  ))->fetchField();
+  if ($sid && $is_new && $clear) {
+    _webform_clear_delete($nid, $sid);
+  }
+}
+
+/**
+ * Implements hook_cron().
+ */
+function webform_clear_cron() {
+  $submissions = db_query("SELECT w.submitted, w.sid, w.nid, wc.clear_time FROM {webform_submissions} w INNER JOIN {webform_clear} wc ON wc.nid = w.nid");
+  foreach ($submissions as $submission) {
+    if ($submission->clear_time == WEBFORM_CLEAR_DO_NOT_DELETE) {
+      continue;
+    }
+    $delete_on = $submission->submitted + $submission->clear_time;
+    $time = _webform_clear_current_time();
+    if ($time > $delete_on) {
+      _webform_clear_delete($submission->nid, $submission->sid);
+    }
+  }
+}
+
+/**
+ * Gets the current time.
+ *
+ * If an argument is passed, the defined time will be added to the current time
+ * in subsequent calls to this function. This functionality is only used in
+ * automated tests, normally this function equals time().
+ *
+ * @param int $add_time
+ *   The number of seconds to add to the current time.
+ *
+ * @return int
+ *   The current timestamp.
+ */
+function _webform_clear_current_time($add_time = NULL) {
+  static $saved_add_time = 0;
+  if (isset($add_time)) {
+    $saved_add_time = (int) $add_time;
+  }
+  return time() + $saved_add_time;
+}
+
+/**
+ * Deletes a specific submission.
+ *
+ * @param int $nid Node ID
+ * @param int $sid Webform submission ID
+ */
+function _webform_clear_delete($nid, $sid) {
+  module_load_include('inc', 'webform', 'includes/webform.submissions');
+  $node = node_load($nid);
+  $submission = webform_get_submission($nid, $sid);
+  webform_submission_delete($node, $submission);
+}
+
+/**
+ * Gets the "Clear time" dropdown options.
+ *
+ * @return array
+ *   Options array
+ */
+function _webform_clear_get_clear_time_options() {
+  return array(
+    WEBFORM_CLEAR_DO_NOT_DELETE      => t('Do not delete submissions'),
+    WEBFORM_CLEAR_DELETE_IMMEDIATELY => t('Delete submissions immediately'),
+    1*24*60*60                       => t('Delete submissions after 1 day'),
+    7*24*60*60                       => t('Delete submissions after @count days', array('@count' => 7)),
+    30*24*60*60                      => t('Delete submissions after @count days', array('@count' => 30)),
+  );
 }
diff --git a/webform_clear.test b/webform_clear.test
new file mode 100644
index 0000000..1afe609
--- /dev/null
+++ b/webform_clear.test
@@ -0,0 +1,149 @@
+<?php
+
+/**
+ * @file
+ * Webform Clear module tests.
+ */
+
+include_once(drupal_get_path('module', 'webform') . '/webform.test');
+
+class WebformClearSubmissionTestCase extends WebformTestCase {
+
+  /**
+   * Implements getInfo().
+   */
+  public static function getInfo() {
+    return array(
+      'name' => t('Webform Clear - Submission tests'),
+      'description' => t('Submits sample webforms with different clear settings and checks the database integrity.'),
+      'group' => t('Webform Clear'),
+    );
+  }
+
+  /**
+   * Implements setUp().
+   */
+  function setUp() {
+    parent::setUp();
+    module_enable(array('webform_clear'));
+  }
+
+  /**
+   * Implements tearDown().
+   */
+  function tearDown() {
+    parent::tearDown();
+  }
+
+  /**
+   * Test submissions with different webform clear options.
+   */
+  function testWebformClear() {
+    // Log in as admin user.
+    $this->drupalLogin($this->webform_users['admin']);
+
+    // Do not delete. Check that node still exists before and after cron.
+    variable_set('webform_clear_default_time', WEBFORM_CLEAR_DO_NOT_DELETE);
+    $this->webformReset();
+    list($submission_exists_before, $submission_exists_after) = $this->webformSubmissionExecute(0);
+    $this->assertTrue($submission_exists_before, 'Submission exists before cron (do not delete)');
+    $this->assertTrue($submission_exists_after, 'Submission exists after cron (do not delete)');
+
+    // Set up immediate clear. Check that node doesn't exist before or after
+    // cron.
+    variable_set('webform_clear_default_time', 0);
+    $this->webformReset();
+    list($submission_exists_before, $submission_exists_after) = $this->webformSubmissionExecute(0);
+    $this->assertFalse($submission_exists_before, 'Submission does not exist before cron (delete immediately)');
+    $this->assertFalse($submission_exists_after, 'Submission does not exist after cron (delete immediately)');
+
+    // Override the deletion by editing webform options:
+
+    // Give admin user the right permission to override default clear times.
+    // Reset cached permissions.
+    $this->checkPermissions(array('set up webform_clear times'), TRUE);
+    $role = $this->drupalCreateRole(array('set up webform_clear times'));
+
+    $this->webform_users['admin']->roles[$role] = $role;
+    user_save($this->webform_users['admin']);
+
+    // Override "immediate clear" default value with "Do not delete".
+    $node = $this->testWebformForm();
+    list($submission_exists_before, $submission_exists_after) = $this->webformSubmissionExecute(0, WEBFORM_CLEAR_DO_NOT_DELETE);
+    $this->assertTrue($submission_exists_before, 'Submission exists before cron (do not delete overriding default)');
+    $this->assertTrue($submission_exists_after, 'Submission exists after cron (do not delete overriding default');
+
+    // Make sure we keep the custom option upon consequent edit.
+    list($submission_exists_before, $submission_exists_after) = $this->webformSubmissionExecute(0);
+    $this->assertTrue($submission_exists_before, 'Submission still exists before cron (do not delete overriding default, second edit)');
+    $this->assertTrue($submission_exists_after, 'Submission still exists before cron (do not delete overriding default, second edit)');
+
+    // Remove clear times permission from the admin user.
+    unset($this->webform_users['admin']->roles[$role]);
+    user_save($this->webform_users['admin']);
+    // Make sure we still have the custom option.
+    list($submission_exists_before, $submission_exists_after) = $this->webformSubmissionExecute(0);
+    $this->assertTrue($submission_exists_before, 'Submission still exists before cron (do not delete overriding default, no admin)');
+    $this->assertTrue($submission_exists_after, 'Submission still exists before cron (do not delete overriding default, no admin)');
+
+    // Set up clear after 1 day. Check that node exists upon submission but
+    // not after 1 day.
+    $this->webformReset();
+    variable_set('webform_clear_default_time', 1*24*60*60);
+    list($submission_exists_before, $submission_exists_after) = $this->webformSubmissionExecute(1*24*60*60);
+    $this->assertTrue($submission_exists_before, 'Submission exists before cron (1 day)');
+    $this->assertFalse($submission_exists_after, 'Submission does not exist after cron (1 day)');
+
+    // Check that the submission is not deleted before the 1 day has passed.
+    $this->webformReset();
+    variable_set('webform_clear_default_time', 1*24*60*60);
+    list($submission_exists_before, $submission_exists_after) = $this->webformSubmissionExecute(60);
+    $this->assertTrue($submission_exists_before, 'Submission exists before cron (1 day)');
+    $this->assertTrue($submission_exists_after, 'Submission exists after cron (1 day, cron at 1 hour)');
+  }
+
+  /**
+   * Execute the submission test.
+   *
+   * @param int $add_time
+   *   Seconds to add to the current time (used to fake cron running in the
+   *   future).
+   *
+   * @param int $override_clear_time
+   *   Override default clear time.
+   */
+  function webformSubmissionExecute($add_time = 0, $override_clear_time = NULL) {
+    $path = drupal_get_path('module', 'webform');
+    module_load_include('inc', 'webform', 'includes/webform.submissions');
+    $node = $this->testWebformForm();
+
+    // Set up new clear times.
+    $edit = array();
+    if (isset($override_clear_time)) {
+      $edit = array('clear_time' => $override_clear_time);
+    }
+    $this->drupalPost('node/' . $node->nid . '/webform/configure', $edit, 'Save configuration');
+
+    $submission_values = array();
+    // Visit the node page with the "foo=bar" query, to test %get[] default values.
+    $this->drupalGet('node/' . $node->nid, array('query' => array('foo' => 'bar')));
+    // Submit our test data.
+    $this->drupalPost(NULL, $submission_values, 'Submit', array(), array(), 'webform-client-form-' . $node->nid);
+
+    // Get the SID of the new submission.
+    $matches = array();
+    preg_match('/sid=([0-9]+)/', $this->getUrl(), $matches);
+    $sid = $matches[1];
+
+    // Check if submission exists.
+    $submission_exists_before = !empty(webform_get_submission($node->nid, $sid, TRUE));
+    _webform_clear_current_time($add_time);
+    // Run the Webform Clear cron.
+    webform_clear_cron();
+    // Reset the time to add.
+    _webform_clear_current_time(0);
+    $submission_exists_after = !empty(webform_get_submission($node->nid, $sid, TRUE));
+
+    return array($submission_exists_before, $submission_exists_after);
+  }
+}
