move code into functions (still more work to do, but test this much now)