refactored the code to be more modular

take out the massive if then from the middle and put that code into separate functions