Fix closing of buffers and add some debug output.