Refactor string functions, fix many defects.

No, we rely on the fact that m_state is an enum and the compiler will complain if we introduce another enum value. 

enumeration value 'X' not handled in switch