Refactor and simplify code