Simplify code and fix bugs