Major refactor

The earlier code was ignoring Ruby's internal IO buffering.