def ps_collate(module, ps_data, result):
    """Collate PS output data

    Given Process Show data (ps_data), collate results according to
    module.parameters.

    These module parameters affect the results returned:

      * module.params['sort_key']: (e.g, "%CPU")
      * module.params['reverse']: Boolean to reverse sort (e.g., True)
      * module.params['number_of_results']: How many results to return

    Note: `result` is passed into function so more data is available in
          output if a module.exit_json is requred.
    """
    headers = ps_data.pop(0)
    ps_data = [dict(zip(headers, row)) for row in ps_data if row]

    if module.params['sort_key'] in headers:
        ps_data = sorted(ps_data,
                         key=lambda k: k[module.params['sort_key']],
                         reverse=module.params['reverse'])
        ps_data = ps_data[:module.params['number_of_results']]
    else:
        module.fail_json(msg='Sort key %s is not in ps headers: %s' % (
            module.params['sort_key'], headers))
        module.exit_json(**result)

    return ps_data