<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_state_as(target_state_m, state, as_template, keep_name=False):
 """ Substitute a target state with a handed state The method generates a state model for the state to be inserted and use function substitute_state to finally substitute the state. In case the state to be inserted is a LibraryState it can be chosen to be inserted as template. It can be chosen that the inserted state keeps the name of the target state. :param rafcon.gui.models.state.AbstractStateModel target_state_m: State model of the state to be substituted :param rafcon.core.states.State state: State to be inserted :param bool as_template: The flag determines if a handed state of type LibraryState is insert as template :param bool keep_name: The flag to keep the name of the target state :return: """


    state_m = get_state_model_class_for_state(state)(state)
    # If inserted as template, we have to extract the state_copy and model otherwise keep original name
    if as_template:
        assert isinstance(state_m, LibraryStateModel)
        state_m = state_m.state_copy
        state_m.state.parent = None

    if keep_name:
        state_m.state.name = target_state_m.state.name

    assert target_state_m.parent.states[target_state_m.state.state_id] is target_state_m
    substitute_state(target_state_m, state_m, as_template)