refined and cleaned up code