 PathScanner = require './path-scanner'
 PathReplacer = require './path-replacer'
 
-MAX_CONCURRENT_SEARCH = 20
+MAX_CONCURRENT_CHUNK = 20
 
 ###
 Single Process
 ###
 
-search = (regex, scanner, searcher, doneCallback) ->
+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
-  pathsSearching = 0
+  pathsRunning = 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, ->
+  runPath = (filePath) ->
+    pathsRunning++
+    execPathFn filePath, ->
       pathCount--
-      pathsSearching--
+      pathsRunning--
       checkIfFinished()
 
   searchNextPath = ->
-    if pathsSearching < MAX_CONCURRENT_SEARCH and pathQueue.length
-      searchPath(pathQueue.shift())
+    if pathsRunning < MAX_CONCURRENT_CHUNK and pathQueue.length
+      runPath(pathQueue.shift())
 
   maybeSearchPath = (filePath) =>
     pathCount++
-    if pathsSearching < MAX_CONCURRENT_SEARCH
-      searchPath(filePath)
+    if pathsRunning < MAX_CONCURRENT_CHUNK
+      runPath(filePath)
     else
       pathQueue.push(filePath)
 

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

    totalReplacements += replacements
    console.log('Replaced', replacements, 'in', filePath) if options.verbose

  replace regex, options.replace, scanner, replacer, ->
    console.timeEnd 'Single Process Search + Replace'
    console.log "Replaced #{totalReplacements} matches in #{totalFiles} files"


## Scanning

scanMain = (options) ->
  scanner = new PathScanner(options.pathToScan, options)
