Refactor to use pthreads & proper state machine.  Clean up style, fix al...

This fixes various robustness problems described with this program.