cleaned up the code

corrected poor style in previous version and cleaned up control flow