Tested, but needs to be optimized - SQL commands can be combined
to make it ~4 times faster. Still lot of extra comments that should
be removed.