Significantly cleaned up the code. Regained 10 sanity.