Major code refactor and cleanup