Major cleanup. Some functions do not belong here