I have tried to comment the script as good as possible. Explanation for some parts of the script can be found at the page the base for this script originates from. Feel free to ask questions, if something is not understandable.