Deduplicate code and use stdlib in string functions

Also fixes some typos, compares strings in-place instead of copying a substr, and fixes style issues.
You missed the second "tocheck" ;)