I would structure this code a little differently to make it more readable: https://gist.github.com/lutter/7530139