use events; split out server loop; other small improvements; litter code with comments