Fixes bug and cleans up code