Based on a Stack Overflow Question with some edits.

For the usage look at http://pastebin.com/uTQN20By
