This var marked as static was causing various buffer issues and wasn't reentrant.  The rest of the changes in this function are to make buffer work as a local variable.