Fix bugs and clean up code