simplify code and fix bug