reorganizing code to clarify logic