Global code improvement and bug fix