Revamping from sort-of-pseudocode to actual code. Separating out itno several functions.