extracted logic out of main
I think I've got all the memory leaks plugged now