Some refactor to make pg code simpler