refactored this monster, thank you GLM