modified code to use buffer