refactor optgroup generation