replaced buffer juggling code at the behest of @naomik