fix bug and simplify logic