So, do you have an actual question? If you have code already, you need to attach the file so that we can see what you are working with. Then, explain what exactly your problem is.
Really the only thing that we can say at this point is: If you don't want to duplicate something in the file the you have to check if it exists first and if it does, don't add it again.