major refactor to reduce duplicate code