General optimization and code cleaning