Debugged buffer writing and stream handling. Appears to work well.