Fixes a few bugs/cleans up code a bit