<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def substitute_selected_state(state, as_template=False, keep_name=False):
 """ Substitute the selected state with the handed state :param rafcon.core.states.state.State state: A state of any functional type that derives from State :param bool as_template: The flag determines if a handed the state of type LibraryState is insert as template :return: """

    # print("substitute_selected_state", state, as_template)
    assert isinstance(state, State)
    from rafcon.core.states.barrier_concurrency_state import DeciderState
    if isinstance(state, DeciderState):
        raise ValueError("State of type DeciderState can not be substituted.")

    smm_m = rafcon.gui.singleton.state_machine_manager_model
    if not smm_m.selected_state_machine_id:
        logger.error("Selected state machine can not be found, please select a state within a state machine first.")
        return False

    selection = smm_m.state_machines[smm_m.selected_state_machine_id].selection
    selected_state_m = selection.get_selected_state()
    if len(selection.states) != 1:
        logger.error("Please select exactly one state for the substitution")
        return False
    if is_selection_inside_of_library_state(selected_elements=[selected_state_m]):
        logger.warning("Substitute is not performed because target state is inside of a library state.")
        return

    gui_helper_state.substitute_state_as(selected_state_m, state, as_template, keep_name)

    return True