docs: def tdt(input_dir_path, experiment_name="Thellier", meas_file_name="measurements.txt",
          spec_file_name="specimens.txt", samp_file_name="samples.txt",
          site_file_name="sites.txt", loc_file_name="locations.txt",
          user="", location="", lab_dec=0, lab_inc=90, moment_units="mA/m",
          samp_name_con="sample=specimen", samp_name_chars=0,
          site_name_con="site=sample", site_name_chars=0, volume=12.,
          output_dir_path=""):
  
      """
      converts TDT formatted files to measurements format files
  
      Parameters
      ----------
      input_dir_path : str
          directory with one or more .tdt files
      experiment: str
          one of: ["Thellier", "ATRM 6 pos", "NLT"], default "Thellier"
      meas_file_name : str
          default "measurements.txt"
      spec_file_name : str
          default "specimens.txt"
      samp_file_name : str
          default "samples.txt"
      site_file_name : str
          default "sites.txt"
      loc_file_name : str
          default "locations.txt"
      user : str
          default ""
      location : str
          default ""
      lab_dec: int
          default: 0
      lab_inc: int
          default 90
      moment_units : str
          must be one of: ["mA/m", "emu", "Am^2"], default "mA/m"
      samp_name_con : str or int
          {1: "sample=specimen", 2: "no. of terminate characters", 3: "character delimited"}
      samp_name_chars : str or int
          number of characters to remove for sample name, (or delimiting character), default 0
      site_name_con : str or int
          {1: "site=sample", 2: "no. of terminate characters", 3: "character delimited"}
      site_name_chars : str or int
          number of characters to remove for site name, (or delimiting character), default 0
      volume : float
          volume in cc, default 12
      output_dir_path : str
          path for file output, defaults to input_dir_path
  
  
      Returns
      ---------
      tuple : (True if program ran else False, measurement outfile name or error message if failed)
      """
  
      # --------------------------------------
      # Read the files
      #
      # Database structure
      # Thellier_type experiment:
      #
      # 1) Each file contains the data one specimen
      # 2) First line is the header: "Thellier-tdt"
      # 3) Second line in header inlucdes 4 fields:
      #    [Blab] ,[unknown_1] , [unknown_2] , [unknown_3] , [unknown_4]
      # 4) Body includes 5 fields
      #    [specimen_name], [treatments], [moment],[meas_dec],[meas_dec
      # Tretment: XXX.0 (zerofield)
      #           XXX.1 (infield)
      #           XXX.2 (pTRM check)
      #           XXX.3 (Tail check)
      #           XXX.4 (Additivity check; Krasa et al., 2003)
      #           XXX.5 (Original Thellier-Thellier protocol. )
      #                 (where .5 is for the second direction and .1 in the first)
      # XXX = temperature in degrees
      #
      #
      # IMPORTANT ASSUMPTION:
      # (1) lab field is always in Z direction (theta=0, phi=90)
      # (2) Thermal demagnetization - NO MICROWAVE
      # (3) if if XXX <50 then assuming that this is NRM (273K)
      #
      # -------------------------------------
      #
      #   ATRM in six positions
      #
      # Tretment: XXX.0 zerofield
      #           XXX.1 +x
      #           XXX.2 +y
      #           XXX.3 +z
      #           XXX.4 -x
      #           XXX.5 -y
      #           XXX.6 -z
      #           XXX.7 alteration check
      #   IMPORTANT REMARKS:
      #
      # (1) If the program check if the direction of the magnetization fits the coding above
      # if not, an error message will appear
      # (2) Alteration ckeck can be in any direction
      # (3) the order of the measurements is not important
      #
  
  
      def get_sample_name(specimen, sample_naming_convention):
          if sample_naming_convention[0] == "sample=specimen":
              sample = specimen
          elif sample_naming_convention[0] == "no. of terminate characters":
              n = int(sample_naming_convention[1])*-1
              sample = specimen[:n]
          elif sample_naming_convention[0] == "charceter delimited":
              d = sample_naming_convention[1]
              sample_splitted = specimen.split(d)
              if len(sample_splitted) == 1:
                  sample = sample_splitted[0]
              else:
                  sample = d.join(sample_splitted[:-1])
          return sample
  
      def get_site_name(sample, site_naming_convention):
          if site_naming_convention[0] == "site=sample":
              site = sample
          elif site_naming_convention[0] == "no. of terminate characters":
              n = int(site_naming_convention[1])*-1
              site = sample[:n]
          elif site_naming_convention[0] == "charceter delimited":
              d = site_naming_convention[1]
              site_splitted = sample.split(d)
              if len(site_splitted) == 1:
                  site = site_splitted[0]
              else:
                  site = d.join(site_splitted[:-1])
          return site
  
      ## format some variables
  
      # convert volume from cc to m^3
      volume = float(volume) * 1e-6
      if not output_dir_path:
          output_dir_path = input_dir_path
      samp_name_cons = {1: 'sample=specimen', 2: 'no. of terminate characters', 3: 'character delimited'}
      if not samp_name_con:
          samp_name_con = "sample=specimen"
      elif samp_name_con not in samp_name_cons.values():
          try:
              samp_name_con =  samp_name_cons.get(int(samp_name_con), 'sample=specimen')
          except ValueError:
              samp_name_con="sample=specimen"
      if samp_name_con == 'no. of terminate characters' and not samp_name_chars:
          print("-W- You have selected the sample naming convention: 'no. of terminate characters',\n    but have provided the number of characters as 0.\n    Defaulting to use 'sample=specimen' instead.")
          samp_name_con = 'sample=specimen'
  
      site_name_cons =  {1: 'site=sample', 2: 'no. of terminate characters', 3: 'character delimited'}
      if not site_name_con:
          site_name_con = "site=sample"
      elif site_name_con not in site_name_cons.values():
          try:
              site_name_con = site_name_cons.get(int(site_name_con), 'site=sample')
          except ValueError:
              site_name_con = "site=sample"
      if site_name_con == 'no. of terminate characters' and not site_name_chars:
          print("-W- You have selected the site naming convention: 'no. of terminate characters',\n    but have provided the number of characters as 0.\n    Defaulting to use 'site=sample' instead.")
          site_name_con = 'site=sample'
  
  
      Data = {}
  
      # -----------------------------------
      # First, read all files and sort data by specimen and by Experiment type
      # -----------------------------------
  
      for files in os.listdir(input_dir_path):
          if files.endswith(".tdt"):
              fname = os.path.join(input_dir_path, files)
              print("Open file: ", fname)
              fin = open(fname, 'r')
              header_codes = ['labfield', 'core_azimuth',
                              'core_plunge', 'bedding_dip_direction', 'bedding_dip']
              body_codes = ['specimen_name',
                            'treatment', 'moment', 'dec', 'inc']
              tmp_body = []
              tmp_header_data = {}
              line_number = 0
              continue_reading = True
              line = fin.readline()  # ignore first line
              lines = fin.readlines()
              fin.close()
              for line in lines:
  
                  if "END" in line:
                      break
  
                  if line.strip('\n') == "":
                      break
  
                  this_line = line.strip('\n').split()
  
                  if len(this_line) < 5:
                      continue
  
                  # ---------------------------------------------------
                  # fix muxworthy funky data format
                  # ---------------------------------------------------
                  if len(this_line) < 5 and line_number != 0:
                      new_line = []
                      for i in range(len(this_line)):
                          if i > 1 and "-" in this_line[i]:
                              tmp = this_line[i].replace("-", " -")
                              tmp1 = tmp.split()
                              for i in range(len(tmp1)):
                                  new_line.append(tmp1[i])
                          else:
                              new_line.append(this_line[i])
                      this_line = list(copy(new_line))
  
                  # -------------------------------
                  # Read infromation from Header and body
                  # The data is stored in a dictionary:
                  # Data[specimen][Experiment_Type]['header_data']=tmp_header_data  --> a dictionary with header data
                  # Data[specimen][Experiment_Type]['meas_data']=[dict1, dict2, ...] --> a list of dictionaries with measurement data
                  # -------------------------------
  
                  # ---------------------------------------------------
                  # header
                  # ---------------------------------------------------
                  if line_number == 0:
  
                      for i in range(len(this_line)):
                          tmp_header_data[header_codes[i]] = this_line[i]
  
                      line_number += 1
  
                  # ---------------------------------------------------
                  # body
                  # ---------------------------------------------------
  
                  else:
                      tmp_data = {}
                      for i in range(min(len(this_line), len(body_codes))):
                          tmp_data[body_codes[i]] = this_line[i]
                      tmp_body.append(tmp_data)
  
                      # ------------
  
                      specimen = tmp_body[0]['specimen_name']
                      line_number += 1
  
              if specimen not in list(Data.keys()):
                  Data[specimen] = {}
              Experiment_Type = experiment_name
              if Experiment_Type not in list(Data[specimen].keys()):
                  Data[specimen][Experiment_Type] = {}
              Data[specimen][Experiment_Type]['meas_data'] = tmp_body
              Data[specimen][Experiment_Type]['header_data'] = tmp_header_data
              Data[specimen][Experiment_Type]['sample_naming_convention'] = [samp_name_con, samp_name_chars]
              Data[specimen][Experiment_Type]['site_naming_convention'] = [site_name_con, site_name_chars]
              Data[specimen][Experiment_Type]['location'] = location
              Data[specimen][Experiment_Type]['user_name'] = user
              Data[specimen][Experiment_Type]['volume'] = volume
              Data[specimen][Experiment_Type]['moment_units'] = moment_units
              Data[specimen][Experiment_Type]['labfield_DI'] = [lab_dec, lab_inc]
  
      # -----------------------------------
      # Convert Data{} to MagIC
      # -----------------------------------
      MeasRecs, SpecRecs, SampRecs, SiteRecs, LocRecs = [], [], [], [], []
      specimens_list = list(Data.keys())
      specimens_list.sort()
      for specimen in specimens_list:
          Experiment_Types_list = list(Data[specimen].keys())
          Experiment_Types_list.sort()
          for Experiment_Type in Experiment_Types_list:
              if Experiment_Type in ["Thellier"]:
  
                  tmp_MeasRecs = []
  
                  # IMORTANT:
                  # phi and theta of lab field are not defined
                  # defaults are defined here:
                  phi, theta = '0.', '90.'
  
                  header_line = Data[specimen][Experiment_Type]['header_data']
                  experiment_treatments = []
                  measurement_running_number = 0
                  # start to make a list of the methcodes. and later will merge it to one string
                  methcodes = ["LP-PI-TRM"]
  
                  for i in range(len(Data[specimen][Experiment_Type]['meas_data'])):
                      meas_line = Data[specimen][Experiment_Type]['meas_data'][i]
  
                      # ------------------
                      # check if the same treatment appears more than once. If yes, assuming that the measurements is repeated twice,
                      # ignore the first, and take only the second one
                      # ------------------
  
                      if i < (len(Data[specimen][Experiment_Type]['meas_data'])-2):
                          Repeating_measurements = True
                          for key in ['treatment', 'specimen_name']:
                              if Data[specimen][Experiment_Type]['meas_data'][i][key] != Data[specimen][Experiment_Type]['meas_data'][i+1][key]:
                                  Repeating_measurements = False
                          if Repeating_measurements == True:
                              "Found a repeating measurement at line %i, sample %s. taking the last one" % (
                                  i, specimen)
                              continue
                      # ------------------
                      # Special treatment for first line (NRM data).
                      # ------------------
  
                      if i == 0:
                          if "." not in meas_line['treatment']:
                              meas_line['treatment'] = "0.0"
                          # if NRM is in the form of ".0" instead of "0.0"
                          elif meas_line['treatment'].split(".")[0] == "" and meas_line['treatment'].split(".")[1] == '0':
                              meas_line['treatment'] = "0.0"
                          # if NRM is in the form of "20.0" instead of "0.0"
                          elif float(meas_line['treatment'].split(".")[0]) < 50 and float(meas_line['treatment'].split(".")[-1]) == 0:
                              meas_line['treatment'] = "0.0"
  
                      # ------------------
                      # fix line in format of XX instead of XX.YY
                      # ------------------
                      if "." not in meas_line['treatment']:
                          meas_line['treatment'] = meas_line['treatment']+".0"
                      if meas_line['treatment'].split(".")[1] == "":
                          meas_line['treatment'] = meas_line['treatment']+"0"
  
                      # ------------------
                      # init names and dictionaries
                      # ------------------
  
                      MeasRec, SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}, {}
  
                      # convert from microT to Tesla
                      labfield = float(header_line['labfield'])*1e-6
                      sample = get_sample_name(
                          specimen, Data[specimen][Experiment_Type]['sample_naming_convention'])
                      site = get_site_name(
                          sample, Data[specimen][Experiment_Type]['site_naming_convention'])
                      location = Data[specimen][Experiment_Type]['location']
                      if location == '':
                          location = 'unknown'
  
                      # ------------------
                      # Fill data
                      # ------------------
  
                      # Start with S'tables and Loc Table
                      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
                          SpecRec['volume'] = Data[specimen][Experiment_Type]['volume']
                          SpecRec['citations'] = "This study"
                          SpecRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          SpecRecs.append(SpecRec)
                      if sample != "" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]:
                          SampRec['sample'] = sample
                          SampRec['site'] = site
                          SampRec['citations'] = "This study"
                          SampRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          SampRecs.append(SampRec)
                      if site != "" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]:
                          SiteRec['site'] = site
                          SiteRec['location'] = location
                          SiteRec['citations'] = "This study"
                          SiteRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          SiteRecs.append(SiteRec)
                      if location != "" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]:
                          LocRec['location'] = location
                          LocRec['citations'] = "This study"
                          LocRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          LocRecs.append(LocRec)
  
                      # now the measurement Rec
                      MeasRec['citations'] = "This study"
                      # experiment is set in pmag.measurements_methods3
                      # MeasRec["experiments"]=""
                      MeasRec["specimen"] = specimen
                      MeasRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                      MeasRec["quality"] = 'g'
                      MeasRec["standard"] = 'u'
                      MeasRec["treat_step_num"] = "%i" % measurement_running_number
                      MeasRec["dir_dec"] = meas_line['dec']
                      MeasRec["dir_inc"] = meas_line['inc']
                      if Data[specimen][Experiment_Type]['moment_units'] == 'mA/m':
                          MeasRec["magn_moment"] = "%5e" % (float(meas_line['moment'])*1e-3*float(
                              Data[specimen][Experiment_Type]['volume']))  # converted to Am^2
                      if Data[specimen][Experiment_Type]['moment_units'] == 'emu':
                          MeasRec["magn_moment"] = "%5e" % (
                              float(meas_line['moment'])*1e-3)  # converted to Am^2
                      if Data[specimen][Experiment_Type]['moment_units'] == 'Am^2':
                          MeasRec["magn_moment"] = "%5e" % (
                              float(meas_line['moment']))  # converted to Am^2
                      MeasRec["meas_temp"] = '273.'  # room temp in kelvin
  
                      # Date and time
  ##                                    date=meas_line['Measurement Date'].strip("\"").split('-')
  # yyyy=date[2];dd=date[1];mm=date[0]
  ##                                    hour=meas_line['Measurement Time'].strip("\"")
  # MeasRec["measurement_date"]=yyyy+':'+mm+":"+dd+":"+hour
  
                      # lab field data: distinguish between PI experiments to AF/Thermal
                      treatments = meas_line['treatment'].split(".")
                      if float(treatments[1]) == 0:
                          MeasRec["treat_dc_field"] = '0'
                          MeasRec["treat_dc_field_phi"] = '0'
                          MeasRec["treat_dc_field_theta"] = '0'
                      else:
                          MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
                          MeasRec["treat_dc_field_phi"] = Data[specimen][Experiment_Type]['labfield_DI'][0]
                          MeasRec["treat_dc_field_theta"] = Data[specimen][Experiment_Type]['labfield_DI'][1]
  
                      # ------------------
                      # Lab Treatments
                      # ------------------
  
                      # NRM
                      if float(treatments[0]) == 0 and float(treatments[1]) == 0:
                          MeasRec["method_codes"] = "LT-NO"
                          experiment_treatments.append('0')
                          MeasRec["treat_temp"] = '273.'
                          IZorZI = ""
  
                      # Zerofield step
                      elif float(treatments[1]) == 0:
                          MeasRec["method_codes"] = "LT-T-Z"
                          MeasRec["treat_temp"] = '%8.3e' % (
                              float(treatments[0])+273.)  # temp in kelvin
  
                          #  check if this is ZI or IZ:
                          for j in range(0, i):
                              previous_lines = Data[specimen][Experiment_Type]['meas_data'][j]
                              if previous_lines['treatment'].split(".")[0] == meas_line['treatment'].split(".")[0]:
                                  if float(previous_lines['treatment'].split(".")[1]) == 1 or float(previous_lines['treatment'].split(".")[1]) == 10:
                                      if "LP-PI-TRM-IZ" not in methcodes:
                                          methcodes.append("LP-PI-TRM-IZ")
                                      IZorZI = ""
                                  else:
                                      IZorZI = "Z"
  
                      # Infield step
                      elif float(treatments[1]) == 1 or float(treatments[1]) == 10:
                          MeasRec["method_codes"] = "LT-T-I"
                          MeasRec["treat_temp"] = '%8.3e' % (
                              float(treatments[0])+273.)  # temp in kelvin
  
                          # check if this is ZI,IZ:
                          for j in range(0, i):
                              previous_lines = Data[specimen][Experiment_Type]['meas_data'][j]
                              if previous_lines['treatment'].split(".")[0] == meas_line['treatment'].split(".")[0]:
                                  if float(previous_lines['treatment'].split(".")[1]) == 0:
                                      if "LP-PI-TRM-ZI" not in methcodes:
                                          methcodes.append("LP-PI-TRM-ZI")
                                          IZorZI = ""
                                  else:
                                      IZorZI = "I"
                      # pTRM check step
                      elif float(treatments[1]) == 2 or float(treatments[1]) == 20:
                          MeasRec["method_codes"] = "LT-PTRM-I"
                          MeasRec["treat_temp"] = '%8.3e' % (
                              float(treatments[0])+273.)  # temp in kelvin
                          if "LP-PI-ALT" not in methcodes:
                              methcodes.append("LP-PI-ALT")
  
                      # Tail check step
                      elif float(treatments[1]) == 3 or float(treatments[1]) == 30:
                          MeasRec["method_codes"] = "LT-PTRM-MD"
                          MeasRec["treat_temp"] = '%8.3e' % (
                              float(treatments[0])+273.)  # temp in kelvin
                          if "LP-PI-BT-MD" not in methcodes:
                              methcodes.append("LP-PI-BT-MD")
                              MeasRec["treat_dc_field"] = "0"
                              MeasRec["treat_dc_field_phi"] = "0"
                              MeasRec["treat_dc_field_theta"] = "0"
  
                      # Additivity check step
                      elif float(treatments[1]) == 4 or float(treatments[1]) == 40:
                          MeasRec["method_codes"] = "LT-PTRM-AC"
                          MeasRec["treat_temp"] = '%8.3e' % (
                              float(treatments[0])+273.)  # temp in kelvin
                          if "LP-PI-BT" not in methcodes:
                              methcodes.append("LP-PI-BT")
  
                      # Thellier Thellier protocol (1 for one direction and 5 for the antiparallel)
                      # Lab field direction of 1 is as put in the GUI dialog box
                      # Lab field direction of 5 is the anti-parallel direction of 1
  
                      elif float(treatments[1]) == 5 or float(treatments[1]) == 50:
                          MeasRec["method_codes"] = "LT-T-I"
                          MeasRec["treat_temp"] = '%8.3e' % (
                              float(treatments[0])+273.)  # temp in kelvin
                          MeasRec["treat_dc_field_phi"] = "%.2f" % (
                              (float(Data[specimen][Experiment_Type]['labfield_DI'][0])+180.) % 360.)
                          MeasRec["treat_dc_field_theta"] = "%.2f" % (
                              float(Data[specimen][Experiment_Type]['labfield_DI'][1])*-1.)
                          if "LP-PI-II" not in methcodes:
                              methcodes.append("LP-PI-II")
  
                      else:
                          print("-E- ERROR in file %s" % Experiment_Type)
                          print("-E- ERROR in treatment ",
                                meas_line['treatment'])
                          print("... exiting until you fix the problem")
  
                      # -----------------------------------
  
                      # MeasRec["method_codes"]=lab_treatment+":"+lab_protocols_string
                      # MeasRec["experiments"]=specimen+":"+lab_protocols_string
  
                      tmp_MeasRecs.append(MeasRec)
                      measurement_running_number += 1
  
                  # arrange method_codes and experiments:
                  method_codes = "LP-PI-TRM"
                  # Coe mothod
                  if "LP-PI-TRM-ZI" in methcodes and "LP-PI-TRM-IZ" not in methcodes and "LP-PI-II" not in methcodes:
                      method_codes = method_codes+":LP-PI-TRM-ZI"
                  if "LP-PI-TRM-ZI" not in methcodes and "LP-PI-TRM-IZ" in methcodes and "LP-PI-II" not in methcodes:
                      method_codes = method_codes+":LP-PI-TRM-IZ"
                  if "LP-PI-TRM-ZI" in methcodes and "LP-PI-TRM-IZ" in methcodes and "LP-PI-II" not in methcodes:
                      method_codes = method_codes+":LP-PI-BT-IZZI"
                  if "LP-PI-II" in methcodes:
                      method_codes = method_codes+":LP-PI-II"
                  if "LP-PI-ALT" in methcodes:
                      method_codes = method_codes+":LP-PI-ALT"
                  if "LP-PI-BT-MD" in methcodes:
                      method_codes = method_codes+":LP-PI-BT-MD"
                  if "LP-PI-BT" in methcodes:
                      method_codes = method_codes+":LP-PI-BT"
                  for i in range(len(tmp_MeasRecs)):
                      STRING = ":".join(
                          [tmp_MeasRecs[i]["method_codes"], method_codes])
                      tmp_MeasRecs[i]["method_codes"] = STRING
                      # experiment is set in pmag.measurements_methods3
                      # STRING=":".join([tmp_MeasRecs[i]["specimen"],method_codes])
                      # tmp_MeasRecs[i]["experiments"]=STRING
                      MeasRecs.append(tmp_MeasRecs[i])
  
              elif Experiment_Type in ["ATRM 6 positions"]:
  
                  tmp_MeasRecs = []
  
                  header_line = Data[specimen][Experiment_Type]['header_data']
                  experiment_treatments = []
                  measurement_running_number = 0
                  # start to make a list of the methcodes. and later will merge it to one string
                  methcodes = ["LP-AN-TRM"]
  
                  for i in range(len(Data[specimen][Experiment_Type]['meas_data'])):
                      meas_line = Data[specimen][Experiment_Type]['meas_data'][i]
  
                      # ------------------
                      # check if the same treatment appears more than once. If yes, assuming that the measurements is repeated twice,
                      # ignore the first, and take only the second one
                      # ------------------
  
                      if i < (len(Data[specimen][Experiment_Type]['meas_data'])-2):
                          Repeating_measurements = True
                          for key in ['treatment', 'specimen_name']:
                              if Data[specimen][Experiment_Type]['meas_data'][i][key] != Data[specimen][Experiment_Type]['meas_data'][i+1][key]:
                                  Repeating_measurements = False
                          if Repeating_measurements == True:
                              "Found a repeating measurement at line %i, sample %s. taking the last one" % (
                                  i, specimen)
                              continue
  
                      # ------------------
                      # fix line in format of XX instead of XX.0
                      # ------------------
                      if "." not in meas_line['treatment']:
                          meas_line['treatment'] = meas_line['treatment']+".0"
                      if meas_line['treatment'].split(".")[1] == "":
                          meas_line['treatment'] = meas_line['treatment']+"0"
  
                      # ------------------
                      # init names and dictionaries
                      # ------------------
  
                      MeasRec, SpecRec, SampRec, SiteRec, LocRec = {}, {}, {}, {}, {}
  
                      # convert from microT to Tesla
                      labfield = float(header_line['labfield'])*1e-6
                      sample = get_sample_name(
                          specimen, Data[specimen][Experiment_Type]['sample_naming_convention'])
                      site = get_site_name(
                          sample, Data[specimen][Experiment_Type]['site_naming_convention'])
                      location = Data[specimen][Experiment_Type]['location']
  
                      # ------------------
                      # Fill data
                      # ------------------
  
                      # Start with S'tables and Loc Table
                      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
                          SpecRec['volume'] = Data[specimen][Experiment_Type]['volume']
                          SpecRec['citations'] = "This study"
                          SpecRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          SpecRecs.append(SpecRec)
                      if sample != "" and sample not in [x['sample'] if 'sample' in list(x.keys()) else "" for x in SampRecs]:
                          SampRec['sample'] = sample
                          SampRec['site'] = site
                          SampRec['citations'] = "This study"
                          SampRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          SampRecs.append(SampRec)
                      if site != "" and site not in [x['site'] if 'site' in list(x.keys()) else "" for x in SiteRecs]:
                          SiteRec['site'] = site
                          SiteRec['location'] = location
                          SiteRec['citations'] = "This study"
                          SiteRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          SiteRecs.append(SiteRec)
                      if location != "" and location not in [x['location'] if 'location' in list(x.keys()) else "" for x in LocRecs]:
                          LocRec['location'] = location
                          LocRec['citations'] = "This study"
                          LocRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                          LocRecs.append(LocRec)
  
                      # Meas data now
                      MeasRec["specimen"] = specimen
                      MeasRec['analysts'] = Data[specimen][Experiment_Type]['user_name']
                      MeasRec['citations'] = "This study"
                      MeasRec["quality"] = 'g'
                      MeasRec["standard"] = 'u'
                      MeasRec["treat_step_num"] = "%i" % measurement_running_number
                      MeasRec["dir_dec"] = meas_line['dec']
                      MeasRec["dir_inc"] = meas_line['inc']
                      MeasRec["magn_moment"] = "%5e" % (float(meas_line['moment'])*1e-3*float(
                          Data[specimen][Experiment_Type]['volume']))  # converted to Am^2
                      MeasRec["meas_temp"] = '273.'  # room temp in kelvin
  
                      treatments = meas_line['treatment'].split(".")
                      if len(treatments[1]) > 1:
                          treatments[1] = treatments[1][0]
  
                      MeasRec["treat_temp"] = '%8.3e' % (
                          float(treatments[0])+273.)  # temp in kelvin
  
                      # labfield direction
                      if float(treatments[1]) == 0:
                          MeasRec["treat_dc_field"] = '0'
                          MeasRec["treat_dc_field_phi"] = '0'
                          MeasRec["treat_dc_field_theta"] = '0'
                          MeasRec["method_codes"] = "LT-T-Z:LP-AN-TRM"
                      else:
  
                          MeasRec["treat_dc_field"] = '%8.3e' % (labfield)
  
                          # alteration check as final measurement
                          if float(treatments[1]) == 7 or float(treatments[1]) == 70:
                              MeasRec["method_codes"] = "LT-PTRM-I:LP-AN-TRM"
                          else:
                              MeasRec["method_codes"] = "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)
                          # atrm declination/inlclination order
                          tdec = [0, 90, 0, 180, 270, 0, 0, 90, 0]
                          # atrm declination/inlclination order
                          tinc = [0, 0, 90, 0, 0, -90, 0, 0, 90]
  
                          ipos_code = int(treatments[1])-1
                          # (2) using the magnetization
                          DEC = float(MeasRec["dir_dec"])
                          INC = float(MeasRec["dir_inc"])
                          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 treatments[1] != '7':
                              print("-E- ERROR: check specimen %s step %s, ATRM measurements, coding does not match the direction of the lab field!" % (
                                  MeasRec["specimen"], ".".join(list(treatments))))
  
                      MeasRecs.append(MeasRec)
                      measurement_running_number += 1
  
              else:
                  print(
                      "-E- ERROR. sorry, file format %s is not supported yet. Please contact rshaar@ucsd.edu" % Experiment_Type)
  
      # -------------------------------------------
      #  measurements.txt
      # -------------------------------------------
  
      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=False)
      con.add_magic_table_from_data(dtype='measurements', data=MeasOuts)
      con.write_table_to_file('specimens', spec_file_name)
      con.write_table_to_file('samples', samp_file_name)
      con.write_table_to_file('sites', site_file_name)
      con.write_table_to_file('locations', loc_file_name)
      meas_file = con.write_table_to_file('measurements', meas_file_name)
      return True, meas_file