function reordering and code cleanup