var assign = require('../util/assign');

/**
 *  Loads rc files for a program.
 *
 *  Should be declared after the env middleware and before the merge
 *  middleware.
 *
 *  @param conf A configuration object for the rc module.
 */
module.exports = function(conf) {
  conf = conf || this.configure().rc;
  return function rc(req, next) {
    if(!arguments.length) return;
    if(!conf) return next();
    var scope = this, errors = this.errors;
    var runcontrol;
    try {
      runcontrol = require('cli-rc');
    }catch(e) {
      return next(errors.ERC_MODULE);
    }
    if(conf.keys && conf.keys.append) {
      var files = req.result.options[conf.keys.append];
      if(files) {
        files = Array.isArray(files) ? files : [files];
        //console.log('got rc search path append value %j', files);
        conf.append = files;
      }
    }
    runcontrol(conf, function(err, rc, runcontrol) {
      if(err) {
        if(err instanceof SyntaxError) {
          return next(errors.ERC_SYNTAX, [err.file], err);
        }
        return next(errors.ERC_LOAD, [err.file]);
      }
      req.runcontrol = runcontrol;
      req.rc = rc;
      if(conf.merge !== false) {
        for(var k in rc) {
          assign.call(scope, null, k, rc[k]);
        }
      }
      next();
    })
  }
}

@@ -297,16 +297,41 @@
 e().rc;%0A
+  if(!conf) return this;%0A
   return
@@ -394,37 +394,8 @@
 rn;%0A
-    if(!conf) return next();%0A
     

Tidy rc middleware return.