Major code cleaning and improvements