Partial code clean up

 * Split into functions
 * Use step-down rule to order declarations

Still needs further work since there is an inconsistent mix of details
and high-level policy within single declarations.