var core  = require('./core');
var fs    = require('fs');
var STARTING_STRING_DELIMITER = "# DO NOT DELETE THIS LINE -- makedepend.js depends on it.";

function appendToOrReplaceInFile(pOutputTo, pArray, pDelimiter){
    try {
        var lOutputFile = fs.readFileSync(pOutputTo, {encoding: 'utf8', flag: 'r'});
        var lLines      = lOutputFile.split('\n');
        var lDelimiterPosition = lLines.indexOf(pDelimiter);
        
        if (lDelimiterPosition > -1){
            fs.writeFileSync(
                pOutputTo,
                lLines.splice(0, lDelimiterPosition).join('\n'),
                {encoding: 'utf8', flag: 'w'}
            );
        }
    } catch (e){
        process.stdout.write("'" + pOutputTo + "' didn't exist. We'll create the file instead.");
    }
    fs.appendFileSync(
        pOutputTo,
        pArray.join(''),
        {encoding: 'utf8', flag: 'a'}
    );
}

exports.main = function (pDirOrFile, pExclude, pOutputTo, pDelimiter){
    var lExclude   = !!pExclude   ? pExclude  : "";
    var lOutputTo  = !!pOutputTo  ? pOutputTo : "Makefile";
    var lDelimiter = !!pDelimiter ? pDelimiter : STARTING_STRING_DELIMITER;

    if ("-" === lOutputTo) {
        core.getDependencyStrings(pDirOrFile, lExclude, lDelimiter).forEach(function(pLine){
            process.stdout.write(pLine);
        });
    } else {
        appendToOrReplaceInFile(
            lOutputTo,
            core.getDependencyStrings(pDirOrFile, lExclude, lDelimiter)
        );
    }
};

@@ -17,16 +17,16 @@
 ire(
-'
+%22
 ./core
-'
+%22
 );%0Av
@@ -48,12 +48,12 @@
 ire(
-'fs'
+%22fs%22
 );%0Av
@@ -893,16 +893,159 @@
   );%0A%7D%0A%0A
+function fileExists(pFile) %7B%0A    try %7B%0A        fs.accessSync(pFile,fs.R_OK);%0A    %7D catch (e)%7B%0A        return false;%0A    %7D%0A    return true;%0A%7D%0A%0A%0A
 exports.
@@ -1296,16 +1296,54 @@
 MITER;%0A%0A
+    if (fileExists(pDirOrFile)) %7B%0A    
     if (
@@ -1359,24 +1359,28 @@
 OutputTo) %7B%0A
+    
         core
@@ -1464,32 +1464,36 @@
 e)%7B%0A            
+    
 process.stdout.w
@@ -1513,24 +1513,28 @@
         
+    
 %7D);%0A    
 %7D else %7B
@@ -1525,16 +1525,20 @@
 %7D);%0A    
+    
 %7D else %7B
@@ -1538,16 +1538,20 @@
  else %7B%0A
+    
         
@@ -1587,16 +1587,20 @@
         
+    
 lOutputT
@@ -1594,32 +1594,36 @@
      lOutputTo,%0A
+    
             core
@@ -1682,24 +1682,146 @@
 er)%0A        
+    );%0A        %7D%0A    %7D else %7B%0A        process.stderr.write(%22Can't open '%22 + pDirOrFile + %22' for reading. Does it exist?%5Cn%22
 );%0A    %7D%0A%7D;%0A

check whether input file/ dir exists