'use strict'
var icons = require('ios-icons')
var lwip = require('lwip')
var Q = require('q')
var path = require('path')
var colors = require('colors')

function openImage(path) {
  var q = Q.defer()
  lwip.open(path, function(err, image) {
    if (err) {
        q.reject(err)
    } else {
        q.resolve(image)
    }
  })
  return q.promise
}

function clone(image) {
  var q = Q.defer()
  image.clone(function(err, clone) {
    if (err) {
      q.reject(err)
    } else {
      q.resolve(clone)
    }
  })
  return q.promise
}

function resize(icon, image) {
  var q = Q.defer()
  image.resize(icon.width, function(err, resized) {
    if (err) return q.reject(err)
    q.resolve(resized)
  })
  return q.promise
}

function writeFile(path, image) {
  var q = Q.defer()
  image.writeFile(path, function(err) {
    if (err) return q.reject(err)
    q.resolve(path)
  })
  return q.promise
}

function successMessage(icon, path) {
  console.info(colors.green('OK'), 'Image resized to', icon.width, 'x', icon.width, 'and written to', path)
}

function errorMessage(e) {
  var message = 'string' === typeof e ? e : (e.msg || e.message)
  console.error(colors.red('ERROR.'), message)
}

function transformAll(icons, output, image) {
  return Q.all(icons
    .map(transform.bind(null, image, output))
  )
}

function transform(image, output, icon) {
  var out = path.join(output, icon.name)
  return clone(image)
    .then(resize.bind(null, icon))
    .then(writeFile.bind(null, out))
    .then(successMessage.bind(null, icon))
    .catch(errorMessage)
}

module.exports = function(input, output) {
  if (!input) {
    errorMessage(new Error('`input` parameter is required.'))
  }
  output = output || process.cwd()
  return openImage(input).then(transformAll.bind(null, icons(), output))
}

@@ -276,28 +276,17 @@
 r)%0A    %7D
- else %7B%0A    
+%0A
     q.re
@@ -298,22 +298,16 @@
 (image)%0A
-    %7D%0A
   %7D)%0A  r
@@ -450,18 +450,9 @@
    %7D
- else %7B%0A  
+%0A
     
@@ -468,22 +468,16 @@
 (clone)%0A
-    %7D%0A
   %7D)%0A  r
@@ -886,16 +886,24 @@
 ge(icon,
+ output,
  path) %7B
@@ -905,16 +905,23 @@
 th) %7B%0A  
+return 
 console.
@@ -1336,16 +1336,25 @@
 ar out =
+ output ?
  path.jo
@@ -1374,16 +1374,24 @@
 on.name)
+ : false
 %0A  retur
@@ -1509,32 +1509,40 @@
 .bind(null, icon
+, output
 ))%0A    .catch(er
@@ -1683,16 +1683,20 @@
 )%0A  %7D%0A  
+var 
 output =

cleaner code