def hysteresis_magic2(path_to_file='.', hyst_file="rmag_hysteresis.txt",
                      save=False, save_folder='.',
                      fmt="svg", plots=True):
    """
    Calculates hysteresis parameters, saves them in rmag_hysteresis format file.
    If selected, this function also plots hysteresis loops, delta M curves,
    d (Delta M)/dB curves, and IRM backfield curves.

    Parameters (defaults are used if not specified)
    ----------
    path_to_file : path to directory that contains files (default is current directory, '.')
    hyst_file : hysteresis file (default is 'rmag_hysteresis.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 'pdf')
    plots: whether or not to display the plots (default is true)
    """
    user, meas_file, rmag_out, rmag_file = "", "agm_measurements.txt", "rmag_hysteresis.txt", ""
    pltspec = ""
    dir_path = save_folder
    verbose = pmagplotlib.verbose
    version_num = pmag.get_version()
    rmag_out = save_folder + '/' + rmag_out
    meas_file = path_to_file + '/' + hyst_file
    rmag_rem = save_folder + "/rmag_remanence.txt"
    #
    #
    meas_data, file_type = pmag.magic_read(meas_file)
    if file_type != 'magic_measurements':
        print(hysteresis_magic.__doc__)
        print('bad file')
        return

    # initialize some variables
    # define figure numbers for hyst,deltaM,DdeltaM curves
    HystRecs, RemRecs = [], []
    HDD = {}
    HDD['hyst'], HDD['deltaM'], HDD['DdeltaM'] = 1, 2, 3
    experiment_names, sids = [], []
    for rec in meas_data:
        meths = rec['magic_method_codes'].split(':')
        methods = []
        for meth in meths:
            methods.append(meth.strip())
        if 'LP-HYS' in methods:
            if 'er_synthetic_name' in list(rec.keys()) and rec['er_synthetic_name'] != "":
                rec['er_specimen_name'] = rec['er_synthetic_name']
            if rec['magic_experiment_name'] not in experiment_names:
                experiment_names.append(rec['magic_experiment_name'])
            if rec['er_specimen_name'] not in sids:
                sids.append(rec['er_specimen_name'])
    #
    fignum = 1
    sample_num = 0
    # initialize variables to record some bulk info in first loop
    first_dcd_rec, first_rec, first_imag_rec = 1, 1, 1
    while sample_num < len(sids):
        sample = sids[sample_num]
        print(sample, sample_num + 1, 'out of ', len(sids))
        # B,M for hysteresis, Bdcd,Mdcd for irm-dcd data
        B, M, Bdcd, Mdcd = [], [], [], []
        Bimag, Mimag = [], []  # Bimag,Mimag for initial magnetization curves
        for rec in meas_data:
            methcodes = rec['magic_method_codes'].split(':')
            meths = []
            for meth in methcodes:
                meths.append(meth.strip())
            if rec['er_specimen_name'] == sample and "LP-HYS" in meths:
                B.append(float(rec['measurement_lab_field_dc']))
                M.append(float(rec['measurement_magn_moment']))
                if first_rec == 1:
                    e = rec['magic_experiment_name']
                    HystRec = {}
                    first_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        HystRec["er_location_name"] = rec["er_location_name"]
                        locname = rec['er_location_name'].replace('/', '-')
                    if "er_sample_name" in list(rec.keys()):
                        HystRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        HystRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        HystRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        HystRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == sample and "LP-IRM-DCD" in meths:
                Bdcd.append(float(rec['treatment_dc_field']))
                Mdcd.append(float(rec['measurement_magn_moment']))
                if first_dcd_rec == 1:
                    RemRec = {}
                    irm_exp = rec['magic_experiment_name']
                    first_dcd_rec = 0
                    if "er_location_name" in list(rec.keys()):
                        RemRec["er_location_name"] = rec["er_location_name"]
                    if "er_sample_name" in list(rec.keys()):
                        RemRec["er_sample_name"] = rec["er_sample_name"]
                    if "er_site_name" in list(rec.keys()):
                        RemRec["er_site_name"] = rec["er_site_name"]
                    if "er_synthetic_name" in list(rec.keys()) and rec['er_synthetic_name'] != "":
                        RemRec["er_synthetic_name"] = rec["er_synthetic_name"]
                    else:
                        RemRec["er_specimen_name"] = rec["er_specimen_name"]
            if rec['er_specimen_name'] == sample and "LP-IMAG" in meths:
                if first_imag_rec == 1:
                    imag_exp = rec['magic_experiment_name']
                    first_imag_rec = 0
                Bimag.append(float(rec['measurement_lab_field_dc']))
                Mimag.append(float(rec['measurement_magn_moment']))
        if len(B) > 0:
            hmeths = []
            for meth in meths:
                hmeths.append(meth)
    #         fignum = 1
            fig = plt.figure(figsize=(8, 8))
            hpars, deltaM, Bdm, B, Mnorm, MadjN = iplot_hys(1, B, M, sample)
            ax1 = fig.add_subplot(2, 2, 1)
            ax1.axhline(0, color='k')
            ax1.axvline(0, color='k')
            ax1.plot(B, Mnorm, 'r')
            ax1.plot(B, MadjN, 'b')
            ax1.set_xlabel('B (T)')
            ax1.set_ylabel("M/Msat")
    #         ax1.set_title(sample)
            ax1.set_xlim(-1, 1)
            ax1.set_ylim(-1, 1)
            bounds = ax1.axis()
            n4 = 'Ms: ' + \
                '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2'
            ax1.text(bounds[1] - .9 * bounds[1], -.9, n4, fontsize=9)
            n1 = 'Mr: ' + \
                '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2'
            ax1.text(bounds[1] - .9 * bounds[1], -.7, n1, fontsize=9)
            n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T'
            ax1.text(bounds[1] - .9 * bounds[1], -.5, n2, fontsize=9)
            if 'hysteresis_xhf' in list(hpars.keys()):
                n3 = r'Xhf: ' + \
                    '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3'
                ax1.text(bounds[1] - .9 * bounds[1], -.3, n3, fontsize=9)
    #         plt.subplot(1,2,2)
    #         plt.subplot(1,3,3)
        DdeltaM = []
        Mhalf = ""
        for k in range(2, len(Bdm)):
            # differnential
            DdeltaM.append(
                old_div(abs(deltaM[k] - deltaM[k - 2]), (Bdm[k] - Bdm[k - 2])))
        for k in range(len(deltaM)):
            if old_div(deltaM[k], deltaM[0]) < 0.5:
                Mhalf = k
                break
        try:
            Bhf = Bdm[Mhalf - 1:Mhalf + 1]
            Mhf = deltaM[Mhalf - 1:Mhalf + 1]
            # best fit line through two bounding points
            poly = polyfit(Bhf, Mhf, 1)
            Bcr = old_div((.5 * deltaM[0] - poly[1]), poly[0])
            hpars['hysteresis_bcr'] = '%8.3e' % (Bcr)
            hpars['magic_method_codes'] = "LP-BCR-HDM"
            if HDD['deltaM'] != 0:
                ax2 = fig.add_subplot(2, 2, 2)
                ax2.plot(Bdm, deltaM, 'b')
                ax2.set_xlabel('B (T)')
                ax2.set_ylabel('Delta M')
                linex = [0, Bcr, Bcr]
                liney = [old_div(deltaM[0], 2.), old_div(deltaM[0], 2.), 0]
                ax2.plot(linex, liney, 'r')
    #             ax2.set_title(sample)
                ax3 = fig.add_subplot(2, 2, 3)
                ax3.plot(Bdm[(len(Bdm) - len(DdeltaM)):], DdeltaM, 'b')
                ax3.set_xlabel('B (T)')
                ax3.set_ylabel('d (Delta M)/dB')
    #             ax3.set_title(sample)

                ax4 = fig.add_subplot(2, 2, 4)
                ax4.plot(Bdcd, Mdcd)
                ax4.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
                ax4.axhline(0, color='k')
                ax4.axvline(0, color='k')
                ax4.set_xlabel('B (T)')
                ax4.set_ylabel('M/Mr')
        except:
            print("not doing it")
            hpars['hysteresis_bcr'] = '0'
            hpars['magic_method_codes'] = ""
        plt.gcf()
        plt.gca()
        plt.tight_layout()
        if save:
            plt.savefig(save_folder + '/' + sample + '_hysteresis.' + fmt)
        plt.show()
        sample_num += 1