def demag_magic(path_to_file='.', file_name='magic_measurements.txt',
                save=False, save_folder='.', fmt='svg', plot_by='loc',
                treat=None, XLP="", individual=None, average_measurements=False,
                single_plot=False):
    '''
    Takes demagnetization data (from magic_measurements file) and outputs
    intensity plots (with optional save).

    Parameters
    -----------
    path_to_file : path to directory that contains files (default is current directory, '.')
    file_name : name of measurements file (default is 'magic_measurements.txt')
    save : boolean argument to save plots (default is False)
    save_folder : relative directory where plots will be saved (default is current directory, '.')
    fmt : format of saved figures (default is 'svg')
    plot_by : specifies what sampling level you wish to plot the data at
        ('loc' -- plots all samples of the same location on the same plot
        'exp' -- plots all samples of the same expedition on the same plot
        'site' -- plots all samples of the same site on the same plot
        'sample' -- plots all measurements of the same sample on the same plot
        'spc' -- plots each specimen individually)
    treat : treatment step
        'T' = thermal demagnetization
        'AF' = alternating field demagnetization
        'M' = microwave radiation demagnetization
        (default is 'AF')
    XLP : filter data by a particular method
    individual : This function outputs all plots by default. If plotting by sample
        or specimen, you may not wish to see (or wait for) every single plot. You can
        therefore specify a particular plot by setting this keyword argument to
        a string of the site/sample/specimen name.
    average_measurements : Option to average demagnetization measurements by
        the grouping specified with the 'plot_by' keyword argument (default is False)
    single_plot : Option to output a single plot with all measurements (default is False)
    '''

    FIG = {}  # plot dictionary
    FIG['demag'] = 1  # demag is figure 1
    in_file, plot_key, LT = os.path.join(
        path_to_file, file_name), 'er_location_name', "LT-AF-Z"
    XLP = ""
    norm = 1
    units, dmag_key = 'T', 'treatment_ac_field'
    plot_num = 0

    if plot_by == 'loc':
        plot_key = 'er_location_name'
    elif plot_by == 'exp':
        plot_key = 'er_expedition_name'
    elif plot_by == 'site':
        plot_key = 'er_site_name'
    elif plot_by == 'sam':
        plot_key = 'er_sample_name'
    elif plot_by == 'spc':
        plot_key = 'er_specimen_name'

    if treat != None:
        LT = 'LT-' + treat + '-Z'  # get lab treatment for plotting
        if LT == 'LT-T-Z':
            units, dmag_key = 'K', 'treatment_temp'
        elif LT == 'LT-AF-Z':
            units, dmag_key = 'T', 'treatment_ac_field'
        elif LT == 'LT-M-Z':
            units, dmag_key = 'J', 'treatment_mw_energy'
        else:
            units = 'U'
    else:
        LT = 'LT-AF-Z'

    plot_dict = {}
    data, file_type = pmag.magic_read(in_file)
    sids = pmag.get_specs(data)
    plt.figure(num=FIG['demag'], figsize=(5, 5))
    print(len(data), ' records read from ', in_file)
    #
    #
    # find desired intensity data
    #
    # get plotlist
    #
    plotlist, intlist = [], ['measurement_magnitude', 'measurement_magn_moment',
                             'measurement_magn_volume', 'measurement_magn_mass']
    IntMeths = []
    FixData = []
    for rec in data:
        meths = []
        methcodes = rec['magic_method_codes'].split(':')
        for meth in methcodes:
            meths.append(meth.strip())
        for key in list(rec.keys()):
            if key in intlist and rec[key] != "":
                if key not in IntMeths:
                    IntMeths.append(key)
                if rec[plot_key] not in plotlist and LT in meths:
                    plotlist.append(rec[plot_key])
                if 'measurement_flag' not in list(rec.keys()):
                    rec['measurement_flag'] = 'g'
                FixData.append(rec)
        plotlist.sort()
    if len(IntMeths) == 0:
        print('No intensity information found')
    data = FixData
    # plot first intensity method found - normalized to initial value anyway -
    # doesn't matter which used
    int_key = IntMeths[0]
    # print plotlist
    if individual is not None:
        if type(individual) == list or type(individual) == tuple:
            plotlist = list(individual)
        else:
            plotlist = []
            plotlist.append(individual)
    for plot in plotlist:
        print(plot, 'plotting by: ', plot_key)
        # fish out all the data for this type of plot
        PLTblock = pmag.get_dictitem(data, plot_key, plot, 'T')
        # fish out all the dmag for this experiment type
        PLTblock = pmag.get_dictitem(PLTblock, 'magic_method_codes', LT, 'has')
        # get all with this intensity key non-blank
        PLTblock = pmag.get_dictitem(PLTblock, int_key, '', 'F')
        if XLP != "":
            # reject data with XLP in method_code
            PLTblock = pmag.get_dictitem(
                PLTblock, 'magic_method_codes', XLP, 'not')
    # for plot in plotlist:
        if len(PLTblock) > 2:
            title = PLTblock[0][plot_key]
            spcs = []
            for rec in PLTblock:
                if rec['er_specimen_name'] not in spcs:
                    spcs.append(rec['er_specimen_name'])
            if average_measurements is False:
                for spc in spcs:
                    # plot specimen by specimen
                    SPCblock = pmag.get_dictitem(
                        PLTblock, 'er_specimen_name', spc, 'T')
                    INTblock = []
                    for rec in SPCblock:
                        INTblock.append([float(rec[dmag_key]), 0, 0, float(
                            rec[int_key]), 1, rec['measurement_flag']])
                    if len(INTblock) > 2:
                        pmagplotlib.plot_mag(
                            FIG['demag'], INTblock, title, 0, units, norm)
            else:
                AVGblock = {}
                for spc in spcs:
                    # plot specimen by specimen
                    SPCblock = pmag.get_dictitem(
                        PLTblock, 'er_specimen_name', spc, 'T')
                    for rec in SPCblock:
                        if rec['measurement_flag'] == 'g':
                            if float(rec[dmag_key]) not in list(AVGblock.keys()):
                                AVGblock[float(rec[dmag_key])] = [
                                    float(rec[int_key])]
                            else:
                                AVGblock[float(rec[dmag_key])].append(
                                    float(rec[int_key]))
                INTblock = []
                for step in sorted(AVGblock.keys()):
                    INTblock.append([float(step), 0, 0, old_div(
                        float(sum(AVGblock[step])), float(len(AVGblock[step]))), 1, 'g'])
                pmagplotlib.plot_mag(FIG['demag'], INTblock,
                                     title, 0, units, norm)
        if save == True:
            plt.savefig(os.path.join(save_folder, title) + '.' + fmt)
        if single_plot is False:
            plt.show()
    if single_plot is True:
        plt.show()
