this function is massively complex. can we break it up for easier readability?