Bug fix, some more code cleanup