Fixed resource leaks, ensured consistent buffering