added comments and cleaned up algo code