Major code refactor