Solution to http://pastebin.com/gg1T8AHP