def get_Tpermutation_distribution(dat_all, nperm, timeAll, labels):
    time_start = timeAll[0][0]
    time_end = timeAll[-1][1]
    dat = dat_all[:, :,
                  int(time_start * 1000) + 100:int(time_end * 1000) + 100]
    # permuta the data and calculate the largest sumed p values for each permutation across labels
    highest_permutation_values = []
    sign = np.ones((dat.shape[0], ))
    sign[:np.int32(np.round(len(sign) / 2.))] = -1
    for index in range(nperm):  #to permute the conditions
        print("permution: " + str(index))
        sign = np.random.permutation(sign)
        dat_perm = sign * np.transpose(dat, [1, 2, 0])
        stats_perm, pval_perm = ttest_1samp(dat_perm, 0, axis=2)
        stc_perm = SourceEstimate(
            -np.log10(pval_perm),
            vertices=[np.arange(10242), np.arange(10242)],
            tmin=time_start,
            tstep=1 / 1000.,
            subject='fsaverage')
        means_of_thresholded_timewinds_labels = []
        for time1, time2 in timeAll:
            stc_perm_timewind = stc_perm.copy().crop(time1, time2)
            for label in labels:
                label_fname = op.join(
                    '/autofs/cluster/kuperberg/nonconMM/MEG/MNE/250Labels',
                    label + '.label')
                label_name = mne.read_label(label_fname,
                                            subject='fsaverage',
                                            color='r')
                stc_label_perm = stc_perm_timewind.in_label(label_name)
                stc_label_perm = threshold_by_pvalue(stc_label_perm, 2)
                means_of_thresholded_timewinds_labels.append(
                    stc_label_perm.data.mean())
        highest_permutation_values.append(
            max(means_of_thresholded_timewinds_labels))
    return highest_permutation_values