fixed and cleaned up code