I cannot express how clean and easily understandable your code was. I liked it so much that i took it as my base code. I added a few more lines and now the function is working perfectly, taking out excess whitespace as well as new lines and horizontal tabs.
Here have a look: