Bug fix and code cleaning