Cleanup and rearrange some functions