started pulling functions around to get a clearer separation of responsibilities