exports = module.exports = function(store) {
  var qs = require('querystring');


  // TODO: If no state, and there's a returnTo option, store that
  //       as initial state.

  function redirect(req, res, next) {
    var options = req.locals || {}
      , optlen = Object.keys(options).length
      , state, q;
    
    if (optlen == 0 || (optlen == 1 && options.state)) {
      q = qs.stringify(options);
      return res.redirect('/login' + (q ? '?' + q : ''));
    }
    
    
    state = { name: 'login' };
    state.maxAttempts = options.maxAttempts || 3;
    if (options.state) { state.parent = options.state; }
    
    store.save(req, state, function(err, h) {
      q = qs.stringify({ state: h });
      return res.redirect('/login' + (q ? '?' + q : ''));
    });
  }


  return [
    redirect
  ];
  
};

exports['@require'] = [
  'http://i.bixbyjs.org/http/state/Store'
];

@@ -256,17 +256,31 @@
   , 
-optlen = 
+state, q;%0A    %0A    if (
 Obje
@@ -306,120 +306,91 @@
 ngth
-%0A      , state, q;%0A    %0A    if (optlen == 0 %7C%7C (optlen == 1 && options.state)) %7B%0A      q = qs.stringify(options)
+ == 0) %7B%0A      q = req.state ? '?' + qs.stringify(%7B state: req.state.handle %7D) : ''
 ;%0A  
@@ -424,34 +424,17 @@
 ogin' + 
-(q ? '?' + q : '')
+q
 );%0A    %7D
@@ -533,23 +533,19 @@
     if (
-options
+req
 .state) 
@@ -565,20 +565,23 @@
 t = 
-options.stat
+req.state.handl
 e; %7D
@@ -636,46 +636,8 @@
 ) %7B%0A
-      q = qs.stringify(%7B state: h %7D);%0A
     
@@ -672,21 +672,16 @@
 n' +
- (q ?
  '?' + q
  : '
@@ -676,21 +676,40 @@
  '?' + q
- : ''
+s.stringify(%7B state: h %7D
 ));%0A    

Improve state handling.