Fix typos and move some lines of code