performance optimisations + fully commented the script