var fs = require('fs'),
    path = require('path'),
    compile = require('./compile'),
    cmd = require('./cmd');

var prefix = '';
var dir = cmd.dir;
if (!dir){
    console.log('You need to pint directory "node watch.js dir=..."');
    return;
}
if (dir[0] !== '/'){
    dir = process.env.PWD + '/' + dir;
}
dir = dir.replace(/\/$/, '') + '/';
var out_dir = cmd.out || dir;
out_dir = out_dir.replace(/\/$/, '') + '/';
if (out_dir[0] !== '/'){
    out_dir = process.env.PWD + '/' + out_dir;
}
var fest = (cmd.fest === 'no' ? false : true);
var watched_files = {};

function do_compile(file, dir, out_dir, prefix){
    console.log('compile: ' + dir + file);
    var source = compile(dir + file, '', '');
    var file_name = (out_dir + file).replace(/\.xml/, '.js');
    var existsSync = fs.existsSync || path.existsSync;
    if (!existsSync(out_dir)){
        fs.mkdirSync(out_dir);
    }
    if (fest){
        fs.writeFileSync(file_name,  ';(function(x){if(!x.fest)x.fest={};x.fest["' + prefix + file.replace(/\.xml$/, '') + '"]=' + source + '})(this);', 'utf8');
    } else {
        fs.writeFileSync(file_name, source, 'utf8');
    }
}

function findfiles(dir, out_dir, prefix){
    fs.readdir(dir, function(err, files){
        files.filter(function(file){return file.indexOf('.xml') > 0;})
             .forEach(function(file){
                 console.log('watch: ' + file);
                 do_compile(file, dir, out_dir, prefix);
             });
        files.filter(function(file){ return fs.statSync(dir + file).isDirectory() })
             .forEach(function(file){
                 console.log('watch directory: ' + dir + file);
                 findfiles(dir + file + '/', out_dir + file + '/', prefix + file + '/');
             });
    });
}

findfiles(dir, out_dir, prefix);

@@ -108,16 +108,67 @@
 ./cmd');
+%0Avar existsSync = fs.existsSync %7C%7C path.existsSync;
 %0A%0Avar pr
@@ -391,16 +391,113 @@
  + '/';%0A
+if (!existsSync(dir))%7B%0A    console.log('directory %22' + dir + '%22 does not exists');%0A    return;%0A%7D%0A
 var out_
@@ -912,63 +912,8 @@
 ');%0A
-    var existsSync = fs.existsSync %7C%7C path.existsSync;%0A
     

check watch input dir