Removed self categories and added loop check to query.