refactored IO stuff for better testability and clearer structure