'use strict';

var http = require('http');
var https = require('https');
var fs = require('fs');
var readChunk = require('read-chunk'); 
var fileType = require('file-type');
var crypto = require('crypto');

module.exports.downloadFile = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var protocolhandler;
  if(url.indexOf('http:') === 0){
    protocolhandler = http;
  }
  
  if(url.indexOf('https:') === 0){
    protocolhandler = https;
  }
  if(typeof protocolhandler === 'undefined'){
    cb({error:'unknown protocol for the url '+url+', must be http or https'});
    return;
  }
  var request = protocolhandler.get(url, function(response) {
var hasher = crypto.createHash('sha256');
hasher.setEncoding('hex');
response.pipe(hasher);
response.pipe(file);
    file.on('finish', function() {
      file.close(function(err,resp){
       if(err){
        cb(err);
        return;
       }
hasher.end();
var thisHash = hasher.read();

var detectedFileType = fileType(readChunk.sync(dest, 0, 262)).ext;
        cb(err,{response:resp,extension:detectedFileType, sha256sum:thisHash}); 
      });
    });
  });
}  

@@ -386,18 +386,16 @@
 tp;%0A  %7D%0A
-  
 %0A  if(ur
@@ -658,16 +658,20 @@
 onse) %7B%0A
+    
 var hash
@@ -704,16 +704,20 @@
 a256');%0A
+    
 hasher.s
@@ -735,16 +735,20 @@
 'hex');%0A
+    
 response
@@ -762,16 +762,20 @@
 asher);%0A
+    
 response
@@ -866,16 +866,17 @@
 %0A       
+ 
 if(err)%7B
@@ -880,24 +880,26 @@
 r)%7B%0A        
+ 
+ 
 cb(err);%0A   
@@ -891,24 +891,26 @@
    cb(err);%0A
+  
         retu
@@ -920,18 +920,27 @@
 %0A       
+ 
 %7D%0A
+        
 hasher.e
@@ -945,16 +945,24 @@
 .end();%0A
+        
 var this
@@ -984,16 +984,24 @@
 ead();%0A%0A
+        
 var dete
@@ -1165,11 +1165,541 @@
 %0A  %7D);%0A%7D
-  
+;%0A%0A//shamelessly copied from http://stackoverflow.com/questions/11293857/fastest-way-to-copy-file-in-node-js%0Amodule.exports.cp = function(source, target, cb)%7B%0A  var cbCalled = false;%0A%0A  var rd = fs.createReadStream(source);%0A  rd.on(%22error%22, function(err) %7B%0A    done(err);%0A  %7D);%0A  var wr = fs.createWriteStream(target);%0A  wr.on(%22error%22, function(err) %7B%0A    done(err);%0A  %7D);%0A  wr.on(%22close%22, function(ex) %7B%0A    done();%0A  %7D);%0A  rd.pipe(wr);%0A%0A  function done(err) %7B%0A    if (!cbCalled) %7B%0A      cb(err);%0A      cbCalled = true;%0A    %7D%0A  %7D%0A%7D
 %0A

add file copy helper