Needs to be refactored, but it works.