Added sql query to matches, some cleanup and bugfixes