added a new state variable, readpos, to keep track of what has been read out of the buffer and what hasn't