var debug = require('debug')('reminder');
var hinterval = require('human-interval');
var conf = require('./conf');
var db = require('./db');
var random = require('./random');
var unansweredDB = db('prompts-unanswered');

// Convert string durations into ms.
['timeBetweenReminders', 'reminderJobInterval']
.forEach(function(key) {
  var hr = conf.get(key);
  var ms = hinterval(conf.get(key));
  conf.set(key, ms);
  debug('transforming', key, hr, ms);
});

var prompt = function() {
  var prompts = conf.get('reminderPrompts');
  return prompts[random().nextInt(0, prompts.length)];
};

var scan = function(reminderHook, done) {
  unansweredDB.createReadStream()
    .on('data', function(data) {
      var nextReminder = new Date(data.value.lastReminder + conf.get('timeBetweenReminders'));
      if (nextReminder < Date.now()) {
        reminderHook({
          hash: data.key.substring('unanswered!'.length),
          prompt: prompt(),
          unansweredPrompt: data.value
        });
      }
    })
    .on('error', function(err) {
      debug('scanning unanswered failed', err);
      if (done) return done(err);
    })
    .on('close', function() {
      if (done) return done();
    });
};

// We don't really need the reminder job to be persistent. Reminders are sent
// only as a function of unanswered prompts. Pass a hook to be called for each
// user that needs a reminder.
//
// reminderHook is passed a payload containing the user hash and reminder prompt
var interval;
exports.start = function(reminderHook, done) {
  if (!reminderHook) throw new Error('reminderHook is undefined');
  interval = setInterval(scan, conf.get('reminderJobInterval'), reminderHook, done);
};

exports.stop = function() {
  if (interval) clearInterval(interval);
};

@@ -719,17 +719,8 @@
 r = 
-new Date(
 data
@@ -773,17 +773,16 @@
 inders')
-)
 ;%0A      
@@ -1513,24 +1513,88 @@
 ok, done) %7B%0A
+  if (interval) throw new Error('reminder is already running');%0A
   if (!remin
@@ -1648,16 +1648,67 @@
 ined');%0A
+  var bound = scan.bind(null, reminderHook, done);%0A
   interv
@@ -1724,20 +1724,21 @@
 nterval(
-scan
+bound
 , conf.g
@@ -1762,36 +1762,16 @@
 terval')
-, reminderHook, done
 );%0A%7D;%0A%0Ae
@@ -1812,16 +1812,22 @@
 nterval)
+ %7B%0A   
  clearIn
@@ -1844,11 +1844,36 @@
 erval);%0A
+    interval = null;%0A  %7D%0A
 %7D;%0A

Fix issues from coderead