code optimization and bug fix