Rearrange code and rename some functions