Fixed some of the code, rearranged a bit