Move definitions near their usage.

This is makes it easier to refer and read the code.
More code rearrangements