Code cleanup and bug fix