public int read(byte[] output, int maxReadLength)
    {
        // Make sure there are enough bytes to read, if not then pause until there are.
        // Note: we don't have to worry about bytes in the middle of the range being false and reading those by accident
        // The loop that reads bytes (see the synchronized section below) will only read until the next 'true'
        while (finished != true && writeRecord[(bufferReadPosition + maxReadLength) % bufferSize] != true)
        {
            log.debug("Buffer - read waiting: " + streamReadPosition);
            try
            {
                Thread.sleep(200);
            }
            catch (InterruptedException e)
            {}
        }
 
        int counter = 0;
        synchronized (this)
        {
            // For all of the bytes that we are about to read, mark them as now free for writing in the buffer
            int startPos = bufferReadPosition;
            for(counter = 0; counter < maxReadLength && writeRecord[bufferReadPosition] == true; counter++)
            {                
                writeRecord[bufferReadPosition] = false;
                bufferReadPosition += 1;
                if (bufferReadPosition >= bufferSize)
                    bufferReadPosition = 0;                
            }
            
            // Get as many bytes as are ready and read them into the output buffer
            if (startPos + counter >= bufferSize)
            {
                // If the bytes we read goes over the end of the buffer then we need to split the
                // array copy into two to handle the wrap around
                int bytesToEnd = bufferSize - startPos;
                System.arraycopy(buffer, startPos, output, 0, bytesToEnd);
                System.arraycopy(buffer, 0, output, bytesToEnd, counter - bytesToEnd);
            }
            else
            {
                System.arraycopy(buffer, startPos, output, 0, counter);
            }
            
            streamReadPosition += counter;
        }
        return counter;
    }