Two things.
I modified your post to place code tags around the code... making it much easier to read.
Second - when writing a script it really helps to write down exactly what you want to accomplish. Don't leave anything out, or assume anything. Write down exactly what you are trying to do as if you are manually doing it online.
That will help you to understand where you may be missing something, and will really help anyone who wants to relay some assistance to you.