finished script (not tested) with comments