Cleanup and reordering of logic