Refactor string functions, fix many defects.

Shouldn't this move to the format file?