Code optimization and bug fixes