var fs=require("fs"),path=require("path"),mkdir=require("mkdir-p");function FileTools(i,n,t){return this.from=i,this.to=n,this.filter=t,this}function copy(i,n,t,r){"function"!=typeof t||r||(r=t,t=null);var o=new FileTools(i,n,t=t||function(i,n,t){return!0});o.find(function(i,n){var t=n.dirs.map(function(i){return path.join(o.to,path.relative(o.from,i))}).concat([o.to]);o.mkdir(t,function(i){o.copyfile(n.files,r)})})}FileTools.prototype.find=function(i){var n=this,t={dirs:[],files:[]},r=function(i,o){fs.readdir(i,function(e,f){if(e)o&&o(e);else{var l=0,c=f.length,u=function(){var e=f[l],c=path.join(i,e);fs.lstat(c,function(i,f){i?o(i):f.isDirectory()?n.filter("directory",c,e)?(t.dirs.push(c),r(c,function(i){s(i)})):s():f.isFile()?(n.filter("file",c,e)&&t.files.push(c),s()):s()})},s=function(i){i?o(i):++l===c?o(null,t):u()};c>0?u():o(null,t)}})};r(this.from,i)},FileTools.prototype.findSync=function(){var i=this,n={dirs:[],files:[]},t=function(r){var o=fs.readdirSync(r),e=0,f=o.length,l=function(){var f=o[e],l=path.join(r,f),u=fs.lstatSync(l);return u.isDirectory()?i.filter("directory",l,f)&&(n.dirs.push(l),t(l)):u.isFile()&&i.filter("file",l,f)&&n.files.push(l),c()},c=function(){return++e===f?n:l()};return f>0?l():n};return t(this.from)},FileTools.prototype.mkdir=function(i,n){var t=0,r=i.length,o=function(){mkdir(i[t],function(i){i?n(i):++t===r?n(null):o()})};i.length>0?o():n(null)},FileTools.prototype.mkdirSync=function(i){var n=0,t=i.length,r=function(){return mkdir.sync(i[n]),++n===t||r()};return!(t>0)||r()},FileTools.prototype.copyfile=function(i,n){var t=this,r=0,o=i.length,e=function(){var f=i[r],l=fs.createReadStream(f),c=fs.createWriteStream(path.join(t.to,path.relative(t.from,f)));l.on("end",function(){++r===o?n(null):e()}),l.pipe(c)};o>0?e():n(null)},FileTools.prototype.copyfileSync=function(i){var n=this;i.length;i.map(function(i){var t=path.join(n.to,path.relative(n.from,i));fs.writeFileSync(t,fs.readFileSync(i,"binary"),"binary")})},copy.sync=function(i,n,t){var r=new FileTools(i,n,t=t||function(i,n,t){return!0}),o=r.findSync(),e=o.dirs.map(function(i){return path.join(r.to,path.relative(r.from,i))});r.mkdirSync(e),r.copyfileSync(o.files)},module.exports=copy;