Refactor min/max functions