Refactored a little and added handling of limit in query.