Fix bug and clean up code