more or less major rewrite of the script. pity i'm such a JS noob