switch from prints to logging.debug. Also refactor some duplicate code