Fix an infinite loop issue and cleaned up a bunch of code, thanks @Rohansi