refactored a bunch into functions, probably only one more left