     scanner.removeListener 'finished-scanning', onFinishedScanning
     doneCallback()
 
-  regex = globalizeRegex(regex)
   scanner.on 'path-found', maybeSearchPath
   scanner.on 'finished-scanning', onFinishedScanning
   scanner.scan()
+
+
+## Searching
+
+search = (regex, scanner, searcher, doneCallback) ->
+  regex = globalizeRegex(regex)
+  execPathFn = (filePath, callback) ->
+    searcher.searchPath(regex, filePath, callback)
+
+  execPathsChunked(scanner, execPathFn, doneCallback)
 
 searchMain = (options) ->
   searcher = new PathSearcher()

    console.timeEnd 'Single Process Search'
    console.log "#{resultCount} matches in #{count} files. Searched #{pathCount} files"

replaceMain = (options) ->
  scanner = new PathScanner(options.pathToScan, options)
  replacer = new PathReplacer({dryReplace: options.dryReplace})

PathScanner = require './path-scanner'
PathReplacer = require './path-replacer'

MAX_CONCURRENT_CHUNK = 20

###
Single Process
###

globalizeRegex = (regex) ->
  if not regex.global
    flags = "g"
    flags += "i" if regex.ignoreCase
    flags += "m" if regex.multiline
    regex = new RegExp(regex.source, flags)
  regex

execPathsChunked = (scanner, execPathFn, doneCallback) ->
  finishedScanning = false
  pathCount = 0
  pathsRunning = 0
  pathQueue = []

  runPath = (filePath) ->
    pathsRunning++
    execPathFn filePath, ->
      pathCount--
      pathsRunning--
      checkIfFinished()

  searchNextPath = ->
    if pathsRunning < MAX_CONCURRENT_CHUNK and pathQueue.length
      runPath(pathQueue.shift())

  maybeSearchPath = (filePath) =>
    pathCount++
    if pathsRunning < MAX_CONCURRENT_CHUNK
      runPath(filePath)
    else
      pathQueue.push(filePath)

