Fix bugs and remove unnecessary code