clean up and demystify the regex code somewhat