Instruction:
Can you generate the documentation for the following Python 3 function
def mst(infile, spec_name='unknown', dir_path=".", input_dir_path="",
        meas_file="measurements.txt", samp_infile="samples.txt",
        user="", specnum=0, samp_con="1", labfield=0.5,
        location='unknown', syn=False, data_model_num=3):
    """
    Convert MsT data (T,M) to MagIC measurements format files

    Parameters
    ----------
    infile : str
        input file name
    specimen : str
        specimen name, default "unknown"
    dir_path : str
        working directory, default "."
    input_dir_path : str
        input file directory IF different from dir_path, default ""
    meas_file : str
        output measurement file name, default "measurements.txt"
    samp_infile : str
        existing sample infile (not required), default "samples.txt"
    user : str
        user name, default ""
    specnum : int
        number of characters to designate a specimen, default 0
    samp_con : str
        sample/site naming convention, default '1', see info below
    labfield : float
        DC_FIELD in Tesla, default : .5
    location : str
        location name, default "unknown"
    syn : bool
       synthetic, default False
    data_model_num : int
        MagIC data model 2 or 3, default 3

    Returns
    --------
    type - Tuple : (True or False indicating if conversion was sucessful, file name written)

    Info
    --------
    Sample naming convention:
        [1] XXXXY: where XXXX is an arbitrary length site designation and Y
            is the single character sample designation.  e.g., TG001a is the
            first sample from site TG001.    [default]
        [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
        [5] site name = sample name
        [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
        [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY

    """

    # deal with input files
    input_dir_path, dir_path = pmag.fix_directories(input_dir_path, dir_path)
    try:
        infile = pmag.resolve_file_name(infile, input_dir_path)
        with open(infile, 'r') as finput:
            data = finput.readlines()
    except (IOError, FileNotFoundError) as ex:
        print(ex)
        print("bad mag file name")
        return False, "bad mag file name"

    samp_file = pmag.resolve_file_name(samp_infile, input_dir_path)
    if os.path.exists(samp_file):
        Samps, file_type = pmag.magic_read(samp_file)
    else:
        Samps = []

    # parse out samp_con
    if "4" in samp_con:
        if "-" not in samp_con:
            print("option [4] must be in form 4-Z where Z is an integer")
            return False, "option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "4"
    if "7" in samp_con:
        if "-" not in samp_con:
            print("option [7] must be in form 7-Z where Z is an integer")
            return False, "option [7] must be in form 7-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "7"

    # initialize some stuff
    specnum = - int(specnum)
    Z = "0"
    citation = 'This study'
    measnum = 1
    MagRecs, specs = [], []
    version_num = pmag.get_version()

    if data_model_num == 2:
        loc_col = "er_location_name"
        software_col = "magic_software_packages"
        treat_dc_col = "treatment_dc_field"
        meas_temp_col = "measurement_temp"
        meth_codes_col = "magic_method_codes"
        meas_magnitude_col = "measurement_magnitude"
        spec_col = "er_specimen_name"
        samp_col = "er_sample_name"
        site_col = "er_site_name"
        synthetic_name_col = "er_synthetic_name"
        inst_col = "magic_instrument_codes"
        analyst_col = "er_analyst_mail_names"
        citation_col = "er_citation_names"
        quality_col = "measurement_flag"
        meas_name_col = "measurement_number"
        experiment_col = "magic_experiment_name"
        meas_file_type = "magic_measurements"
        if meas_file == "measurements.txt":
            meas_file = "magic_measurements.txt"
    else:
        loc_col = "location"
        software_col = "software_packages"
        treat_dc_col = "treat_dc_field"
        meas_temp_col = "meas_temp"
        meth_codes_col = "method_codes"
        meas_magnitude_col = "magn_uncal"
        spec_col = "specimen"
        samp_col = "sample"
        site_col = "site"
        synthetic_name_col = "specimen"
        inst_col = "instrument_codes"
        analyst_col = "analysts"
        citation_col = "citations"
        quality_col = "quality"
        meas_name_col = "measurement"
        experiment_col = "experiment"
        meas_file_type = "measurements"

    meas_file = pmag.resolve_file_name(meas_file, dir_path)
    dir_path = os.path.split(meas_file)[0]

    T0 = float(data[0].split()[0])
    for line in data:
        instcode = ""
        if len(line) > 1:
            MagRec = {}
            if syn == 0:
                MagRec[loc_col] = location
            MagRec[software_col] = version_num
            MagRec[treat_dc_col] = labfield
            rec = line.split()
            T = float(rec[0])
            MagRec[meas_temp_col] = '%8.3e' % (
                float(rec[0])+273.)  # temp in kelvin
            if T > T0:
                MagRec[meth_codes_col] = 'LP-MW-I'
            elif T < T0:
                MagRec[meth_codes_col] = 'LP-MC-I'
                T0 = T
            elif data.index(line) == 0: # NRM step
                MagRec[meth_codes_col] = "LP-NO"
            else:
                print('skipping repeated temperature step')
                MagRec[meth_codes_col] = ''
            T0 = T
            MagRec[meas_magnitude_col] = '%10.3e' % (
                float(rec[1]))  # uncalibrated magnitude
            if syn == 0:
                MagRec[spec_col] = spec_name
                MagRec[site_col] = ""
                if specnum != 0:
                    MagRec[samp_col] = spec_name[:specnum]
                else:
                    MagRec[samp_col] = spec_name
                if Samps:
                    for samp in Samps:
                        if samp[samp_col] == MagRec[samp_col]:
                            MagRec[loc_col] = samp.get(loc_col, location)
                            MagRec[site_col] = samp[site_col]
                            break
                elif int(samp_con) != 6:
                    site = pmag.parse_site(
                        MagRec[samp_col], samp_con, Z)
                    MagRec[site_col] = site
                if MagRec[site_col] == "":
                    print('No site name found for: ',
                          MagRec[spec_col], MagRec[samp_col])
                if not MagRec[loc_col]:
                    print('no location name for: ', MagRec[spec_col])
            else: # synthetic
                MagRec[loc_col] = ""
                MagRec[samp_col] = ""
                MagRec[site_col] = ""
                MagRec[spec_col] = ""
                MagRec[synthetic_name_col] = spec_name

            MagRec[inst_col] = instcode
            MagRec[analyst_col] = user
            MagRec[citation_col] = citation
            MagRec[quality_col] = 'g'
            MagRec[meas_name_col] = str(measnum)
            if data_model_num == 3:
                MagRec['sequence'] = measnum
            MagRecs.append(MagRec)
            measnum += 1
    new_MagRecs = []
    for rec in MagRecs:  # sort out the measurements by experiment type
        rec[experiment_col] = spec_name
        if rec[meth_codes_col] == 'LP-MW-I':
            rec[experiment_col] = spec_name + ':LP-MW-I:Curie'
        elif rec[meth_codes_col] == 'LP-MC-I':
            rec[experiment_col] = spec_name +':LP-MC-I'
        elif rec[meth_codes_col] == "LP-NO":
            rec[experiment_col] = spec_name + ":LP-NO"
        if data_model_num == 3:
            rec[meas_name_col] = rec[experiment_col] + "_" + rec[meas_name_col]
        new_MagRecs.append(rec)

    pmag.magic_write(meas_file, new_MagRecs, meas_file_type)
    print("results put in ", meas_file)
    # try to extract location/site/sample/specimen info into tables
    con = cb.Contribution(dir_path)
    con.propagate_measurement_info()
    for table in con.tables:
        if table in ['samples', 'sites', 'locations']:
            # add in location name by hand
            if table == 'sites':
                con.tables['sites'].df['location'] = location
            con.write_table_to_file(table)

    return True, meas_file

Response: Convert MsT data to MagIC measurements format files


