Several improvements made by @ShelMi http://forum.evilmadscientist.com/discussion/comment/2206#Comment_2206