Massive refactor, hopefully fixed some crashes.