Fixed a bug and cleaned up code