def save_results(results, path, task=None, top_n_nodes=30, perm=-1):
    import networkx as nx
    from matplotlib import pyplot as plt
    coords = np.loadtxt("../hcp-suite/data/parcellations/RenTianGlasser.coords")
    labels = load_list_from_file("../hcp-suite/data/parcellations/RenTianGlasser.labels")
    names = load_list_from_file("../hcp-suite/data/parcellations/RenTianGlasser.names")
    cmap = 'gist_ncar'
    colorbar = False

    safesave(results, os.path.join(path, "{}-results".format(task)))

    # Plot predictions and save them as separate files
    g = plot_predictions(results['prediction_results'][perm], tail="glm", color="green")
    g.get_figure().savefig(os.path.join(path, "{}-predictions_glm.svg".format(task)))
    g.clear()
    g = plot_predictions(results['prediction_results'][perm], tail="pos", color="red")
    g.get_figure().savefig(os.path.join(path, "{}-predictions_pos.svg".format(task)))
    g.clear()
    g = plot_predictions(results['prediction_results'][perm], tail="neg", color="blue")
    g.get_figure().savefig(os.path.join(path, "{}-predictions_neg.svg".format(task)))
    g.clear()
    plt.close('all')

    masks = get_suprathr_edges_new(results['fselection_results'][perm], top_n_pos=100, top_n_neg=100)
    m_cons = {}
    m_cons['pos'] = get_consistent_edges(masks, "pos", coords=coords, color='red', thresh=1, title="{}, positive".format(task), output_file=os.path.join(path, "{}-connectome_pos.svg".format(task)))
    m_cons['neg'] = get_consistent_edges(masks, "neg", coords=coords, color='blue', thresh=1, title="{}, negative".format(task), output_file=os.path.join(path, "{}-connectome_neg.svg".format(task)))

    r_mat, p_mat = pcorr_dfs_to_rmat_pmat(results['fselection_results'][perm])
    color = 'red'
    for tail, m in m_cons.items():
        reduced_dict = reduce_matrix_by_threshold(m[0], coords=coords)
        if tail == 'neg':
            reduced_dict['reduced_matrix'] = reduced_dict['reduced_matrix'] * -1
        webconnectome = plotting.view_connectome(reduced_dict['reduced_matrix'], reduced_dict['reduced_coords'], symmetric_cmap=False, colorbar=False)
        webconnectome.save_as_html(os.path.join(path, "{}-connectome_{}.html".format(task, tail)))

        m_cons_r = m[0] * r_mat
        m_cons_r_mean = np.mean(m_cons_r, axis=0)
        if tail == 'neg':
            color = 'blue'
        figures = plot_top_n_edges(m_cons_r_mean, 20, img_base="../RTG_thumbnails/", labels=labels, check_for_symmetry=False, color=color)
        for n in range(len(figures)):
            fname=os.path.join(path, "{}-top_{}_{}".format(task, tail, str(n).zfill(2)))
            figures[n].savefig(fname, bbox_inches='tight')
        plt.close('all')

    degrees_sorted, G = get_top_n_nodes(results, None, labels=labels, names=names, coords=coords)
    img_dict = {}
    for tail_name, tail_data in degrees_sorted.items():
        figures_dict, viewer, img = plot_nodes(degrees_sorted[tail_name], "../hcp-suite/data/parcellations/RenTianGlasser_MNI.nii.gz", None, n_slices=6)
            img_dict[tail_name] = img
            nib.save(img, os.path.join(path, "{}-weighted_nodes_{}.nii.gz".format(task, tail_name)))
            split_nodes = {}
            split_nodes['noncerebellar_nodes'] = tail_data[tail_data['Node'] > 99]
            split_nodes['cerebellar_nodes'] = tail_data[tail_data['Node'] < 100]


            for region, nodes in split_nodes.items():
                if region == 'cerebellar_nodes':
                    if tail_name == 'pos': top_n_nodes = 12
                        if tail_name == 'neg': top_n_nodes = 8
                    if region == 'noncerebellar_nodes':
                        if tail_name == 'pos': top_n_nodes = 47
                            if tail_name == 'neg': top_n_nodes = 41
                            else:
                                top_n_nodes = 30
                    for plot_degree in [False, True]:
                        if plot_degree:
                            if tail_name == 'pos':
                                cmap = 'hot'
                                    if tail_name == 'neg': cmap = 'cool'
                                    colorbar=True
                                    tail_name += '-degree'
                            else:
                                colorbar = False
                                    tail_name = tail_name.replace('-degree', '')
                                    cmap = 'gist_ncar'
                            figures_dict, viewer, img = plot_nodes(nodes[0:top_n_nodes], "../hcp-suite/data/parcellations/RenTianGlasser_MNI.nii.gz", "../MNI152_T1_0.5mm_brain.nii.gz", n_slices=6, plot_degree=plot_degree, colorbar=colorbar, cmap=cmap)
                            plt.close('all')
                            for view, figure in figures_dict.items():
                                safesave(figure, os.path.join(path, "{}-top_{}_{}_{}".format(task, region, tail_name, view)))


                            nodes[0:top_n_nodes].to_markdown(buf=os.path.join(path, "{}-top_{}_{}-table.md".format(task, region, tail_name)), index=False)
                            if not plot_degree:
                                nodes.to_csv(os.path.join(path, "{}-{}_{}-table.csv".format(task, region, tail_name)))
                            viewer.save_as_html(os.path.join(path, "{}-top_{}_{}-viewer.html".format(task, region, tail_name)))
                            s = add_color_to_nodes_table(nodes[0:top_n_nodes], cmap=cmap)
                            s.to_html(buf=os.path.join(path, "{}-top_{}_{}-table.html".format(task, region, tail_name)))
                            s.to_latex(buf=os.path.join(path, "{}-top_{}_{}-table.tex".format(task, region, tail_name)))

    plt.close('all')
    plot, min_value, max_value, count, min_p = plot_permutation_results(results['prediction_results'])
    safesave(plot, os.path.join(path, "{}-permutations".format(task)))
    plt.close('all')

    return img_dict


