Start refactoring mega function. Mostly broken