Rewrite g_string_replace() to be simpler and safer

Fixes #9.