     console.timeEnd 'Single Process Search'
     console.log "#{resultCount} matches in #{count} files. Searched #{pathCount} files"
 
+
+## Replacing
+
+replace = (regex, replacement, scanner, replacer, doneCallback) ->
+  regex = globalizeRegex(regex)
+  execPathFn = (filePath, callback) ->
+    replacer.replacePath(regex, replacement, filePath, callback)
+
+  execPathsChunked(scanner, execPathFn, doneCallback)
+
 replaceMain = (options) ->
   scanner = new PathScanner(options.pathToScan, options)
   replacer = new PathReplacer({dryReplace: options.dryReplace})

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

MAX_CONCURRENT_SEARCH = 20

###
Single Process
###

search = (regex, scanner, searcher, doneCallback) ->
  finishedScanning = false
  pathCount = 0
  pathsSearching = 0
  pathQueue = []

  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

  searchPath = (filePath) ->
    pathsSearching++
    searcher.searchPath regex, filePath, ->
      pathCount--
      pathsSearching--
      checkIfFinished()

  searchNextPath = ->
    if pathsSearching < MAX_CONCURRENT_SEARCH and pathQueue.length
      searchPath(pathQueue.shift())

  maybeSearchPath = (filePath) =>
    pathCount++
    if pathsSearching < MAX_CONCURRENT_SEARCH
      searchPath(filePath)
    else
      pathQueue.push(filePath)


    scanner.removeListener 'finished-scanning', onFinishedScanning
    doneCallback()

  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()
