fixes #5, matching algorithm for Gallery2 similar to Gallery3 (much less SQL queries, simpler to read and maintain)