Rearrange code, and some minor changes