reworked and cleaned up the code