Simplify code and fix a bug