Rearrange code, fix endif