VERY EXPERIENTAL rework of SQL code VERY BUGGY DO NOT USE ON PRODUCTION SERVER