Rewritten mysql function. Changed some bits. Improved comments