This code could probably be simplified using our buffer library.