#####################################################################
## Example code for overlap plots and corresponding colored tables ##
#####################################################################
perm = -1
for behav in ['CardSort_AgeAdj', 'Flanker_AgeAdj', 'DDisc_AUC_200', 'DDisc_AUC_40K', 'PMAT24_A_CR', 'WM_Task_2bk_Acc']:
    overlap, degrees_sorted, top_n_edges, plot_dict, m_cons = get_overlap([results['BMI'], results[behav]], odd_one_out=0, coords=coords, plot_top_nodes=True, top_n_edges=50)
        dir = "./results_overlap_with_tex/{}".format(behav)
        os.system("mkdir -p {}".format(dir))

        safesave(overlap, "{}/Overlap_{}-overlap".format(dir, behav))
        for tail in ['pos', 'neg']:
            split_nodes = {}
                split_nodes['noncerebellar_nodes'] = degrees_sorted[tail][degrees_sorted[tail]['Node'] > 99]
                split_nodes['cerebellar_nodes'] = degrees_sorted[tail][degrees_sorted[tail]['Node'] < 100]


                # Nodes
                nib.save(plot_dict[tail]['nodes_img'], "{}/Overlap_{}-weighted_nodes_{}.nii.gz".format(dir, behav, tail))
                for region in ['cerebellar', 'noncerebellar']:
                    plot_n_nodes = 50
                        if region == 'cerebellar':
                            plot_n_nodes = 20
                        for view, figure in plot_dict[tail]['{}_nodes'.format(region)].items():
                            safesave(figure, "{}/Overlap_{}-top_{}_nodes_{}_{}".format(dir, behav, region, tail, view))
                        plot_dict[tail]['{}_nodes_viewer'.format(region)].save_as_html("{}/Overlap_{}-top_{}_nodes_{}-viewer.html".format(dir, behav, region, tail))

                        # Tables
                        s = add_color_to_nodes_table(split_nodes['{}_nodes'.format(region)][0:plot_n_nodes])
                        s.to_html("{}/Overlap_{}-top_{}_nodes_{}-table.html".format(dir, behav, region, tail))
                        s.to_latex("{}/Overlap_{}-top_{}_nodes_{}-table.tex".format(dir, behav, region, tail))
                        split_nodes['{}_nodes'.format(region)][0:50].to_markdown(buf="{}/Overlap_{}-top_{}_nodes_{}-table.md".format(dir, behav, region, tail))

                # Connectome
                plot_dict[tail]['connectome'].savefig("{}/Overlap_{}-connectome_all_{}.svg".format(dir, behav, tail))
                plot_dict[tail]['top_n_edges'].savefig("{}/Overlap_{}-connectome_{}.svg".format(dir, behav, tail))
                plot_dict[tail]['connectome_viewer'].save_as_html("{}/Overlap_{}-connectome_{}.html".format(dir, behav, tail))
                plt.close('all')
        plt.close('all')
