def check_perm_cycles(perm, operation):
    """
    This function checks the cycles in a given permutation according to the provided operation order and type.
    It counts the legal and illegal cycles in the permutation
    :param perm:
    :param op_order: 
    :param op_type: 
    :return: the number of illegal cycles, the number of molecules in illegal cycles, a dictionary of cycle lengths-
    with key =length cycle, val= mnumber of cycles of that length, and an array of the indices in bad cycles
    """
    op_order = operation.order
    op_type = operation.type
    checked = [False] * len(perm)
    num_molecules_in_bad_cycles = 0
    num_good_cycles = 0
    num_bad_cycles = 0
    cycle_counts = {}
    indices_in_bad_cycles = []
    for i, index in enumerate(perm):
        if checked[i]:
            continue
        checked[i] = True
        cycle = [index]
        while not checked[index]:
            checked[index] = True
            index = perm[index]
            cycle.append(index)
        cycle_len = len(cycle)
        if cycle_len in cycle_counts:
            cycle_counts[cycle_len] += 1
        else:
            cycle_counts[cycle_len] = 1
        if (cycle_len == 1 or cycle_len == op_order or cycle_len == 2 and 
            op_type == 'SN'):
            num_good_cycles += 1
        else:
            num_molecules_in_bad_cycles += cycle_len
            num_bad_cycles += 1
            indices_in_bad_cycles += cycle
    return (num_bad_cycles, num_molecules_in_bad_cycles, cycle_counts,
        indices_in_bad_cycles)
