Code optimization and minor fixes