var fs            = require('fs');
var path          = require('path');
var _             = require('underscore')
var phantom       = require('node-phantom');
var execSync      = require('exec-sync');
var pngIn         = 'banquo_temp_in.png';
var pngOut        = 'banquo_temp_out.png';
var writePath     = path.resolve(__dirname, '/tmp')

function banquo(opts, callback) {
  var settings = _.extend({
    mode: 'base64',
    viewport_width: 1280,
    viewport_height: 900,
    trim: 0,
    delay: 5000,
    selector: 'body',
    css_file: ''
  }, opts);

  // Append 'http://' if protocol not specified
  if (!settings.url.match(/^\w+:\/\//)) {
    settings.url = 'http://' + settings.url;
  }

  var css_text;
  if (settings.css_hide){
    css_text = settings.css_file += "\n\n " + settings.css_hide + " { display: none; }\n";
  }

  // phantomjs heavily relies on callback functions
  var page;
  var ph;

  console.log('Requesting', settings.url);
  console.log(settings)

  phantom.create(createPage)

  function createPage(err, _ph) {
    ph = _ph;
    ph.createPage(openPage);
  }

  function openPage(err, _page) {
    page = _page;
    page.set('onError', function() { return; });
    page.onConsoleMessage = function (msg) { console.log(msg); };
    page.set('viewportSize', {width: settings.viewport_width, height: settings.viewport_height});
    page.open(settings.url, prepForRender);
  }

  function prepForRender(err, status) {
    setTimeout(function() {
      page.evaluate(runInPhantomBrowser, renderImage, settings.selector, css_text);
    }, settings.delay);
  }

  function runInPhantomBrowser(selector, css_text) {
    if (css_text) {
      var style = document.createElement('style');
      style.appendChild(document.createTextNode(css_text));
      document.head.appendChild(style);
    }
    var element = document.querySelector(selector);
    return element.getBoundingClientRect();
  }

  function renderImage(err, rect) {
    page.set('clipRect', rect);
    if (settings.mode != 'save'){
      page.renderBase64('PNG', base64Rendered);
    }else{
      page.render(settings.out_file, cleanup);
      callback('Writing to file... ' + settings.out_file);
    }
  }

  function base64Rendered(err, image_data){
    if (err){
      console.log(err);
    }

    if (settings.trim === '1') {
      image_data = trimWhitespace(image_data)
    }
    
    callback(image_data)
    cleanup();
  }

  function cleanup() {
    ph.exit();
  }
  
  function trimWhitespace(image_data) {
    var fIn  = path.resolve(writePath, pngIn),
        fOut = path.resolve(writePath, pngOut),
        result = fs.writeFileSync(fIn, image_data, 'base64'),
        cmd = "convert -trim " + fIn + " " + fOut
    
    execSync(cmd)
    
    var data = fs.readFileSync(fOut, 'base64');
    
    fs.unlink(fIn)
    fs.unlink(fOut)
    
    return data
  }
}

module.exports = {
  capture: banquo
}

@@ -202,57 +202,15 @@
 var 
-pngIn         = 'banquo_temp_in.png';%0Avar pngOut 
+imgTemp
     
@@ -230,12 +230,8 @@
 temp
-_out
 .png
@@ -282,12 +282,20 @@
 e, '
-/tmp
+../../../../
 ')%0A%0A
@@ -441,16 +441,60 @@
 rim: 0,%0A
+    thumbnail: 0,%0A    dimension: '256x144',%0A
     dela
@@ -500,11 +500,8 @@
 ay: 
-500
 0,%0A 
@@ -2302,16 +2302,46 @@
 trim ===
+ '1' %7C%7C settings.thumbnail ===
  '1') %7B%0A
@@ -2359,30 +2359,30 @@
 _data = 
-trimWhitespace
+runImageMagick
 (image_d
@@ -2502,22 +2502,22 @@
 ion 
-trimWhitespace
+runImageMagick
 (ima
@@ -2537,17 +2537,18 @@
   var fI
-n
+mg
   = path
@@ -2571,61 +2571,15 @@
 th, 
-pngIn),%0A        fOut = path.resolve(writePath, pngOut
+imgTemp
 ),%0A 
@@ -2613,17 +2613,18 @@
 eSync(fI
-n
+mg
 , image_
@@ -2638,17 +2638,16 @@
 base64')
-,
 %0A       
@@ -2651,72 +2651,402 @@
     
-cmd = %22convert -trim %22 + fIn + %22 %22 + fOut%0A    %0A    execSync(cmd)
+%0A    if (settings.trim === '1') %7B%0A      var cmdTrim = %22convert -trim %22 + fImg + %22 %22 + fImg %0A      console.log('Trimming: ' + cmdTrim)%0A      execSync(cmdTrim)%0A    %7D%0A    %0A    if (settings.thumbnail === '1') %7B%0A      var cmdThumbnail = %22convert %22 + fImg + %22 -thumbnail %22 + settings.dimension + %22 %22 + fImg%0A      console.log('Processing thumbnail: ' + cmdThumbnail)%0A      execSync(cmdThumbnail)%0A    %7D
 %0A   
@@ -3079,19 +3079,19 @@
 leSync(f
-Out
+Img
 , 'base6
@@ -3120,29 +3120,10 @@
 k(fI
-n)%0A    fs.unlink(fOut
+mg
 )%0A  

Add thumbnail with dimension support