Major code cleanup and optimizations: still more todo but much cleaner now