Code refactoring to reduce code duplication, added support for read-only buffers and various corrections