Fix some bugs, rearrange some code and make formatting work