#!/usr/bin/env ruby
# extracts the embedded PNG data from .skitch SVG files

require 'nokogiri'
require 'base64'

IMAGE_HEADER = "data:image/png;base64,"

ARGV.each do |filename|
  svg_document = Nokogiri::XML(File.open(filename))

  # get rid of the namespaces, facilitates the xpath search
  svg_document.remove_namespaces!

  # retrieve the href attribute that contains the image data
  image_attribute = svg_document.xpath("//image/@href")[0]

  # remove the header
  image_data = image_attribute.value.slice(IMAGE_HEADER.length..-1)

  png_filename = filename.gsub(/(.*)(\.skitch)/,'\1.png')
  File.write(png_filename, Base64.decode64(image_data))
end