Optimzations and code cleanup