Revised version, estimating buffer sizes on both input and output for stability