bug fix and code cleanup