Rearrange code and make it more clean