Refactor and rearrange code