Lots of improvements, code rearrangements