re-organize and simplify code