use a for loop rather than complex regex/reversing/replacing
added meaningful error messages
added tests to prove 95388c9 and bba1ebb