this function seems massive, can it be refactored into several smaller functions?