modified program to write out buffer to file continuously instead of at the end