wow, holy levels of nesting :P

This really needs to be refactored (split out into multiple smaller methods) because currently it's really hard to read / follow it.