Added query function, refactoring