Refactored code, also improved es_query