Fix errors and clean up code