var Codesearch = require('../web/codesearch.js'),
    fs         = require('fs'),
    path       = require('path'),
    common     = require('./common.js');

common.parser.add('--dump-stats', {type: 'string', target: 'dump_stats'});
common.parser.add('--iterations', {type: 'int', default: 10});
var options = common.parseopts();
var queries = common.load_queries();
var cs = common.get_codesearch(['--timeout=0']);

var times = { };

var ITERATIONS = options.iterations;

function loop(i) {
  if (i == queries.length) {
    if (--ITERATIONS == 0) {
      done();
    } else {
      loop(0);
    }
    return;
  }
  var q = queries[i];
  var start = new Date();
  var search = cs.search(q);
  var results = 0;
  search.on('match', function () {
              results++;
            })
  search.on('done',
            function (stats) {
              var end = new Date();
              var time = +(end - start);
              if (!(q in times))
                times[q] = [];
              stats.time = time;
              stats.nmatch = results;
              times[q].push(stats);
              cs.once('ready', function() {
                        loop(i+1);
                      });
            });
}

function average(l, field) {
  var sum = 0;
  l.forEach(function (e) {sum += e[field];});
  return sum / l.length;
}

function rpad(str, len, chr) {
  if (chr === undefined)
    chr = ' '
  str = '' + str;
  while (str.length < len)
    str += chr;
  return str;
}

function done() {
  var results = [];
  if (options.dump_stats)
    fs.writeFileSync(options.dump_stats,
                     JSON.stringify(times))
  for (q in times) {
    results.push([q, times[q], average(times[q], 'time')]);
  }
  results.sort(function (a,b) {
                 return b[2] - a[2]
               });
  console.log("*** RESULTS ***")
  function fmt(re) {
    var WIDTH = 20;
    if (re.length < WIDTH) {
      re = rpad(re, WIDTH);
    }
    if (re.length > WIDTH) {
      var start = re.substr(0, WIDTH / 2);
      var end   = re.substring(re.length - (WIDTH - start.length - 3));
      re = start + '...' + end;
    }
    return re;
  }
  function num(n) {
    n = Math.round(n);
    var str;
    if (n === 0.0)
      str = '0.0'
    else
      str = ''+(n/1000);
    return rpad(str, 6, '0')
  }
  results.forEach(function (r) {
                    var min_time = Math.min.apply(
                      Math, r[1].map(function(r) {return r.time}));
                    var max_time = Math.max.apply(
                      Math, r[1].map(function(r) {return r.time}));
                    function time(name) {
                      var tm = Math.round(average(r[1], name + '_time'));
                      return num(tm);
                    }

                    console.log("[%s]: %s<%ss (re2: %s, index: %s)",
                                fmt(r[0]),
                                num(min_time),
                                num(r[2]),
                                time('re2'), time('index'));
                  });
  process.exit(0);
}

cs.once('ready', function() {
          console.log("Begin searching...");
          loop(0);
        });

@@ -1498,21 +1498,16 @@
  results
- = %5B%5D
 ;%0A  if (
@@ -1610,16 +1610,132 @@
 (times))
+%0A%0A  results = collate(times);%0A  print_one(results);%0A%0A  process.exit(0);%0A%7D%0A%0Afunction collate(times) %7B%0A  var out = %5B%5D;
 %0A  for (
@@ -1752,23 +1752,19 @@
 ) %7B%0A    
-results
+out
 .push(%5Bq
@@ -1816,126 +1816,21 @@
   re
-sults.sort(function (a,b) %7B%0A                 return b%5B2%5D - a%5B2%5D%0A               %7D);%0A  console.log(%22*** RESULTS ***%22)%0A  
+turn out;%0A%7D%0A%0A
 func
@@ -1844,18 +1844,16 @@
 t(re) %7B%0A
-  
   var WI
@@ -1862,18 +1862,16 @@
 H = 20;%0A
-  
   if (re
@@ -1889,26 +1889,24 @@
 IDTH) %7B%0A    
- 
- 
 re = rpad(re
@@ -1915,26 +1915,22 @@
 WIDTH);%0A
-  
   %7D%0A  
- 
- 
 if (re.l
@@ -1942,26 +1942,24 @@
  %3E WIDTH) %7B%0A
-  
     var star
@@ -1987,26 +1987,24 @@
 H / 2);%0A    
-  
 var end   = 
@@ -2061,18 +2061,16 @@
 ));%0A    
-  
 re = sta
@@ -2087,24 +2087,20 @@
  + end;%0A
-  
   %7D%0A
-  
   return
@@ -2104,22 +2104,19 @@
 urn re;%0A
-  %7D%0A  
+%7D%0A%0A
 function
@@ -2125,18 +2125,16 @@
 um(n) %7B%0A
-  
   n = Ma
@@ -2146,18 +2146,16 @@
 und(n);%0A
-  
   var st
@@ -2157,18 +2157,16 @@
 ar str;%0A
-  
   if (n 
@@ -2174,26 +2174,24 @@
 == 0.0)%0A    
-  
 str = '0.0'%0A
@@ -2190,18 +2190,16 @@
 = '0.0'%0A
-  
   else%0A 
@@ -2201,18 +2201,16 @@
 lse%0A    
-  
 str = ''
@@ -2222,18 +2222,16 @@
 000);%0A  
- 
- 
 return r
@@ -2247,19 +2247,170 @@
 6, '0')%0A
-  %7D
+%7D%0A%0Afunction print_one(results) %7B%0A  console.log(%22*** RESULTS ***%22)%0A%0A  results.sort(function (a,b) %7B%0A                 return b%5B2%5D - a%5B2%5D%0A               %7D);%0A
 %0A  resul
@@ -3135,35 +3135,16 @@
     %7D);%0A
-  process.exit(0);%0A
 %7D%0A%0Acs.on

Refactor output code.