Code clean up and bug fix