major refactor to handle complex cases