Instruction:
Can you tell what is the following Python 3 function doing
def pmd(mag_file, dir_path=".", input_dir_path="",
        meas_file="measurements.txt", spec_file='specimens.txt',
        samp_file='samples.txt', site_file="sites.txt", loc_file="locations.txt",
        lat="", lon="", specnum=0, samp_con='1', location="unknown",
        noave=0, meth_code="LP-NO"):
    """
    converts PMD (Enkin)  format files to MagIC format files

    Parameters
    ----------
    mag_file : str
        input file name, required
    dir_path : str
        working directory, default "."
    input_dir_path : str
        input file directory IF different from dir_path, default ""
    spec_file : str
        output specimen file name, default "specimens.txt"
    samp_file: str
        output sample file name, default "samples.txt"
    site_file : str
        output site file name, default "sites.txt"
    loc_file : str
        output location file name, default "locations.txt"
    lat : float or str
        latitude, default ""
    lon : float or str
        longitude, default ""
    specnum : int
        number of characters to designate a specimen, default 0
    samp_con : str
        sample/site naming convention, default '1', see info below
    location : str
        location name, default "unknown"
    noave : bool
       do not average duplicate measurements, default False (so by default, DO average)
    meth_code : str
        default "LP-NO"
        e.g. [SO-MAG, SO-SUN, SO-SIGHT, ...]

    Returns
    ---------
    Tuple : (True or False indicating if conversion was sucessful, file name written)

    Info
    --------
    Sample naming convention:
        [1] XXXXY: where XXXX is an arbitrary length site designation and Y
            is the single character sample designation.  e.g., TG001a is the
            first sample from site TG001.    [default]
        [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
        [5] site name = sample name
        [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
        [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY

    """
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    specnum = - int(specnum)
    samp_con = str(samp_con)
    version_num = pmag.get_version()

    if "4" in samp_con:
        if "-" not in samp_con:
            print(
                "naming convention option [4] must be in form 4-Z where Z is an integer")
            return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "4"
    elif "7" in samp_con:
        if "-" not in samp_con:
            print("option [7] must be in form 7-Z where Z is an integer")
            return False, "naming convention option [7] must be in form 7-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "7"
    else:
        Z = 1

    # format variables
    mag_file = pmag.resolve_file_name(mag_file, input_dir_path)
    meas_file = pmag.resolve_file_name(meas_file, output_dir_path)
    spec_file = pmag.resolve_file_name(spec_file, output_dir_path)
    samp_file = pmag.resolve_file_name(samp_file, output_dir_path)
    site_file = pmag.resolve_file_name(site_file, output_dir_path)

    # parse data
    try:
        with open(mag_file, 'r') as f:
            data = f.readlines()
    except IOError:
        print('mag_file field is required option')
        return False, 'mag_file field is required option'
    comment = data[0]
    line = data[1].strip()
    line = line.replace("=", "= ")  # make finding orientations easier
    rec = line.split()  # read in sample orientation, etc.
    specimen = rec[0]
    SpecRecs, SampRecs, SiteRecs, LocRecs, MeasRecs = [], [], [], [], []
    SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}  # make a  sample record
    if specnum != 0:
        sample = rec[0][:specnum]
    else:
        sample = rec[0]
    if int(samp_con) < 6:
        site = pmag.parse_site(sample, samp_con, Z)
    else:
        if 'site' in list(SampRec.keys()):
            site = ErSampREc['site']
        if 'location' in list(SampRec.keys()):
            location = ErSampREc['location']
    az_ind = rec.index('a=')+1
    SampRec['sample'] = sample
    SampRec['description'] = comment.replace('\n', '').replace('\t', '')
    SampRec['azimuth'] = rec[az_ind]
    dip_ind = rec.index('b=')+1
    dip = -float(rec[dip_ind])
    SampRec['dip'] = '%7.1f' % (dip)
    strike_ind = rec.index('s=')+1
    SampRec['bed_dip_direction'] = '%7.1f' % (float(rec[strike_ind])+90.)
    bd_ind = rec.index('d=')+1
    SampRec['bed_dip'] = rec[bd_ind]
    v_ind = rec.index('v=')+1
    vol = rec[v_ind][:-3]
    date = rec[-2]
    time = rec[-1]
    SampRec['method_codes'] = meth_code
    SampRec['site'] = site
    SampRec['citations'] = 'This study'
    SampRec['method_codes'] = 'SO-NO'

    SpecRec['specimen'] = specimen
    SpecRec['sample'] = sample
    SpecRec['citations'] = 'This study'

    SiteRec['site'] = site
    SiteRec['location'] = location
    SiteRec['citations'] = 'This study'
    SiteRec['lat'] = lat
    SiteRec['lon'] = lon

    LocRec['location'] = location
    LocRec['citations'] = 'This study'
    LocRec['lat_n'] = lat
    LocRec['lat_s'] = lat
    LocRec['lon_e'] = lon
    LocRec['lon_w'] = lon

    SpecRecs.append(SpecRec)
    SampRecs.append(SampRec)
    SiteRecs.append(SiteRec)
    LocRecs.append(LocRec)
    for k in range(3, len(data)):  # read in data
        line = data[k]
        rec = line.split()
        if len(rec) > 1:  # skip blank lines at bottom
            MeasRec = {}
            MeasRec['description'] = 'Date: '+date+' '+time
            MeasRec["citations"] = "This study"
            MeasRec['software_packages'] = version_num
            MeasRec["treat_temp"] = '%8.3e' % (273)  # room temp in kelvin
            MeasRec["meas_temp"] = '%8.3e' % (273)  # room temp in kelvin
            MeasRec["quality"] = 'g'
            MeasRec["standard"] = 'u'
            MeasRec["treat_step_num"] = 0
            MeasRec["specimen"] = specimen
            if rec[0] == 'NRM':
                meas_type = "LT-NO"
            elif rec[0][0] == 'M' or rec[0][0] == 'H':
                meas_type = "LT-AF-Z"
            elif rec[0][0] == 'T':
                meas_type = "LT-T-Z"
            else:
                print("measurement type unknown")
                return False, "measurement type unknown"
            X = [float(rec[1]), float(rec[2]), float(rec[3])]
            Vec = pmag.cart2dir(X)
            MeasRec["magn_moment"] = '%10.3e' % (Vec[2])  # Am^2
            MeasRec["magn_volume"] = rec[4]  # A/m
            MeasRec["dir_dec"] = '%7.1f' % (Vec[0])
            MeasRec["dir_inc"] = '%7.1f' % (Vec[1])
            MeasRec["treat_ac_field"] = '0'
            if meas_type != 'LT-NO':
                treat = float(rec[0][1:])
            else:
                treat = 0
            if meas_type == "LT-AF-Z":
                MeasRec["treat_ac_field"] = '%8.3e' % (
                    treat*1e-3)  # convert from mT to tesla
            elif meas_type == "LT-T-Z":
                MeasRec["treat_temp"] = '%8.3e' % (
                    treat+273.)  # temp in kelvin
            MeasRec['method_codes'] = meas_type
            MeasRecs.append(MeasRec)

    con = cb.Contribution(output_dir_path, read_tables=[])

    con.add_magic_table_from_data(dtype='specimens', data=SpecRecs)
    con.add_magic_table_from_data(dtype='samples', data=SampRecs)
    con.add_magic_table_from_data(dtype='sites', data=SiteRecs)
    con.add_magic_table_from_data(dtype='locations', data=LocRecs)
    MeasOuts = pmag.measurements_methods3(MeasRecs, noave)
    con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)

    con.tables['specimens'].write_magic_file(custom_name=spec_file,dir_path=dir_path)
    con.tables['samples'].write_magic_file(custom_name=samp_file,dir_path=dir_path)
    con.tables['sites'].write_magic_file(custom_name=site_file,dir_path=dir_path)
    con.tables['locations'].write_magic_file(custom_name=loc_file,dir_path=dir_path)
    con.tables['measurements'].write_magic_file(custom_name=meas_file,dir_path=dir_path)

    return True, meas_file

Response: This function converts PMD format files to MagIC format files.


Instruction:
Write a Python 3 script to
convert Scripps Institution of Oceanography measurement files to MagIC data base model 3.0 Parameters _________ magfile : input measurement file dir_path : output directory path, default "." input_dir_path : input file directory IF different from dir_path, default "" meas_file : output file measurement file name, default "measurements.txt" spec_file : output file specimen file name, default "specimens.txt" samp_file : output file sample file name, default "samples.tt" site_file : output file site file name, default "sites.txt" loc_file : output file location file name, default "locations.txt" samp_infile : output file to append to, default "" syn : if True, this is a synthetic specimen, default False syntype : sample material type, default "" instrument : instrument on which the measurements were made (e.g., "SIO-2G"), default "" labfield : lab field in microtesla for TRM, default 0 phi, theta : direction of lab field [-1,-1 for anisotropy experiments], default 0, 0 peakfield : peak af field in mT for ARM, default 0 specnum : number of terminal characters distinguishing specimen from sample, default 0 samp_con : sample/site naming convention, default '1' "1" XXXXY: where XXXX is an arbitr[ary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] "2" XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) "3" XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) "4-Z" XXXX[YYY]: YYY is sample designation with Z characters from site XXX "5" site name same as sample "6" site is entered under a separate column NOT CURRENTLY SUPPORTED "7-Z" [XXXX]YYY: XXXX is site designation with Z characters with sample name XXXXYYYY NB: all others you will have to customize your self or e-mail ltauxe@ucsd.edu for help. "8" synthetic - has no site name "9" ODP naming convention location : location name for study, default "unknown" lat : latitude of sites, default "" lon : longitude of sites, default "" noave : boolean, if False, average replicates, default False codelist : colon delimited string of lab protocols (e.g., codelist="AF"), default "" AF: af demag T: thermal including thellier but not trm acquisition S: Shaw method I: IRM (acquisition) N: NRM only TRM: trm acquisition ANI: anisotropy experiment D: double AF demag G: triple AF demag (GRM protocol) CR: cooling rate experiment. The treatment coding of the measurement file should be: XXX.00,XXX.10, XXX.20 ...XX.70 etc. (XXX.00 is optional) where XXX in the temperature and .10,.20... are running numbers of the cooling rates steps. XXX.00 is optional zerofield baseline. XXX.70 is alteration check. syntax in sio_magic is: -LP CR xxx,yyy,zzz,..... xxx -A where xxx, yyy, zzz...xxx are cooling time in [K/minutes], seperated by comma, ordered at the same order as XXX.10,XXX.20 ...XX.70 if you use a zerofield step then no need to specify the cooling rate for the zerofield It is important to add to the command line the -A option so the measurements will not be averaged. But users need to make sure that there are no duplicate measurements in the file cooling_rates : cooling rate in K/sec for cooling rate dependence studies (K/minutes) in comma separated list for each cooling rate (e.g., "43.6,1.3,43.6") coil : 1,2, or 3 unist of IRM field in volts using ASC coil #1,2 or 3 the fast and slow experiments in comma separated string (e.g., fast: 43.6 K/min, slow: 1.3 K/min) timezone : timezone of date/time string in comment string, default "UTC" user : analyst, default "" Effects _______ creates MagIC formatted tables

