def modify_segment_num(df):
    """
    modify_segment_num(df)

    Modifies stimulus segment numbers for the Gabors and visual flow if they 
    repeat.

    Arguments:
        df (pandas): stimulus table

    Returns:
        df (pandas): stimulus table, with updated stimulus segment numbers.
    """

    df = df.copy()

    df = df.sort_values("start_frame_twop").reset_index(drop=True)
    df = df.reset_index()

    stimulus_types = ["gabors", "visflow"]
    for stimulus in stimulus_types:
        stimulus_location = df["stimulus_type"] == stimulus
        stimulus_df_start_idx = df.loc[
            stimulus_location & (df["orig_stimulus_segment"] == 0), "index"
        ].tolist() + [len(df)]
        add_segment_num = 0
        for i in range(len(stimulus_df_start_idx[:-1])):
            sub_stimulus_location = stimulus_location & df["index"].isin(
                range(stimulus_df_start_idx[i], stimulus_df_start_idx[i + 1])
            )
            df.loc[
                sub_stimulus_location, "orig_stimulus_segment"
                ] += add_segment_num
            add_segment_num = (
                df.loc[
                    sub_stimulus_location, "orig_stimulus_segment"
                    ].max() + 1
            )

    df = df.drop(columns=["index"])

    return df