rearrange main loop to fix GL_INVALID_OPERATION