Response:
def sio(mag_file, dir_path=".", input_dir_path="",
        meas_file="measurements.txt", spec_file="specimens.txt",
        samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
        samp_infile="", institution="", syn=False, syntype="", instrument="",
        labfield=0, phi=0, theta=0, peakfield=0,
        specnum=0, samp_con='1', location="unknown", lat="", lon="",
        noave=False, codelist="", cooling_rates="", coil='', timezone="UTC",
        user=""):
    """
    converts Scripps Institution of Oceanography measurement files to MagIC data base model 3.0

    Parameters
    _________
    magfile : input measurement file
    dir_path : output directory path, default "."
    input_dir_path : input file directory IF different from dir_path, default ""
    meas_file : output file measurement file name, default "measurements.txt"
    spec_file : output file specimen file name, default "specimens.txt"
    samp_file : output file sample file name, default "samples.tt"
    site_file : output file site file name, default "sites.txt"
    loc_file : output file location file name, default "locations.txt"
    samp_infile : output file to append to, default ""
    syn : if True, this is a synthetic specimen, default False
    syntype :  sample material type, default ""
    instrument : instrument on which the measurements were made (e.g., "SIO-2G"), default ""
    labfield : lab field in microtesla for TRM, default 0
    phi, theta : direction of lab field [-1,-1 for anisotropy experiments], default 0, 0
    peakfield : peak af field in mT for ARM, default 0
    specnum : number of terminal characters distinguishing specimen from sample, default 0
    samp_con :  sample/site naming convention, default '1'
            "1" XXXXY: where XXXX is an arbitr[ary length site designation and Y
                is the single character sample designation.  e.g., TG001a is the
                first sample from site TG001.    [default]
            "2" XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
            "3" XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
            "4-Z" XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
            "5" site name same as sample
            "6" site is entered under a separate column NOT CURRENTLY SUPPORTED
            "7-Z" [XXXX]YYY:  XXXX is site designation with Z characters with sample name XXXXYYYY
            NB: all others you will have to customize your self
                 or e-mail ltauxe@ucsd.edu for help.

            "8" synthetic - has no site name
            "9" ODP naming convention
    location : location name for study, default "unknown"
    lat : latitude of sites, default ""
    lon : longitude of sites, default ""
    noave : boolean, if False, average replicates, default False
    codelist : colon delimited string of lab protocols (e.g., codelist="AF"), default ""
        AF:  af demag
        T: thermal including thellier but not trm acquisition
        S: Shaw method
        I: IRM (acquisition)
        N: NRM only
        TRM: trm acquisition
        ANI: anisotropy experiment
        D: double AF demag
        G: triple AF demag (GRM protocol)
        CR: cooling rate experiment.
            The treatment coding of the measurement file should be: XXX.00,XXX.10, XXX.20 ...XX.70 etc. (XXX.00 is optional)
            where XXX in the temperature and .10,.20... are running numbers of the cooling rates steps.
            XXX.00 is optional zerofield baseline. XXX.70 is alteration check.
            syntax in sio_magic is: -LP CR xxx,yyy,zzz,..... xxx -A
            where xxx, yyy, zzz...xxx  are cooling time in [K/minutes], seperated by comma, ordered at the same order as XXX.10,XXX.20 ...XX.70
            if you use a zerofield step then no need to specify the cooling rate for the zerofield
            It is important to add to the command line the -A option so the measurements will not be averaged.
            But users need to make sure that there are no duplicate measurements in the file
    cooling_rates :  cooling rate in K/sec for cooling rate dependence studies (K/minutes)
            in comma separated list for each cooling rate (e.g., "43.6,1.3,43.6")
    coil : 1,2, or 3 unist of IRM field in volts using ASC coil #1,2 or 3
        the fast and slow experiments in comma separated string (e.g., fast:  43.6 K/min,  slow:  1.3 K/min)
    timezone : timezone of date/time string in comment string, default "UTC"
    user : analyst, default ""

    Effects
    _______
    creates MagIC formatted tables
    """

    # initialize some stuff
    methcode = "LP-NO"
    pTRM, MD = 0, 0
    dec = [315, 225, 180, 135, 45, 90, 270, 270, 270, 90, 180, 180, 0, 0, 0]
    inc = [0, 0, 0, 0, 0, -45, -45, 0, 45, 45, 45, -45, -90, -45, 45]
    tdec = [0, 90, 0, 180, 270, 0, 0, 90, 0]
    tinc = [0, 0, 90, 0, 0, -90, 0, 0, 90]
    missing = 1
    demag = "N"
    citations = 'This study'
    fmt = 'old'
    Samps = []
    trm = 0
    irm = 0

    # get args
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    # measurement outfile
    meas_file = pmag.resolve_file_name(meas_file, output_dir_path)
    spec_file = pmag.resolve_file_name(spec_file, output_dir_path)
    samp_file = pmag.resolve_file_name(samp_file, output_dir_path)
    site_file = pmag.resolve_file_name(site_file, output_dir_path)
    loc_file = pmag.resolve_file_name(loc_file, output_dir_path)
    mag_file = pmag.resolve_file_name(mag_file, input_dir_path)
    labfield = float(labfield) * 1e-6
    phi = float(phi)
    theta = float(theta)
    peakfield = float(peakfield) * 1e-3
    specnum = int(specnum)
    samp_con = str(samp_con)

    # make sure all initial values are correctly set up (whether they come from the command line or a GUI)
    if samp_infile:
        Samps, file_type = pmag.magic_read(samp_infile)
    if coil:
        coil = str(coil)
        methcode = "LP-IRM"
        irmunits = "V"
        if coil not in ["1", "2", "3"]:
            print(__doc__)
            print('not a valid coil specification')
            return False, '{} is not a valid coil specification'.format(coil)
    if mag_file:
        lines = pmag.open_file(mag_file)
        if not lines:
            print("you must provide a valid mag_file")
            return False, "you must provide a valid mag_file"
    if not mag_file:
        print(__doc__)
        print("mag_file field is required option")
        return False, "mag_file field is required option"
    if specnum != 0:
        specnum = -specnum
    if "4" == samp_con[0]:
        if "-" not in samp_con:
            print(
                "naming convention option [4] must be in form 4-Z where Z is an integer")
            print('---------------')
            return False, "naming convention option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "4"
    if "7" == samp_con[0]:
        if "-" not in samp_con:
            print("option [7] must be in form 7-Z where Z is an integer")
            return False, "option [7] must be in form 7-Z where Z is an integer"
        else:
            Z = samp_con.split("-")[1]
            samp_con = "7"
    else:
        Z = 0

    if codelist:
        codes = codelist.split(':')
        if "AF" in codes:
            demag = 'AF'
            if'-dc' not in sys.argv:
                methcode = "LT-AF-Z"
            if'-dc' in sys.argv:
                methcode = "LT-AF-I"
        if "T" in codes:
            demag = "T"
            if '-dc' not in sys.argv:
                methcode = "LT-T-Z"
            if '-dc' in sys.argv:
                methcode = "LT-T-I"
        if "I" in codes:
            methcode = "LP-IRM"
            irmunits = "mT"
        if "I3d" in codes:
            methcode = "LT-T-Z:LP-IRM-3D"
        if "S" in codes:
            demag = "S"
            methcode = "LP-PI-TRM:LP-PI-ALT-AFARM"
            trm_labfield = labfield
            ans = input("DC lab field for ARM step: [50uT] ")
            if ans == "":
                arm_labfield = 50e-6
            else:
                arm_labfield = float(ans)*1e-6
            ans = input("temperature for total trm step: [600 C] ")
            if ans == "":
                trm_peakT = 600+273  # convert to kelvin
            else:
                trm_peakT = float(ans)+273  # convert to kelvin
        if "G" in codes:
            methcode = "LT-AF-G"
        if "D" in codes:
            methcode = "LT-AF-D"
        if "TRM" in codes:
            demag = "T"
            trm = 1
        if "CR" in codes:
            demag = "T"
            cooling_rate_experiment = 1
            # command_line does not exist in this code
            cooling_rates_list = cooling_rates.split(',')
            # if command_line:
            #    ind=sys.argv.index("CR")
            #    cooling_rates=sys.argv[ind+1]
            #    cooling_rates_list=cooling_rates.split(',')
            # else:
            #    cooling_rates_list=str(cooling_rates).split(',')
    if demag == "T" and "ANI" in codes:
        methcode = "LP-AN-TRM"
    if demag == "T" and "CR" in codes:
        methcode = "LP-CR-TRM"
    if demag == "AF" and "ANI" in codes:
        methcode = "LP-AN-ARM"
        if labfield == 0:
            labfield = 50e-6
        if peakfield == 0:
            peakfield = .180

    MeasRecs, SpecRecs, SampRecs, SiteRecs, LocRecs = [], [], [], [], []
    version_num = pmag.get_version()

    ##################################

    for line in lines:
        instcode = ""
        if len(line) > 2:
            MeasRec, SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}, {}
            MeasRec['software_packages'] = version_num
            MeasRec["description"] = ""
            MeasRec["treat_temp"] = '%8.3e' % (273)  # room temp in kelvin
            MeasRec["meas_temp"] = '%8.3e' % (273)  # room temp in kelvin
            MeasRec["treat_ac_field"] = '0'
            MeasRec["treat_dc_field"] = '0'
            MeasRec["treat_dc_field_phi"] = '0'
            MeasRec["treat_dc_field_theta"] = '0'
            meas_type = "LT-NO"
            rec = line.split()
            try:
                float(rec[0])
                print("No specimen name for line #%d in the measurement file" %
                      lines.index(line))
                continue
            except ValueError:
                pass
            if rec[1] == ".00":
                rec[1] = "0.00"
            treat = rec[1].split('.')
            if methcode == "LP-IRM":
                if irmunits == 'mT':
                    labfield = float(treat[0])*1e-3
                else:
                    labfield = pmag.getfield(irmunits, coil, treat[0])
                if rec[1][0] != "-":
                    phi, theta = 0., 90.
                else:
                    phi, theta = 0., -90.
                meas_type = "LT-IRM"
                MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                MeasRec["treat_dc_field_phi"] = '%7.1f' % (phi)
                MeasRec["treat_dc_field_theta"] = '%7.1f' % (theta)
            if len(rec) > 6:
                # break e.g., 10/15/02;7:45 indo date and time
                code1 = rec[6].split(';')
                if len(code1) == 2:  # old format with AM/PM
                    missing = 0
                    code2 = code1[0].split('/')  # break date into mon/day/year
                    # break e.g., AM;C34;200  into time;instr/axes/measuring pos;number of measurements
                    code3 = rec[7].split(';')
                    yy = int(code2[2])
                    if yy < 90:
                        yyyy = str(2000+yy)
                    else:
                        yyyy = str(1900+yy)
                    mm = int(code2[0])
                    if mm < 10:
                        mm = "0"+str(mm)
                    else:
                        mm = str(mm)
                    dd = int(code2[1])
                    if dd < 10:
                        dd = "0"+str(dd)
                    else:
                        dd = str(dd)
                    time = code1[1].split(':')
                    hh = int(time[0])
                    if code3[0] == "PM":
                        hh = hh+12
                    if hh < 10:
                        hh = "0"+str(hh)
                    else:
                        hh = str(hh)
                    min = int(time[1])
                    if min < 10:
                        min = "0"+str(min)
                    else:
                        min = str(min)
                    dt = yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00"
                    local = pytz.timezone(timezone)
                    naive = datetime.datetime.strptime(dt, "%Y:%m:%d:%H:%M:%S")
                    local_dt = local.localize(naive, is_dst=None)
                    utc_dt = local_dt.astimezone(pytz.utc)
                    MeasRec["timestamp"] = utc_dt.strftime(
                        "%Y-%m-%dT%H:%M:%S")+"Z"
                    if instrument == "":
                        if code3[1][0] == 'C':
                            instcode = 'SIO-bubba'
                        if code3[1][0] == 'G':
                            instcode = 'SIO-flo'
                    else:
                        instcode = ''
                    MeasRec["meas_n_orient"] = code3[1][2]
                elif len(code1) > 2:  # newest format (cryo7 or later)
                    if "LP-AN-ARM" not in methcode:
                        labfield = 0
                    fmt = 'new'
                    date = code1[0].split('/')  # break date into mon/day/year
                    yy = int(date[2])
                    if yy < 90:
                        yyyy = str(2000+yy)
                    else:
                        yyyy = str(1900+yy)
                    mm = int(date[0])
                    if mm < 10:
                        mm = "0"+str(mm)
                    else:
                        mm = str(mm)
                    dd = int(date[1])
                    if dd < 10:
                        dd = "0"+str(dd)
                    else:
                        dd = str(dd)
                    time = code1[1].split(':')
                    hh = int(time[0])
                    if hh < 10:
                        hh = "0"+str(hh)
                    else:
                        hh = str(hh)
                    min = int(time[1])
                    if min < 10:
                        min = "0"+str(min)
                    else:
                        min = str(min)
                    dt = yyyy+":"+mm+":"+dd+":"+hh+":"+min+":00"
                    local = pytz.timezone(timezone)
                    naive = datetime.datetime.strptime(dt, "%Y:%m:%d:%H:%M:%S")
                    local_dt = local.localize(naive, is_dst=None)
                    utc_dt = local_dt.astimezone(pytz.utc)
                    MeasRec["timestamp"] = utc_dt.strftime(
                        "%Y-%m-%dT%H:%M:%S")+"Z"
                    if instrument == "":
                        if code1[6][0] == 'C':
                            instcode = 'SIO-bubba'
                        if code1[6][0] == 'G':
                            instcode = 'SIO-flo'
                    else:
                        instcode = ''
                    if len(code1) > 1:
                        MeasRec["meas_n_orient"] = code1[6][2]
                    else:
                        # takes care of awkward format with bubba and flo being different
                        MeasRec["meas_n_orient"] = code1[7]
                    if user == "":
                        user = code1[5]
                    if code1[2][-1].upper() == 'C':
                        demag = "T"
                        if code1[4] == 'microT' and float(code1[3]) != 0. and "LP-AN-ARM" not in methcode:
                            labfield = float(code1[3])*1e-6
                    if code1[2] == 'mT' and methcode != "LP-IRM":
                        demag = "AF"
                        if code1[4] == 'microT' and float(code1[3]) != 0.:
                            labfield = float(code1[3])*1e-6
                    if code1[4] == 'microT' and labfield != 0. and meas_type != "LT-IRM":
                        phi, theta = 0., -90.
                        if demag == "T":
                            meas_type = "LT-T-I"
                        if demag == "AF":
                            meas_type = "LT-AF-I"
                        MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                        MeasRec["treat_dc_field_phi"] = '%7.1f' % (phi)
                        MeasRec["treat_dc_field_theta"] = '%7.1f' % (theta)
                    if code1[4] == '' or labfield == 0. and meas_type != "LT-IRM":
                        if demag == 'T':
                            meas_type = "LT-T-Z"
                        if demag == "AF":
                            meas_type = "LT-AF-Z"
                        MeasRec["treat_dc_field"] = '0'
            if not syn:
                specimen = rec[0]
                MeasRec["specimen"] = specimen
                if specnum != 0:
                    sample = rec[0][:specnum]
                else:
                    sample = rec[0]
                if samp_infile and Samps:  # if samp_infile was provided AND yielded sample data
                    samp = pmag.get_dictitem(Samps, 'sample', sample, 'T')
                    if len(samp) > 0:
                        location = samp[0]["location"]
                        site = samp[0]["site"]
                    else:
                        location = ''
                        site = ''
                else:
                    site = pmag.parse_site(sample, samp_con, Z)
                if location != '' and location not in [x['location'] if 'location' in list(x.keys()) else '' for x in LocRecs]:
                    LocRec['location'] = location
                    LocRec['lat_n'] = lat
                    LocRec['lat_s'] = lat
                    LocRec['lon_e'] = lon
                    LocRec['lon_w'] = lon
                    LocRecs.append(LocRec)
                if site != '' and site not in [x['site'] if 'site' in list(x.keys()) else '' for x in SiteRecs]:
                    SiteRec['location'] = location
                    SiteRec['site'] = site
                    SiteRec['lat'] = lat
                    SiteRec['lon'] = lon
                    SiteRecs.append(SiteRec)
                if sample != '' and sample not in [x['sample'] if 'sample' in list(x.keys()) else '' for x in SampRecs]:
                    SampRec['site'] = site
                    SampRec['sample'] = sample
                    SampRecs.append(SampRec)
                if specimen != '' and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else '' for x in SpecRecs]:
                    SpecRec["specimen"] = specimen
                    SpecRec['sample'] = sample
                    SpecRecs.append(SpecRec)
            else:
                specimen = rec[0]
                MeasRec["specimen"] = specimen
                if specnum != 0:
                    sample = rec[0][:specnum]
                else:
                    sample = rec[0]
                site = pmag.parse_site(sample, samp_con, Z)
                if location != '' and location not in [x['location'] if 'location' in list(x.keys()) else '' for x in LocRecs]:
                    LocRec['location'] = location
                    LocRec['lat_n'] = lat
                    LocRec['lat_s'] = lat
                    LocRec['lon_e'] = lon
                    LocRec['lon_w'] = lon
                    LocRecs.append(LocRec)
                if site != '' and site not in [x['site'] if 'site' in list(x.keys()) else '' for x in SiteRecs]:
                    SiteRec['location'] = location
                    SiteRec['site'] = site
                    SiteRec['lat'] = lat
                    SiteRec['lon'] = lon
                    SiteRecs.append(SiteRec)
                if sample != '' and sample not in [x['sample'] if 'sample' in list(x.keys()) else '' for x in SampRecs]:
                    SampRec['site'] = site
                    SampRec['sample'] = sample
                    SampRecs.append(SampRec)
                if specimen != '' and specimen not in [x['specimen'] if 'specimen' in list(x.keys()) else '' for x in SpecRecs]:
                    SpecRec["specimen"] = specimen
                    SpecRec['sample'] = sample
                    SpecRecs.append(SpecRec)
                SampRec["institution"] = institution
                SampRec["material_type"] = syntype
            # MeasRec["sample"]=sample
            if float(rec[1]) == 0:
                pass
            elif demag == "AF":
                if methcode != "LP-AN-ARM":
                    MeasRec["treat_ac_field"] = '%8.3e' % (
                        float(rec[1])*1e-3)  # peak field in tesla
                    if meas_type == "LT-AF-Z":
                        MeasRec["treat_dc_field"] = '0'
                else:  # AARM experiment
                    if treat[1][0] == '0':
                        meas_type = "LT-AF-Z:LP-AN-ARM:"
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            peakfield)  # peak field in tesla
                        MeasRec["treat_dc_field"] = '%8.3e' % (0)
                        if labfield != 0 and methcode != "LP-AN-ARM":
                            print(
                                "Warning - inconsistency in mag file with lab field - overriding file with 0")
                    else:
                        meas_type = "LT-AF-I:LP-AN-ARM"
                        ipos = int(treat[0])-1
                        MeasRec["treat_dc_field_phi"] = '%7.1f' % (dec[ipos])
                        MeasRec["treat_dc_field_theta"] = '%7.1f' % (inc[ipos])
                        MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            peakfield)  # peak field in tesla
            elif demag == "T" and methcode == "LP-AN-TRM":
                MeasRec["treat_temp"] = '%8.3e' % (
                    float(treat[0])+273.)  # temp in kelvin
                if treat[1][0] == '0':
                    meas_type = "LT-T-Z:LP-AN-TRM"
                    MeasRec["treat_dc_field"] = '%8.3e' % (0)
                    MeasRec["treat_dc_field_phi"] = '0'
                    MeasRec["treat_dc_field_theta"] = '0'
                else:
                    MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                    if treat[1][0] == '7':  # alteration check as final measurement
                        meas_type = "LT-PTRM-I:LP-AN-TRM"
                    else:
                        meas_type = "LT-T-I:LP-AN-TRM"

                    # find the direction of the lab field in two ways:
                    # (1) using the treatment coding (XX.1=+x, XX.2=+y, XX.3=+z, XX.4=-x, XX.5=-y, XX.6=-z)
                    ipos_code = int(treat[1][0])-1
                    # (2) using the magnetization
                    DEC = float(rec[4])
                    INC = float(rec[5])
                    if INC < 45 and INC > -45:
                        if DEC > 315 or DEC < 45:
                            ipos_guess = 0
                        if DEC > 45 and DEC < 135:
                            ipos_guess = 1
                        if DEC > 135 and DEC < 225:
                            ipos_guess = 3
                        if DEC > 225 and DEC < 315:
                            ipos_guess = 4
                    else:
                        if INC > 45:
                            ipos_guess = 2
                        if INC < -45:
                            ipos_guess = 5
                    # prefer the guess over the code
                    ipos = ipos_guess
                    MeasRec["treat_dc_field_phi"] = '%7.1f' % (tdec[ipos])
                    MeasRec["treat_dc_field_theta"] = '%7.1f' % (tinc[ipos])
                    # check it
                    if ipos_guess != ipos_code and treat[1][0] != '7':
                        print("-E- ERROR: check specimen %s step %s, ATRM measurements, coding does not match the direction of the lab field!" %
                              (rec[0], ".".join(list(treat))))

            elif demag == "S":  # Shaw experiment
                if treat[1][1] == '0':
                    if int(treat[0]) != 0:
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            float(treat[0])*1e-3)  # AF field in tesla
                        MeasRec["treat_dc_field"] = '0'
                        meas_type = "LT-AF-Z"  # first AF
                    else:
                        meas_type = "LT-NO"
                        MeasRec["treat_ac_field"] = '0'
                        MeasRec["treat_dc_field"] = '0'
                elif treat[1][1] == '1':
                    if int(treat[0]) == 0:
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            peakfield)  # peak field in tesla
                        MeasRec["treat_dc_field"] = '%8.3e' % (arm_labfield)
                        MeasRec["treat_dc_field_phi"] = '%7.1f' % (phi)
                        MeasRec["treat_dc_field_theta"] = '%7.1f' % (theta)
                        meas_type = "LT-AF-I"
                    else:
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            float(treat[0])*1e-3)  # AF field in tesla
                        MeasRec["treat_dc_field"] = '0'
                        meas_type = "LT-AF-Z"
                elif treat[1][1] == '2':
                    if int(treat[0]) == 0:
                        MeasRec["treat_ac_field"] = '0'
                        MeasRec["treat_dc_field"] = '%8.3e' % (trm_labfield)
                        MeasRec["treat_dc_field_phi"] = '%7.1f' % (phi)
                        MeasRec["treat_dc_field_theta"] = '%7.1f' % (theta)
                        MeasRec["treat_temp"] = '%8.3e' % (trm_peakT)
                        meas_type = "LT-T-I"
                    else:
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            float(treat[0])*1e-3)  # AF field in tesla
                        MeasRec["treat_dc_field"] = '0'
                        meas_type = "LT-AF-Z"
                elif treat[1][1] == '3':
                    if int(treat[0]) == 0:
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            peakfield)  # peak field in tesla
                        MeasRec["treat_dc_field"] = '%8.3e' % (arm_labfield)
                        MeasRec["treat_dc_field_phi"] = '%7.1f' % (phi)
                        MeasRec["treat_dc_field_theta"] = '%7.1f' % (theta)
                        meas_type = "LT-AF-I"
                    else:
                        MeasRec["treat_ac_field"] = '%8.3e' % (
                            float(treat[0])*1e-3)  # AF field in tesla
                        MeasRec["treat_dc_field"] = '0'
                        meas_type = "LT-AF-Z"

            # Cooling rate experient # added by rshaar
            elif demag == "T" and methcode == "LP-CR-TRM":
                MeasRec["treat_temp"] = '%8.3e' % (
                    float(treat[0])+273.)  # temp in kelvin
                if treat[1][0] == '0':
                    meas_type = "LT-T-Z:LP-CR-TRM"
                    MeasRec["treat_dc_field"] = '%8.3e' % (0)
                    MeasRec["treat_dc_field_phi"] = '0'
                    MeasRec["treat_dc_field_theta"] = '0'
                else:
                    MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                    if treat[1][0] == '7':  # alteration check as final measurement
                        meas_type = "LT-PTRM-I:LP-CR-TRM"
                    else:
                        meas_type = "LT-T-I:LP-CR-TRM"
                    MeasRec["treat_dc_field_phi"] = '%7.1f' % (
                        phi)  # labfield phi
                    MeasRec["treat_dc_field_theta"] = '%7.1f' % (
                        theta)  # labfield theta

                    indx = int(treat[1][0])-1
                    # alteration check matjed as 0.7 in the measurement file
                    if indx == 6:
                        cooling_time = cooling_rates_list[-1]
                    else:
                        cooling_time = cooling_rates_list[indx]
                    MeasRec["description"] = "cooling_rate" + \
                        ":"+cooling_time+":"+"K/min"
                    noave = 1
            elif demag != 'N':
                if len(treat) == 1:
                    treat.append('0')
                MeasRec["treat_temp"] = '%8.3e' % (
                    float(treat[0])+273.)  # temp in kelvin
                if trm == 0:  # demag=T and not trmaq
                    if treat[1][0] == '0':
                        meas_type = "LT-T-Z"
                    else:
                        # labfield in tesla (convert from microT)
                        MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                        MeasRec["treat_dc_field_phi"] = '%7.1f' % (
                            phi)  # labfield phi
                        MeasRec["treat_dc_field_theta"] = '%7.1f' % (
                            theta)  # labfield theta
                        if treat[1][0] == '1':
                            meas_type = "LT-T-I"  # in-field thermal step
                        if treat[1][0] == '2':
                            meas_type = "LT-PTRM-I"  # pTRM check
                            pTRM = 1
                        if treat[1][0] == '3':
                            # this is a zero field step
                            MeasRec["treat_dc_field"] = '0'
                            meas_type = "LT-PTRM-MD"  # pTRM tail check
                else:
                    labfield = float(treat[1])*1e-6
                    # labfield in tesla (convert from microT)
                    MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                    MeasRec["treat_dc_field_phi"] = '%7.1f' % (
                        phi)  # labfield phi
                    MeasRec["treat_dc_field_theta"] = '%7.1f' % (
                        theta)  # labfield theta
                    meas_type = "LT-T-I:LP-TRM"  # trm acquisition experiment

            MeasRec["dir_csd"] = rec[2]
            MeasRec["magn_moment"] = '%10.3e' % (
                float(rec[3])*1e-3)  # moment in Am^2 (from emu)
            MeasRec["dir_dec"] = rec[4]
            MeasRec["dir_inc"] = rec[5]
            MeasRec["instrument_codes"] = instcode
            MeasRec["analysts"] = user
            MeasRec["citations"] = citations
            if "LP-IRM-3D" in methcode:
                meas_type = methcode
            # MeasRec["method_codes"]=methcode.strip(':')
            MeasRec["method_codes"] = meas_type
            MeasRec["quality"] = 'g'
            if 'std' in rec[0]:
                MeasRec["standard"] = 's'
            else:
                MeasRec["standard"] = 'u'
            MeasRec["treat_step_num"] = 0
            # print MeasRec['treat_temp']
            MeasRecs.append(MeasRec)

    con = cb.Contribution(output_dir_path, read_tables=[])

    # create MagIC tables
    con.add_magic_table_from_data(dtype='specimens', data=SpecRecs)
    con.add_magic_table_from_data(dtype='samples', data=SampRecs)
    con.add_magic_table_from_data(dtype='sites', data=SiteRecs)
    con.add_magic_table_from_data(dtype='locations', data=LocRecs)
    MeasOuts = pmag.measurements_methods3(MeasRecs, noave)
    con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)
    # write MagIC tables to file
    con.tables['specimens'].write_magic_file(custom_name=spec_file,dir_path=dir_path)
    con.tables['samples'].write_magic_file(custom_name=samp_file,dir_path=dir_path)
    con.tables['sites'].write_magic_file(custom_name=site_file,dir_path=dir_path)
    con.tables['locations'].write_magic_file(custom_name=loc_file,dir_path=dir_path)
    meas_file = con.tables['measurements'].write_magic_file(
        custom_name=meas_file,dir_path=dir_path)
    return True, meas_file


