reorganized code for easier reading