Heavily refactored version. Cost me 1/1000th of my sanity