code reorg into functions and added headers