The calculations used the amount of bytes read instead of amount of bytes available and also read one byte too much.