Fix bugs and simplify code