Takes demagnetization data (from magic_measurements file) and outputs
    intensity plots (with optional save).

    Parameters
    -----------
    path_to_file : path to directory that contains files (default is current directory, '.')
    file_name : name of measurements file (default is 'magic_measurements.txt')
    save : boolean argument to save plots (default is False)
    save_folder : relative directory where plots will be saved (default is current directory, '.')
    fmt : format of saved figures (default is 'svg')
    plot_by : specifies what sampling level you wish to plot the data at
        ('loc' -- plots all samples of the same location on the same plot
        'exp' -- plots all samples of the same expedition on the same plot
        'site' -- plots all samples of the same site on the same plot
        'sample' -- plots all measurements of the same sample on the same plot
        'spc' -- plots each specimen individually)
    treat : treatment step
        'T' = thermal demagnetization
        'AF' = alternating field demagnetization
        'M' = microwave radiation demagnetization
        (default is 'AF')
    XLP : filter data by a particular method
    individual : This function outputs all plots by default. If plotting by sample
        or specimen, you may not wish to see (or wait for) every single plot. You can
        therefore specify a particular plot by setting this keyword argument to
        a string of the site/sample/specimen name.
    average_measurements : Option to average demagnetization measurements by
        the grouping specified with the 'plot_by' keyword argument (default is False)
    single_plot : Option to output a single plot with all measurements (default is False)