#!/usr/bin/env node

'use strict';

var concat = require('concat-stream')
  , prompt = require('cli-prompt')
  , uniq = require('uniq')
  , output = require('simple-output');

var spawn = require('child_process').spawn
  , util = require('util');

output.stdout = output.stderr;


(function (argv) {
  if (argv.length != 1) {
    output.info('Usage: ' + process.argv[1] + ' <name>');
    process.exit(1);
  }
  var procname = argv[0];

  spawn('pgrep', ['-x', procname], {
    stdio: 'pipe'
  }).stdout.pipe(concat({ encoding: 'string' }, function (pids) {
    pids = pids.trim().split(/\s+/).map(Number);

    if (10 <= pids.length) {
      output.error('More than 10 processes found. I can\'t handle it.');
      process.exit(1);
    }

    (function printPstrees(pids, index, cb) {
      if (index < pids.length) {
        spawn('pstree', [pids[index]], {
          stdio: 'pipe'
        }).stdout.pipe(concat({ encoding: 'string' }, function (tree) {
          util.puts(index + ') ' + tree.trim().replace(/\n/g, '\n   '));
          printPstrees(pids, index + 1, cb);
        }));
      }
      else {
        cb();
      }
    }(pids, 0, function () {

      prompt('kill: ', function (indices) {
        indices = uniq(indices.trim().split(''));

        (function killLoop() {
          if (indices.length) {
            spawn('kill', [pids[indices.shift()]]).on('exit', killLoop);
          }
        }());
      });
    }));
  }));
}(process.argv.slice(2)));
@@ -604,140 +604,8 @@
 );%0A%0A
-    if (10 %3C= pids.length) %7B%0A      output.error('More than 10 processes found. I can%5C't handle it.');%0A      process.exit(1);%0A    %7D%0A%0A
     
@@ -642,24 +642,24 @@
 ndex, cb) %7B%0A
+
       if (in
@@ -1060,24 +1060,571 @@
 (indices) %7B%0A
+        // If there are no more than 10 matches, a string of digits is a perfectly valid input.%0A        // Otherwise, choices must be separated by commas or spaces.%0A%0A        if (pids.length %3C= 10) %7B%0A          indices = indices.match(/%5Cd/g);%0A        %7D%0A        else %7B%0A          indices = indices.replace(/,/g, ' ')%0A                           .replace(/%5B%5E%5Cd%5Cs%5D+/g, '')%0A                           .trim()%0A                           .split(/%5Cs+/)%0A          // Mapping to Number will equate 1 and 01.%0A                           .map(Number);%0A        %7D%0A%0A
         indi
@@ -1645,25 +1645,8 @@
 ices
-.trim().split('')
 );%0A%0A

Split input by commas and spaces