cleaned up code and reworked logic; needs testing