Useful function. Well done.
I would like to point out, though, that by copying and pasting the code for your function into SSMS, I got a bunch of bogus error messages when trying to execute it.
After a couple of minutes of testing, I realized there must be some hidden characters in it. After retyping your code into a new query window it worked fine.
May I suggest using the SQL Prettifier when submitting code: http://www.simple-talk.com/prettifier
Ciao for now,