def get_fw_by_task_index(wf, task_tag, index=1):
    """
    Given a workflow object (with connection to the db) returns the wf corresponding to the task_type.

    Args:
        wf: a fireworks Workflow object.
        task_tag: the task tag associated with the task as defined in abinit_workflows. Should not include the index.
        index: the numerical or text index of the task. If negative the the last fw corresponding to task_tag will
            be selected. If None, no index will be considered and the first match will be returned.

    Returns:
        a fireworks Firework object. None if no match is found.
    """
    task_index = None
    if index is not None and index >= 0:
        task_index = "{}_{}".format(task_tag, index)

    selected_fw = None
    max_ind = -1
    for fw in wf.fws:
        fw_task_index = fw.spec.get('wf_task_index', '')
        if task_index:
            if fw_task_index == task_index:
                return fw
        else:
            if task_tag in fw_task_index:
                if index is None:
                    return fw
                # the last part of the task_index can be text (i.e. "autoparal") so the conversion to int may fail
                # if no other indices has been found select that one
                try:
                    fw_ind = int(fw_task_index.split('_')[-1])
                    if fw_ind > max_ind:
                        selected_fw = fw
                        max_ind = fw_ind
                except Exception:
                    if selected_fw is None:
                        selected_fw = fw

    return selected_fw