Thanks for your help so far. I will do quite many changes to the script once I get it fully working like this. It's much easier to add functionalities when I can also test it.
I got the script working with your example. However I still cannot quite get what was wrong with my original output even though I went through the doc alterego posted.