changed code to have less shared state and be more testable