Instruction:
Can you generate the documentation for the following Python 3 function
def s_magic(sfile, anisfile="specimens.txt", dir_path=".", atype="AMS",
            coord_type="s", sigma=False, samp_con="1", specnum=0,
            location="unknown", spec="unknown", sitename="unknown",
            user="", data_model_num=3, name_in_file=False, input_dir_path=""):
    """
    converts .s format data to measurements  format.

    Parameters
    ----------
    sfile : str
       .s format file, required
    anisfile : str
        specimen filename, default 'specimens.txt'
    dir_path : str
        output directory, default "."
    atype : str
        anisotropy type (AMS, AARM, ATRM, default AMS)
    coord_type : str
       coordinate system ('s' for specimen, 't' for tilt-corrected,
       or 'g' for geographic, default 's')
    sigma : bool
       if True, last column has sigma, default False
    samp_con : str
        sample/site naming convention, default '1', see info below
    specnum : int
        number of characters to designate a specimen, default 0
    location : str
        location name, default "unknown"
    spec : str
        specimen name, default "unknown"
    sitename : str
        site name, default "unknown"
    user : str
        user name, default ""
    data_model_num : int
        MagIC data model 2 or 3, default 3
    name_in_file : bool
        first entry of each line is specimen name, default False
    input_dir_path : input directory path IF different from dir_path, default ""

    Returns
    ---------
    Tuple : (True or False indicating if conversion was sucessful, meas_file name written)

    Input format
    --------
        X11,X22,X33,X12,X23,X13  (.s format file)
        X11,X22,X33,X12,X23,X13,sigma (.s format file with -sig option)
        SID, X11,X22,X33,X12,X23,X13  (.s format file with -n option)

    Info
    --------
    Sample naming convention:
        [1] XXXXY: where XXXX is an arbitrary length site designation and Y
            is the single character sample designation.  e.g., TG001a is the
            first sample from site TG001.    [default]
        [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
        [5] site name = sample name
        [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
        [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY

    """
    con, Z = "", 1
    if samp_con:
        samp_con = str(samp_con)
        if "4" in samp_con:
            if "-" not in samp_con:
                print("option [4] must be in form 4-Z where Z is an integer")
                return False, "option [4] must be in form 4-Z where Z is an integer"
            else:
                Z = samp_con.split("-")[1]
                samp_con = "4"
        if samp_con == '6':
            print("option [6] is not currently supported")
            return
    else:
        samp_con = con

    coord_dict = {'s': '-1', 't': '100', 'g': '0'}
    coord = coord_dict.get(coord_type, '-1')
    specnum = -specnum

    if data_model_num == 2:
        specimen_col = "er_specimen_name"
        sample_col = "er_sample_name"
        site_col = "er_site_name"
        loc_col = "er_location_name"
        citation_col = "er_citation_names"
        analyst_col = "er_analyst_mail_names"
        aniso_type_col = "anisotropy_type"
        experiment_col = "magic_experiment_names"
        sigma_col = "anisotropy_sigma"
        unit_col = "anisotropy_unit"
        tilt_corr_col = "anisotropy_tilt_correction"
        method_col = "magic_method_codes"
        outfile_type = "rmag_anisotropy"
    else:
        specimen_col = "specimen"
        sample_col = "sample"
        site_col = "site"
        loc_col = "location"
        citation_col = "citations"
        analyst_col = "analysts"
        aniso_type_col = "aniso_type"
        experiment_col = "experiments"
        sigma_col = "aniso_s_sigma"
        unit_col = "aniso_s_unit"
        tilt_corr_col = "aniso_tilt_correction"
        method_col = "method_codes"
        outfile_type = "specimens"
    # get down to bidness
    input_dir_path, dir_path = pmag.fix_directories(input_dir_path, dir_path)
    sfile = pmag.resolve_file_name(sfile, input_dir_path)
    anisfile = pmag.resolve_file_name(anisfile, dir_path)
    try:
        with open(sfile, 'r') as f:
            lines = f.readlines()
    except FileNotFoundError:
        return False, "No such file: {}".format(sfile)
    AnisRecs = []
    citation = "This study"
    # read in data
    for line in lines:
        AnisRec = {}
        rec = line.split()
        if name_in_file:
            k = 1
            spec = rec[0]
        else:
            k = 0
        trace = float(rec[k])+float(rec[k+1])+float(rec[k+2])
        s1 = '%10.9e' % (float(rec[k]) / trace)
        s2 = '%10.9e' % (float(rec[k+1]) / trace)
        s3 = '%10.9e' % (float(rec[k+2]) / trace)
        s4 = '%10.9e' % (float(rec[k+3]) / trace)
        s5 = '%10.9e' % (float(rec[k+4]) / trace)
        s6 = '%10.9e' % (float(rec[k+5]) / trace)
        AnisRec[citation_col] = citation
        AnisRec[specimen_col] = spec
        if specnum != 0:
            AnisRec[sample_col] = spec[:specnum]
        else:
            AnisRec[sample_col] = spec
        # if samp_con == "6":
        #    for samp in Samps:
        #        if samp['er_sample_name'] == AnisRec["er_sample_name"]:
        #            sitename = samp['er_site_name']
        #            location = samp['er_location_name']
        if samp_con != "":
            sitename = pmag.parse_site(AnisRec[sample_col], samp_con, Z)
        AnisRec[loc_col] = location
        AnisRec[site_col] = sitename
        AnisRec[analyst_col] = user
        if atype == 'AMS':
            AnisRec[aniso_type_col] = "AMS"
            AnisRec[experiment_col] = spec+":LP-X"
        else:
            AnisRec[aniso_type_col] = atype
            AnisRec[experiment_col] = spec+":LP-"+atype
        if data_model_num != 3:
            AnisRec["anisotropy_s1"] = s1
            AnisRec["anisotropy_s2"] = s2
            AnisRec["anisotropy_s3"] = s3
            AnisRec["anisotropy_s4"] = s4
            AnisRec["anisotropy_s5"] = s5
            AnisRec["anisotropy_s6"] = s6
        else:
            AnisRec['aniso_s'] = ":".join(
                [str(s) for s in [s1, s2, s3, s4, s5, s6]])
        if sigma:
            AnisRec[sigma_col] = '%10.8e' % (
                float(rec[k+6]) / trace)
            AnisRec[unit_col] = 'SI'
            AnisRec[tilt_corr_col] = coord
            AnisRec[method_col] = 'LP-' + atype
        AnisRecs.append(AnisRec)
    pmag.magic_write(anisfile, AnisRecs, outfile_type)
    print('data saved in ', anisfile)
    # try to extract location/site/sample info into tables
    con = cb.Contribution(dir_path, custom_filenames={"specimens": anisfile})
    con.propagate_all_tables_info()
    for table in con.tables:
        if table in ['samples', 'sites', 'locations']:
            # add in location name by hand
            if table == 'sites':
                con.tables['sites'].df['location'] = location
            con.write_table_to_file(table)
    return True, anisfile

