Template tested, (possibly) ready for use.

Fixed buffer over-read by 1.
Fixed reporting free space as 0 when buffer empty.