fix up logic and clean up code