fix typos, rearrange some code