var grunt = require('grunt');
var spawn = require('child_process').spawn;

var gruntCmd = (process.platform === 'win32') ? 'grunt.cmd' : 'grunt';

var makeOptions = function (options) {

  var baseOptions = {
    base: null,
    prefix: 'grunt-',
    verbose: false
  };

  if (options) {
    for (var key in options) {
      baseOptions[key] = options[key];
      if(key != 'base' && key != 'prefix'){
        grunt.option(key, options[key]);
      }
    }
  }

  return baseOptions;
};

module.exports = function (gulp, options) {
  var tasks = getTasks(options);

  for (var name in tasks) {
    if (tasks.hasOwnProperty(name)) {
      var fn = tasks[name];
      gulp.task(name, fn);
    }
  }

};

var getTasks = module.exports.tasks = function (options) {
  var opt = makeOptions(options);

  if (opt.base) {
    grunt.file.setBase(opt.base);
  }

  grunt.task.init([]);

  var gruntTasks = grunt.task._tasks,
    finalTasks = {};

  function registerGruntTask (name) {
    finalTasks[opt.prefix + name] = function (cb) {
      if (opt.verbose) {
        console.log('[grunt-gulp] Running Grunt "' + name + '" task...');
      }
      var args = [name, '--force', '--verbose=' + opt.verbose];
      for(var key in opt)
      {
        if(key != 'base' && key != 'prefix'){
        args = args.concat('--' + key + '=' + opt[key]);
        }
      }
      var child = spawn(
        gruntCmd,
        args
      );
      child.stdout.on('data', function(d) {
        grunt.log.write(d);
      });
      child.stderr.on('data', function(d) {
        grunt.log.error(d);
      });
       child.on('close', function(code) {
        if (opt.verbose) {
          grunt.log.ok('[grunt-gulp] Done running Grunt "' + name + '" task.');
        }
        cb();
      });
    };
  }

  for (var name in gruntTasks) {
    if (gruntTasks.hasOwnProperty(name)) {
      // add tasks
      registerGruntTask(name);
      // also add target-specific tasks
      for (var target in grunt.config.get(name)) {
        registerGruntTask(name + ':' + target);
      }
    }
  }

  return finalTasks;
};

@@ -796,26 +796,87 @@
 %0A%0A  
-if (opt.base) %7B%0A  
+var oldCwd = process.cwd();%0A  var cwd = opt.base != null ? opt.base : oldCwd;%0A%0A
   gr
@@ -896,22 +896,13 @@
 ase(
-opt.base);%0A  %7D
+cwd);
 %0A%0A  
@@ -919,24 +919,50 @@
 .init(%5B%5D);%0A%0A
+  process.chdir(oldCwd);%0A%0A
   var gruntT
@@ -1480,16 +1480,36 @@
     args
+,%0A        %7Bcwd: cwd%7D
 %0A      )

fix #3 by restoring old cwd after initializing grunt and passing new cwd when calling spawn