updated the code for you - working based on the test i did
usage in comments at the top, hope it helps