Bug fix and code clean up