Code cleanup and fixed a potential bug.