/*!
 * grunt-svg2png
 * https://github.com/dbushell/grunt-svg2png
 *
 * Copyright (c) 2013 David Bushell
 * Licensed under The MIT License (MIT)
 */

var fs = require('fs'),
    page,
    files = JSON.parse(phantom.args[0]),
    total = files.length,
    next = 0,

    file, svgdata, frag, img, svg, width, svgWidth, height, svgHeight;

var nextFile = function()
{
    page = require('webpage').create();

    if (next >= total) {
        phantom.exit(0);
        return;
    }

    file = files[next++];

    svgdata = fs.read(file.src) || '';

    frag = window.document.createElement('div');
    frag.innerHTML = svgdata;

    svg = frag.querySelector('svg');

    svgWidth = parseFloat(svg.getAttribute('width').replace('px', ''));
    svgHeight = parseFloat(svg.getAttribute('height').replace('px', ''));

    if (file.width && file.width > 0) {
        width = parseFloat(file.width);
        height = parseFloat(svgHeight * width / svgWidth);
   } else {
        width = svgWidth;
        height = svgHeight;
    }

    img = window.document.createElement('img');
    img.src = 'data:image/svg+xml;utf8,' + svgdata;
    img.setAttribute('width', width);
    img.setAttribute('height', height);
    img.style.cssText = 'display: block; width:' + width + '; height:' + height;

    page.viewportSize = {
        width: width,
        height: height
    };


    // page.open('data:image/svg+xml;utf8,' + svgdata, function(status)
    page.open('data:text/html,<!doctype html><title>svg!</title><body style="padding:0;margin:0">' + img.outerHTML + '</body></html>', function(status)
    {
        page.render(file.dest);
        console.log(JSON.stringify({ 'file': file, 'status': status }));
        nextFile();
    });
};

nextFile();

@@ -673,27 +673,16 @@
 Width = 
-parseFloat(
 svg.getA
@@ -698,16 +698,59 @@
 'width')
+ %7C%7C '1';%0A    svgWidth = parseFloat(svgWidth
 .replace
@@ -778,27 +778,16 @@
 eight = 
-parseFloat(
 svg.getA
@@ -804,16 +804,61 @@
 height')
+ %7C%7C '1';%0A    svgHeight = parseFloat(svgHeight
 .replace
@@ -1182,24 +1182,35 @@
 svgdata;%0A   
+ if (width)
  img.setAttr
@@ -1231,24 +1231,36 @@
  width);%0A   
+ if (height)
  img.setAttr
@@ -1288,77 +1288,72 @@
 t);%0A
+%0A
     
-img.style.cssText = 'display: block;
+page.viewportSize = %7B%0A       
  width:
-' +
  width
- + ';
+,%0A       
  height:
 ' + 
@@ -1352,84 +1352,166 @@
 ght:
-' +
  height
+%0A    %7D
 ;%0A%0A    
-page.viewportSize = %7B%0A        width: width,%0A       
+if (width %3C 1) width = 'auto';%0A    if (height %3C 1) width = 'height';%0A    img.style.cssText = 'display: block; width:' + width + ';
  height:
  hei
@@ -1506,31 +1506,27 @@
  height:
+' +
  height
-%0A    %7D;%0A
+;
 %0A%0A    //

Do a better job reading dimensions