Rearrange and simplify code