fix bugs and clean up code