Response: This function converts. s format data to measurements.


Instruction:
Can you write a function in Python 3 where it
converts ascii files generated by SUFAR ver.4.0 to MagIC files Parameters ---------- ascfile : str input ASC file, required meas_output : str measurement output filename, default "measurements.txt" aniso_output : str anisotropy output filename, MagIC 2 only, "rmag_anisotropy.txt" spec_infile : str specimen infile, default None spec_outfile : str specimen outfile, default "specimens.txt" samp_outfile : str sample outfile, default "samples.txt" site_outfile : str site outfile, default "sites.txt" specnum : int number of characters to designate a specimen, default 0 sample_naming_con : str sample/site naming convention, default '1', see info below user : str user name, default "" locname : str location name, default "unknown" instrument : str instrument name, default "" static_15_position_mode : bool specify static 15 position mode - default False (is spinning) dir_path : str output directory, default "." input_dir_path : str input file directory IF different from dir_path, default "" data_model_num : int MagIC data model 2 or 3, default 3 Returns -------- type - Tuple : (True or False indicating if conversion was sucessful, file name written) Info -------- Sample naming convention: [1] XXXXY: where XXXX is an arbitrary length site designation and Y is the single character sample designation. e.g., TG001a is the first sample from site TG001. [default] [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length) [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length) [4-Z] XXXX[YYY]: YYY is sample designation with Z characters from site XXX [5] site name = sample name [6] site name entered in site_name column in the orient.txt format input file -- NOT CURRENTLY SUPPORTED [7-Z] [XXX]YYY: XXX is site designation with Z characters from samples XXXYYY

