Maybe put this distinct in for all queries, e.g. put it on line 410?  That way it will be more obvious what's going on here.