Response:
def sufar4(ascfile, meas_output='measurements.txt', aniso_output='rmag_anisotropy.txt',
           spec_infile=None, spec_outfile='specimens.txt', samp_outfile='samples.txt',
           site_outfile='sites.txt', specnum=0, sample_naming_con='1', user="",
           locname="unknown", instrument='', static_15_position_mode=False,
           dir_path='.', input_dir_path='', data_model_num=3):
    """
    Converts ascii files generated by SUFAR ver.4.0 to MagIC files

    Parameters
    ----------
    ascfile : str
        input ASC file, required
    meas_output : str
        measurement output filename, default "measurements.txt"
    aniso_output : str
        anisotropy output filename, MagIC 2 only, "rmag_anisotropy.txt"
    spec_infile : str
        specimen infile, default None
    spec_outfile : str
        specimen outfile, default "specimens.txt"
    samp_outfile : str
        sample outfile, default "samples.txt"
    site_outfile : str
        site outfile, default "sites.txt"
    specnum : int
        number of characters to designate a specimen, default 0
    sample_naming_con : str
        sample/site naming convention, default '1', see info below
    user : str
        user name, default ""
    locname : str
        location name, default "unknown"
    instrument : str
        instrument name, default ""
    static_15_position_mode : bool
        specify static 15 position mode - default False (is spinning)
    dir_path : str
        output directory, default "."
    input_dir_path : str
        input file directory IF different from dir_path, default ""
    data_model_num : int
        MagIC data model 2 or 3, default 3

    Returns
    --------
    type - Tuple : (True or False indicating if conversion was sucessful, file name written)

    Info
    --------
    Sample naming convention:
        [1] XXXXY: where XXXX is an arbitrary length site designation and Y
            is the single character sample designation.  e.g., TG001a is the
            first sample from site TG001.    [default]
        [2] XXXX-YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [3] XXXX.YY: YY sample from site XXXX (XXX, YY of arbitary length)
        [4-Z] XXXX[YYY]:  YYY is sample designation with Z characters from site XXX
        [5] site name = sample name
        [6] site name entered in site_name column in the orient.txt format input file  -- NOT CURRENTLY SUPPORTED
        [7-Z] [XXX]YYY:  XXX is site designation with Z characters from samples  XXXYYY

    """

    citation = 'This study'
    cont = 0
    Z = 1
    AniRecSs, AniRecs, SpecRecs, SampRecs, SiteRecs, MeasRecs = [], [], [], [], [], []
    isspec = '0'
    spin = 0
    data_model_num = int(float(data_model_num))

    # set defaults for MagIC 2
    if data_model_num == 2:
        if meas_output == 'measurements.txt':
            meas_output = 'magic_measurements.txt'
        if spec_outfile == 'specimens.txt':
            spec_outfile = 'er_specimens.txt'
        if samp_outfile == 'samples.txt':
            samp_outfile = 'er_samples.txt'
        if site_outfile == 'sites.txt':
            site_outfile = 'er_sites.txt'

    # set column names for MagIC 3
    spec_name_col = 'specimen'
    samp_name_col = 'sample'
    site_name_col = 'site'
    loc_name_col = 'location'
    citation_col = 'citations'
    method_col = 'method_codes'
    site_description_col = 'description'
    expedition_col = 'expedition_name'
    instrument_col = 'instrument_codes'
    experiment_col = 'experiments'
    analyst_col = 'analysts'
    quality_col = 'quality'
    aniso_quality_col = 'result_quality'
    meas_standard_col = 'standard'
    meas_description_col = 'description'
    aniso_type_col = 'aniso_type'
    aniso_unit_col = 'aniso_s_unit'
    aniso_n_col = 'aniso_s_n_measurements'
    azimuth_col = 'azimuth'
    spec_volume_col = 'volume'
    samp_dip_col = 'dip'
    bed_dip_col = 'bed_dip'
    bed_dip_direction_col = 'bed_dip_direction'
    chi_vol_col = 'susc_chi_volume'
    aniso_sigma_col = 'aniso_s_sigma'
    aniso_unit_col = 'aniso_s_unit'
    aniso_tilt_corr_col = 'aniso_tilt_correction'
    meas_table_name = 'measurements'
    spec_table_name = 'specimens'
    samp_table_name = 'samples'
    site_table_name = 'sites'

    # set column names for MagIC 2
    if data_model_num == 2:
        spec_name_col = 'er_specimen_name'
        samp_name_col = 'er_sample_name'
        site_name_col = 'er_site_name'
        loc_name_col = 'er_location_name'
        citation_col = 'er_citation_names'
        method_col = 'magic_method_codes'
        site_description_col = 'site_description'
        expedition_col = 'er_expedition_name'
        instrument_col = 'magic_instrument_codes'
        experiment_col = 'magic_experiment_names'
        analyst_col = 'er_analyst_mail_names'
        quality_col = 'measurement_flag'
        aniso_quality_col = 'anisotropy_flag'
        meas_standard_col = 'measurement_standard'
        meas_description_col = 'measurement_description'
        aniso_type_col = 'anisotropy_type'
        aniso_unit_col = 'anisotropy_unit'
        aniso_n_col = 'anisotropy_n'
        azimuth_col = 'sample_azimuth'
        spec_volume_col = 'specimen_volume'
        samp_dip_col = 'sample_dip'
        bed_dip_col = 'sample_bed_dip'
        bed_dip_direction_col = 'sample_bed_dip_direction'
        chi_vol_col = 'measurement_chi_volume'
        aniso_sigma_col = 'anisotropy_sigma'
        aniso_unit_col = 'anisotropy_unit'
        aniso_tilt_corr_col = 'anisotropy_tilt_correction'
        meas_table_name = 'magic_measurements'
        spec_table_name = 'er_specimens'
        samp_table_name = 'er_samples'
        site_table_name = 'er_sites'

    # create full path for files
    input_dir_path, output_dir_path = pmag.fix_directories(input_dir_path, dir_path)
    ascfile = os.path.join(input_dir_path, ascfile)
    aniso_output = os.path.join(output_dir_path, aniso_output)
    # initialized but not used
    meas_output = os.path.join(output_dir_path, meas_output)

    spec_outfile = os.path.join(output_dir_path, spec_outfile)
    samp_outfile = os.path.join(output_dir_path, samp_outfile)
    site_outfile = os.path.join(output_dir_path, site_outfile)

    if "4" in sample_naming_con:
        if "-" not in sample_naming_con:
            print("option [4] must be in form 4-Z where Z is an integer")
            return False, "option [4] must be in form 4-Z where Z is an integer"
        else:
            Z = sample_naming_con.split("-")[1]
            sample_naming_con = "4"
    if "7" in sample_naming_con:
        if "-" not in sample_naming_con:
            print("option [7] must be in form 7-Z where Z is an integer")
            return False, "option [7] must be in form 7-Z where Z is an integer"
        else:
            Z = sample_naming_con.split("-")[1]
            sample_naming_con = "7"

    if static_15_position_mode:
        spin = 0

    if spec_infile:
        if os.path.isfile(os.path.join(input_dir_path, str(spec_infile))):
            # means an er_specimens.txt file has been provided with sample,
            # site, location (etc.) info
            isspec = '1'

    specnum = int(specnum)

    if isspec == "1":
        specs, file_type = pmag.magic_read(spec_infile)

    specnames, sampnames, sitenames = [], [], []
    # if '-new' not in sys.argv: # see if there are already specimen,sample, site files lying around
    #    try:
    #        SpecRecs,file_type=pmag.magic_read(input_dir_path+'/er_specimens.txt')
    #        for spec in SpecRecs:
    #            if spec['er_specimen_name'] not in specnames:
    #                specnames.append(samp['er_specimen_name'])
    #    except:
    #        SpecRecs,specs=[],[]
    #    try:
    #        SampRecs,file_type=pmag.magic_read(input_dir_path+'/er_samples.txt')
    #        for samp in SampRecs:
    #            if samp['er_sample_name'] not in sampnames:sampnames.append(samp['er_sample_name'])
    #    except:
    #        sampnames,SampRecs=[],[]
    #    try:
    #        SiteRecs,file_type=pmag.magic_read(input_dir_path+'/er_sites.txt')
    #        for site in SiteRecs:
    #            if site['er_site_names'] not in sitenames:sitenames.append(site['er_site_name'])
    #    except:
    #        sitenames,SiteRecs=[],[]

    try:
        file_input = open(ascfile, 'r')
    except:
        print('Error opening file: ', ascfile)
        return False, 'Error opening file: {}'.format(ascfile)
    Data = file_input.readlines()
    file_input.close()
    k = 0
    while k < len(Data):
        line = Data[k]
        words = line.split()
        if "ANISOTROPY" in words:  # first line of data for the spec
            MeasRec, AniRec, SpecRec, SampRec, SiteRec = {}, {}, {}, {}, {}
            specname = words[0]
            AniRec[spec_name_col] = specname
            if isspec == "1":
                for spec in specs:
                    if spec[spec_name_col] == specname:
                        AniRec[samp_name_col] = spec[samp_name_col]
                        AniRec[site_name_col] = spec[site_name_col]
                        AniRec[loc_name_col] = spec[loc_name_col]
                        break
            elif isspec == "0":
                if specnum != 0:
                    sampname = specname[:-specnum]
                else:
                    sampname = specname
                AniRec[samp_name_col] = sampname
                SpecRec[spec_name_col] = specname
                SpecRec[samp_name_col] = sampname
                SampRec[samp_name_col] = sampname
                SiteRec[samp_name_col] = sampname
                SiteRec[site_description_col] = 's'
                if sample_naming_con != "9":
                    AniRec[site_name_col] = pmag.parse_site(
                        AniRec[samp_name_col], sample_naming_con, Z)
                    SpecRec[site_name_col] = pmag.parse_site(
                        AniRec[samp_name_col], sample_naming_con, Z)
                    SampRec[site_name_col] = pmag.parse_site(
                        AniRec[samp_name_col], sample_naming_con, Z)
                    SiteRec[site_name_col] = pmag.parse_site(
                        AniRec[samp_name_col], sample_naming_con, Z)
                else:
                    AniRec[site_name_col] = specname
                    SpecRec[site_name_col] = specname
                    SampRec[site_name_col] = specname
                    SiteRec[site_name_col] = specname
                    pieces = specname.split('-')
                    AniRec[expedition_col] = pieces[0]
                    SpecRec[expedition_col] = pieces[0]
                    SampRec[expedition_col] = pieces[0]
                    SiteRec[expedition_col] = pieces[0]
                    location = pieces[1]
                AniRec[loc_name_col] = locname
                SpecRec[loc_name_col] = locname
                SampRec[loc_name_col] = locname
                SiteRec[loc_name_col] = locname
                AniRec[citation_col] = "This study"
                SpecRec[citation_col] = "This study"
                SampRec[citation_col] = "This study"
                SiteRec[citation_col] = "This study"
            AniRec[citation_col] = "This study"
            AniRec[instrument_col] = instrument
            AniRec[method_col] = "LP-X:AE-H:LP-AN-MS"
            AniRec[experiment_col] = specname + ":" + "LP-AN-MS"
            AniRec[analyst_col] = user
            for key in list(AniRec.keys()):
                MeasRec[key] = AniRec[key]
            if data_model_num == 2:
                MeasRec['magic_experiment_name'] = AniRec.get('magic_experiment_names', '')
                if 'magic_experiment_names' in MeasRec:
                    MeasRec.pop('magic_experiment_names')
            if data_model_num == 3:
                MeasRec['experiment'] = AniRec.get('experiments', '')
                if 'experiments' in MeasRec:
                    MeasRec.pop('experiments')
            MeasRec[quality_col] = 'g'
            AniRec[aniso_quality_col] = 'g'
            MeasRec[meas_standard_col] = 'u'
            MeasRec[meas_description_col] = 'Bulk sucsecptibility measurement'
            AniRec[aniso_type_col] = "AMS"
            AniRec[aniso_unit_col] = "Normalized by trace"
            if spin == 1:
                AniRec[aniso_n_col] = "192"
            else:
                AniRec[aniso_n_col] = "15"
        if 'Azi' in words and isspec == '0':
            az = float(words[1])
            P1 = float(words[4])
            P2 = float(words[5])
            P3 = float(words[6])
            # P4 relates to a fabric or bedding measurement -- not dealt with
            # here
            P4 = float(words[7])
            az = az + P1 * 360. / 12. - P3 * 360. / 12.
            if az >= 360:
                az = az - 360
            elif az <= -360:
                az = az + 360
            labaz = az
            SampRec[azimuth_col] = str(round(az, 1))
        if 'Dip' in words:
            # convert actual volume to m^3 from cm^3
            SpecRec[spec_volume_col] = '%8.3e' % (float(words[10]) * 1e-6)
            dip = float(words[1])
            if P2 == 90:
                dip = dip - 90.
            labdip = dip
            SampRec[samp_dip_col] = str(round(dip, 1))
        if 'T1' in words and 'F1' in words:
            k += 2  # read in fourth line down
            line = Data[k]
            rec = line.split()
            dd = rec[1].split('/')
            dip_direction = int(dd[0]) + 90
            SampRec[bed_dip_direction_col] = '%i' % (dip_direction)
            SampRec[bed_dip_col] = dd[1]
            bed_dip = float(dd[1])
        if "Mean" in words:
            k += 4  # read in fourth line down
            line = Data[k]
            rec = line.split()
            MeasRec[chi_vol_col] = rec[1]
            sigma = .01 * float(rec[2]) / 3.
            AniRec[aniso_sigma_col] = '%7.4f' % (sigma)
            AniRec[aniso_unit_col] = 'SI'
        if "factors" in words:
            k += 4  # read in second line down
            line = Data[k]
            rec = line.split()
        if "Specimen" in words:  # first part of specimen data
            # eigenvalues sum to unity - not 3
            s1_val = '%7.4f' % (float(words[5]) / 3.)
            s2_val = '%7.4f' % (float(words[6]) / 3.)
            s3_val = '%7.4f' % (float(words[7]) / 3.)
            k += 1
            line = Data[k]
            rec = line.split()
            # eigenvalues sum to unity - not 3
            s4_val= '%7.4f' % (float(rec[5]) / 3.)
            s5_val = '%7.4f' % (float(rec[6]) / 3.)
            s6_val = '%7.4f' % (float(rec[7]) / 3.)
            # parse for data model 2
            if data_model_num == 2:
                AniRec['anisotropy_s1'] = s1_val
                AniRec['anisotropy_s2'] = s2_val
                AniRec['anisotropy_s3'] = s3_val
                AniRec['anisotropy_s4'] = s4_val
                AniRec['anisotropy_s5'] = s5_val
                AniRec['anisotropy_s6'] = s6_val
            # parse for data model 3
            else:
                vals = (s1_val, s2_val, s3_val, s4_val, s5_val, s6_val)
                AniRec['aniso_s'] = ":".join([v.strip() for v in vals])
            #
            AniRec[aniso_tilt_corr_col] = '-1'
            AniRecs.append(AniRec)
            AniRecG, AniRecT = {}, {}
            for key in list(AniRec.keys()):
                AniRecG[key] = AniRec[key]
            for key in list(AniRec.keys()):
                AniRecT[key] = AniRec[key]
            sbar = []
            sbar.append(float(s1_val))
            sbar.append(float(s2_val))
            sbar.append(float(s3_val))
            sbar.append(float(s4_val))
            sbar.append(float(s5_val))
            sbar.append(float(s6_val))
            sbarg = pmag.dosgeo(sbar, labaz, labdip)
            s1_g = '%12.10f' % (sbarg[0])
            s2_g = '%12.10f' % (sbarg[1])
            s3_g = '%12.10f' % (sbarg[2])
            s4_g = '%12.10f' % (sbarg[3])
            s5_g = '%12.10f' % (sbarg[4])
            s6_g = '%12.10f' % (sbarg[5])
            if data_model_num == 2:
                AniRecG["anisotropy_s1"] = s1_g
                AniRecG["anisotropy_s2"] = s2_g
                AniRecG["anisotropy_s3"] = s3_g
                AniRecG["anisotropy_s4"] = s4_g
                AniRecG["anisotropy_s5"] = s5_g
                AniRecG["anisotropy_s6"] = s6_g
            else:
                vals = (s1_g, s2_g, s3_g, s4_g, s5_g, s6_g)
                AniRecG['aniso_s'] = ":".join([v.strip() for v in vals])
            AniRecG[aniso_tilt_corr_col] = '0'
            AniRecs.append(AniRecG)
            if bed_dip != "" and bed_dip != 0:  # have tilt correction
                sbart = pmag.dostilt(sbarg, dip_direction, bed_dip)
                s1_t = '%12.10f' % (sbart[0])
                s2_t = '%12.10f' % (sbart[1])
                s3_t = '%12.10f' % (sbart[2])
                s4_t = '%12.10f' % (sbart[3])
                s5_t = '%12.10f' % (sbart[4])
                s6_t = '%12.10f' % (sbart[5])
                if data_model_num == 2:
                    AniRecT["anisotropy_s1"] = s1_t
                    AniRecT["anisotropy_s2"] = s2_t
                    AniRecT["anisotropy_s3"] = s3_t
                    AniRecT["anisotropy_s4"] = s4_t
                    AniRecT["anisotropy_s5"] = s5_t
                    AniRecT["anisotropy_s6"] = s6_t
                else:
                    vals = (s1_t, s2_t, s3_t, s4_t, s5_t, s6_t)
                    AniRecT["aniso_s"] = ":".join([v.strip() for v in vals])
                AniRecT[aniso_tilt_corr_col] = '100'
                AniRecs.append(AniRecT)
            MeasRecs.append(MeasRec)
            if SpecRec[spec_name_col] not in specnames:
                SpecRecs.append(SpecRec)
                specnames.append(SpecRec[spec_name_col])
            if SampRec[samp_name_col] not in sampnames:
                SampRecs.append(SampRec)
                sampnames.append(SampRec[samp_name_col])
            if SiteRec[site_name_col] not in sitenames:
                SiteRecs.append(SiteRec)
                sitenames.append(SiteRec[site_name_col])
        k += 1  # skip to next specimen

    pmag.magic_write(meas_output, MeasRecs, meas_table_name)
    print("bulk measurements put in ", meas_output)
    # if isspec=="0":
    SpecOut, keys = pmag.fillkeys(SpecRecs)
    #
    # for MagIC 2, anisotropy records go in rmag_anisotropy
    if data_model_num == 2:
        pmag.magic_write(aniso_output, AniRecs, 'rmag_anisotropy')
        print("anisotropy tensors put in ", aniso_output)
    # for MagIC 3, anisotropy records go in specimens
    if data_model_num == 3:
        full_SpecOut = []
        spec_list = []
        for rec in SpecOut:
            full_SpecOut.append(rec)
            spec_name = rec[spec_name_col]
            if spec_name not in spec_list:
                spec_list.append(spec_name)
                ani_recs = pmag.get_dictitem(AniRecs, spec_name_col, spec_name, 'T')
                full_SpecOut.extend(ani_recs)

        # FILL KEYS
        full_SpecOut, keys = pmag.fillkeys(full_SpecOut)
    else:
        full_SpecOut = SpecOut
    pmag.magic_write(spec_outfile, full_SpecOut, spec_table_name)
    print("specimen/anisotropy info put in ", spec_outfile)
    SampOut, keys = pmag.fillkeys(SampRecs)
    pmag.magic_write(samp_outfile, SampOut, samp_table_name)
    print("sample info put in ", samp_outfile)
    SiteOut, keys = pmag.fillkeys(SiteRecs)
    pmag.magic_write(site_outfile, SiteOut, site_table_name)
    print("site info put in ", site_outfile)
    return True, meas_output