#!/usr/bin/env python
# -*-coding: utf-8 -*-

# -----------------------------------------------------------------------------------------------------------------------

# Name:		pysills_app.py
# Author:	Maximilian A. Beeskow
# Version:	v1.0.5
# Date:		28.06.2024

# -----------------------------------------------------------------------------------------------------------------------

## MODULES
# external
import os, pathlib, sys, re, datetime, csv, string, math, webbrowser, time
import numpy as np
import pandas as pd
import scipy.io
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import tkinter as tk
from tkinter import filedialog, ttk, font
import random as rd
# internal
try:
    from pysills.pypitzer.Pitzer.models import FluidPitzer
except:
    from pypitzer.Pitzer.models import FluidPitzer

try:
    from pysills.modules.chemistry import PeriodicSystem
    from pysills.modules.chemistry import PeriodicSystemOfElements as PSE
    from pysills.modules.data import Data
    from pysills.modules.data_reduction import DataExtraction as DE
    from pysills.modules.data_reduction import IntensityQuantification as IQ
    from pysills.modules.data_reduction import SensitivityQuantification as SQ
    from pysills.modules.essential_functions import Essentials as ES
    from pysills.modules.essential_functions import EssentialsSRM as ESRM
    from pysills.modules.gui_elements import SimpleElements as SE
    from pysills.modules.spike_elimination import GrubbsTestSILLS, OutlierDetection
except:
    from modules.chemistry import PeriodicSystem
    from modules.chemistry import PeriodicSystemOfElements as PSE
    from modules.data import Data
    from modules.data_reduction import DataExtraction as DE
    from modules.data_reduction import IntensityQuantification as IQ
    from modules.data_reduction import SensitivityQuantification as SQ
    from modules.essential_functions import Essentials as ES
    from modules.essential_functions import EssentialsSRM as ESRM
    from modules.gui_elements import SimpleElements as SE
    from modules.spike_elimination import GrubbsTestSILLS, OutlierDetection

# import subprocess
import string

###############
### PySILLS ###
###############
class PySILLS(tk.Frame):
    #
    def __init__(self, parent, var_screen_width, var_screen_height, var_path=None):
        tk.Frame.__init__(self, parent)
        var_screen_width = var_screen_width
        var_screen_height = var_screen_height
        var_scaling_horizontal = round(1920/var_screen_width, 2)
        var_scaling_vertical = round(1080/var_screen_height, 2)
        if var_scaling_horizontal == 1.0 and var_scaling_vertical == 1.0:
            var_scaling = 1.3

        ## Current version
        # val_version = subprocess.check_output(['git', 'log', '-n', '1', '--pretty=tformat:%h']).strip()
        # self.val_version = val_version.decode("utf-8")
        #self.val_version = ''.join(rd.choice(string.ascii_letters) for i in range(8))
        self.val_version = "1.0.6 - 28.06.2024"

        ## Colors
        self.green_dark = "#282D28"
        self.green_medium = "#616D61"
        self.green_light = "#CFD3CF"
        green_dict = {"Dark": self.green_dark, "Medium": self.green_medium, "Light": self.green_light}
        self.red_dark = "#E76F51"
        self.red_medium = "#F1A896"
        self.red_light = "#FDF0ED"
        red_dict = {"Dark": self.red_dark, "Medium": self.red_medium, "Light": self.red_light}
        self.yellow_dark = "#E9C46A"
        self.yellow_medium = "#F3DFAE"
        self.yellow_light = "#FDFAF2"
        yellow_dict = {"Dark": self.yellow_dark, "Medium": self.yellow_medium, "Light": self.yellow_light}
        self.blue_dark = "#5B828E"
        self.blue_medium = "#8CA7AF"
        self.blue_light = "#CDD9DD"
        blue_dict = {"Dark": self.blue_dark, "Medium": self.blue_medium, "Light": self.blue_light}
        self.brown_dark = "#AC7E62"
        self.brown_medium = "#C4A491"
        self.brown_light = "#EEE5DF"
        brown_dict = {"Dark": self.brown_dark, "Medium": self.brown_medium, "Light": self.brown_light}
        self.slate_grey_dark = "#6E7894"
        self.slate_grey_medium = "#9AA1B4"
        self.slate_grey_light = "#E2E4EA"
        slategrey_dict = {"Dark": self.slate_grey_dark, "Medium": self.slate_grey_medium,
                          "Light": self.slate_grey_light}
        #
        self.bg_colors = {"Super Dark": "#2C2C2C", "Very Dark": "#3C3C3C", "Dark": "#676767", "Medium": "#909090",
                          "Light": "#BABABA", "Very Light": "#E3E3E3", "Dark Font": "#292929", "Light Font": "#F7F7F7",
                          "White": "#FFFFFF", "Black": "#000000"}
        self.accent_color = "#E76F51"
        self.colors_ma = {"Very Dark": "#2F3E46", "Dark": "#354F52", "Medium": "#52796F", "Light": "#84A98C",
                          "Very Light": "#CAD2C5", "Dark Font": "#182320", "Light Font": "#F2F6F5"}
        self.colors_fi = {"Very Dark": "#722F1C", "Dark": "#A04228", "Medium": "#D36A4D", "Light": "#E4A694",
                          "Very Light": "#F6E1DB", "Dark Font": "#411B10", "Light Font": "#FCF4F2"}
        self.colors_mi = {"Very Dark": "#013a63", "Dark": "#014f86", "Medium": "#2c7da0", "Light": "#61a5c2",
                          "Very Light": "#a9d6e5", "Dark Font": "#0D242E", "Light Font": "#EEF7FA"}
        self.colors_intervals = {"BG": "#7F4F24", "SIG": "#414833", "MAT": "#414833", "INCL": "#F4D35E",
                                 "BG LB": "#D9A578", "SIG LB": "#A4AF8E", "MAT LB": "#A4AF8E", "INCL LB": "#F9E9AE"}
        #
        self.font_dark = "#000000"
        self.font_light = "#FFFFFF"
        self.sign_red = "#E84258"
        self.sign_yellow = "#FFDE00"
        self.sign_green = "#B0D8A4"
        sign_dict = {"Green": self.sign_green, "Red": self.sign_red, "Yellow": self.sign_yellow}

        style = ttk.Style()
        style.theme_use("default")
        style.configure(
            "Vertical.TScrollbar", bg=self.bg_colors["Very Light"], bordercolor=self.bg_colors["Very Dark"],
            arrowcolor=self.bg_colors["Dark"])
        style.configure(
            "Horizontal.TScrollbar", bg=self.bg_colors["Very Light"], bordercolor=self.bg_colors["Very Dark"],
            arrowcolor=self.bg_colors["Dark"])
        ## Constants
        self.list_std = []
        self.list_smpl = []
        self.chemistry_data = {
            "O": 15.999, "Na": 22.990, "Mg": 24.305, "Al": 26.982, "Si": 28.085, "P": 30.974, "K": 39.098, "Ca": 40.078,
            "Ti": 47.867, "Cr": 51.996, "Mn": 54.938, "Fe": 55.845, "Ga": 69.723, "Ge": 72.630, "Zr": 91.224,
            "Ba": 137.33, "B": 10.81, "Ag": 107.87, "As": 74.922, "Li": 6.94, "Rb": 85.468, "Cs": 132.91, "Sr": 87.62,
            "Sc": 44.956, "Y": 88.906, "Hf": 178.49, "V": 50.942, "Nb": 92.906, "Ta": 180.95, "Mo": 95.962, "W": 183.84,
            "Tc": 98.906, "Re": 186.21, "Ru": 101.07, "Os": 190.23, "Co": 58.933, "Rh": 102.91, "Ir": 192.22,
            "Ni": 58.693, "Pd": 106.42, "Pt": 195.08, "Cu": 63.546, "Au": 196.97, "Zn": 65.38, "Cd": 112.41,
            "Hg": 200.59, "In": 114.82, "Tl": 204.38, "C": 12.011, "Sn": 118.71, "Pb": 207.2, "N": 14.007, "Sb": 121.76,
            "Bi": 208.98, "S": 32.06, "Se": 78.96, "Te": 127.60, "Po": 209.98, "Cl": 35.45, "Br": 79.904, "I": 126.90,
            "At": 210.99, "La": 138.91, "Ce": 140.12, "Pr": 140.91, "Nd": 144.24, "Pm": 146.92, "Sm": 150.36,
            "Eu": 151.96, "Gd": 157.25, "Tb": 158.93, "Dy": 162.50, "Ho": 164.93, "Er": 167.26, "Tm": 168.93,
            "Yb": 173.05, "Lu": 174.97, "Ac": 227.03, "Th": 232.04, "Pa": 231.04, "U": 238.05, "Be": 9.0122,
            "F": 18.998, "H": 1.008}
        self.chemistry_data_sills = {
            "O": 16.000, "Na": 22.990, "Mg": 24.300, "Al": 26.980, "Si": 28.090, "P": 30.970, "K": 39.100, "Ca": 40.080,
            "Ti": 47.870, "Cr": 52.000, "Mn": 54.940, "Fe": 55.850, "Ga": 69.720, "Ge": 72.610, "Zr": 91.220,
            "Ba": 137.300}
        self.chemistry_data_oxides = {
            "SiO2": 60.083, "Al2O3": 101.961, "Fe2O3": 159.687, "FeO": 71.844, "Na2O": 61.979, "TiO2": 79.865,
            "MnO": 70.937, "Mn2O3": 157.873, "SnO": 134.709, "Li2O": 29.879, "Ga2O3": 187.443, "B2O3": 69.617,
            "BeO": 25.0112, "GeO2": 104.628, "CaO": 56.077, "Rb2O": 186.935, "AgO": 123.869, "As2O3": 197.841,
            "Au2O": 409.939, "BaO": 153.32, "Br2O": 175.807, "Cl2O": 86.899, "Cs2O": 281.819, "CuO": 79.545,
            "PbO": 223.199, "SO3": 80.057, "Sb2O3": 291.517, "SrO": 103.619, "WO3": 231.837, "ZnO": 81.379,
            "MgO": 40.304, "K2O": 55.097, "SnO2": 150.708, "Ag2O": 231.739, "Bi2O5": 497.955, "CO2": 44.009,
            "CdO": 128.409, "Ce2O3": 328.237, "CeO2": 172.118, "CoO": 74.932, "Cr2O3": 151.989, "Dy2O3": 372.997,
            "Er2O3": 382.517, "Eu2O3": 351.917, "Gd2O3": 362.497, "HfO2": 404.977, "HgO": 216.589, "Ho2O3": 377.857,
            "In2O3": 277.637, "IrO": 208.219, "La2O3": 325.817, "Lu2O3": 397.937, "MnO2": 86.936, "MoO3": 143.959,
            "N2O5": 108.009, "Nb2O5": 265.807, "Nd2O3": 336.477, "NiO": 74.692, "OsO": 206.229, "P2O5": 141.943,
            "PbO2": 239.198, "PdO": 122.419, "Pr2O3": 329.817, "Pr6O11": 1021.449, "PtO": 211.079, "ReO": 202.209,
            "RhO": 118.909, "RuO": 117.069, "SO4": 96.056, "Sb2O5": 323.515, "Sc2O3": 137.909, "SeO3": 126.957,
            "Sm2O3": 348.717, "Ta2O5": 441.895, "Tb2O3": 365.857, "Tb4O7": 747.713, "TeO3": 175.597, "ThO2": 264.038,
            "Tl2O3": 456.757, "Tm2O3": 385.857, "UO2": 270.048, "UO3": 286.047, "U3O8": 842.142, "V2O5": 181.879,
            "Y2O3": 225.809, "Yb2O3": 394.097, "ZrO2": 123.222, "I2O4": 317.796, "I2O5": 333.795, "I4O9": 651.591,
            "I2O": 269.799, "Ni2O3": 165.383, "Co2O3": 165.863, "CrO": 67.995}

        self.conversion_factors = {
            "SiO2": round((self.chemistry_data["Si"]/self.chemistry_data_oxides["SiO2"])**(-1), 4),
            "Al2O3": round((2*self.chemistry_data["Al"]/self.chemistry_data_oxides["Al2O3"])**(-1), 4),
            "Fe2O3": round((2*self.chemistry_data["Fe"]/self.chemistry_data_oxides["Fe2O3"])**(-1), 4),
            "FeO": round((self.chemistry_data["Fe"]/self.chemistry_data_oxides["FeO"])**(-1), 4),
            "Na2O": round((2*self.chemistry_data["Na"]/self.chemistry_data_oxides["Na2O"])**(-1), 4),
            "TiO2": round((self.chemistry_data["Ti"]/self.chemistry_data_oxides["TiO2"])**(-1), 4),
            "MnO": round((self.chemistry_data["Mn"]/self.chemistry_data_oxides["MnO"])**(-1), 4),
            "Mn2O3": round((2*self.chemistry_data["Mn"]/self.chemistry_data_oxides["Mn2O3"])**(-1), 4),
            "SnO": round((self.chemistry_data["Sn"]/self.chemistry_data_oxides["SnO"])**(-1), 4),
            "Li2O": round((2*self.chemistry_data["Li"]/self.chemistry_data_oxides["Li2O"])**(-1), 4),
            "Ga2O3": round((2*self.chemistry_data["Ga"]/self.chemistry_data_oxides["Ga2O3"])**(-1), 4),
            "B2O3": round((2*self.chemistry_data["B"]/self.chemistry_data_oxides["B2O3"])**(-1), 4),
            "BeO": round((self.chemistry_data["Be"]/self.chemistry_data_oxides["BeO"])**(-1), 4),
            "GeO2": round((self.chemistry_data["Ge"]/self.chemistry_data_oxides["GeO2"])**(-1), 4),
            "CaO": round((self.chemistry_data["Ca"]/self.chemistry_data_oxides["CaO"])**(-1), 4),
            "Rb2O": round((2*self.chemistry_data["Rb"]/self.chemistry_data_oxides["Rb2O"])**(-1), 4),
            "AgO": round((self.chemistry_data["Ag"]/self.chemistry_data_oxides["AgO"])**(-1), 4),
            "As2O3": round((2*self.chemistry_data["As"]/self.chemistry_data_oxides["As2O3"])**(-1), 4),
            "Au2O": round((2*self.chemistry_data["Au"]/self.chemistry_data_oxides["Au2O"])**(-1), 4),
            "BaO": round((self.chemistry_data["Ba"]/self.chemistry_data_oxides["BaO"])**(-1), 4),
            "Br2O": round((2*self.chemistry_data["Br"]/self.chemistry_data_oxides["Br2O"])**(-1), 4),
            "Cl2O": round((2*self.chemistry_data["Cl"]/self.chemistry_data_oxides["Cl2O"])**(-1), 4),
            "Cs2O": round((2*self.chemistry_data["Cs"]/self.chemistry_data_oxides["Cs2O"])**(-1), 4),
            "CuO": round((self.chemistry_data["Cu"]/self.chemistry_data_oxides["CuO"])**(-1), 4),
            "PbO": round((self.chemistry_data["Pb"]/self.chemistry_data_oxides["PbO"])**(-1), 4),
            "SO3": round((self.chemistry_data["S"]/self.chemistry_data_oxides["SO3"])**(-1), 4),
            "Sb2O3": round((2*self.chemistry_data["Sb"]/self.chemistry_data_oxides["Sb2O3"])**(-1), 4),
            "SrO": round((self.chemistry_data["Sr"]/self.chemistry_data_oxides["SrO"])**(-1), 4),
            "WO3": round((self.chemistry_data["W"]/self.chemistry_data_oxides["WO3"])**(-1), 4),
            "ZnO": round((self.chemistry_data["Zn"]/self.chemistry_data_oxides["ZnO"])**(-1), 4),
            "MgO": round((self.chemistry_data["Mg"]/self.chemistry_data_oxides["MgO"])**(-1), 4),
            "K2O": round((2*self.chemistry_data["K"]/self.chemistry_data_oxides["K2O"])**(-1), 4),
            "SnO2": round((self.chemistry_data["Sn"]/self.chemistry_data_oxides["SnO2"])**(-1), 4),
            "Ag2O": round((2*self.chemistry_data["Ag"]/self.chemistry_data_oxides["Ag2O"])**(-1), 4),
            "Bi2O5": round((2*self.chemistry_data["Bi"]/self.chemistry_data_oxides["Bi2O5"])**(-1), 4),
            "CO2": round((self.chemistry_data["C"]/self.chemistry_data_oxides["CO2"])**(-1), 4),
            "CdO": round((self.chemistry_data["Cd"]/self.chemistry_data_oxides["CdO"])**(-1), 4),
            "Ce2O3": round((2*self.chemistry_data["Ce"]/self.chemistry_data_oxides["Ce2O3"])**(-1), 4),
            "CeO2": round((self.chemistry_data["Ce"]/self.chemistry_data_oxides["CeO2"])**(-1), 4),
            "CoO": round((self.chemistry_data["Co"]/self.chemistry_data_oxides["CoO"])**(-1), 4),
            "CrO": round((self.chemistry_data["Cr"]/self.chemistry_data_oxides["CrO"])**(-1), 4),
            "Cr2O3": round((2*self.chemistry_data["Cr"]/self.chemistry_data_oxides["Cr2O3"])**(-1), 4),
            "Dy2O3": round((2*self.chemistry_data["Dy"]/self.chemistry_data_oxides["Dy2O3"])**(-1), 4),
            "Er2O3": round((2*self.chemistry_data["Er"]/self.chemistry_data_oxides["Er2O3"])**(-1), 4),
            "Eu2O3": round((2*self.chemistry_data["Eu"]/self.chemistry_data_oxides["Eu2O3"])**(-1), 4),
            "Gd2O3": round((2*self.chemistry_data["Gd"]/self.chemistry_data_oxides["Gd2O3"])**(-1), 4),
            "HfO2": round((self.chemistry_data["Hf"]/self.chemistry_data_oxides["HfO2"])**(-1), 4),
            "HgO": round((self.chemistry_data["Hg"]/self.chemistry_data_oxides["HgO"])**(-1), 4),
            "Ho2O3": round((2*self.chemistry_data["Ho"]/self.chemistry_data_oxides["Ho2O3"])**(-1), 4),
            "In2O3": round((2*self.chemistry_data["In"]/self.chemistry_data_oxides["In2O3"])**(-1), 4),
            "IrO": round((self.chemistry_data["Ir"]/self.chemistry_data_oxides["IrO"])**(-1), 4),
            "La2O3": round((2*self.chemistry_data["La"]/self.chemistry_data_oxides["La2O3"])**(-1), 4),
            "Lu2O3": round((2*self.chemistry_data["Lu"]/self.chemistry_data_oxides["Lu2O3"])**(-1), 4),
            "MnO2": round((self.chemistry_data["Mn"]/self.chemistry_data_oxides["MnO2"])**(-1), 4),
            "MoO3": round((self.chemistry_data["Mo"]/self.chemistry_data_oxides["MoO3"])**(-1), 4),
            "N2O5": round((2*self.chemistry_data["N"]/self.chemistry_data_oxides["N2O5"])**(-1), 4),
            "Nb2O5": round((2*self.chemistry_data["Nb"]/self.chemistry_data_oxides["Nb2O5"])**(-1), 4),
            "Nd2O3": round((2*self.chemistry_data["Nd"]/self.chemistry_data_oxides["Nd2O3"])**(-1), 4),
            "NiO": round((self.chemistry_data["Ni"]/self.chemistry_data_oxides["NiO"])**(-1), 4),
            "OsO": round((self.chemistry_data["Os"]/self.chemistry_data_oxides["OsO"])**(-1), 4),
            "P2O5": round((2*self.chemistry_data["P"]/self.chemistry_data_oxides["P2O5"])**(-1), 4),
            "PbO2": round((self.chemistry_data["Pb"]/self.chemistry_data_oxides["PbO2"])**(-1), 4),
            "PdO": round((self.chemistry_data["Pd"]/self.chemistry_data_oxides["PdO"])**(-1), 4),
            "Pr2O3": round((2*self.chemistry_data["Pr"]/self.chemistry_data_oxides["Pr2O3"])**(-1), 4),
            "Pr6O11": round((6*self.chemistry_data["Pr"]/self.chemistry_data_oxides["Pr6O11"])**(-1), 4),
            "PtO": round((self.chemistry_data["Pt"]/self.chemistry_data_oxides["PtO"])**(-1), 4),
            "ReO": round((self.chemistry_data["Re"]/self.chemistry_data_oxides["ReO"])**(-1), 4),
            "RhO": round((self.chemistry_data["Rh"]/self.chemistry_data_oxides["RhO"])**(-1), 4),
            "RuO": round((self.chemistry_data["Ru"]/self.chemistry_data_oxides["RuO"])**(-1), 4),
            "SO4": round((self.chemistry_data["S"]/self.chemistry_data_oxides["SO4"])**(-1), 4),
            "Sb2O5": round((2*self.chemistry_data["Sb"]/self.chemistry_data_oxides["Sb2O5"])**(-1), 4),
            "Sc2O3": round((2*self.chemistry_data["Sc"]/self.chemistry_data_oxides["Sc2O3"])**(-1), 4),
            "SeO3": round((self.chemistry_data["Se"]/self.chemistry_data_oxides["SeO3"])**(-1), 4),
            "Sm2O3": round((2*self.chemistry_data["Sm"]/self.chemistry_data_oxides["Sm2O3"])**(-1), 4),
            "Ta2O5": round((2*self.chemistry_data["Ta"]/self.chemistry_data_oxides["Ta2O5"])**(-1), 4),
            "Tb2O3": round((2*self.chemistry_data["Tb"]/self.chemistry_data_oxides["Tb2O3"])**(-1), 4),
            "Tb4O7": round((4*self.chemistry_data["Tb"]/self.chemistry_data_oxides["Tb4O7"])**(-1), 4),
            "TeO3": round((self.chemistry_data["Te"]/self.chemistry_data_oxides["TeO3"])**(-1), 4),
            "ThO2": round((self.chemistry_data["Th"]/self.chemistry_data_oxides["ThO2"])**(-1), 4),
            "Tl2O3": round((2*self.chemistry_data["Tl"]/self.chemistry_data_oxides["Tl2O3"])**(-1), 4),
            "Tm2O3": round((2*self.chemistry_data["Tm"]/self.chemistry_data_oxides["Tm2O3"])**(-1), 4),
            "UO2": round((self.chemistry_data["U"]/self.chemistry_data_oxides["UO2"])**(-1), 4),
            "UO3": round((self.chemistry_data["U"]/self.chemistry_data_oxides["UO3"])**(-1), 4),
            "U3O8": round((3*self.chemistry_data["U"]/self.chemistry_data_oxides["U3O8"])**(-1), 4),
            "V2O5": round((2*self.chemistry_data["V"]/self.chemistry_data_oxides["V2O5"])**(-1), 4),
            "Y2O3": round((2*self.chemistry_data["Y"]/self.chemistry_data_oxides["Y2O3"])**(-1), 4),
            "Yb2O3": round((2*self.chemistry_data["Yb"]/self.chemistry_data_oxides["Yb2O3"])**(-1), 4),
            "ZrO2": round((self.chemistry_data["Zr"]/self.chemistry_data_oxides["ZrO2"])**(-1), 4),
            "I2O4": round((2*self.chemistry_data["I"]/self.chemistry_data_oxides["I2O4"])**(-1), 4),
            "I2O5": round((2*self.chemistry_data["I"]/self.chemistry_data_oxides["I2O5"])**(-1), 4),
            "I4O9": round((4*self.chemistry_data["I"]/self.chemistry_data_oxides["I4O9"])**(-1), 4),
            "I2O": round((2*self.chemistry_data["I"]/self.chemistry_data_oxides["I2O"])**(-1), 4),
            "Co2O3": round((2*self.chemistry_data["Co"]/self.chemistry_data_oxides["Co2O3"])**(-1), 4),
            "Ni2O3": round((2*self.chemistry_data["Ni"]/self.chemistry_data_oxides["Ni2O3"])**(-1), 4)}

        # self.chemistry_oxides_sorted = {
        #     "H": ["H2O"], "Li": ["Li2O"], "Be": ["BeO"], "B": ["B2O3"], "C": ["CO", "CO2"],
        #     "N": ["NO", "N2O3", "NO2", "N2O5"], "Na": ["Na2O"], "Mg": ["MgO"], "Al": ["Al2O3"], "Si": ["SiO2"],
        #     "P": ["P2O3", "P2O5"], "S": ["SO", "SO2", "SO3"], "Cl": ["Cl2O", "ClO2", "Cl2O3", "Cl2O5", "Cl2O7"],
        #     "K": ["K2O"], "Ca": ["CaO"], "Sc": ["Sc2O3"], "Ti": ["Ti2O3", "TiO2"], "V": ["VO", "V2O3", "VO2", "V2O5"],
        #     "Cr": ["CrO", "Cr2O3", "CrO3"], "Mn": ["MnO", "Mn2O3", "MnO2", "MnO3", "Mn2O7"],
        #     "Fe": ["FeO", "Fe2O3", "FeO3"], "Co": ["CoO", "Co2O3"], "Ni": ["NiO", "Ni2O3"], "Cu": ["Cu2O", "CuO"],
        #     "Zn": ["ZnO"], "Ga": ["Ga2O3"], "Ge": ["GeO2"], "As": ["As2O3", "As2O5"], "Se": ["SeO2", "SiO3"],
        #     "Br": ["Br2O", "Br2O3", "Br2O5", "Br2O7"], "Kr": ["KrO"], "Rb": ["Rb2O"], "Sr": ["SrO"], "Y": ["Y2O3"],
        #     "Zr": ["ZrO2"], "Nb": ["Nb2O3", "Nb2O5"], "Mo": ["MoO", "Mo2O3", "MoO2", "Mo2O5", "MoO3"], "Tc": ["Tc2O7"],
        #     "Ru": ["RuO", "Ru2O3", "RuO2", "RuO3", "RuO4"], "Rh": ["Rh2O", "RhO", "Rh2O3", "RhO2", "Rh2O5"],
        #     "Pd": ["PdO", "PdO2"], "Ag": ["Ag2O", "AgO"], "Cd": ["CdO"], "In": ["In2O3"], "Sn": ["SnO", "SnO2"],
        #     "Sb": ["Sb2O3", "Sb2O5"], "Te": ["TeO2", "TeO3"], "I": ["I2O", "I2O4", "I2O5", "I4O9"],
        #     "Xe": ["XeO", "XeO2", "XeO3"], "Cs": ["Cs2O"], "Ba": ["BaO"], "La": ["La2O3"], "Ce": ["Ce2O3", "CeO2"],
        #     "Pr": ["Pr2O3", "PrO2"], "Nd": ["Nd2O3"], "Pm": ["Pm2O3"], "Sm": ["SmO", "Sm2O3"], "Eu": ["EuO", "Eu2O3"],
        #     "Gd": ["Gd2O3"], "Tb": ["Tb2O3", "TbO2"], "Dy": ["Dy2O3"], "Ho": ["Ho2O3"], "Er": ["Er2O3"],
        #     "Tm": ["TmO", "Tm2O3"], "Yb": ["YbO", "Yb2O3"], "Lu": ["Lu2O3"], "Hf": ["HfO2"], "Ta": ["Ta2O5"],
        #     "W": ["WO", "WO2O3", "WO2", "W2O5", "WO3"], "Re": ["ReO", "ReO2", "ReO3", "Re2O7"],
        #     "Os": ["OsO", "Os2O3", "OsO2", "OsO3", "OsO4"], "Ir": ["Ir2O", "IrO", "Ir2O3", "IrO2", "IrO3"],
        #     "Pt": ["PtO", "PtO2"], "Au": ["Au2O", "Au2O3"], "Hg": ["Hg2O", "HgO"], "Tl": ["Tl2O", "Tl2O3"],
        #     "Pb": ["PbO", "PbO2"], "Bi": ["Bi2O3", "B2O5"], "Po": ["PoO", "PoO2", "PoO3"],
        #     "At": ["At2O", "At2O3", "At2O5", "At2O7"], "Rn": ["RnO"], "Fr": ["Fr2O"], "Ra": ["RaO"], "Ac": ["Ac2O3"],
        #     "Th": ["ThO2"], "Pa": ["PaO2", "Pa2O5"], "U": ["U2O3", "UO2", "U2O5", "UO3"],
        #     "Np": ["Np2O3", "NpO2", "Np2O5", "NpO3"], "Pu": ["Pu2O3", "PuO2", "Pu2O5", "PuO3"],
        #     "Am": ["Am2O3", "AmO2", "Am2O5", "AmO3"], "Cm": ["Cm2O3", "CmO2"], "Bk": ["Bk2O3", "BkO2"],
        #     "Cf": ["Cf2O3", "CfO2"], "Es": ["Es2O3"], "Fm": ["Fm2O3"], "Md": ["Md2O3"], "No": ["NoO", "No2O3"],
        #     "Lr": ["Lr2O3"]}

        self.chemistry_oxides_sorted = {
            "H": ["H2O"], "Li": ["Li2O"], "Be": ["BeO"], "B": ["B2O3"], "C": ["CO", "CO2"],
            "N": ["NO", "N2O3", "NO2", "N2O5"], "Na": ["Na2O"], "Mg": ["MgO"], "Al": ["Al2O3"], "Si": ["SiO2"],
            "P": ["P2O3", "P2O5"], "S": ["SO3"], "Cl": ["Cl2O"],
            "K": ["K2O"], "Ca": ["CaO"], "Sc": ["Sc2O3"], "Ti": ["TiO2"], "V": ["V2O5"],
            "Cr": ["CrO", "Cr2O3", "CrO3"], "Mn": ["MnO", "Mn2O3"],
            "Fe": ["FeO", "Fe2O3"], "Co": ["Co2O3"], "Ni": ["NiO", "Ni2O3"], "Cu": ["Cu2O", "CuO"],
            "Zn": ["ZnO"], "Ga": ["Ga2O3"], "Ge": ["GeO2"], "As": ["As2O3", "As2O5"], "Se": ["SeO2", "SiO3"],
            "Br": ["Br2O"], "Kr": ["KrO"], "Rb": ["Rb2O"], "Sr": ["SrO"], "Y": ["Y2O3"],
            "Zr": ["ZrO2"], "Nb": ["Nb2O3", "Nb2O5"], "Mo": ["MoO", "Mo2O3", "MoO2", "Mo2O5", "MoO3"], "Tc": ["Tc2O7"],
            "Ru": ["RuO", "Ru2O3", "RuO2", "RuO3", "RuO4"], "Rh": ["Rh2O", "RhO", "Rh2O3", "RhO2", "Rh2O5"],
            "Pd": ["PdO", "PdO2"], "Ag": ["Ag2O", "AgO"], "Cd": ["CdO"], "In": ["In2O3"], "Sn": ["SnO", "SnO2"],
            "Sb": ["Sb2O3", "Sb2O5"], "Te": ["TeO2", "TeO3"], "I": ["I2O"],
            "Xe": ["XeO", "XeO2", "XeO3"], "Cs": ["Cs2O"], "Ba": ["BaO"], "La": ["La2O3"], "Ce": ["Ce2O3", "CeO2"],
            "Pr": ["Pr2O3", "PrO2"], "Nd": ["Nd2O3"], "Pm": ["Pm2O3"], "Sm": ["SmO", "Sm2O3"], "Eu": ["EuO", "Eu2O3"],
            "Gd": ["Gd2O3"], "Tb": ["Tb2O3", "TbO2"], "Dy": ["Dy2O3"], "Ho": ["Ho2O3"], "Er": ["Er2O3"],
            "Tm": ["TmO", "Tm2O3"], "Yb": ["YbO", "Yb2O3"], "Lu": ["Lu2O3"], "Hf": ["HfO2"], "Ta": ["Ta2O5"],
            "W": ["WO", "WO2O3", "WO2", "W2O5", "WO3"], "Re": ["ReO", "ReO2", "ReO3", "Re2O7"],
            "Os": ["OsO", "Os2O3", "OsO2", "OsO3", "OsO4"], "Ir": ["Ir2O", "IrO", "Ir2O3", "IrO2", "IrO3"],
            "Pt": ["PtO", "PtO2"], "Au": ["Au2O", "Au2O3"], "Hg": ["Hg2O", "HgO"], "Tl": ["Tl2O", "Tl2O3"],
            "Pb": ["PbO", "PbO2"], "Bi": ["Bi2O3", "B2O5"], "Po": ["PoO", "PoO2", "PoO3"],
            "At": ["At2O", "At2O3", "At2O5", "At2O7"], "Rn": ["RnO"], "Fr": ["Fr2O"], "Ra": ["RaO"], "Ac": ["Ac2O3"],
            "Th": ["ThO2"], "Pa": ["PaO2", "Pa2O5"], "U": ["U2O3", "UO2", "U2O5", "UO3"],
            "Np": ["Np2O3", "NpO2", "Np2O5", "NpO3"], "Pu": ["Pu2O3", "PuO2", "Pu2O5", "PuO3"],
            "Am": ["Am2O3", "AmO2", "Am2O5", "AmO3"], "Cm": ["Cm2O3", "CmO2"], "Bk": ["Bk2O3", "BkO2"],
            "Cf": ["Cf2O3", "CfO2"], "Es": ["Es2O3"], "Fm": ["Fm2O3"], "Md": ["Md2O3"], "No": ["NoO", "No2O3"],
            "Lr": ["Lr2O3"]}

        # General Settings
        self.parent = parent
        # self.parent.tk.call("tk", "scaling", var_scaling)
        self.parent.title("PySILLS - LA-ICP-MS data reduction")
        var_geometry = ""
        var_window_width = int(440)
        var_geometry += str(var_window_width)
        var_geometry += "x"
        var_window_height = int(950)
        var_geometry += str(var_window_height)
        var_geometry += "+0+0"
        self.parent.geometry(var_geometry)
        self.parent.resizable(True, True)
        self.parent["bg"] = self.bg_colors["Very Light"]
        #
        self.list_alphabet = list(string.ascii_uppercase)
        #
        var_os = sys.platform
        self.var_os = var_os
        # ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo',
        # 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']

        if var_os == "linux":
            self.defaultFont = font.nametofont("TkDefaultFont")
            default_font = font.nametofont("TkDefaultFont")
            default_font.configure(family="Ubuntu", size=10, weight=font.BOLD)
            self.parent.option_add("*Font", default_font)
            mpl.use("TkAgg")
        elif var_os == "darwin":
            self.defaultFont = font.nametofont("TkDefaultFont")
            default_font = font.nametofont("TkDefaultFont")
            self.parent.option_add("*Font", default_font)
            mpl.use("MacOSX")
        else:
            self.defaultFont = font.nametofont("TkDefaultFont")
            # default_font = font.nametofont("TkDefaultFont")
            # self.parent.option_add("*Font", default_font)
            mpl.use("TkAgg")
        #
        ## Data Container
        self.container_elements = {}
        self.gui_elements = {}
        self.container_gui = {}
        self.window_created = {}
        menu_list = ["main", "SRM", "ma_setting", "ma_datareduction", "ma_dataexploration", "ma_datareduction_files",
                     "fi_setting", "fi_datareduction_isotopes", "fi_datareduction_files", "fi_datareduction",
                     "fi_dataexploration", "mi_setting", "mi_datareduction",
                     "mi_dataexploration", "plotting", "PSE", "salt_correction", "fi_method_setting",
                     "mi_method_setting", "se_method_setting", "dwell_times", "general_settings"]
        gui_categories = ["Label", "Button", "Option Menu", "Entry", "Frame", "Radiobutton", "Checkbox", "Listbox",
                          "Canvas", "Treeview"]
        for menu in menu_list:
            self.container_elements[menu] = {}
            self.container_elements[menu]["Label"] = []
            self.container_elements[menu]["Button"] = []
            self.container_elements[menu]["Option Menu"] = []
            self.container_elements[menu]["Entry"] = []
            self.container_elements[menu]["Frame"] = []
            self.container_elements[menu]["Radiobutton"] = []
            self.container_elements[menu]["Checkbox"] = []
            self.container_elements[menu]["Listbox"] = []
            self.container_elements[menu]["Canvas"] = []
            self.container_elements[menu]["Treeview"] = []
            self.container_gui[menu] = {}
            self.window_created[menu] = False
            #
            self.gui_elements[menu] = {}
            for gui_category in gui_categories:
                self.gui_elements[menu][gui_category] = {}
                self.gui_elements[menu][gui_category]["General"] = []
                self.gui_elements[menu][gui_category]["Specific"] = []
                self.container_gui[menu][gui_category] = {}
                self.container_gui[menu][gui_category]["General"] = []
                self.container_gui[menu][gui_category]["Specific"] = []

        ## SUBWINDOWS
        self.gui_subwindows = {}
        main_categories = ["Mineral Analysis", "Fluid Inclusions", "Melt Inclusions"]
        sub_categories = ["Check SRM", "Check IS", "Check Intervals", "Check Files"]
        gui_elements = ["Frame", "Label", "Button", "Entry", "Checkbox", "Radiobutton", "Option Menu", "Listbox",
                        "Treeview"]
        priorities = ["Permanent", "Temporary"]

        for main_category in main_categories:
            self.gui_subwindows[main_category] = {}
            for sub_category in sub_categories:
                self.gui_subwindows[main_category][sub_category] = {}
                for gui_element in gui_elements:
                    self.gui_subwindows[main_category][sub_category][gui_element] = {}
                    for priority in priorities:
                        self.gui_subwindows[main_category][sub_category][gui_element][priority] = []

        ## Container (Variables)
        categories = ["main"]
        subcategories = ["Label", "Entry", "Radiobutton", "Checkbox"]

        self.helper_option_menus = {}
        self.container_listbox_files = {"STD": None, "SMPL": None, "STD Manager": None, "SMPL Manager": None}

        self.container_var = {}
        for category in categories:
            self.container_var[category] = {}
            for subcategory in subcategories:
                self.container_var[category][subcategory] = []
        self.container_var["SRM"] = {"default": [tk.StringVar(), tk.StringVar()]}
        for variable in self.container_var["SRM"]["default"]:
            variable.set("Select SRM")
        self.container_var["isotopes"] = {"default": tk.StringVar()}
        self.container_var["acquisition times"] = {"STD": {}, "SMPL": {}}
        self.container_var["mineral"] = tk.StringVar()
        self.container_var["mineral"].set("Select Mineral")
        self.container_var["srm_window"] = {}
        self.container_var["srm_window"]["Option Menu"] = {
            "SRM": tk.StringVar(), "Mineral": tk.StringVar(), "Entry": {}}
        self.container_var["ma_setting"] = {}
        self.container_var["ma_datareduction_isotopes"] = {}
        self.container_var["ma_datareduction_files"] = {}
        self.container_var["fi_setting"] = []
        self.container_var["mi_setting"] = []
        self.container_var["fi_setting"] = {}
        self.container_var["fi_datareduction_isotopes"] = {}
        self.container_var["fi_datareduction_files"] = {}
        self.container_var["mi_setting"] = {}
        self.container_var["salt_correction"] = {}
        self.container_var["salt_correction"]["Checkboxes"] = {}
        self.container_var["salt_correction"]["Salinity"] = tk.StringVar()
        self.container_var["salt_correction"]["Salinity"].set("Set salinity")
        self.container_var["salt_correction"]["Concentration"] = {}
        self.container_var["dwell_times"] = {}
        self.container_var["dwell_times"]["Entry"] = {}
        self.container_var["dwell_times"]["Entry"]["Default"] = tk.StringVar()
        self.container_var["dwell_times"]["Entry"]["Default"].set("0.002")
        self.container_var["IS STD Default"] = tk.StringVar()
        self.container_var["IS STD Default"].set("0.0")
        self.container_var["IS SMPL Default"] = tk.StringVar()
        self.container_var["IS SMPL Default"].set("0.0")
        self.container_var["x-y diagram"] = {"x": tk.StringVar(), "y": tk.StringVar(), "z": tk.StringVar()}
        self.container_var["x-y diagram"]["x"].set("Select x")
        self.container_var["x-y diagram"]["y"].set("Select y")
        self.container_var["x-y diagram"]["z"].set("Select z")
        self.copied_file = False
        self.helper_salt_composition = {}
        self.charge_balance_check = {}
        self.counter_calculation_runs = 0
        self.molality_based_quantification = tk.BooleanVar()
        self.molality_based_quantification.set(False)
        # Quantification Method
        self.container_var["Quantification Mineral"] = {"Method": tk.StringVar()}
        self.container_var["Quantification Mineral"]["Method"].set("Internal Standard")

        # 100 wt.% Oxides
        self.container_var["Oxides Quantification"] = {"Major": {}, "Minor": {}, "Ratios": {}, "Total Amounts": {}}
        self.container_var["Oxides Quantification INCL"] = {"Major": {}, "Minor": {}, "Ratios": {}, "Total Amounts": {}}
        list_major_oxides = [
            "SiO2", "TiO2", "Al2O3", "FeO", "Fe2O3", "MnO", "Mn2O3", "MgO", "CaO", "Na2O", "K2O", "P2O5", "SO3"]
        list_industrial_metal_oxides = [
            "CrO", "Cr2O3", "NiO", "Ni2O3", "ZnO", "CuO", "PbO", "PbO2", "SnO2", "WO3", "MoO2", "MoO3", "V2O5", "ZrO2",
            "Nb2O5", "HfO2", "Ta2O5", "Co2O3", "ThO2", "UO2"]
        list_precious_metals = ["AgO", "PdO", "PtO", "Au2O", "OsO", "RuO", "IrO", "RhO"]
        list_rareearth_metals = [
            "Ce2O3", "Nd2O3", "La2O3", "Y2O3", "Sc2O3", "Pr2O3", "Pr6O11", "Sm2O3", "Gd2O3", "Dy2O3", "Er2O3", "Yb2O3",
            "Eu2O3", "Ho2O3", "Tb2O3", "Tb4O7", "Lu2O3", "Tm2O3"]
        list_other_elements = [
            "Li2O", "Ga2O3", "B2O3", "BeO", "GeO2", "As2O3", "Sb2O3", "BaO", "SrO", "Cl2O", "Br2O", "I2O", "Rb2O",
            "Cs2O", "Fr2O",]
        list_oxideratios = ["Fe-Ratio", "Mn-Ratio", "Pb-Ratio", "Pr-Ratio", "Tb-Ratio"]
        for oxide in list_major_oxides:
            self.container_var["Oxides Quantification"]["Major"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification"]["Major"][oxide].set(0)
            self.container_var["Oxides Quantification INCL"]["Major"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification INCL"]["Major"][oxide].set(0)
        for oxide in list_industrial_metal_oxides:
            self.container_var["Oxides Quantification"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification"]["Minor"][oxide].set(0)
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide].set(0)
        for oxide in list_precious_metals:
            self.container_var["Oxides Quantification"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification"]["Minor"][oxide].set(0)
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide].set(0)
        for oxide in list_rareearth_metals:
            self.container_var["Oxides Quantification"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification"]["Minor"][oxide].set(0)
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide].set(0)
        for oxide in list_other_elements:
            self.container_var["Oxides Quantification"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification"]["Minor"][oxide].set(0)
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide] = tk.IntVar()
            self.container_var["Oxides Quantification INCL"]["Minor"][oxide].set(0)
        for ratio in list_oxideratios:
            if "Fe" in ratio:
                value_default = "0.0"
            else:
                value_default = "1.0"

            self.container_var["Oxides Quantification"]["Ratios"][ratio] = tk.StringVar()
            self.container_var["Oxides Quantification"]["Ratios"][ratio].set(value_default)
            self.container_var["Oxides Quantification INCL"]["Ratios"][ratio] = tk.StringVar()
            self.container_var["Oxides Quantification INCL"]["Ratios"][ratio].set(value_default)

        # Detailed Data Analysis
        self.container_var["Detailed Data Analysis"] = {
            "Filename STD": tk.StringVar(), "Filename SMPL": tk.StringVar(), "Datatype": tk.IntVar(),
            "Focus": tk.IntVar(), "Intensity Results": tk.StringVar(), "Sensitivity Results": tk.StringVar(),
            "Concentration Results": tk.StringVar()}
        self.container_var["Detailed Data Analysis"]["Filename STD"].set("Select Standard File")
        self.container_var["Detailed Data Analysis"]["Filename SMPL"].set("Select Sample File")
        self.container_var["Detailed Data Analysis"]["Datatype"].set(0)
        self.container_var["Detailed Data Analysis"]["Focus"].set(1)
        self.container_var["Detailed Data Analysis"]["Intensity Results"].set("Select Parameter")
        self.container_var["Detailed Data Analysis"]["Sensitivity Results"].set("Select Parameter")
        self.container_var["Detailed Data Analysis"]["Concentration Results"].set("Select Parameter")

        self.container_var["General Settings"] = {
            "Language": tk.StringVar(), "Default Author": tk.StringVar(), "Default SRM": tk.StringVar(),
            "Colormap": tk.StringVar(), "Line width": tk.StringVar(), "File type": tk.StringVar(),
            "Delimiter": tk.StringVar(), "Default IS MA": tk.StringVar(), "Default IS FI": tk.StringVar(),
            "Default IS MI": tk.StringVar(), "Accuracy Intensity": tk.IntVar(), "Accuracy Sensitivity": tk.IntVar(),
            "Accuracy Concentration": tk.IntVar(), "Sensitivity Drift": tk.IntVar(), "LOD Selection": tk.IntVar(),
            "Desired Average": tk.IntVar(), "Interval Processing": tk.IntVar(), "BG Offset Start": tk.IntVar(),
            "BG Offset End": tk.IntVar(), "MAT Offset Start": tk.IntVar(), "MAT Offset End": tk.IntVar(),
            "Calculation Accuracy": tk.IntVar()}
        self.container_var["General Settings"]["Language"].set("English")
        self.container_var["General Settings"]["Default Author"].set("J. Doe")
        self.container_var["General Settings"]["Default SRM"].set("Select SRM")
        self.container_var["General Settings"]["Colormap"].set("turbo")
        self.container_var["General Settings"]["Line width"].set("1.0")
        self.container_var["General Settings"]["File type"].set("*.csv")
        self.container_var["General Settings"]["Delimiter"].set("semicolon")
        self.container_var["General Settings"]["Default IS MA"].set("Select IS")
        self.container_var["General Settings"]["Default IS FI"].set("Select IS")
        self.container_var["General Settings"]["Default IS MI"].set("Select IS")
        self.container_var["General Settings"]["Accuracy Intensity"].set(6)
        self.container_var["General Settings"]["Accuracy Sensitivity"].set(4)
        self.container_var["General Settings"]["Accuracy Concentration"].set(4)
        self.container_var["General Settings"]["Sensitivity Drift"].set(0)
        self.container_var["General Settings"]["LOD Selection"].set(0)
        self.container_var["General Settings"]["Desired Average"].set(1)
        self.container_var["General Settings"]["Interval Processing"].set(1)
        self.container_var["General Settings"]["BG Offset Start"].set(15)
        self.container_var["General Settings"]["BG Offset End"].set(15)
        self.container_var["General Settings"]["MAT Offset Start"].set(15)
        self.container_var["General Settings"]["MAT Offset End"].set(15)
        self.container_var["General Settings"]["Calculation Accuracy"].set(1)

        self.container_var["Plotting"] = {"MA": {"Quickview": {}, "Time-Signal": {}, "Time-Ratio": {}},
                                          "FI": {"Quickview": {}, "Time-Signal": {}, "Time-Ratio": {}},
                                          "MI": {"Quickview": {}, "Time-Signal": {}, "Time-Ratio": {}}}
        self.container_var["Subwindows"] = {"MA": {}, "FI": {}, "MI": {}}

        self.container_var["Spike Elimination Check"] = {"RB Value STD": tk.IntVar(), "RB Value SMPL": tk.IntVar()}
        self.container_var["Spike Elimination Check"]["RB Value STD"].set(1)
        self.container_var["Spike Elimination Check"]["RB Value SMPL"].set(1)
        self.container_var["Geothermometry"] = {"Titanium in Quartz": tk.IntVar()}
        self.container_var["Geothermometry"]["Titanium in Quartz"].set(0)

        self.container_var["Spike Elimination"] = {
            "STD": {"State": False}, "SMPL": {"State": False}, "Threshold": {}, "Alpha": tk.StringVar()}
        self.container_var["Spike Elimination"]["Alpha"].set("0.05")

        self.container_var["Initialization"] = {"STD": False, "SMPL": False, "ISOTOPES": False}

        self.container_icpms = {"name": None, "skipheader": 1, "skipfooter": 0, "timestamp": 0}
        self.container_var["ICP-MS Info"] = {"name": tk.StringVar(), "skipheader": tk.IntVar(),
                                             "skipfooter": tk.IntVar(), "timestamp": tk.IntVar()}
        self.container_var["ICP-MS Info"]["name"].set("Unknown ICP-MS")
        self.container_var["ICP-MS Info"]["skipheader"].set(1)
        self.container_var["ICP-MS Info"]["skipfooter"].set(0)
        self.container_var["ICP-MS Info"]["timestamp"].set(0)

        self.container_var["Halter2002"] = {
            "Dimension a": tk.StringVar(), "Dimension b": tk.StringVar(), "Rho(Host)": tk.StringVar(),
            "Rho(Incl)": tk.StringVar(), "Laser Radius": tk.StringVar(), "Name": tk.StringVar()}
        self.container_var["Halter2002"]["Dimension a"].set("50.0")
        self.container_var["Halter2002"]["Dimension b"].set("50.0")
        self.container_var["Halter2002"]["Rho(Host)"].set("2700.0")
        self.container_var["Halter2002"]["Rho(Incl)"].set("1200.0")
        self.container_var["Halter2002"]["Laser Radius"].set("75.0")
        self.container_var["Halter2002"]["Name"].set("Select isotope")

        self.container_var["Borisova2021"] = {
            "Radius Inclusion": tk.StringVar(), "Radius Host": tk.StringVar(), "Rho(Host)": tk.StringVar(),
            "Rho(Incl)": tk.StringVar(), "Name": tk.StringVar()}
        self.container_var["Borisova2021"]["Radius Inclusion"].set("50.0")
        self.container_var["Borisova2021"]["Radius Host"].set("75.0")
        self.container_var["Borisova2021"]["Rho(Host)"].set("2700.0")
        self.container_var["Borisova2021"]["Rho(Incl)"].set("1200.0")
        self.container_var["Borisova2021"]["Name"].set("Select isotope")

        self.file_system_need_update = True
        self.pypitzer_performed = False
        self.initialization_run_std = True
        self.initialization_run_smpl = True

        self.bool_incl_is_massbalance = False
        self.bool_incl_is_chargebalance = False
        self.bool_incl_is_pypitzer = False
        self.bool_incl_is_custom = False
        self.bool_incl_is_external = False
        self.str_incl_is_custom_external = "Unknown"

        self.bool_matrixonlytracer = False
        self.bool_secondinternalstandard = False
        self.bool_halter2002 = False
        self.bool_borisova2021 = False

        self.container_flags = {"STD": {"Initialization": False}, "SMPL": {"Initialization": False}}

        self.list_std_changed = False
        self.list_smpl_changed = False
        self.list_std_previous = []
        self.list_smpl_previous = []

        self.container_spike_values = {}

        self.old_file = False
        self.without_pypitzer = False
        #
        self.counter_fast_track_std = 0
        self.counter_fast_track_smpl = 0
        #
        self.container_spikes = {}
        #
        self.autodetection_bg = False
        self.autodetection_sig = False
        #
        self.init_fi_massbalance = False
        self.init_fi_chargebalance = False
        #
        self.container_checkup = {"STD": [], "SMPL": [], "Counter STD": 0, "Counter SMPL": 0}
        #
        ## ALL
        self.container_intensity = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_intensity_mix = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_intensity_corrected = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_intensity_ratio = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_normalized_sensitivity = {"STD": {"RAW": {}, "SMOOTHED": {}},
                                                 "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_analytical_sensitivity = {"STD": {"RAW": {}, "SMOOTHED": {}},
                                                 "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_rsf = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_concentration = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_mixed_concentration = {"SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_mixed_concentration_error = {"SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_concentration_ratio = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_lod = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_mixed_concentration_ratio = {"SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_mixing_ratio = {"SMPL": {"RAW": {}, "SMOOTHED": {}}}
        #
        self.container_signs = {"STD": {}, "SMPL": {}}
        self.rb_report = tk.IntVar()
        self.rb_report.set(0)

        ## LANGUAGE SUPPORT
        self.language_dict = {
            "Select Mode": {
                "English": "Select Mode", "German": "Modusauswahl", "Chinese": "选择模式",
                "Greek": "Επιλέξτε Λειτουργία",
                "Russian": "Выбор режима", "Spanish": "Seleccionar modo", "Italian": "Selezionare la modalità"},
            "Standard Files": {"English": "Standard Files", "German": "Standardmessungen", "Chinese": "标准文件"},
            "Sample Files": {"English": "Sample Files", "German": "Probenmessungen", "Chinese": "样本文件"},
            "ICP-MS File Setup": {"English": "ICP-MS File Setup", "German": "ICP-MS Dateikonfiguration"},
            "Select ICP-MS": {"English": "Select ICP-MS", "German": "ICP-MS Auswahl"},
            "Define ICP-MS": {"English": "Define ICP-MS", "German": "ICP-MS einstellen"},
            "Add": {"English": "Add", "German": "Hinzufügen"},
            "Standard file": {"English": "Standard file", "German": "Standardmessung"},
            "Sample file": {"English": "Sample file", "German": "Probenmessung"},
            "Confirm all": {"English": "Confirm all", "German": "Alles bestätigen"},
            "Measured isotopes": {"English": "Measured isotopes", "German": "Isotopenübersicht"},
            "Copy": {"English": "Copy", "German": "Kopieren"},
            "Delete": {"English": "Delete", "German": "Löschen"},
            "Rename": {"English": "Rename", "German": "Umbenennen"},
            "Time-Signal Diagram": {"English": "Time-Signal Diagram", "German": "Zeit-Signal Diagramm"},
            "New Project": {"English": "New Project", "German": "Neues Projekt"},
            "Load Project": {"English": "Open Project", "German": "Projekt laden"},
            "Save Project": {"English": "Save Project", "German": "Projekt speichern"},
            "General Settings": {"English": "Main Settings", "German": "Haupteinstellungen"},
            "About": {"English": "About PySILLS", "German": "Über PySILLS"},
            "Before": {"English": "Before", "German": "Zurück"},
            "Next": {"English": "Next", "German": "Weiter"},
            "Quit": {"English": "Quit", "German": "Beenden"},
            "Manager": {"English": "Manager", "German": "Manager"},
            "Setup": {"English": "Setup", "German": "Einstellungen"},
            "Select ICP-MS": {"English": "Select ICP-MS", "German": "ICP-MS Auswahl"},
            "Mineral Analysis": {"English": "Mineral Analysis", "German": "Minerale"},
            "Settings": {"English": "Settings", "German": "Einstellungen"},
            "Results": {"English": "Results", "German": "Ergebnisse"},
            "Extras": {"English": "Extras", "German": "Extras"},
            "Fluid Inclusions": {"English": "Fluid Inclusions", "German": "Flüssigkeitseinschlüsse"},
            "Melt Inclusions": {"English": "Melt Inclusions", "German": "Schmelzeinschlüsse"},
            "Development": {"English": "Development", "German": "Entwicklung"},
            "Additional Information": {"English": "Additional Information", "German": "Weitere Informationen"},
            "Citation": {"English": "Citing PySILLS", "German": "PySILLS zitieren"},
            "Matrix Settings": {"English": "Matrix Settings", "German": "Einstellungen - Matrix"},
            "References": {"English": "References", "German": "Quellen"},
            "Project Information": {"English": "Project Information", "German": "Projektinformationen"},
            "Calculation Accuracy": {"English": "Calculation Accuracy", "German": "Numerische Genauigkeit"},
            "Sensitivity Drift": {"English": "Sensitivity Drift", "German": "Sensitivitätsverschiebung"},
            "Limit of Detection": {"English": "Limit of Detection", "German": "Nachweisgrenze"},
            "Offset Automatic Interval Detection": {
                "English": "Offset Automatic Interval Detection",
                "German": "Versatz der automatischen Intervalerkennung"},
            "Colormap": {"English": "Colormap", "German": "Farbpalette"},
            "Report File": {"English": "Report File", "German": "Ausgabedatei"},
            "Plotting Setup": {"English": "Plotting Setup", "German": "Diagrammeinstellungen"},
            "Language Selection": {"English": "Language Selection", "German": "Sprachauswahl"},
            "Data Processing": {"English": "Data Processing", "German": "Datenverarbeitung"},
            "MINERAL ANALYSIS - Setup": {
                "English": "MINERAL ANALYSIS - Setup", "German": "MINERALANALYSE - Einstellungen"},
            "Author": {"English": "Author", "German": "Autor"},
            "Source ID": {"English": "Source ID", "German": "Proben ID"},
            "Standard Reference Material (SRM)": {
                "English": "Standard Reference Material (SRM)", "German": "Standard/Referenzmaterial (SRM)"},
            "Isotopes": {"English": "Isotopes", "German": "Isotope"},
            "Dwell times (in s)": {"English": "Dwell times (in s)", "German": "Haltezeiten (in s)"},
            "Sample Settings": {"English": "Sample Settings", "German": "Probeneinstellungen"},
            "Dwell Time Settings": {"English": "Dwell Time Settings", "German": "Einstellungen - Haltezeiten"},
            "Default Time Window (Background)": {
                "English": "Default Time Interval (Background)", "German": "Einstellungen Zeitintervall (Untergrund)"},
            "Default Time Window (Matrix)": {
                "English": "Default Time Interval (Matrix)", "German": "Einstellungen - Zeitintervall (Matrix)"},
            "Default Time Window (Sample)": {
                "English": "Default Time Interval (Sample)", "German": "Einstellungen - Zeitintervall (Probe)"},
            "Check-Up - Standard Reference Material": {
                "English": "Check-Up - Standard Reference Material",
                "German": "Kontrolle - Standard/Referenzmaterial (SRM)"},
            "SRM values": {"English": "SRM values", "German": "SRM Werte"},
            "Name": {"English": "Name", "German": "Name"},
            "SRM": {"English": "SRM", "German": "SRM"},
            "Concentration (ppm)": {"English": "Concentration (ppm)", "German": "Konzentration (ppm)"},
            "Element": {"English": "Element", "German": "Element"},
            "Start": {"English": "Start", "German": "Start"},
            "End": {"English": "End", "German": "Ende"},
            "Run": {"English": "Run", "German": "Ausführen"},
            "Spike Elimination": {"English": "Spike Elimination", "German": "Einstellungen - Ausreißer"},
            "Calculation Method": {"English": "Calculation Method", "German": "Berechnungsmethode"},
            "Check-Up": {"English": "Check-Up", "German": "Kontrolle"},
            "Internal Standard": {"English": "Internal Standard", "German": "Interner Standard"},
            "Exclude inclusion": {"English": "Exclude inclusion", "German": "Inklusion ausschließen"},
            "Quantification Method": {"English": "Quantification Method", "German": "Quantifizierungsmethode"},
            "Inclusion Settings": {"English": "Inclusion Settings", "German": "Einstellungen - Flüssigkeitseinschluss"},
            "Significance level": {"English": "Significance level", "German": "Signifikanzniveau"},
            "Threshold": {"English": "Threshold", "German": "Schwellenwert"},
            "Remove all": {"English": "Remove all", "German": "Alles entfernen"},
            "Apply to all": {"English": "Apply to all", "German": "Auf alles anwenden"},
            "Check": {"English": "Check", "German": "Überprüfen"},
            "Calculation Intervals": {"English": "Calculation intervals", "German": "Zeitintervalle"},
            "Acquisition Times": {"English": "Acquisition Times", "German": "Messzeiten (Experiment)"},
            "Imported Files": {"English": "Imported Files", "German": "Importierte Dateien"},
            "100 wt.% oxides": {"English": "100 wt.% oxides", "German": "100 Gew.-% Oxide"},
            "Auto-Detection": {"English": "Auto-Detection", "German": "Auto-Erkennung"},
            "Set start time": {"English": "Set start time", "German": "Startzeit setzen"},
            "Set end time": {"English": "Set end time", "German": "Endzeit setzen"},
            "Select oxide": {"English": "Select oxide", "German": "Oxid auswählen"},
            "Select isotope": {"English": "Select isotope", "German": "Isotop auswählen"},
            "Select element": {"English": "Select element", "German": "Element auswählen"},
            "Assemblage Settings": {"English": "Assemblage Settings", "German": "Einstellungen - Assemblage"},
            "Isotope Dwell Times": {"English": "Isotope Dwell Times", "German": "Haltezeiten je Isotop"},
            "Matrix Settings": {"English": "Matrix Settings", "German": "Einstellungen - Matrix"},
            "Inclusion Settings": {"English": "Inclusion Settings", "German": "Einstellungen - Einschlüsse"},
            "Internal Standard Setup": {
                "English": "Internal Standard Setup", "German": "Einstellungen interner Standard"},
            "Oxide Calculation": {"English": "Oxide Calculation", "German": "Oxidberechnung"},
            "Default settings": {"English": "Default settings", "German": "Voreinstellungen"},
            "Select IS": {"English": "Select IS", "German": "IS auswählen"},
            "Select mineral": {"English": "Select mineral", "German": "Mineral auswählen"},
            "Element Calculation": {"English": "Element Calculation", "German": "Elementberechnung"},
            "Experimental Data": {"English": "Experimental Data", "German": "Experimentelle Daten"},
            "Custom Data": {"English": "Custom Data", "German": "Manuelle Dateneingabe"},
            "Oxide Setup": {"English": "Oxide Setup", "German": "Oxideinstellungen"},
            "Import data": {"English": "Import data", "German": "Daten importieren"},
            "Composition Setup": {"English": "Composition Setup", "German": "Zusammensetzung\n definieren"},
            "Mineral Calculation": {"English": "Mineral Calculation", "German": "Mineralberechnung"},
            "File-specific Setup": {"English": "File-specific Setup", "German": "Datei-spezifische\n Einstellungen"}}

        # str_lbl_01 = self.language_dict["Sample Files"][self.var_language]

        self.var_language = self.container_var["General Settings"]["Language"].get()

        ## MINERAL ANALYSIS
        str_var_01 = self.language_dict["Set start time"][self.var_language]
        str_var_02 = self.language_dict["Set end time"][self.var_language]
        str_var_03 = self.language_dict["Select IS"][self.var_language]
        str_var_04 = self.language_dict["Select oxide"][self.var_language]
        str_var_05 = self.language_dict["Select element"][self.var_language]
        str_var_06 = self.language_dict["Select mineral"][self.var_language]

        self.container_var["settings"] = {
            "Time BG Start": tk.StringVar(), "Time BG End": tk.StringVar(), "Time SIG Start": tk.StringVar(),
            "Time SIG End": tk.StringVar(), "Author": tk.StringVar(), "Source ID": tk.StringVar(),
            "IS Concentration": tk.StringVar(), "SE Alpha": tk.StringVar()}
        self.container_var["settings"]["Time BG Start"].set(str_var_01)
        self.container_var["settings"]["Time BG End"].set(str_var_02)
        self.container_var["settings"]["Time SIG Start"].set(str_var_01)
        self.container_var["settings"]["Time SIG End"].set(str_var_02)
        self.container_var["settings"]["Source ID"].set("RUR01")
        self.container_var["settings"]["IS Concentration"].set("0.0")
        self.container_var["settings"]["SE Alpha"].set("0.05")

        self.container_var["ma_setting"]["Data Type Plot"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Analyse Mode Plot"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Display RAW"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Display SMOOTHED"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Time-Signal Lines"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Time-Ratio Lines"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Checkboxes Isotope Diagram"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Calculation Interval"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Calculation Interval Visibility"] = {"STD": {}, "SMPL": {}}
        self.container_var["ma_setting"]["Default IS STD"] = tk.StringVar()
        self.container_var["ma_setting"]["Default IS STD"].set(str_var_03)
        self.container_var["ma_setting"]["Default IS SMPL"] = tk.StringVar()
        self.container_var["ma_setting"]["Default IS SMPL"].set(str_var_03)
        self.container_var["ma_setting"]["Time BG Start"] = tk.StringVar()
        self.container_var["ma_setting"]["Time BG Start"].set(str_var_01)
        self.container_var["ma_setting"]["Time BG End"] = tk.StringVar()
        self.container_var["ma_setting"]["Time BG End"].set(str_var_02)
        self.container_var["ma_setting"]["Time MAT Start"] = tk.StringVar()
        self.container_var["ma_setting"]["Time MAT Start"].set(str_var_01)
        self.container_var["ma_setting"]["Time MAT End"] = tk.StringVar()
        self.container_var["ma_setting"]["Time MAT End"].set(str_var_02)
        self.container_var["ma_setting"]["Author"] = tk.StringVar()
        self.container_var["ma_setting"]["Source ID"] = tk.StringVar()
        self.container_var["ma_setting"]["Source ID"].set("RUR01")
        self.container_var["ma_setting"]["Oxide"] = tk.StringVar()
        self.container_var["ma_setting"]["Oxide"].set(str_var_04)
        self.container_var["ma_setting"]["Oxide Concentration"] = tk.StringVar()
        self.container_var["ma_setting"]["Oxide Concentration"].set("100")
        self.container_var["ma_setting"]["Element"] = tk.StringVar()
        self.container_var["ma_setting"]["Element"].set(str_var_05)
        self.container_var["ma_setting"]["Element Concentration"] = tk.StringVar()
        self.container_var["ma_setting"]["Element Concentration"].set("1000000")
        self.container_var["ma_setting"]["Mineral"] = tk.StringVar()
        self.container_var["ma_setting"]["Mineral"].set(str_var_06)
        self.container_var["ma_setting"]["Mineral Concentration"] = tk.StringVar()
        self.container_var["ma_setting"]["Mineral Concentration"].set("100")
        self.container_var["ma_setting"]["SE Alpha"] = tk.StringVar()
        self.container_var["ma_setting"]["SE Alpha"].set("0.05")
        self.container_var["ma_setting"]["SE Threshold"] = tk.StringVar()
        self.container_var["ma_setting"]["SE Threshold"].set("5000")
        self.container_var["ma_setting"]["Host Setup Selection"] = tk.IntVar()
        self.container_var["ma_setting"]["Host Setup Selection"].set(1)
        self.container_var["ma_setting"]["Quantification Method"] = tk.IntVar()
        self.container_var["ma_setting"]["Quantification Method"].set(1)
        self.container_var["ma_setting"]["Time-Signal Checker"] = tk.IntVar()
        self.container_var["ma_setting"]["Time-Signal Checker"].set(1)

        self.container_var["ma_datareduction_isotopes"]["File Type"] = tk.IntVar()  # e.g. Sample files
        self.container_var["ma_datareduction_isotopes"]["File Type"].set(1)
        self.container_var["ma_datareduction_isotopes"]["Data Type"] = tk.IntVar()  # e.g. RAW data
        self.container_var["ma_datareduction_isotopes"]["Data Type"].set(0)
        self.container_var["ma_datareduction_isotopes"]["Focus"] = tk.IntVar()  # e.g. Matrix
        self.container_var["ma_datareduction_isotopes"]["Focus"].set(0)
        self.container_var["ma_datareduction_isotopes"]["Result Category"] = tk.IntVar()  # e.g. Concentration
        self.container_var["ma_datareduction_isotopes"]["Result Category"].set(0)
        self.container_var["ma_datareduction_isotopes"]["Display Option"] = tk.IntVar()  # e.g. Table mode
        self.container_var["ma_datareduction_isotopes"]["Display Option"].set(0)
        #
        self.container_var["ma_datareduction_files"]["File Type"] = tk.IntVar()  # e.g. Sample files
        self.container_var["ma_datareduction_files"]["File Type"].set(1)
        self.container_var["ma_datareduction_files"]["Data Type"] = tk.IntVar()  # e.g. RAW data
        self.container_var["ma_datareduction_files"]["Data Type"].set(0)
        self.container_var["ma_datareduction_files"]["Focus"] = tk.IntVar()  # e.g. Matrix
        self.container_var["ma_datareduction_files"]["Focus"].set(0)
        self.container_var["ma_datareduction_files"]["Result Category"] = tk.IntVar()  # e.g. Concentration
        self.container_var["ma_datareduction_files"]["Result Category"].set(0)
        self.container_var["ma_datareduction_files"]["Display Option"] = tk.IntVar()  # e.g. Table mode
        self.container_var["ma_datareduction_files"]["Display Option"].set(0)
        #
        self.container_var["ma_datareduction"] = {}
        self.container_var["ma_dataexploration"] = {}
        self.container_var["ma_datareduction"]["Option ID"] = tk.StringVar()
        self.container_var["ma_datareduction"]["Option ID"].set("Select Assemblage")
        self.container_var["ma_datareduction"]["Option IS"] = tk.StringVar()
        self.container_var["ma_datareduction"]["Option Drift"] = tk.StringVar()
        #
        self.container_var["ma_dataexploration"]["Exploration Mode"] = tk.IntVar()
        self.container_var["ma_dataexploration"]["Exploration Mode"].set(0)
        self.container_var["ma_dataexploration"]["STD File"] = tk.StringVar()
        self.container_var["ma_dataexploration"]["STD File"].set("Select File")
        self.container_var["ma_dataexploration"]["SMPL File"] = tk.StringVar()
        self.container_var["ma_dataexploration"]["SMPL File"].set("Select File")
        self.container_var["ma_dataexploration"]["Isotope"] = tk.StringVar()
        self.container_var["ma_dataexploration"]["Isotope"].set("Select Isotope")
        #
        self.var_mode_ma = False
        self.var_init_ma_setting = False
        self.var_init_ma_datareduction = False
        self.var_init_fi_datareduction = False
        self.var_init_mi_datareduction = False
        self.var_init_ma_dataexploration = False
        #
        ## FLUID/MELT INCLUSION ANALYSIS
        keys = ["fi_setting", "mi_setting"]
        for key_setting in keys:
            self.container_var[key_setting]["Time BG Start"] = tk.StringVar()
            self.container_var[key_setting]["Time BG Start"].set(str_var_01)
            self.container_var[key_setting]["Time BG End"] = tk.StringVar()
            self.container_var[key_setting]["Time BG End"].set(str_var_02)
            self.container_var[key_setting]["Time MAT Start"] = tk.StringVar()
            self.container_var[key_setting]["Time MAT Start"].set(str_var_01)
            self.container_var[key_setting]["Time MAT End"] = tk.StringVar()
            self.container_var[key_setting]["Time MAT End"].set(str_var_02)
            self.container_var[key_setting]["Time INCL Start"] = tk.StringVar()
            self.container_var[key_setting]["Time INCL Start"].set(str_var_01)
            self.container_var[key_setting]["Time INCL End"] = tk.StringVar()
            self.container_var[key_setting]["Time INCL End"].set(str_var_02)
            self.container_var[key_setting]["Author"] = tk.StringVar()
            self.container_var[key_setting]["Source ID"] = tk.StringVar()
            self.container_var[key_setting]["Source ID"].set("RUR01")
            self.container_var[key_setting]["Method"] = tk.StringVar()
            self.container_var[key_setting]["Method"].set("Select Method")
            self.container_var[key_setting]["Host Setup Selection"] = tk.IntVar()
            self.container_var[key_setting]["Host Setup Selection"].set(1)
            self.container_var[key_setting]["Inclusion Setup Selection"] = tk.IntVar()
            self.container_var[key_setting]["Inclusion Setup Selection"].set(1)
            self.container_var[key_setting]["Inclusion Setup Option"] = tk.StringVar()
            self.container_var[key_setting]["Inclusion Setup Option"].set("Mass Balance")
            self.container_var[key_setting]["Last solid"] = tk.StringVar()
            self.container_var[key_setting]["Last solid"].set("Select last solid")

            if key_setting == "mi_setting":
                self.container_var[key_setting]["Inclusion Setup Option"].set("100 wt.% Oxides")
            else:
                self.container_var[key_setting]["Inclusion Setup Option"].set("Mass Balance")

            self.container_var[key_setting]["Quantification Method"] = tk.IntVar()
            self.container_var[key_setting]["Quantification Method"].set(1)
            self.container_var[key_setting]["Quantification Method Option"] = tk.StringVar()
            self.container_var[key_setting]["Quantification Method Option"].set("Matrix-only Tracer (SILLS)")
            self.container_var[key_setting]["IS MAT Default"] = tk.StringVar()
            self.container_var[key_setting]["IS MAT Default"].set(str_var_03)
            self.container_var[key_setting]["IS MAT Default Concentration"] = tk.StringVar()
            self.container_var[key_setting]["IS MAT Default Concentration"].set("1000000")
            self.container_var[key_setting]["IS INCL Default"] = tk.StringVar()
            self.container_var[key_setting]["IS INCL Default"].set(str_var_03)
            self.container_var[key_setting]["IS INCL Default Concentration"] = tk.StringVar()
            self.container_var[key_setting]["IS INCL Default Concentration"].set("1000000")
            self.container_var[key_setting]["Oxide"] = tk.StringVar()
            self.container_var[key_setting]["Oxide"].set(str_var_04)
            self.container_var[key_setting]["Oxide Concentration"] = tk.StringVar()
            self.container_var[key_setting]["Oxide Concentration"].set("100")
            self.container_var[key_setting]["Oxide Inclusion"] = tk.StringVar()
            self.container_var[key_setting]["Oxide Inclusion"].set(str_var_04)
            self.container_var[key_setting]["Oxide Inclusion Concentration"] = tk.StringVar()
            self.container_var[key_setting]["Oxide Inclusion Concentration"].set("100")
            self.container_var[key_setting]["Element"] = tk.StringVar()
            self.container_var[key_setting]["Element"].set("Select Element")
            self.container_var[key_setting]["Element Concentration"] = tk.StringVar()
            self.container_var[key_setting]["Element Concentration"].set("100")
            self.container_var[key_setting]["Sulfide"] = tk.StringVar()
            self.container_var[key_setting]["Sulfide"].set("Select Sulfide")
            self.container_var[key_setting]["Sulfide Concentration"] = tk.StringVar()
            self.container_var[key_setting]["Sulfide Concentration"].set("100")
            self.container_var[key_setting]["Halide"] = tk.StringVar()
            self.container_var[key_setting]["Halide"].set("Select Halide")
            self.container_var[key_setting]["Halide Concentration"] = tk.StringVar()
            self.container_var[key_setting]["Halide Concentration"].set("100")
            self.container_var[key_setting]["Mineral"] = tk.StringVar()
            self.container_var[key_setting]["Mineral"].set("Select mineral")
            self.container_var[key_setting]["Mineral Concentration"] = tk.StringVar()
            self.container_var[key_setting]["Mineral Concentration"].set("100")
            self.container_var[key_setting]["Host Only"] = tk.StringVar()
            self.container_var[key_setting]["Host Only"].set("Select Isotope")
            self.container_var[key_setting]["2nd Internal"] = tk.StringVar()
            self.container_var[key_setting]["2nd Internal"].set("Select Isotope")
            self.container_var[key_setting]["2nd Internal Concentration Default"] = tk.StringVar()
            self.container_var[key_setting]["2nd Internal Concentration Default"].set("0")
            self.container_var[key_setting]["Matrix-Only Concentration Default"] = tk.StringVar()
            self.container_var[key_setting]["Matrix-Only Concentration Default"].set("0")
            self.container_var[key_setting]["Matrix Amount Default"] = tk.StringVar()
            self.container_var[key_setting]["Matrix Amount Default"].set("100")
            self.container_var[key_setting]["IS Selection"] = tk.IntVar()
            self.container_var[key_setting]["IS Selection"].set(1)
            self.container_var[key_setting]["Spike Elimination Inclusion"] = tk.IntVar()
            self.container_var[key_setting]["Spike Elimination Inclusion"].set(2)
            self.container_var[key_setting]["Check Inclusion Exclusion"] = tk.BooleanVar()
            self.container_var[key_setting]["Check Inclusion Exclusion"].set(True)
            self.container_var[key_setting]["SE Alpha"] = tk.StringVar()
            self.container_var[key_setting]["SE Alpha"].set("0.05")
            self.container_var[key_setting]["SE Threshold"] = tk.StringVar()
            self.container_var[key_setting]["SE Threshold"].set("5000")
            self.container_var[key_setting]["Inclusion Plugin"] = {
                "Intensity BG": tk.IntVar(), "Intensity MAT": tk.IntVar(), "Intensity MIX": tk.IntVar(),
                "Intensity INCL": tk.IntVar(), "Analytical Sensitivity": tk.IntVar(), "Concentration SRM": tk.IntVar()}
            self.container_var[key_setting]["Time-Signal Checker"] = tk.IntVar()
            self.container_var[key_setting]["Time-Signal Checker"].set(1)
            self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
            self.container_var[key_setting]["Inclusion Intensity Calculation"].set(0)
            self.container_var[key_setting]["Inclusion Concentration Calculation"] = tk.IntVar()
            self.container_var[key_setting]["Inclusion Concentration Calculation"].set(0)
            #
            for key, item in self.container_var[key_setting]["Inclusion Plugin"].items():
                item.set(1)
            #
            self.molar_masses_compounds = {}
            self.container_var[key_setting]["Salt Correction"] = {
                "Chlorides": {}, "Carbonates": {}, "Sulfates": {}, "Salinity": tk.StringVar(),
                "Default Salinity": tk.StringVar(), "Default Concentration": tk.StringVar(),
                "Default IS": tk.StringVar(), "Salinity SMPL": {}}
            self.container_var[key_setting]["Salt Correction"]["Salinity"].set("0.0")
            self.container_var[key_setting]["Salt Correction"]["Default Salinity"].set("Set Salinity (in %)")
            self.container_var[key_setting]["Salt Correction"]["Default Concentration"].set("0.0")
            self.container_var[key_setting]["Salt Correction"]["Default IS"].set(str_var_03)
            salt_chlorides = ["NaCl", "KCl", "CaCl2", "MgCl2", "LiCl", "FeCl2"]
            salt_carbonates = ["Na2CO3", "K2CO3", "NaHCO3"]
            salt_sulfates = ["Na2SO4"]
            for salt in salt_chlorides:
                self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt] = {
                    "State": tk.IntVar(), "Weight": tk.StringVar()}
                if salt == "NaCl":
                    self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["State"].set(1)
                    self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["Weight"].set("1.0")
                else:
                    self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["State"].set(0)
                    self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["Weight"].set("1.0")
            for salt in salt_carbonates:
                self.container_var[key_setting]["Salt Correction"]["Carbonates"][salt] = {
                    "State": tk.IntVar(), "Weight": tk.StringVar()}
                self.container_var[key_setting]["Salt Correction"]["Carbonates"][salt]["State"].set(0)
                self.container_var[key_setting]["Salt Correction"]["Carbonates"][salt]["Weight"].set("1.0")
            for salt in salt_sulfates:
                self.container_var[key_setting]["Salt Correction"]["Sulfates"][salt] = {
                    "State": tk.IntVar(), "Weight": tk.StringVar()}
                self.container_var[key_setting]["Salt Correction"]["Sulfates"][salt]["State"].set(0)
                self.container_var[key_setting]["Salt Correction"]["Sulfates"][salt]["Weight"].set("1.0")
            self.container_var[key_setting]["Data Type Plot"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Analyse Mode Plot"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Display RAW"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Display SMOOTHED"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Time-Signal Lines"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Time-Ratio Lines"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Checkboxes Isotope Diagram"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Calculation Interval"] = {"STD": {}, "SMPL": {}}
            self.container_var[key_setting]["Calculation Interval Visibility"] = {"STD": {}, "SMPL": {}}

        self.oxide_calculation_mat = tk.IntVar()
        self.oxide_calculation_incl = tk.IntVar()
        self.oxide_calculation_mat.set(0)
        self.oxide_calculation_incl.set(0)

        self.container_var["fi_datareduction_isotopes"]["File Type"] = tk.IntVar()  # e.g. Sample files
        self.container_var["fi_datareduction_isotopes"]["File Type"].set(1)
        self.container_var["fi_datareduction_isotopes"]["Data Type"] = tk.IntVar()  # e.g. RAW data
        self.container_var["fi_datareduction_isotopes"]["Data Type"].set(0)
        self.container_var["fi_datareduction_isotopes"]["Focus"] = tk.IntVar()  # e.g. Inclusion
        self.container_var["fi_datareduction_isotopes"]["Focus"].set(1)
        self.container_var["fi_datareduction_isotopes"]["Result Category"] = tk.IntVar()  # e.g. Concentration
        self.container_var["fi_datareduction_isotopes"]["Result Category"].set(0)
        self.container_var["fi_datareduction_isotopes"]["Display Option"] = tk.IntVar()  # e.g. Table mode
        self.container_var["fi_datareduction_isotopes"]["Display Option"].set(0)
        self.container_var["fi_datareduction_isotopes"]["Isotope Left Plot"] = tk.StringVar()  # e.g. Si29
        self.container_var["fi_datareduction_isotopes"]["Isotope Left Plot"].set("Select Isotope")
        self.container_var["fi_datareduction_isotopes"]["Isotope 1 Right Plot"] = tk.StringVar()  # e.g. Si29
        self.container_var["fi_datareduction_isotopes"]["Isotope 1 Right Plot"].set("Select Isotope")
        self.container_var["fi_datareduction_isotopes"]["Isotope 2 Right Plot"] = tk.StringVar()  # e.g. Si29
        self.container_var["fi_datareduction_isotopes"]["Isotope 2 Right Plot"].set("Select Isotope")
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Diagrams"] = {
            "Left": {"FIG": None, "CANVAS": None, "AX": None}, "Right": {"FIG": None, "CANVAS": None, "AX": None}}
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"] = {
            "Sensitivity Drift": {"FIG": None, "CANVAS": None, "AX": None},
            "Sensitivity Drift Change": {"FIG": None, "CANVAS": None, "AX": None},
            "Sensitivity Comparison": {"FIG": None, "CANVAS": None, "AX": None},
            "Histograms": {"FIG": None, "CANVAS": None, "AX": None},
            "Box Plots": {"FIG": None, "CANVAS": None, "AX": None}}

        self.container_var["fi_datareduction_files"]["File Type"] = tk.IntVar()  # e.g. Sample files
        self.container_var["fi_datareduction_files"]["File Type"].set(1)
        self.container_var["fi_datareduction_files"]["Data Type"] = tk.IntVar()  # e.g. RAW data
        self.container_var["fi_datareduction_files"]["Data Type"].set(0)
        self.container_var["fi_datareduction_files"]["Focus"] = tk.IntVar()  # e.g. Inclusion
        self.container_var["fi_datareduction_files"]["Focus"].set(1)
        self.container_var["fi_datareduction_files"]["Result Category"] = tk.IntVar()  # e.g. Concentration
        self.container_var["fi_datareduction_files"]["Result Category"].set(0)
        self.container_var["fi_datareduction_files"]["Display Option"] = tk.IntVar()  # e.g. Table mode
        self.container_var["fi_datareduction_files"]["Display Option"].set(0)
        self.container_var["fi_datareduction_files"]["Isotope Left Plot"] = tk.StringVar()  # e.g. Si29
        self.container_var["fi_datareduction_files"]["Isotope Left Plot"].set("Select Isotope")
        self.container_var["fi_datareduction_files"]["Isotope 1 Right Plot"] = tk.StringVar()  # e.g. Si29
        self.container_var["fi_datareduction_files"]["Isotope 1 Right Plot"].set("Select Isotope")
        self.container_var["fi_datareduction_files"]["Isotope 2 Right Plot"] = tk.StringVar()  # e.g. Si29
        self.container_var["fi_datareduction_files"]["Isotope 2 Right Plot"].set("Select Isotope")
        self.container_var["fi_datareduction_files"]["Sensitivity Diagrams"] = {
            "Left": {"FIG": None, "CANVAS": None, "AX": None}, "Right": {"FIG": None, "CANVAS": None, "AX": None}}
        #
        self.container_var["fi_datareduction"] = {}
        self.container_var["fi_dataexploration"] = {}
        self.var_mode_fi = False
        #
        self.container_var["mi_setting"]["Time BG Start"] = tk.StringVar()
        self.container_var["mi_setting"]["Time BG Start"].set("Set start time")
        self.container_var["mi_setting"]["Time BG End"] = tk.StringVar()
        self.container_var["mi_setting"]["Time BG End"].set("Set end time")
        self.container_var["mi_setting"]["Time MAT Start"] = tk.StringVar()
        self.container_var["mi_setting"]["Time MAT Start"].set("Set start time")
        self.container_var["mi_setting"]["Time MAT End"] = tk.StringVar()
        self.container_var["mi_setting"]["Time MAT End"].set("Set end time")
        self.container_var["mi_setting"]["Time INCL Start"] = tk.StringVar()
        self.container_var["mi_setting"]["Time INCL Start"].set("Set start time")
        self.container_var["mi_setting"]["Time INCL End"] = tk.StringVar()
        self.container_var["mi_setting"]["Time INCL End"].set("Set end time")
        self.container_var["mi_setting"]["Author"] = tk.StringVar()
        self.container_var["mi_setting"]["Source ID"] = tk.StringVar()
        self.container_var["mi_setting"]["Source ID"].set("RUR01")
        self.container_var["mi_datareduction"] = {}
        self.container_var["mi_dataexploration"] = {}
        self.container_var["ma_datareduction"]["Radiobutton"] = [
            tk.IntVar(), tk.IntVar(), tk.IntVar(), tk.IntVar(), tk.IntVar()]
        for var_rb in self.container_var["ma_datareduction"]["Radiobutton"]:
            var_rb.set(0)
        self.var_mode_mi = False
        #
        self.container_var["mineralchemistry"] = []
        self.container_var["plotting"] = {}
        self.container_var["IS"] = {}
        self.container_var["IS"]["Default STD"] = tk.StringVar()
        self.container_var["IS"]["Default STD"].set(str_var_03)
        self.container_var["IS"]["Default SMPL"] = tk.StringVar()
        self.container_var["IS"]["Default SMPL"].set(str_var_03)
        self.container_var["IS"]["Default SMPL Concentration"] = tk.StringVar()
        self.container_var["IS"]["Default SMPL Concentration"].set("1000000")
        self.container_var["ID"] = {}
        # self.container_var["ID"]["Default STD"] = tk.StringVar()
        # self.container_var["ID"]["Default STD"].set("A")
        self.container_var["ID"]["Default SMPL"] = tk.StringVar()
        self.container_var["ID"]["Default SMPL"].set("A")
        self.container_var["ID"]["Results Isotopes"] = tk.StringVar()
        self.container_var["ID"]["Results Isotopes"].set("A")
        self.container_var["ID"]["Results Files"] = tk.StringVar()
        self.container_var["ID"]["Results Files"].set("A")
        #self.container_var["STD"] = {}
        #self.container_var["SMPL"] = {}
        for type in ["STD", "SMPL"]:
            if type not in self.container_var:
                self.container_var[type] = {}
                self.container_var[type]["Project manager"] = tk.IntVar()
                self.container_var[type]["Project manager"].set(0)
        self.container_var["LASER"] = tk.StringVar()
        self.container_var["LASER"].set("Argon")
        self.container_var["charge"] = {}
        self.container_var["Gas Energy"] = tk.StringVar()
        self.container_var["Gas Energy"].set("15.760")
        self.container_var["Spike Elimination Method"] = tk.StringVar()
        self.container_var["Spike Elimination Method"].set("Grubbs test")
        #self.list_se_methods = ["Grubbs-Test", "Grubbs-Test (SILLS)", "PySILLS Spike Finder"]
        self.list_se_methods = ["Grubbs test", "Whisker analysis"]
        self.list_isotopes = []
        self.srm_actual = {}
        self.container_files = {}
        self.container_files["STD"] = {}
        self.container_files["SRM"] = {}
        self.container_files["SMPL"] = {}
        self.container_optionmenu = {}
        self.container_optionmenu["STD"] = {}
        self.container_optionmenu["SMPL"] = {}
        self.container_optionmenu["ISOTOPES"] = {}
        self.container_measurements = {}
        categories_01 = ["RAW", "SELECTED", "EDITED"]
        for category_01 in categories_01:
            self.container_measurements[category_01] = {}
        #
        self.mineral_chem = {}
        self.time_ratio_data = {}
        #
        self.last_rb_setup = {}
        #
        self.container_helper = {}
        self.container_helper["STD"] = {}
        self.container_helper["SMPL"] = {}
        self.container_helper["positions"] = {}
        self.container_helper["positions"]["BG STD"] = {}
        self.container_helper["positions"]["SIG STD"] = {}
        self.container_helper["positions"]["MAT STD"] = {}
        self.container_helper["positions"]["INCL STD"] = {}
        self.container_helper["positions"]["SPK STD"] = {}
        self.container_helper["positions"]["BG SMPL"] = {}
        self.container_helper["positions"]["SIG SMPL"] = {}
        self.container_helper["positions"]["MAT SMPL"] = {}
        self.container_helper["positions"]["INCL SMPL"] = {}
        self.container_helper["positions"]["SPK SMPL"] = {}
        self.container_helper["positions"]["BG"] = {}
        self.container_helper["positions"]["SIG"] = {}
        self.container_helper["positions"]["SPK"] = {}
        self.container_helper["positions"]["MAT"] = {}
        self.container_helper["positions"]["INCL"] = {}
        self.container_helper["indices"] = {}
        self.container_helper["limits BG"] = {}
        self.container_helper["limits SIG"] = {}
        self.container_helper["limits MAT"] = {}
        self.container_helper["limits INCL"] = {}
        self.container_helper["limits SPK"] = {}
        self.container_helper["limits BG Ratio"] = {}
        self.container_helper["limits SIG Ratio"] = {}
        self.container_helper["limits MAT Ratio"] = {}
        self.container_helper["limits INCL Ratio"] = {}
        self.container_helper["limits SPK Ratio"] = {}
        self.container_helper["Default BG"] = {}
        self.container_helper["Default BG"]["Times"] = [0, 0]
        self.container_helper["Default BG"]["Positions"] = [0, 0]
        self.container_helper["Default SIG"] = {}
        self.container_helper["Default SIG"]["Times"] = [0, 0]
        self.container_helper["Default SIG"]["Positions"] = [0, 0]
        #
        self.container_lists = {}
        #
        self.container_lists["Colors PySILLS"] = {}
        categories = ["Dark", "Medium", "Light", "Sign"]
        subcategories = ["Green", "Red", "Blue", "Yellow", "Brown", "Slate Grey"]
        for category in categories:
            self.container_lists["Colors PySILLS"][category] = {}
            for subcategory in subcategories:
                if category != "Sign":
                    if subcategory == "Green":
                        self.container_lists["Colors PySILLS"][category][subcategory] = green_dict[category]
                    elif subcategory == "Red":
                        self.container_lists["Colors PySILLS"][category][subcategory] = red_dict[category]
                    elif subcategory == "Blue":
                        self.container_lists["Colors PySILLS"][category][subcategory] = blue_dict[category]
                    elif subcategory == "Yellow":
                        self.container_lists["Colors PySILLS"][category][subcategory] = yellow_dict[category]
                    elif subcategory == "Brown":
                        self.container_lists["Colors PySILLS"][category][subcategory] = brown_dict[category]
                    elif subcategory == "Slate Grey":
                        self.container_lists["Colors PySILLS"][category][subcategory] = slategrey_dict[category]
                else:
                    if subcategory in ["Red", "Yellow", "Green"]:
                        self.container_lists["Colors PySILLS"][category][subcategory] = sign_dict[subcategory]

        self.container_lists["Selected Cations"] = []
        self.container_lists["Selected Anions"] = []
        self.container_lists["Possible Cations"] = []
        self.container_lists["Possible Anions"] = []
        self.container_lists["Salt Chemistry"] = {}
        self.container_lists["Selected Salts"] = []
        self.container_lists["SRM Data"] = {}
        self.container_lists["SRM"] = []
        self.container_lists["SRM Library"] = []
        self.container_lists["ICPMS Library"] = []
        self.container_lists["SRM Files"] = {}
        self.container_lists["SRM Isotopes"] = {}
        self.container_lists["IS"] = []
        self.container_lists["ID"] = []
        self.container_lists["Possible IS"] = []
        self.container_lists["ID Files"] = {}
        self.container_lists["STD"] = {}
        self.container_lists["STD"]["Long"] = []
        self.container_lists["STD"]["Short"] = []
        self.container_lists["STD"]["Old"] = []
        self.container_lists["STD"]["SRM"] = {}
        self.container_lists["SMPL"] = {}
        self.container_lists["SMPL"]["Long"] = []
        self.container_lists["SMPL"]["Short"] = []
        self.container_lists["SMPL"]["Old"] = []
        self.container_lists["ISOTOPES"] = []
        self.container_lists["Measured Isotopes"] = {}
        self.container_lists["Measured Isotopes"]["All"] = []
        self.container_lists["Possible Oxides"] = {}
        self.container_lists["Possible Oxides"]["All"] = []
        self.container_lists["Measured Elements"] = {}
        self.container_lists["Measured Elements"]["All"] = []
        self.container_lists["Acquisition Times Delta"] = {}
        self.container_lists["Analytical Sensitivity Regression"] = {}
        self.container_lists["Analytical Sensitivity Regression RAW"] = {}
        self.container_lists["Analytical Sensitivity Regression SMOOTHED"] = {}
        self.container_lists["Possible IS STD"] = []
        self.container_lists["Possible IS SMPL"] = []
        self.container_lists["Plugins FI"] = {}  # FI = Fluid Inclusion
        self.container_lists["Plugins FI"]["Names"] = []
        self.container_lists["Plugins FI"]["Files"] = []
        self.container_lists["Plugins MI"] = {}  # MI = Melt Inclusion
        self.container_lists["Plugins MI"]["Names"] = []
        self.container_lists["Plugins MI"]["Files"] = []
        self.container_lists["Plugins SE"] = {}  # SE = Spike Elimination
        self.container_lists["Plugins SE"]["Names"] = []
        self.container_lists["Plugins SE"]["Files"] = []

        self.helper_checkbuttons = {"Isotopes": {}, "On": [], "Off": []}
        self.temp_checkbuttons_pypitzer = {}

        self.container_lists["Oxides"] = []
        #self.container_lists["Oxides"] = [
        #    "SiO2", "TiO2", "Al2O3", "Fe2O3", "Fe3O4", "FeO", "MgO", "MnO", "CaO", "BaO", "Na2O", "K2O", "P2O5",
        #    "Cr2O3", "ZrO2"]
        self.container_lists["Sulfides"] = [
            "FeS2", "ZnS" "PbS", "Ag2S", "Na2S", "MoS2", "CdS", "SeS2", "BaS", "BeS", "CoS", "Cu2S", "CuS", "FeS",
            "Fe2S3", "Hg2S", "HgS", "MnS", "NiS", "Tl2S", "SnS", "SnS2"]
        self.container_lists["Halides"] = [
            "NaCl", "KCl", "KI", "LiCl", "CuCl2", "AgCl", "CaCl2", "ClF", "CH3Br", "CHI3", "HCl", "HBr"]
        self.container_lists["Elements"] = []
        self.container_lists["Selected Oxides"] = {"All": [], "Conversion Factor": {"SiO2", 2.1392}}

        self.maximum_amounts = {}

        for oxide in self.conversion_factors.keys():
            key = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide)
            element_cation = key.group(1)

            if key.group(2) != "":
                index_cation = int(key.group(2))
            else:
                index_cation = 1

            if key.group(4) != "":
                index_anion = int(key.group(4))
            else:
                index_anion = 1

            molar_mass_cation = self.chemistry_data[element_cation]
            molar_mass_anion = 15.999
            molar_mass_oxide = index_cation*molar_mass_cation + index_anion*molar_mass_anion
            amount_cation_ppm = round((index_cation*molar_mass_cation)/molar_mass_oxide*10**6, 4)

            if element_cation in self.maximum_amounts:
                if amount_cation_ppm > self.maximum_amounts[element_cation]:
                    self.maximum_amounts[element_cation] = amount_cation_ppm
            else:
                self.maximum_amounts[element_cation] = amount_cation_ppm

        self.mineral_chemistry = {}
        list_minerals = ["Quartz", "Chloro-Apatite", "Fluor-Apatite", "Hydroxy-Apatite"]
        for mineral in list_minerals:
            self.mineral_chemistry[mineral] = {}
            if mineral == "Quartz":  # SiO2
                mass_si = self.chemistry_data["Si"]
                mass_o = self.chemistry_data["O"]
                mass_total = 1*mass_si + 2*mass_o
                w_si = 1*mass_si/mass_total
                self.mineral_chemistry[mineral]["Si"] = round(w_si, 10)
            elif mineral == "Chloro-Apatite":  # Ca5 (PO4)3 Cl
                mass_ca = self.chemistry_data["Ca"]
                mass_p = self.chemistry_data["P"]
                mass_cl = self.chemistry_data["Cl"]
                mass_o = self.chemistry_data["O"]
                mass_total = 5*mass_ca + 3*(1*mass_p + 4*mass_o) + 1*mass_cl
                w_ca = 5*mass_ca/mass_total
                w_p = 3*mass_p/mass_total
                w_cl = 1*mass_cl/mass_total
                self.mineral_chemistry[mineral]["Ca"] = round(w_ca, 10)
                self.mineral_chemistry[mineral]["P"] = round(w_p, 10)
                self.mineral_chemistry[mineral]["Cl"] = round(w_cl, 10)
            elif mineral == "Fluor-Apatite":  # Ca5 (PO4)3 F
                mass_ca = self.chemistry_data["Ca"]
                mass_p = self.chemistry_data["P"]
                mass_f = self.chemistry_data["F"]
                mass_o = self.chemistry_data["O"]
                mass_total = 5*mass_ca + 3*(1*mass_p + 4*mass_o) + 1*mass_f
                w_ca = 5*mass_ca/mass_total
                w_p = 3*mass_p/mass_total
                self.mineral_chemistry[mineral]["Ca"] = round(w_ca, 10)
                self.mineral_chemistry[mineral]["P"] = round(w_p, 10)
            elif mineral == "Hydroxy-Apatite":  # Ca5 (PO4)3 (OH)
                mass_ca = self.chemistry_data["Ca"]
                mass_p = self.chemistry_data["P"]
                mass_h = self.chemistry_data["H"]
                mass_o = self.chemistry_data["O"]
                mass_total = 5*mass_ca + 3*(1*mass_p + 4*mass_o) + 1*(mass_h + mass_o)
                w_ca = 5*mass_ca/mass_total
                w_p = 3*mass_p/mass_total
                self.mineral_chemistry[mineral]["Ca"] = round(w_ca, 10)
                self.mineral_chemistry[mineral]["P"] = round(w_p, 10)

        self.container_results = {}
        self.container_results["STD"] = {}
        self.container_results["STD"]["RAW"] = {}
        self.container_results["STD"]["SMOOTHED"] = {}
        self.container_results["SMPL"] = {}
        self.container_results["SMPL"]["RAW"] = {}
        self.container_results["SMPL"]["SMOOTHED"] = {}
        self.xi_std_time = {}
        self.xi_regr = None
        #
        self.demo_view = False
        #
        self.fast_track_std = False
        self.fast_track_smpl = False
        #
        self.file_loaded = False
        #
        self.spikes_isotopes = {}
        #
        self.diagrams_setup = {}
        categories_01 = ["STD", "SMPL"]
        for category_01 in categories_01:
            self.diagrams_setup[category_01] = {}
        #
        self.container_diagrams = {}
        self.container_listboxes = {}
        categories_01 = ["STD", "SMPL"]
        for category_01 in categories_01:
            self.container_diagrams[category_01] = {}
            self.container_listboxes[category_01] = {}
            self.spikes_isotopes[category_01] = {}
        #
        # Calculation Report
        self.container_report = {}
        categories_01 = ["Total STD", "Total SMPL"]
        categories_02 = ["intensity bg", "intensity sig corr", "intensity ratio", "sensitivity", "concentration", "RSF",
                         "LOD"]
        for category_01 in categories_01:
            self.container_report[category_01] = {}
            self.container_report[category_01]["Mean"] = {}
            self.container_report[category_01]["Error"] = {}
            for category_02 in categories_02:
                self.container_report[category_01]["Mean"][category_02] = {}
                self.container_report[category_01]["Error"][category_02] = {}
                self.container_report[category_01]["Mean"][category_02]["filename"] = category_01
                self.container_report[category_01]["Error"][category_02]["filename"] = category_01
        #
        self.list_srm = np.array(
            [["NIST 606"], ["NIST 610"], ["NIST 610 (GeoReM)"], ["NIST 610 (Spandler)"], ["NIST 611"],
             ["NIST 611 (GeoReM)"], ["NIST 612"], ["NIST 612 (GeoReM)"], ["NIST 613"], ["NIST 613 (GeoReM)"],
             ["NIST 614"], ["NIST 614 (GeoReM)"], ["NIST 615"], ["NIST 615 (GeoReM)"], ["NIST 616"],
             ["NIST 616 (GeoReM)"], ["NIST 617"], ["NIST 617 (GeoReM)"], ["USGS BCR-2G (GeoReM)"],
             ["USGS GSD-1G (GeoReM)"], ["USGS GSE-1G (GeoReM)"], ["B6"], ["Durango Apatite"], ["Scapolite 17"],
             ["BAM-376"], ["BCR-2G"], ["BL-Q"], ["Br-Glass"], ["GSD-1G (GeoReM)"], ["GSE-1G (GeoReM)"], ["GSE-2G"],
             ["HAL-O"], ["K-Br"], ["MACS-3"], ["Po 724"], ["STDGL-2B2"]])[:, 0]

        self.path_pysills = os.path.dirname(os.path.realpath(sys.argv[0]))
        self.path_pysills_main = self.path_pysills

        if "/pysills" in self.path_pysills_main:
            self.path_pysills_main = self.path_pysills_main.replace("/pysills", "")
        elif "/tests" in self.path_pysills_main:
            self.path_pysills_main = self.path_pysills_main.replace("/tests", "")
        elif "/bin" in self.path_pysills_main:
            self.path_pysills_main = os.path.abspath(__file__)
            self.path_pysills_main = self.path_pysills_main.replace("/pysills_app.py", "")

        helper_srm_library = []

        try:
            folder_path = os.path.join(self.path_pysills_main, "lib", "srm")
            helper_srm_library = os.listdir(folder_path)
        except:
            helper_srm_library = os.listdir(self.path_pysills_main + str("/pysills/lib/srm/"))

        helper_srm_library.remove("__init__.py")

        try:
            helper_srm_library.remove(".DS_Store")
        except:
            pass

        helper_srm_library.sort()

        for var_srm in helper_srm_library:
            var_srm_new = var_srm.replace("_", " ")
            var_srm_new = var_srm_new.replace(".csv", "")
            if "GeoReM" in var_srm_new:
                var_srm_new = var_srm_new.replace("GeoReM", "(GeoReM)")
            if "Spandler" in var_srm_new:
                var_srm_new = var_srm_new.replace("Spandler", "(Spandler)")
            if "BAM 376" in var_srm_new:
                var_srm_new = var_srm_new.replace("BAM 376", "BAM-376")
            if "BCR 2G" in var_srm_new:
                var_srm_new = var_srm_new.replace("BCR 2G", "BCR-2G")
            if "BL Q" in var_srm_new:
                var_srm_new = var_srm_new.replace("BL Q", "BL-Q")
            if "Br Glass" in var_srm_new:
                var_srm_new = var_srm_new.replace("Br Glass", "Br-Glass")
            if " 1G" in var_srm_new:
                var_srm_new = var_srm_new.replace(" 1G", "-1G")
            if " 2G" in var_srm_new:
                var_srm_new = var_srm_new.replace(" 2G", "-2G")
            if " 2B2" in var_srm_new:
                var_srm_new = var_srm_new.replace(" 2B2", "-2B2")
            if "HAL O" in var_srm_new:
                var_srm_new = var_srm_new.replace("HAL O", "HAL-O")
            if "K Br" in var_srm_new:
                var_srm_new = var_srm_new.replace("K Br", "K-Br")
            if "MACS 3" in var_srm_new:
                var_srm_new = var_srm_new.replace("MACS 3", "MACS-3")
            if "BCR2G" in var_srm_new:
                var_srm_new = var_srm_new.replace("BCR2G", "BCR-2G")
            if "GSD1G" in var_srm_new:
                var_srm_new = var_srm_new.replace("GSD1G", "GSD-1G")
            if "GSE1G" in var_srm_new:
                var_srm_new = var_srm_new.replace("GSE1G", "GSE-1G")

            self.container_lists["SRM Library"].append(var_srm_new)

        helper_icpms_library = []

        try:
            folder_path = os.path.join(self.path_pysills_main, "lib", "icpms")
            helper_icpms_library = os.listdir(folder_path)
        except:
            helper_icpms_library = os.listdir(self.path_pysills_main + str("/pysills/lib/icpms/"))

        if "__init__.py" in helper_icpms_library:
            helper_icpms_library.remove("__init__.py")
        if ".DS_Store" in helper_icpms_library:
            helper_icpms_library.remove(".DS_Store")

        try:
            helper_icpms_library.remove(".DS_Store")
        except:
            pass

        helper_icpms_library.sort()

        for var_icpms in helper_icpms_library:
            var_icpms_new = var_icpms.replace("_", " ")
            var_icpms_new = var_icpms_new.replace(".csv", "")
            self.container_lists["ICPMS Library"].append(var_icpms_new)

        self.srm_window_checker = tk.IntVar()
        self.srm_window_checker.set(0)
        self.previous_std_list = []
        self.list_pse = PSE().get_element_names()
        self.ionization_energies = {}
        self.ionization_energies["First"] = {}
        self.ionization_energies["Second"] = {}
        for element in self.list_pse:
            data_element = PeriodicSystem(name=element).get_data()
            if len(data_element) == 13:
                self.ionization_energies["First"][element] = data_element[-2]
                self.ionization_energies["Second"][element] = data_element[-1]
            elif len(data_element) == 12:
                self.ionization_energies["First"][element] = data_element[-1]
                self.ionization_energies["Second"][element] = 0.0
        #
        self.container_settings = {}
        categories_01 = ["MA", "FI", "MI"]  # MA=Mineral Analysis, FI=Fluid Inclusions, MI=Melt Inclusions
        categories_02 = ["Start BG", "End BG", "Start SIG", "End SIG", "Start MAT", "End MAT", "Start INCL", "End INCL"]
        categories_03 = ["Deviation", "Threshold", "Author", "Source ID"]
        for category_01 in categories_01:
            self.container_settings[category_01] = {}
            for category_02 in categories_02:
                if category_01 == "MA" and category_02 in ["Start MAT", "End MAT", "Start INCL", "End INCL"]:
                    pass
                elif category_01 in ["FI", "MI"] and category_02 in ["Start SIG", "End SIG"]:
                    pass
                else:
                    self.container_settings[category_01][category_02] = tk.StringVar()
            for category_03 in categories_03:
                self.container_settings[category_01][category_03] = tk.StringVar()
        #
        self.mineral_list = ["Quartz", "Calcite", "Fluorite", "Apatite-Cl", "Apatite-F", "Apatite-OH", "Forsterite",
                             "Fayalite", "Tephroite", "Albite", "Anorthite", "Orthoclase", "Microcline", "Zircon",
                             "Enargite", "Pyrite", "Chalcopyrite", "Bornite", "Arsenopyrite", "Sphalerite", "Galena",
                             "Molybdenite", "Hematite", "Magnetite", "Chromite", "Gahnite", "Meionite", "Marialite",
                             "Strontianite", "Titanite", "Aegirine", "Diopside", "Hedenbergite", "Ferrosilite",
                             "Enstatite", "Monazite-La", "Monazite-Ce", "Monazite-Pr", "Monazite-Nd", "Monazite-Sm",
                             "Monazite-Eu", "Monazite-Gd", "Monazite-Th", "Barite", "Ilvaite"]
        self.mineral_list.sort()
        self.container_lists["Minerals"] = self.mineral_list
        #
        self.calculate_mineral_chemistry()
        self.create_srm_data_list()
        #
        window_width = var_window_width
        window_height = var_window_height
        row_min = 25
        row_min = int(var_window_height/40)
        n_rows = int(window_height/row_min)
        column_min = 20
        column_min = int(var_window_width/90)
        n_columns = int(window_width/column_min)
        row_min = 25
        self.n_rows = 38
        window_height = int(row_min*self.n_rows)
        column_min = 20
        self.n_columns = 22
        window_width = int(column_min*self.n_columns)
        var_geometry = str(window_width) + "x" + str(window_height) + "+0+0"
        self.parent.geometry(var_geometry)
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(self.parent, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.parent, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            self.parent.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.parent.grid_columnconfigure(i, minsize=column_min)

        ################################################################################################################
        #
        ## FRAMES
        #
        frame_01 = tk.Frame(self.parent, bg=self.bg_colors["Super Dark"], borderwidth=0, highlightthickness=0)
        frame_01.grid(row=0, column=0, rowspan=42, columnspan=22, sticky="nesw")
        frame_02 = tk.Frame(self.parent, bg=self.red_dark, borderwidth=0, highlightthickness=0)
        frame_02.grid(row=2, column=0, rowspan=1, columnspan=22, sticky="nesw")
        #
        ## USER SETTINGS
        project_path_prew = self.path_pysills[:]
        project_path = project_path_prew.strip("/pysills")

        try:
            file_usersettings = open(self.path_pysills_main + str("/user_settings.txt"), "r")
            for index, file_data in enumerate(file_usersettings):
                file_data_splitted = file_data.split(";")

                try:
                    self.container_var["General Settings"][file_data_splitted[0]].set(file_data_splitted[1])
                except:
                    pass

                if "Dwell Times" in file_data_splitted:
                    self.container_var["dwell_times"]["Entry"]["Default"].set(file_data_splitted[1])
        except:
            print("There is no user_settings file!")

        ## GUI
        self.pysills_mode = None
        self.demo_mode = True

        self.place_main_window_static_elements()

        ## Initialization
        self.quick_plot_figure_std = Figure(
            figsize=(10, 5), dpi=150, tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.quick_plot_figure_smpl = Figure(
            figsize=(10, 5), dpi=150, tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.lb_std.bind("<Double-1>", lambda event, var_filetype="STD": self.quick_plot_file(var_filetype, event))
        self.lb_smpl.bind("<Double-1>", lambda event, var_filetype="SMPL": self.quick_plot_file(var_filetype, event))
        self.select_experiment(var_rb=self.var_rb_mode)

    def place_main_window_static_elements(self):
        # Initial constants
        start_row = 3
        start_column = 0
        n_rows_header = 2
        common_n_rows = 1
        common_n_columns = 10
        n_columns_button = 3
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_header = self.bg_colors["Super Dark"]
        background_color_elements = self.bg_colors["Light"]
        background_color_listbox = self.bg_colors["Very Light"]
        accent_color = self.accent_color
        font_header = "sans 14 bold"
        font_elements = "sans 10 bold"
        self.var_language = self.container_var["General Settings"]["Language"].get()
        self.update_variables_initial_values()
        ## Logo
        try:
            try:
                if self.var_os in ["darwin", "linux"]:
                    if r"/pysills" in self.path_pysills_main:
                        pysills_logo = tk.PhotoImage(file=self.path_pysills_main + str(r"/lib/images/PySILLS_Logo.png"))
                    else:
                        pysills_logo = tk.PhotoImage(
                            file=self.path_pysills_main + str("/pysills/lib/images/PySILLS_Logo.png"))
                else:
                    if r"\pysills" in self.path_pysills_main:
                        pysills_logo = tk.PhotoImage(file=self.path_pysills_main + str(r"\lib\images\PySILLS_Logo.png"))
                    else:
                        pysills_logo = tk.PhotoImage(
                            file=self.path_pysills_main + str(r"\pysills\lib\images\PySILLS_Logo.png"))
            except:
                if self.var_os in ["darwin", "linux"]:
                    pysills_logo = tk.PhotoImage(file=self.path_pysills + str(
                        r"/pysills/lib/images/PySILLS_Logo.png"))
                else:
                    pysills_logo = tk.PhotoImage(file=self.path_pysills + str(
                        r"\pysills\lib/images\PySILLS_Logo.png"))

            pysills_logo = pysills_logo.subsample(1, 1)
            img = tk.Label(self.parent, image=pysills_logo, bg=background_color_header)
            img.image = pysills_logo
            img.grid(
                row=start_row - 3, column=start_column, rowspan=n_rows_header, columnspan=common_n_columns + 12,
                sticky="nesw")
        except:
            self.parent.bell()
            print("There is a problem with the PySILLS header image.")

        ## Icon
        try:
            try:
                if self.var_os in ["darwin", "linux"]:
                    if r"/pysills" in self.path_pysills_main:
                        pysills_icon = tk.PhotoImage(file=self.path_pysills_main + str(r"/lib/images/PySILLS_Icon.png"))
                    else:
                        pysills_icon = tk.PhotoImage(
                            file=self.path_pysills_main + str(r"/pysills/lib/images/PySILLS_Icon.png"))
                else:
                    if r"\pysills" in self.path_pysills_main:
                        pysills_icon = tk.PhotoImage(file=self.path_pysills_main + str(r"\lib\images\PySILLS_Icon.png"))
                    else:
                        pysills_icon = tk.PhotoImage(
                            file=self.path_pysills_main + str(r"\pysills\lib\images\PySILLS_Icon.png"))
            except:
                if self.var_os in ["darwin", "linux"]:
                    pysills_icon = tk.PhotoImage(file=self.path_pysills + str(r"/pysills/lib/images/PySILLS_Icon.png"))
                else:
                    pysills_icon = tk.PhotoImage(file=self.path_pysills + str(r"\pysills\lib\images\PySILLS_Icon.png"))

            self.parent.iconphoto(False, pysills_icon)
        except:
            self.parent.bell()
            print("There is a problem with the PySILLS icon.")

        # LABELS
        var_lbl_01 = self.language_dict["Select Mode"][self.var_language]
        var_lbl_02 = self.language_dict["Standard Files"][self.var_language]
        var_lbl_03 = self.language_dict["Sample Files"][self.var_language]
        var_lbl_04 = self.language_dict["ICP-MS File Setup"][self.var_language]
        var_lbl_04b = self.language_dict["Select ICP-MS"][self.var_language]
        var_lbl_04c = self.language_dict["Define ICP-MS"][self.var_language]

        lbl_01 = SE(
            parent=self.parent, row_id=start_row, column_id=start_column, n_rows=n_rows_header,
            n_columns=common_n_columns, fg=font_color_light, bg=background_color_header).create_simple_label(
            text="PySILLS", relief=tk.FLAT, fontsize=font_header)
        lbl_01 = SE(
            parent=self.parent, row_id=start_row, column_id=start_column + 11, n_rows=n_rows_header,
            n_columns=common_n_columns, fg=font_color_light, bg=background_color_header).create_simple_label(
            text=var_lbl_01, relief=tk.FLAT, fontsize=font_header)
        lbl_02 = SE(
            parent=self.parent, row_id=start_row + 18, column_id=start_column, n_rows=n_rows_header,
            n_columns=common_n_columns, fg=font_color_light, bg=background_color_header).create_simple_label(
            text=var_lbl_02, relief=tk.FLAT, fontsize=font_header)
        lbl_03 = SE(
            parent=self.parent, row_id=start_row + 18, column_id=start_column + 11, n_rows=n_rows_header,
            n_columns=common_n_columns, fg=font_color_light, bg=background_color_header).create_simple_label(
            text=var_lbl_03, relief=tk.FLAT, fontsize=font_header)
        lbl_04 = SE(
            parent=self.parent, row_id=start_row + 14, column_id=start_column, n_rows=n_rows_header,
            n_columns=common_n_columns + 11, fg=font_color_light, bg=background_color_header).create_simple_label(
            text=var_lbl_04, relief=tk.FLAT, fontsize=font_header)
        lbl_04b = SE(
            parent=self.parent, row_id=start_row + 16, column_id=start_column, n_rows=common_n_rows,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=var_lbl_04b, relief=tk.FLAT, fontsize=font_elements)
        lbl_04c = SE(
            parent=self.parent, row_id=start_row + 16, column_id=start_column + common_n_columns + 1,
            n_rows=common_n_rows,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=var_lbl_04c, relief=tk.FLAT, fontsize=font_elements)
        #now = datetime.datetime.now()
        #now = now.strftime("%Y/%m/%d-%H%M")
        lbl_version = SE(
            parent=self.parent, row_id=self.n_rows - 1, column_id=start_column, n_rows=common_n_rows,
            n_columns=common_n_columns + 11, fg=font_color_light, bg=background_color_header).create_simple_label(
            text="Version: " + self.val_version, relief=tk.FLAT, fontsize="sans 8")
        lbl_dev = SE(
            parent=self.parent, row_id=start_row - 1, column_id=start_column, n_rows=common_n_rows,
            n_columns=common_n_columns + 11, fg=font_color_light, bg=accent_color).create_simple_label(
            text="Major, minor and trace element analysis of minerals, fluid and melt inclusions", relief=tk.FLAT,
            fontsize="sans 8", sticky="news")

        # LISTBOXES
        self.lb_std = SE(
            parent=self.parent, row_id=start_row + 22, column_id=start_column, n_rows=self.n_rows - 26,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_listbox).create_simple_listbox()
        self.lb_smpl = SE(
            parent=self.parent, row_id=start_row + 22, column_id=start_column + 11, n_rows=self.n_rows - 26,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_listbox).create_simple_listbox()

        self.container_listbox_files["STD"] = self.lb_std
        self.container_listbox_files["SMPL"] = self.lb_smpl

        # RADIOBUTTONS
        if self.var_language == "English":
            list_mode = ["Mineral Analysis", "Fluid Inclusions", "Melt Inclusions"]
        elif self.var_language == "German":
            list_mode = ["Minerale", "Flüssigkeitseinschlüsse", "Schmelzeinschlüsse"]

        self.var_rb_mode = tk.IntVar()
        for index, mode in enumerate(list_mode):
            rb_mode = SE(
                parent=self.parent, row_id=start_row + 2 + index, column_id=start_column + 11, n_rows=common_n_rows,
                n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
                var_rb=self.var_rb_mode, value_rb=index, color_bg=background_color_elements, fg=font_color_dark,
                text=mode, sticky="NESW", relief=tk.FLAT, font=font_elements, command=lambda var_rb=self.var_rb_mode:
                self.select_experiment(var_rb))
            if mode in ["Report Analysis"]:
                rb_mode.configure(state="disabled")

            self.gui_elements["main"]["Radiobutton"]["General"].append(rb_mode)

        # BUTTONS
        var_btn_01 = self.language_dict["Add"][self.var_language]
        var_btn_02 = self.language_dict["Copy"][self.var_language]
        var_btn_03 = self.language_dict["Delete"][self.var_language]
        var_btn_04 = self.language_dict["New Project"][self.var_language]
        var_btn_05 = self.language_dict["Load Project"][self.var_language]
        var_btn_06 = self.language_dict["Save Project"][self.var_language]
        var_btn_07 = self.language_dict["General Settings"][self.var_language]
        var_btn_08 = self.language_dict["About"][self.var_language]
        var_btn_09 = self.language_dict["Quit"][self.var_language]
        var_btn_10 = self.language_dict["Setup"][self.var_language]
        var_btn_11 = self.language_dict["Manager"][self.var_language]

        SE(
            parent=self.parent, row_id=start_row + 20, column_id=start_column, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_01, bg_active=accent_color, fg_active=font_color_dark, command=lambda datatype="STD":
            self.open_csv(datatype))
        SE(
            parent=self.parent, row_id=start_row + 21, column_id=start_column, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_02, bg_active=accent_color, fg_active=font_color_dark, command=lambda filetype="STD":
            self.copy_file(filetype))
        SE(
            parent=self.parent, row_id=start_row + 20, column_id=n_columns_button + 2, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_03, bg_active=accent_color, fg_active=font_color_dark,
            command=lambda var_lb=self.lb_std, var_list=self.list_std: self.delete_csv(var_lb, var_list))
        btn_11_std = SE(
            parent=self.parent, row_id=start_row + 21, column_id=n_columns_button + 2, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_11, bg_active=accent_color, fg_active=font_color_dark,
            command=lambda type="STD": self.project_manager(type))
        btn_11_std.configure(state="disabled")
        SE(
            parent=self.parent, row_id=start_row + 20, column_id=11, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_01, bg_active=accent_color, fg_active=font_color_dark, command=lambda datatype="SMPL":
            self.open_csv(datatype))
        SE(
            parent=self.parent, row_id=start_row + 21, column_id=11, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_02, bg_active=accent_color, fg_active=font_color_dark, command=lambda filetype="SMPL":
            self.copy_file(filetype))
        SE(
            parent=self.parent, row_id=start_row + 20, column_id=5*n_columns_button + 1, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_03, bg_active=accent_color, fg_active=font_color_dark,
            command=lambda var_lb=self.lb_smpl, var_list=self.list_smpl: self.delete_csv(var_lb, var_list))
        btn_11_smpl = SE(
            parent=self.parent, row_id=start_row + 21, column_id=5*n_columns_button + 1, n_rows=common_n_rows,
            n_columns=n_columns_button + 2, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_11, bg_active=accent_color, fg_active=font_color_dark,
            command=lambda type="SMPL": self.project_manager(type))
        btn_11_smpl.configure(state="disabled")
        SE(
            parent=self.parent, row_id=start_row + 2, column_id=start_column, n_rows=common_n_rows + 1,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=var_btn_04, bg_active=accent_color, fg_active=font_color_dark, command=self.restart_pysills)
        SE(
            parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=common_n_rows + 1,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=var_btn_05, bg_active=accent_color, fg_active=font_color_dark, command=self.open_project)
        self.btn_save_project = SE(
            parent=self.parent, row_id=start_row + 6, column_id=start_column, n_rows=common_n_rows + 1,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=var_btn_06, bg_active=accent_color, fg_active=font_color_dark, command=self.save_project)
        self.btn_save_project.configure(state="disabled")
        SE(
            parent=self.parent, row_id=start_row + 8, column_id=start_column, n_rows=common_n_rows + 1,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=var_btn_07, bg_active=accent_color, fg_active=font_color_dark,
            command=self.subwindow_general_settings)
        btn_about = SE(
            parent=self.parent, row_id=start_row + 10, column_id=start_column, n_rows=common_n_rows + 1,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=var_btn_08, bg_active=accent_color, fg_active=font_color_dark, command=self.about_pysills)
        SE(
            parent=self.parent, row_id=start_row + 12, column_id=start_column, n_rows=common_n_rows + 1,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=var_btn_09, bg_active=accent_color, fg_active=font_color_dark, command=self.close_pysills)
        btn_icp = SE(
            parent=self.parent, row_id=start_row + 17, column_id=start_column + common_n_columns + 1,
            n_rows=common_n_rows, n_columns=common_n_columns, fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=var_btn_10, bg_active=accent_color, fg_active=font_color_dark, command=self.define_icp_ms_import_setup)

        # OPTION MENUS
        self.var_opt_icp = tk.StringVar()
        str_opt_icpms = self.language_dict["Select ICP-MS"][self.var_language]
        self.var_opt_icp.set(str_opt_icpms)
        opt_icp = SE(
            parent=self.parent, row_id=start_row + 17, column_id=start_column, n_rows=common_n_rows,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_elements).create_simple_optionmenu(
            var_opt=self.var_opt_icp, var_default=self.var_opt_icp.get(),
            var_list=self.container_lists["ICPMS Library"], fg_active=font_color_dark, bg_active=accent_color,
            command=lambda var_opt=self.var_opt_icp: self.select_icp_ms(var_opt))

    def close_pysills(self):
        self.parent.quit()
        self.parent.destroy()
        exit()

    def define_icp_ms_import_setup(self):
        """Window for the ICP-MS file setup."""
        ## Window Settings
        window_width = 340
        window_height = 200
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_icpms_setup = tk.Toplevel(self.parent)
        self.subwindow_icpms_setup.title("ICP-MS File Setup")
        self.subwindow_icpms_setup.geometry(var_geometry)
        self.subwindow_icpms_setup.resizable(False, False)
        self.subwindow_icpms_setup["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_icpms_setup, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_icpms_setup, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_icpms_setup.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_icpms_setup.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 16
        int_category_n = 8

        # LABELS
        lbl_01 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="ICP-MS File Setup", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Name", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 2, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Line of Timestamp", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 3, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Skip Header", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 4, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Skip Footer", relief=tk.FLAT, fontsize="sans 10 bold")

        # ENTRIES
        current_val_name = self.container_var["ICP-MS Info"]["name"].get()
        current_val_timestamp = self.container_var["ICP-MS Info"]["timestamp"].get()
        current_val_skipheader = self.container_var["ICP-MS Info"]["skipheader"].get()
        current_val_skipfooter = self.container_var["ICP-MS Info"]["skipfooter"].get()

        entr_002 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 1, column_id=var_column_start + int_category_n,
            n_rows=1, n_columns=(var_header_n - int_category_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["ICP-MS Info"]["name"], text_default=current_val_name)
        entr_002 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 2, column_id=var_column_start + int_category_n,
            n_rows=1, n_columns=(var_header_n - int_category_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["ICP-MS Info"]["timestamp"], text_default=current_val_timestamp)
        entr_002 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 3, column_id=var_column_start + int_category_n,
            n_rows=1, n_columns=(var_header_n - int_category_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["ICP-MS Info"]["skipheader"], text_default=current_val_skipheader)
        entr_002 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 4, column_id=var_column_start + int_category_n,
            n_rows=1, n_columns=(var_header_n - int_category_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["ICP-MS Info"]["skipfooter"], text_default=current_val_skipfooter)

        # BUTTONS
        btn_02 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 6,
            column_id=var_column_start + (var_header_n - int_category_n), n_rows=1,
            n_columns=(var_header_n - int_category_n), fg=self.bg_colors["Dark Font"],
            bg=self.accent_color).create_simple_button(
            text="Confirm Settings", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.confirm_icpms_settings)
        btn_002 = SE(
            parent=self.subwindow_icpms_setup, row_id=var_row_start + 6,
            column_id=var_column_start, n_rows=1,
            n_columns=(var_header_n - int_category_n), fg=self.bg_colors["Dark Font"],
            bg=self.accent_color).create_simple_button(
            text="Save ICP-MS Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.save_icpms_settings)

    def confirm_icpms_settings(self):
        self.var_opt_icp.set(self.container_var["ICP-MS Info"]["name"].get())
        self.container_icpms["timestamp"] = self.container_var["ICP-MS Info"]["timestamp"].get()
        self.container_icpms["skipheader"] = self.container_var["ICP-MS Info"]["skipheader"].get()
        self.container_icpms["skipfooter"] = self.container_var["ICP-MS Info"]["skipfooter"].get()

    def save_icpms_settings(self):
        str_icpms_name = self.container_var["ICP-MS Info"]["name"].get()
        int_icpms_skipheader = self.container_var["ICP-MS Info"]["skipheader"].get()
        int_icpms_skipfooter = self.container_var["ICP-MS Info"]["skipfooter"].get()
        int_icpms_timestamp = self.container_var["ICP-MS Info"]["timestamp"].get()

        filename_export = filedialog.asksaveasfile(
            mode="w", initialfile=str_icpms_name, defaultextension=".csv", filetypes=[("csv", "*.csv")])
        filename_export = filename_export.name

        with open(filename_export, "w") as file_content:
            file_content.write("name" + "," + str(str_icpms_name) + "\n")
            file_content.write("skipheader" + "," + str(int_icpms_skipheader) + "\n")
            file_content.write("skipfooter" + "," + str(int_icpms_skipfooter) + "\n")
            file_content.write("timestamp" + "," + str(int_icpms_timestamp) + "\n")

    def select_icp_ms(self, var_opt):
        path = os.getcwd()
        path = self.path_pysills

        if self.file_loaded == False:
            if self.demo_mode:
                try:
                    var_instrument_raw = var_opt.get()
                except:
                    var_instrument_raw = var_opt
                var_instrument = var_instrument_raw.replace(" ", "_")
            else:
                var_instrument = var_opt.replace(" ", "_")
        else:
            var_instrument_raw = var_opt.get()
            if var_instrument_raw != "Select ICP-MS":
                var_instrument = var_instrument_raw.replace(" ", "_")

        if var_instrument_raw != "Select ICP-MS":
            try:
                file_long = self.path_pysills_main + str("/lib/icpms/" + var_instrument + ".csv")
                file_content = open(file_long)
            except:
                file_long = self.path_pysills_main + str("/pysills/lib/icpms/" + var_instrument + ".csv")
                file_content = open(file_long)

            for index, line in enumerate(file_content):
                line_parts = line.split(",")
                if "\n" in line_parts[-1]:
                    line_parts[-1] = line_parts[-1].replace("\n", "")
                try:
                    self.container_icpms[line_parts[0]] = int(line_parts[-1])
                except:
                    self.container_icpms[line_parts[0]] = line_parts[-1]

    def copy_file(self, filetype):
        if self.pysills_mode == "MA":
            info_key = "ma_setting"
        elif self.pysills_mode == "FI":
            info_key = "fi_setting"
        elif self.pysills_mode == "MI":
            info_key = "mi_setting"

        if filetype == "STD":
            var_lb = self.lb_std
            var_list = self.list_std
        elif filetype == "SMPL":
            var_lb = self.lb_smpl
            var_list = self.list_smpl

        item = var_lb.curselection()
        var_file_long = var_list[item[0]]
        var_file_long_parts = var_file_long.split(".")
        var_file_extension = var_file_long_parts[-1]
        if "_copy" in var_file_long_parts[0]:
            if "_copy" == var_file_long_parts[0][-5:]:
                str_added = "_copy2"
                file_base = var_file_long_parts[0][:-5]
            else:
                number_current = var_file_long_parts[0][-5:][-1]
                new_number = int(number_current) + 1
                str_added = "_copy" + str(new_number)
                file_base = var_file_long_parts[0][:-6]
        else:
            str_added = "_copy"
            file_base = var_file_long_parts[0]
        var_file_long_copy = file_base + str_added + "." + var_file_extension

        file_parts = var_file_long.split("/")
        file_short_original = file_parts[-1]
        file_isotopes_original = self.container_lists["Measured Isotopes"][file_short_original]

        problem_present = False
        try:
            with open(var_file_long, "r") as file:
                content = file.read()

            with open(var_file_long_copy, "w") as copied_file:
                copied_file.write(content)
        except:
            problem_present = True
            print("File cannot be read.")

        if var_file_long_copy not in var_list:
            var_list.append(var_file_long_copy)
            file_parts_copy = var_file_long_copy.split("/")
            var_file_short_copy = file_parts_copy[-1]
            var_lb.insert(tk.END, var_file_short_copy)

            self.container_lists["Measured Isotopes"][var_file_short_copy] = file_isotopes_original
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short_copy]

            self.add_needed_variables_for_later_added_files(
                filename_long=var_file_long_copy, filename_short=var_file_short_copy, filetype=filetype,
                file_isotopes=file_isotopes)

            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]

            if problem_present == False:
                dates, times = Data(filename=var_file_long_copy).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                try:
                    dates, times = Data(filename=var_file_long).import_as_list(
                        skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
                except:
                    dates = 0
                    times_input = self.container_var["acquisition times"][filetype][file_short_original].get()
                    times_input_parts = times_input.split(":")
                    times = [[times_input_parts[0], times_input_parts[1], times_input_parts[2]]]

            t_start = datetime.timedelta(hours=int(times[0][0]), minutes=int(times[0][1]), seconds=int(times[0][2]))

            if var_file_short_copy not in self.container_var["acquisition times"][filetype]:
                self.container_var["acquisition times"][filetype][var_file_short_copy] = tk.StringVar()
                self.container_var["acquisition times"][filetype][var_file_short_copy].set(
                    times[0][0] + ":" + times[0][1] + ":" + times[0][2])

            if var_file_short_copy not in self.container_measurements["RAW"]:
                self.container_measurements["RAW"][var_file_short_copy] = {}

            for key, item in self.container_measurements["RAW"][file_short_original].items():
                self.container_measurements["RAW"][var_file_short_copy][key] = item

            df_data = self.container_measurements["Dataframe"][file_short_original]
            self.container_measurements["Dataframe"][var_file_short_copy] = df_data

            if file_short_original in self.container_spikes:
                self.container_spikes[var_file_short_copy] = self.container_spikes[file_short_original].copy()
            else:
                self.container_spikes[var_file_short_copy] = {}

            self.copied_file = True

            try:
                if self.pysills_mode == "MA":
                    self.subwindow_ma_settings.destroy()
                    self.ma_settings()
                elif self.pysills_mode == "FI":
                    self.subwindow_fi_settings.destroy()
                    self.fi_settings()
                elif self.pysills_mode == "MI":
                    self.subwindow_mi_settings.destroy()
                    self.mi_settings()
            except:
                if self.pysills_mode == "MA":
                    self.ma_settings()
                elif self.pysills_mode == "FI":
                    self.fi_settings()
                elif self.pysills_mode == "MI":
                    self.mi_settings()
        else:
            file_parts_copy = var_file_long_copy.split("/")
            var_file_short_copy = file_parts_copy[-1]

            var_file_long_parts = var_file_long_copy.split(".")
            var_file_extension = var_file_long_parts[-1]

            if "_copy" in var_file_long_parts[0]:
                if "_copy" == var_file_long_parts[0][-5:]:
                    str_added = "_copy2"
                    file_base = var_file_long_parts[0][:-5]
                else:
                    number_current = var_file_long_parts[0][-5:][-1]
                    new_number = int(number_current) + 1
                    str_added = "_copy" + str(new_number)
                    file_base = var_file_long_parts[0][:-6]
            else:
                str_added = "_copy"
                file_base = var_file_long_parts[0]

            var_file_long_copy = file_base + str_added + "." + var_file_extension
            file_parts_copy = var_file_long_copy.split("/")
            var_file_short_copy = file_parts_copy[-1]
            var_list.append(var_file_long_copy)
            var_lb.insert(tk.END, var_file_short_copy)

            self.container_lists["Measured Isotopes"][var_file_short_copy] = file_isotopes_original
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short_copy]

            self.add_needed_variables_for_later_added_files(
                filename_long=var_file_long_copy, filename_short=var_file_short_copy, filetype=filetype,
                file_isotopes=file_isotopes)

            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]

            if problem_present == False:
                dates, times = Data(filename=var_file_long_copy).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                try:
                    dates, times = Data(filename=var_file_long).import_as_list(
                        skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp,
                        icpms=var_icpms)
                except:
                    dates = 0
                    times_input = self.container_var["acquisition times"][filetype][file_short_original].get()
                    times_input_parts = times_input.split(":")
                    times = [[times_input_parts[0], times_input_parts[1], times_input_parts[2]]]

            t_start = datetime.timedelta(hours=int(times[0][0]), minutes=int(times[0][1]), seconds=int(times[0][2]))

            if var_file_short_copy not in self.container_var["acquisition times"][filetype]:
                self.container_var["acquisition times"][filetype][var_file_short_copy] = tk.StringVar()
                self.container_var["acquisition times"][filetype][var_file_short_copy].set(
                    times[0][0] + ":" + times[0][1] + ":" + times[0][2])

            if var_file_short_copy not in self.container_measurements["RAW"]:
                self.container_measurements["RAW"][var_file_short_copy] = {}

            for key, item in self.container_measurements["RAW"][file_short_original].items():
                self.container_measurements["RAW"][var_file_short_copy][key] = item

            df_data = self.container_measurements["Dataframe"][file_short_original]
            self.container_measurements["Dataframe"][var_file_short_copy] = df_data

            if file_short_original in self.container_spikes:
                self.container_spikes[var_file_short_copy] = self.container_spikes[file_short_original].copy()
            else:
                self.container_spikes[var_file_short_copy] = {}

            self.copied_file = True

            try:
                if self.pysills_mode == "MA":
                    self.subwindow_ma_settings.destroy()
                    self.ma_settings()
                elif self.pysills_mode == "FI":
                    self.subwindow_fi_settings.destroy()
                    self.fi_settings()
                elif self.pysills_mode == "MI":
                    self.subwindow_mi_settings.destroy()
                    self.mi_settings()
            except:
                if self.pysills_mode == "MA":
                    self.ma_settings()
                elif self.pysills_mode == "FI":
                    self.fi_settings()
                elif self.pysills_mode == "MI":
                    self.mi_settings()

    def add_needed_variables_for_later_added_files(self, filename_long, filename_short, filetype, file_isotopes):
        if self.pysills_mode == "MA":
            info_key = "ma_setting"
        elif self.pysills_mode == "FI":
            info_key = "fi_setting"
        elif self.pysills_mode == "MI":
            info_key = "mi_setting"

        if filename_long not in self.container_lists[filetype]["Long"]:
            self.container_lists[filetype]["Long"].append(filename_long)
            self.container_lists[filetype]["Short"].append(filename_short)

        self.container_var[info_key]["Data Type Plot"][filetype][filename_short] = tk.IntVar()
        self.container_var[info_key]["Data Type Plot"][filetype][filename_short].set(0)
        self.container_var[info_key]["Analyse Mode Plot"][filetype][filename_short] = tk.IntVar()
        self.container_var[info_key]["Analyse Mode Plot"][filetype][filename_short].set(0)
        self.container_var[info_key]["Display RAW"][filetype][filename_short] = {}
        self.container_var[info_key]["Display SMOOTHED"][filetype][filename_short] = {}

        if filename_short not in self.container_var["ma_setting"]["Time-Signal Lines"][filetype]:
            self.container_var[info_key]["Time-Signal Lines"][filetype][filename_short] = {}
            self.container_var[info_key]["Time-Ratio Lines"][filetype][filename_short] = {}
            self.container_var[info_key]["Checkboxes Isotope Diagram"][filetype][filename_short] = {}
            self.container_var[info_key]["Calculation Interval"][filetype][
                filename_short] = tk.IntVar()
            self.container_var[info_key]["Calculation Interval"][filetype][filename_short].set(3)
            self.container_var[info_key]["Calculation Interval Visibility"][filetype][
                filename_short] = {}

        for isotope in file_isotopes:
            self.build_checkbutton_isotope_visibility(
                var_mode=info_key, var_filetype=filetype, var_filename_short=filename_short,
                var_isotope=isotope)

            self.container_var[info_key]["Time-Signal Lines"][filetype][filename_short][isotope] = {
                "RAW": None, "SMOOTHED": None}
            self.container_var[info_key]["Time-Ratio Lines"][filetype][filename_short][isotope] = {
                "RAW": None, "SMOOTHED": None}
            self.container_var[info_key]["Checkboxes Isotope Diagram"][filetype][filename_short][
                isotope] = {"RAW": None, "SMOOTHED": None}

        self.container_var["Plotting"][self.pysills_mode]["Quickview"] = {"Canvas": None, "Toolbar": None}
        self.container_var["Plotting"][self.pysills_mode]["Time-Signal"] = {"Canvas": None, "Toolbar": None}
        self.container_var["Plotting"][self.pysills_mode]["Time-Ratio"] = {"Canvas": None, "Toolbar": None}

    def select_experiment(self, var_rb):
        start_row = 9
        start_column = 11

        str_btn_01 = self.language_dict["Settings"][self.var_language]
        str_btn_02 = self.language_dict["Results"][self.var_language]
        str_btn_03 = self.language_dict["Extras"][self.var_language]

        if var_rb.get() == 0:  # Mineral Analysis
            self.pysills_mode = "MA"
            ## Cleaning
            for gui_category in ["Label", "Button"]:
                if len(self.gui_elements["main"][gui_category]["Specific"]) > 0:
                    for gui_item in self.gui_elements["main"][gui_category]["Specific"]:
                        gui_item.grid_remove()
                    self.gui_elements["main"][gui_category]["Specific"].clear()
            #
            ## Labels
            str_lbl_01 = self.language_dict["Mineral Analysis"][self.var_language]
            lb_01 = SE(
                parent=self.parent, row_id=start_row, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize="sans 14 bold")
            #
            self.gui_elements["main"]["Label"]["Specific"].append(lb_01)
            #
            ## Buttons
            btn_01 = SE(
                parent=self.parent, row_id=start_row + 2, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.ma_settings)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.ma_datareduction_files)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_03, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.ma_extras)

            self.gui_elements["main"]["Button"]["Specific"].extend([btn_01, btn_02, btn_03])

        elif var_rb.get() == 1:  # Fluid Inclusions
            self.pysills_mode = "FI"
            ## Cleaning
            for gui_category in ["Label", "Button"]:
                if len(self.gui_elements["main"][gui_category]["Specific"]) > 0:
                    for gui_item in self.gui_elements["main"][gui_category]["Specific"]:
                        gui_item.grid_remove()
                    self.gui_elements["main"][gui_category]["Specific"].clear()
            #
            ## Labels
            str_lbl_01 = self.language_dict["Fluid Inclusions"][self.var_language]
            if self.var_language == "German":
                str_lbl_01 = "Flüssigkeits-\neinschlüsse"
            lb_01 = SE(
                parent=self.parent, row_id=start_row, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize="sans 14 bold")
            #
            self.gui_elements["main"]["Label"]["Specific"].append(lb_01)
            #
            ## Buttons
            btn_01 = SE(
                parent=self.parent, row_id=start_row + 2, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.fi_settings)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.fi_datareduction_files)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_03, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda init=True: self.fi_extras(init))

            self.gui_elements["main"]["Button"]["Specific"].extend([btn_01, btn_02, btn_03])

        elif var_rb.get() == 2:  # Melt Inclusions
            self.pysills_mode = "MI"
            ## Cleaning
            for gui_category in ["Label", "Button"]:
                if len(self.gui_elements["main"][gui_category]["Specific"]) > 0:
                    for gui_item in self.gui_elements["main"][gui_category]["Specific"]:
                        gui_item.grid_remove()
                    self.gui_elements["main"][gui_category]["Specific"].clear()

            ## Labels
            str_lbl_01 = self.language_dict["Melt Inclusions"][self.var_language]
            lb_01 = SE(
                parent=self.parent, row_id=start_row, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize="sans 14 bold")

            self.gui_elements["main"]["Label"]["Specific"].append(lb_01)

            ## Buttons
            btn_01 = SE(
                parent=self.parent, row_id=start_row + 2, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.mi_settings)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.fi_datareduction_files)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_03, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda init=True: self.mi_extras(init))

            self.gui_elements["main"]["Button"]["Specific"].extend([btn_01, btn_02, btn_03])

        elif var_rb.get() == 3:  # Report Analysis
            self.pysills_mode = "OA"
            ## Cleaning
            for gui_category in ["Label", "Button"]:
                if len(self.gui_elements["main"][gui_category]["Specific"]) > 0:
                    for gui_item in self.gui_elements["main"][gui_category]["Specific"]:
                        gui_item.grid_remove()
                    self.gui_elements["main"][gui_category]["Specific"].clear()
            #
            ## Labels
            lb_01 = SE(
                parent=self.parent, row_id=start_row, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Report Analysis", relief=tk.FLAT, fontsize="sans 14 bold")
            #
            self.gui_elements["main"]["Label"]["Specific"].append(lb_01)
            #
            ## Buttons
            btn_01 = SE(
                parent=self.parent, row_id=start_row + 2, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=10,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_03, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.ma_datareduction_files)
            btn_03.configure(state="disabled")
            #
            self.gui_elements["main"]["Button"]["Specific"].extend([btn_01, btn_02, btn_03])

    def build_srm_database(self):
        for key, item in self.container_var["SRM"].items():
            if key != "default":
                if key in self.container_lists["Measured Isotopes"]["All"]:
                    self.container_lists["SRM Isotopes"][key] = item.get()
                else:
                    key_short = key.split("/")[-1]
                    var_srm_file = self.container_var["STD"][key]["SRM"].get()
                    self.container_lists["SRM Files"][key_short] = var_srm_file

        self.collect_srm_data()

    def collect_srm_data(self):
        helper_list = []
        for var_srm in self.container_lists["SRM Files"].values():
            if var_srm not in helper_list and var_srm != "Select SRM":
                helper_list.append(var_srm)

        if len(helper_list) > 0:
            for var_srm in helper_list:
                self.fill_srm_values(var_srm=var_srm)

    def load_data_as_dataframe(self, filename_short, filename_long, with_isotopes=False):
        if self.file_loaded == False:
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=filename_long).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=filename_long).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
        else:
            df_data = self.container_measurements["Dataframe"][filename_short]

        times = DE().get_times(dataframe=df_data)

        if with_isotopes == True:
            isotopes = DE().get_isotopes(dataframe=df_data)

        if with_isotopes == True:
            return df_data, times, isotopes
        else:
            return df_data, times

    def build_container_measurements(self, filetype, filename_short):
        index_filename = self.container_lists[filetype]["Short"].index(filename_short)
        filename_long = self.container_lists[filetype]["Long"][index_filename]

        self.container_measurements["RAW"][filename_short] = {}
        self.container_measurements["EDITED"][filename_short] = {}
        self.container_measurements["SELECTED"][filename_short] = {}
        self.container_measurements["SELECTED"][filename_short]["RAW"] = {}
        self.container_measurements["SELECTED"][filename_short]["SMOOTHED"] = {}

        df_data, times = self.load_data_as_dataframe(filename_short=filename_short, filename_long=filename_long)

        self.container_measurements["RAW"][filename_short]["Time"] = times.tolist()
        self.container_measurements["EDITED"][filename_short]["Time"] = times.tolist()
        self.container_measurements["SELECTED"][filename_short]["Time"] = times.tolist()

        file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
        for isotope in file_isotopes:
            self.container_measurements["RAW"][filename_short][isotope] = df_data[isotope].tolist()
            self.container_measurements["EDITED"][filename_short][isotope] = {}
            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope] = {}
            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope] = {}
            self.container_measurements["EDITED"][filename_short][isotope]["BG"] = []
            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["BG"] = []
            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["BG"] = []

            if self.pysills_mode == "MA":
                self.container_measurements["EDITED"][filename_short][isotope]["MAT"] = []
                self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["MAT"] = []
                self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
            elif self.pysills_mode in ["FI", "MI"]:
                self.container_measurements["EDITED"][filename_short][isotope]["MAT"] = []
                self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["MAT"] = []
                self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                self.container_measurements["EDITED"][filename_short][isotope]["INCL"] = []
                self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["INCL"] = []
                self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["INCL"] = []
                self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["INCL"] = []

    def spike_elimination_all(self, filetype, algorithm, mode="MA"):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if algorithm == "Grubbs":
            if filetype == "STD":
                for filename_long in self.list_std:
                    parts = filename_long.split("/")
                    filename_short = parts[-1]
                    #
                    self.container_measurements["RAW"][filename_short] = {}
                    self.container_measurements["EDITED"][filename_short] = {}
                    self.container_measurements["SELECTED"][filename_short] = {}
                    self.container_measurements["SELECTED"][filename_short]["RAW"] = {}
                    self.container_measurements["SELECTED"][filename_short]["SMOOTHED"] = {}
                    #
                    if self.diagrams_setup[filetype][filename_short]["FIG"] == None:
                        self.diagrams_setup[filetype][filename_short]["FIG"] = Figure(
                            figsize=(10, 5), facecolor=self.green_light)
                        self.diagrams_setup[filetype][filename_short]["AX"] = \
                            self.diagrams_setup[filetype][filename_short][
                                "FIG"].add_subplot()
                    #
                    if self.diagrams_setup[filetype][filename_short]["FIG_RATIO"] == None:
                        self.diagrams_setup[filetype][filename_short]["FIG_RATIO"] = Figure(
                            figsize=(10, 5), facecolor=self.green_light)
                        self.diagrams_setup[filetype][filename_short]["AX_RATIO"] = \
                            self.diagrams_setup[filetype][filename_short][
                                "FIG_RATIO"].add_subplot()

                    if self.file_loaded == False:
                        if self.container_icpms["name"] != None:
                            var_skipheader = self.container_icpms["skipheader"]
                            var_skipfooter = self.container_icpms["skipfooter"]
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        else:
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=3, skip_footer=1)
                    else:
                        df_data = self.container_measurements["Dataframe"][filename_short]

                    times = DE().get_times(dataframe=df_data)
                    start_time = times.iloc[0]
                    end_time = times.iloc[-1]
                    start_index = times[times == start_time].index[0]
                    end_index = times[times == end_time].index[0]
                    spk_id = 1
                    #
                    box_spk = self.diagrams_setup[filetype][filename_short]["AX"].axvspan(
                        start_time, end_time, alpha=0.125, color=self.yellow_dark)
                    box_spk_ratio = self.diagrams_setup[filetype][filename_short]["AX_RATIO"].axvspan(
                        start_time, end_time, alpha=0.125, color=self.yellow_dark)
                    #
                    isotope = "".join(self.container_lists["ISOTOPES"])
                    #
                    self.container_measurements["RAW"][filename_short]["Time"] = times.tolist()
                    self.container_measurements["EDITED"][filename_short]["Time"] = times.tolist()
                    self.container_measurements["SELECTED"][filename_short]["Time"] = times.tolist()

                    df_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                    for isotope in df_isotopes:
                        self.container_measurements["RAW"][filename_short][isotope] = df_data[isotope].tolist()
                        self.container_measurements["EDITED"][filename_short][isotope] = {}
                        self.container_measurements["SELECTED"][filename_short]["RAW"][isotope] = {}
                        self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope] = {}
                        #
                        self.container_measurements["EDITED"][filename_short][isotope]["BG"] = []
                        self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["BG"] = []
                        self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["BG"] = []
                        if mode == "MA":
                            self.container_measurements["EDITED"][filename_short][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            #
                            var_settings = "ma_setting"
                        elif mode in ["FI", "MI"]:
                            self.container_measurements["EDITED"][filename_short][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            self.container_measurements["EDITED"][filename_short][isotope]["INCL"] = []
                            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["INCL"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["INCL"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["INCL"] = []
                            if mode == "FI":
                                var_settings = "fi_setting"
                            elif mode == "MI":
                                var_settings = "mi_setting"

                        self.spikes_isotopes["STD"][filename_short][isotope] = []
                        self.spikes_isotopes["STD"][filename_short][isotope].append([start_index, end_index])

                self.do_spike_elimination_all_grubbs(filetype=filetype)
                self.fast_track_std = True
                self.counter_fast_track_std += 1
                self.container_var["Spike Elimination"]["STD"]["State"] = True
                #
                self.frm_spk_std.config(background=self.sign_green, bd=1)
                #
            elif filetype == "SMPL":
                for filename_long in self.list_smpl:
                    parts = filename_long.split("/")
                    filename_short = parts[-1]
                    #
                    self.container_measurements["RAW"][filename_short] = {}
                    self.container_measurements["EDITED"][filename_short] = {}
                    self.container_measurements["SELECTED"][filename_short] = {}
                    self.container_measurements["SELECTED"][filename_short]["RAW"] = {}
                    self.container_measurements["SELECTED"][filename_short]["SMOOTHED"] = {}
                    #
                    if self.diagrams_setup[filetype][filename_short]["FIG"] == None:
                        self.diagrams_setup[filetype][filename_short]["FIG"] = Figure(
                            figsize=(10, 5), facecolor=self.green_light)
                        self.diagrams_setup[filetype][filename_short]["AX"] = \
                            self.diagrams_setup[filetype][filename_short][
                                "FIG"].add_subplot()
                    #
                    if self.diagrams_setup[filetype][filename_short]["FIG_RATIO"] == None:
                        self.diagrams_setup[filetype][filename_short]["FIG_RATIO"] = Figure(
                            figsize=(10, 5), facecolor=self.green_light)
                        self.diagrams_setup[filetype][filename_short]["AX_RATIO"] = \
                            self.diagrams_setup[filetype][filename_short][
                                "FIG_RATIO"].add_subplot()

                    if self.file_loaded == False:
                        if self.container_icpms["name"] != None:
                            var_skipheader = self.container_icpms["skipheader"]
                            var_skipfooter = self.container_icpms["skipfooter"]
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        else:
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=3, skip_footer=1)
                    else:
                        try:
                            df_data = self.container_measurements["Dataframe"][filename_short]
                        except:
                            if "_copy" in filename_short:
                                filename_short_original = filename_short.replace("_copy", "")
                                filename_short = filename_short_original
                                df_data = self.container_measurements["Dataframe"][filename_short]
                            else:
                                df_data = self.container_measurements["Dataframe"][filename_short]

                    list_names = list(df_data.columns.values)
                    list_names.pop(0)
                    df_isotopes = list_names
                    times = DE().get_times(dataframe=df_data)
                    start_time = times.iloc[0]
                    end_time = times.iloc[-1]
                    start_index = times[times == start_time].index[0]
                    end_index = times[times == end_time].index[0]
                    spk_id = 1
                    #
                    box_spk = self.diagrams_setup[filetype][filename_short]["AX"].axvspan(
                        start_time, end_time, alpha=0.125, color=self.yellow_dark)
                    box_spk_ratio = self.diagrams_setup[filetype][filename_short]["AX_RATIO"].axvspan(
                        start_time, end_time, alpha=0.125, color=self.yellow_dark)
                    #
                    isotope = "".join(self.container_lists["ISOTOPES"])
                    #
                    self.container_measurements["RAW"][filename_short]["Time"] = times.tolist()
                    self.container_measurements["EDITED"][filename_short]["Time"] = times.tolist()
                    self.container_measurements["SELECTED"][filename_short]["Time"] = times.tolist()

                    # for isotope in self.container_lists["ISOTOPES"]:
                    for isotope in df_isotopes:
                        self.container_measurements["RAW"][filename_short][isotope] = df_data[isotope].tolist()
                        self.container_measurements["EDITED"][filename_short][isotope] = {}
                        self.container_measurements["SELECTED"][filename_short]["RAW"][isotope] = {}
                        self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope] = {}
                        #
                        self.container_measurements["EDITED"][filename_short][isotope]["BG"] = []
                        self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["BG"] = []
                        self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["BG"] = []
                        if mode == "MA":
                            self.container_measurements["EDITED"][filename_short][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            #
                            var_settings = "ma_setting"
                        elif mode in ["FI", "MI"]:
                            self.container_measurements["EDITED"][filename_short][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope]["MAT"] = []
                            self.container_measurements["EDITED"][filename_short][isotope]["INCL"] = []
                            self.container_measurements["SELECTED"][filename_short]["RAW"][isotope]["INCL"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope][
                                "INCL"] = []
                            self.container_measurements["SELECTED"][filename_short]["SMOOTHED"][isotope][
                                "INCL"] = []
                            if mode == "FI":
                                var_settings = "fi_setting"
                            elif mode == "MI":
                                var_settings = "mi_setting"
                        #
                        self.spikes_isotopes["SMPL"][filename_short][isotope] = []
                        self.spikes_isotopes["SMPL"][filename_short][isotope].append([start_index, end_index])

                self.do_spike_elimination_all_grubbs(filetype=filetype)
                self.fast_track_smpl = True
                self.counter_fast_track_smpl += 1
                self.container_var["Spike Elimination"]["SMPL"]["State"] = True
                #
                if self.pysills_mode == "MA":
                    self.frm_spk_smpl.config(background=self.sign_green, bd=1)
                elif self.pysills_mode == "FI":
                    if self.container_var[key_setting]["Spike Elimination Inclusion"].get() == 1:
                        self.frm_spk_smpl.config(background=self.sign_green, bd=1)
                    elif self.container_var[key_setting]["Spike Elimination Inclusion"].get() == 2:
                        if len(self.container_helper["SMPL"][filename_short]["INCL"]["Content"]) == 0:
                            self.frm_spk_smpl.config(background=self.sign_yellow, bd=1)
                        else:
                            self.frm_spk_smpl.config(background=self.sign_green, bd=1)

    def change_carrier_gas(self, var_opt):
        if var_opt == "Helium":
            try:
                self.var_entr_10.set("24.587")
                var_energy = self.var_entr_10.get()
            except:
                self.container_var["Gas Energy"].set("24.587")
                var_energy = self.container_var["Gas Energy"].get()
            #
            for isotope in self.container_lists["ISOTOPES"]:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if float(var_energy) >= float(self.ionization_energies["First"][element]) \
                        and float(var_energy) >= float(self.ionization_energies["Second"][element]):
                    fg_color = self.accent_color
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("2+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
                else:
                    fg_color = self.bg_colors["Dark Font"]
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
            #
        elif var_opt == "Neon":
            try:
                self.var_entr_10.set("21.565")
                var_energy = self.var_entr_10.get()
            except:
                self.container_var["Gas Energy"].set("21.565")
                var_energy = self.container_var["Gas Energy"].get()
            #
            for isotope in self.container_lists["ISOTOPES"]:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if float(var_energy) >= float(self.ionization_energies["First"][element]) \
                        and float(var_energy) >= float(self.ionization_energies["Second"][element]):
                    fg_color = self.accent_color
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("2+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
                else:
                    fg_color = self.bg_colors["Very Dark"]
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
        elif var_opt == "Argon":
            try:
                self.var_entr_10.set("15.760")
                var_energy = self.var_entr_10.get()
            except:
                self.container_var["Gas Energy"].set("15.760")
                var_energy = self.container_var["Gas Energy"].get()
            #
            for isotope in self.container_lists["ISOTOPES"]:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if float(var_energy) >= float(self.ionization_energies["First"][element]) \
                        and float(var_energy) >= float(self.ionization_energies["Second"][element]):
                    fg_color = self.accent_color
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("2+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
                else:
                    fg_color = self.bg_colors["Very Dark"]
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
        elif var_opt == "Krypton":
            try:
                self.var_entr_10.set("14.000")
                var_energy = self.var_entr_10.get()
            except:
                self.container_var["Gas Energy"].set("14.000")
                var_energy = self.container_var["Gas Energy"].get()
            #
            for isotope in self.container_lists["ISOTOPES"]:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if float(var_energy) >= float(self.ionization_energies["First"][element]) \
                        and float(var_energy) >= float(self.ionization_energies["Second"][element]):
                    fg_color = self.accent_color
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("2+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
                else:
                    fg_color = self.bg_colors["Very Dark"]
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
        elif var_opt == "Xenon":
            try:
                self.var_entr_10.set("12.130")
                var_energy = self.var_entr_10.get()
            except:
                self.container_var["Gas Energy"].set("12.130")
                var_energy = self.container_var["Gas Energy"].get()
            #
            for isotope in self.container_lists["ISOTOPES"]:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if float(var_energy) >= float(self.ionization_energies["First"][element]) \
                        and float(var_energy) >= float(self.ionization_energies["Second"][element]):
                    fg_color = self.accent_color
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("2+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
                else:
                    fg_color = self.bg_colors["Very Dark"]
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
        elif var_opt == "Radon":
            try:
                self.var_entr_10.set("10.749")
                var_energy = self.var_entr_10.get()
            except:
                self.container_var["Gas Energy"].set("10.749")
                var_energy = self.container_var["Gas Energy"].get()
            #
            for isotope in self.container_lists["ISOTOPES"]:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if float(var_energy) >= float(self.ionization_energies["First"][element]) \
                        and float(var_energy) >= float(self.ionization_energies["Second"][element]):
                    fg_color = self.accent_color
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("2+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)
                else:
                    fg_color = self.bg_colors["Very Dark"]
                    bg_color = self.bg_colors["Very Light"]
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    self.container_var["charge"][isotope]["labelvar"].config(bg=bg_color, fg=fg_color)

    def change_std_is(self, element, file):
        self.container_var["STD"][file]["IS"].set(element)
        parts = file.split("/")
        self.container_files["STD"][parts[-1]]["IS"].set(element)

    #
    def change_std_is_default(self, element, mineral=None):
        self.container_var["IS"]["Default STD"].set(element)
        for file in self.list_std:
            self.container_var["STD"][file]["IS"].set(element)
            parts = file.split("/")
            self.container_files["STD"][parts[-1]]["IS"].set(element)
        #
        if element in self.container_lists["ISOTOPES"]:
            key_is = re.search(r"(\D+)(\d+)", element)
            element_is = key_is.group(1)
        if mineral != None and mineral != "Select Mineral":
            if element in self.mineral_chem[mineral]:
                # self.var_entr_09.set(self.mineral_chem[mineral][element])
                self.container_var["settings"]["IS Concentration"].set(self.mineral_chem[mineral][element])
            elif element_is in self.mineral_chem[mineral]:
                # self.var_entr_09.set(self.mineral_chem[mineral][element_is])
                self.container_var["settings"]["IS Concentration"].set(self.mineral_chem[mineral][element_is])
            else:
                # self.var_entr_09.set(0.0)
                self.container_var["settings"]["IS Concentration"].set(0.0)
            #
            if self.container_var["IS"]["Default SMPL"].get() == "Select IS":
                self.change_smpl_is_default(element=element, mineral=mineral)
            #
        else:
            warning_is = tk.Toplevel(self.parent)
            warning_is.title("Warning")
            warning_is.geometry("250x100+0+0")
            warning_is.resizable(False, False)
            warning_is["bg"] = self.green_light
            #
            window_width = 250
            window_height = 100
            row_min = 25
            n_rows = int(window_height/row_min)
            column_min = 20
            n_columns = int(window_width/column_min)
            #
            for x in range(n_columns):
                tk.Grid.columnconfigure(warning_is, x, weight=1)
            for y in range(n_rows):
                tk.Grid.rowconfigure(warning_is, y, weight=1)
            #
            # Rows
            for i in range(0, n_rows):
                warning_is.grid_rowconfigure(i, minsize=row_min)
            # Columns
            for i in range(0, n_columns):
                warning_is.grid_columnconfigure(i, minsize=column_min)
            #
            lbl_01 = SE(
                parent=warning_is, row_id=0, column_id=0, n_rows=n_rows, n_columns=n_columns, fg=self.green_dark,
                bg=self.red_dark).create_simple_label(
                text="Please load your internal\n standard concentration data\n or select a mineral", relief=tk.GROOVE,
                fontsize="sans 10 bold")
            #
            self.container_var["IS"]["Default STD"].set("Select IS")

    #
    def change_smpl_is(self, element, file, mineral=None):
        self.container_var["SMPL"][file]["IS"].set(element)
        if mineral != None:
            parts = file.split("/")
            key_i = re.search(r"(\D+)(\d+)", element)
            var_element = key_i.group(1)
            self.container_files["SMPL"][parts[-1]]["IS Concentration"].set(self.mineral_chem[mineral][var_element])
            #
            self.container_var["SMPL"][file]["IS Data"]["IS"].set(element)
            self.container_var["SMPL"][file]["IS Data"]["Concentration"].set(
                self.mineral_chem[mineral][element])
            #

    #
    def change_smpl_is_default(self, element, mineral=None):
        self.container_var["IS"]["Default SMPL"].set(element)
        for file in self.list_smpl:
            self.container_var["SMPL"][file]["IS"].set(element)
        #
        if element in self.container_lists["ISOTOPES"]:
            key_is = re.search(r"(\D+)(\d+)", element)
            element_is = key_is.group(1)
        if mineral != None and mineral != "Select Mineral":
            if element in self.mineral_chem[mineral]:
                # self.var_entr_09.set(self.mineral_chem[mineral][element])
                self.container_var["settings"]["IS Concentration"].set(self.mineral_chem[mineral][element])
                for file in self.list_smpl:
                    parts = file.split("/")
                    self.container_files["SMPL"][parts[-1]]["IS"].set(element)
                    self.container_files["SMPL"][parts[-1]]["IS Concentration"].set(self.mineral_chem[mineral][element])
                    #
                    self.container_var["SMPL"][file]["IS Data"]["IS"].set(element)
                    self.container_var["SMPL"][file]["IS Data"]["Concentration"].set(
                        self.mineral_chem[mineral][element])
                    #
            elif element_is in self.mineral_chem[mineral]:
                # self.var_entr_09.set(self.mineral_chem[mineral][element_is])
                self.container_var["settings"]["IS Concentration"].set(self.mineral_chem[mineral][element_is])
                for file in self.list_smpl:
                    parts = file.split("/")
                    self.container_files["SMPL"][parts[-1]]["IS"].set(element)
                    self.container_files["SMPL"][parts[-1]]["IS Concentration"].set(
                        self.mineral_chem[mineral][element_is])
                    #
                    self.container_var["SMPL"][file]["IS Data"]["IS"].set(element)
                    self.container_var["SMPL"][file]["IS Data"]["Concentration"].set(
                        self.mineral_chem[mineral][element_is])
                    #
            #
            if self.container_var["IS"]["Default SMPL"].get() == "Select IS":
                self.change_std_is_default(element=element, mineral=mineral)
        else:
            warning_is = tk.Toplevel(self.parent)
            warning_is.title("Warning")
            warning_is.geometry("250x100+0+0")
            warning_is.resizable(False, False)
            warning_is["bg"] = self.green_light
            #
            window_width = 250
            window_height = 100
            row_min = 25
            n_rows = int(window_height/row_min)
            column_min = 20
            n_columns = int(window_width/column_min)
            #
            for x in range(n_columns):
                tk.Grid.columnconfigure(warning_is, x, weight=1)
            for y in range(n_rows):
                tk.Grid.rowconfigure(warning_is, y, weight=1)
            #
            # Rows
            for i in range(0, n_rows):
                warning_is.grid_rowconfigure(i, minsize=row_min)
            # Columns
            for i in range(0, n_columns):
                warning_is.grid_columnconfigure(i, minsize=column_min)
            #
            lbl_01 = SE(
                parent=warning_is, row_id=0, column_id=0, n_rows=n_rows, n_columns=n_columns, fg=self.green_dark,
                bg=self.red_dark).create_simple_label(
                text="Please load your internal\n standard concentration data\n or select a mineral", relief=tk.GROOVE,
                fontsize="sans 10 bold")
            #
            self.container_var["IS"]["Default SMPL"].set("Select IS")

    def change_srm_default(self, var_srm, key="STD"):
        if key == "STD":
            for file in self.list_std:
                parts = file.split("/")
                self.container_var["STD"][file]["SRM"].set(var_srm)
                self.container_files["STD"][parts[-1]]["SRM"].set(var_srm)
                try:
                    self.container_var["SRM"][file].set(var_srm)
                except:
                    print(file, self.container_var["SRM"][file])
            if self.container_var["SRM"]["default"][1].get() == "Select SRM":
                self.container_var["SRM"]["default"][1].set(var_srm)
                for isotope in self.container_lists["ISOTOPES"]:
                    self.container_files["SRM"][isotope].set(var_srm)

                    try:
                        self.container_var["SRM"][isotope].set(var_srm)
                    except:
                        print(isotope, self.container_var["SRM"][isotope])
        elif key == "isotope":
            for isotope in self.container_lists["ISOTOPES"]:
                self.container_files["SRM"][isotope].set(var_srm)

                try:
                    self.container_var["SRM"][isotope].set(var_srm)
                except:
                    print(isotope, self.container_var["SRM"][isotope])
            if self.container_var["SRM"]["default"][0].get() == "Select SRM":
                self.container_var["SRM"]["default"][0].set(var_srm)
                for file in self.list_std:
                    parts = file.split("/")
                    self.container_var["STD"][file]["SRM"].set(var_srm)
                    self.container_files["STD"][parts[-1]]["SRM"].set(var_srm)
                    try:
                        self.container_var["SRM"][file].set(var_srm)
                    except:
                        print(file, self.container_var["SRM"][file])

        self.fill_srm_values(var_srm=var_srm)

    def quick_plot_file(self, var_filetype, event):
        if var_filetype == "STD":
            click_id = self.lb_std.curselection()
            var_fig = self.quick_plot_figure_std
        elif var_filetype == "STD Manager":
            click_id = self.lb_std_manager.curselection()
            var_fig = self.quick_plot_figure_std
            var_filetype = "STD"
        elif var_filetype == "SMPL":
            click_id = self.lb_smpl.curselection()
            var_fig = self.quick_plot_figure_smpl
        elif var_filetype == "SMPL Manager":
            click_id = self.lb_smpl_manager.curselection()
            var_fig = self.quick_plot_figure_smpl
            var_filetype = "SMPL"

        click_id = click_id[0]
        file_long = self.container_lists[var_filetype]["Long"][click_id]
        file_short = self.container_lists[var_filetype]["Short"][click_id]
        file_isotopes = self.container_lists["Measured Isotopes"][file_short]

        ## Window Settings
        window_width = 1000
        window_height = 700
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_quickplotter = tk.Toplevel(self.parent)
        subwindow_quickplotter.title("Quick Plotter")
        subwindow_quickplotter.geometry(var_geometry)
        subwindow_quickplotter.resizable(False, False)
        subwindow_quickplotter["bg"] = self.bg_colors["Very Light"]

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_quickplotter, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_quickplotter, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_quickplotter.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_quickplotter.grid_columnconfigure(i, minsize=column_min)

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

        row_start = 0
        column_start = 0

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_quickplotter, row_id=row_start, column_id=column_start, n_rows=1, n_columns=40,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Time-Signal Diagram", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_quickplotter, row_id=row_start, column_id=column_start + 40, n_rows=1, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Isotopes", relief=tk.FLAT, fontsize="sans 10 bold")

        if self.file_loaded == False:
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=file_long).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=file_long).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
        else:
            if file_short not in self.container_measurements["Dataframe"] and "_copy" in file_short:
                file_short_original = file_short.replace("_copy", "")
                df_data = self.container_measurements["Dataframe"][file_short_original]
            else:
                df_data = self.container_measurements["Dataframe"][file_short]

        list_keys = list(df_data.columns.values)
        del list_keys[0]
        dataset_time = list(df_data.iloc[:, 0])
        x_max = max(dataset_time)

        if len(file_isotopes) == 0:
            self.container_lists["ISOTOPES"] = list_keys
            self.define_isotope_colors()

        icp_measurements = np.array([[df_data[isotope] for isotope in file_isotopes]])
        y_max = np.amax(icp_measurements)

        ## ISOTOPE LIST
        frm_isotopes = SE(
            parent=subwindow_quickplotter, row_id=row_start + 1, column_id=column_start + 40, n_rows=n_rows - 3,
            n_columns=20, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb = ttk.Scrollbar(master=frm_isotopes, orient="vertical")
        text = tk.Text(
            master=frm_isotopes, width=30, height=15, yscrollcommand=vsb.set, bg=self.bg_colors["Very Light"])
        vsb.config(command=text.yview)
        vsb.pack(side="right", fill="y")
        text.pack(side="left", fill="both", expand=True)

        self.temp_checkbuttons = {}
        for index, isotope in enumerate(file_isotopes):
            self.temp_checkbuttons[isotope] = tk.IntVar(value=1)

            cb_i = tk.Checkbutton(
                master=frm_isotopes, text=isotope, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"],
                variable=self.temp_checkbuttons[isotope],
                command=lambda var_isotope=isotope, var_file_short=file_short:
                self.show_line(var_isotope, var_file_short))

            text.window_create("end", window=cb_i)
            text.insert("end", "\n")
            cb_i.select()

        ## DIAGRAMS
        var_fig = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        var_ax = var_fig.add_subplot(label=np.random.uniform())

        self.temp_lines = {}

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5

        try:
            for isotope in file_isotopes:
                ln = var_ax.plot(
                    dataset_time, df_data[isotope], label=isotope, color=self.isotope_colors[isotope], linewidth=var_lw,
                    visible=True)
                self.temp_lines[isotope] = ln
        except:
            self.define_temporary_colors(filename_short=file_short)
            for isotope in file_isotopes:
                ln = var_ax.plot(
                    dataset_time, df_data[isotope], label=isotope, color=self.isotope_colors_temporary[isotope],
                    linewidth=var_lw, visible=True)
                self.temp_lines[isotope] = ln

        var_ax.grid(True)
        var_ax.set_yscale("log")
        var_ax.set_xlim(left=0, right=x_max)
        var_ax.set_xticks(np.arange(0, x_max, 20))
        var_ax.set_ylim(top=1.5*y_max)
        var_ax.grid(which="major", linestyle="-", linewidth=1)
        var_ax.minorticks_on()
        var_ax.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        var_ax.set_axisbelow(True)
        var_ax.set_title(file_short, fontsize=9)
        var_ax.set_xlabel("Time (s)", labelpad=0.5, fontsize=8)
        var_ax.set_ylabel("Signal (cps)", labelpad=0.5, fontsize=8)
        var_ax.xaxis.set_tick_params(labelsize=8)
        var_ax.yaxis.set_tick_params(labelsize=8)

        # Canvas
        var_canvas = FigureCanvasTkAgg(var_fig, master=subwindow_quickplotter)
        var_canvas.get_tk_widget().grid(
            row=row_start + 1, column=column_start, rowspan=n_rows - 3, columnspan=40, sticky="nesw")
        # Toolbar
        var_toolbarFrame = tk.Frame(master=subwindow_quickplotter)
        var_toolbarFrame.grid(row=n_rows - 2, column=0, rowspan=2, columnspan=40, sticky="ew")
        var_toolbar = NavigationToolbar2Tk(var_canvas, var_toolbarFrame)
        var_toolbar.config(
            bg=self.bg_colors["Very Light"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
            highlightcolor=self.bg_colors["Dark Font"], bd=0)
        var_toolbar._message_label.config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        var_toolbar.winfo_children()[-2].config(background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])

        self.container_var["Plotting"][self.pysills_mode]["Quickview"][file_short] = {
            "Figure": var_fig, "Canvas": var_canvas, "Toolbar": var_toolbar, "Axes": var_ax}

        ## BUTTONS
        btn_01 = SE(
            parent=subwindow_quickplotter, row_id=n_rows - 2, column_id=column_start + 40, n_rows=2, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Show All", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_file_short=file_short: self.show_all_lines(var_file_short))
        btn_02 = SE(
            parent=subwindow_quickplotter, row_id=n_rows - 2, column_id=column_start + 45, n_rows=2, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Hide All", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_file_short=file_short: self.hide_all_lines(var_file_short))

    def show_line(self, var_isotope, var_file_short):
        if self.temp_checkbuttons[var_isotope].get() == 1:
            self.temp_lines[var_isotope][0].set_visible(True)
        else:
            self.temp_lines[var_isotope][0].set_visible(False)
        #
        self.container_var["Plotting"][self.pysills_mode]["Quickview"][var_file_short]["Canvas"].draw()

    #
    def show_all_lines(self, var_file_short):
        file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
        for isotope in file_isotopes:
            self.temp_checkbuttons[isotope].set(1)
            self.temp_lines[isotope][0].set_visible(True)

        self.container_var["Plotting"][self.pysills_mode]["Quickview"][var_file_short]["Canvas"].draw()

    def hide_all_lines(self, var_file_short):
        file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
        for isotope in file_isotopes:
            self.temp_checkbuttons[isotope].set(0)
            self.temp_lines[isotope][0].set_visible(False)

        self.container_var["Plotting"][self.pysills_mode]["Quickview"][var_file_short]["Canvas"].draw()

    def place_srm_values(self, var_srm, header_col, default=False):
        #
        lbl_srm_03 = SE(parent=self.parent, row_id=0, column_id=header_col, n_rows=1, n_columns=42, fg=self.green_light,
                        bg=self.green_dark).create_simple_label(text=str(var_srm) + " - Element Concentrations (ppm)",
                                                                relief=tk.GROOVE, fontsize="sans 10 bold")
        self.container_elements["SRM"]["Label"].append(lbl_srm_03)
        #
        if default:
            for file in self.list_std:
                parts = file.split("/")
                self.container_var["SRM"][file].set(var_srm)
                self.container_files["STD"][parts[-1]]["SRM"].set(var_srm)
        #
        try:
            ESRM().place_srm_values(srm_name=var_srm, srm_dict=self.srm_actual)
        except:
            self.srm_actual[var_srm] = {}
            ESRM().place_srm_values(srm_name=var_srm, srm_dict=self.srm_actual)
        #
        for element in self.list_pse:
            if element in self.srm_actual[var_srm]:
                self.container_var["SRM"][element].set(self.srm_actual[var_srm][element])
            else:
                self.container_var["SRM"][element].set(0.0)

    #
    def fill_srm_values(self, var_srm):
        if var_srm not in self.srm_actual:
            self.srm_actual[var_srm] = {}
            ESRM().place_srm_values(srm_name=var_srm, srm_dict=self.srm_actual)

    #
    def calculate_mineral_chemistry(self):
        #
        M_H = 1.008
        M_C = 12.011
        M_O = 15.999
        M_F = 18.998
        M_Na = 22.990
        M_Mg = 24.305
        M_Al = 26.982
        M_Si = 28.085
        M_P = 30.974
        M_S = 32.059
        M_Cl = 35.450
        M_K = 39.098
        M_Ca = 40.078
        M_Ti = 47.867
        M_Cr = 51.996
        M_Mn = 54.938
        M_Fe = 55.845
        M_Cu = 63.546
        M_Zn = 65.382
        M_As = 74.922
        M_Sr = 87.620
        M_Zr = 91.224
        M_Mo = 95.950
        M_Ba = 137.33
        M_La = 138.91
        M_Ce = 140.12
        M_Pr = 140.91
        M_Nd = 144.24
        M_Sm = 150.360
        M_Eu = 151.960
        M_Gd = 157.25
        M_Pb = 207.200
        M_Th = 232.04
        #
        # self.mineral_chem = {}
        for mineral in self.mineral_list:
            self.mineral_chem[mineral] = {}
            if mineral == "Quartz":  # SiO2
                M_Qz = M_Si + 2*M_O
                w_Si = (M_Si)/(M_Qz)*1000000
                self.mineral_chem[mineral]["Si"] = w_Si
            elif mineral == "Arsenopyrite":  # FeAsS
                M_Apy = M_Fe + M_As + M_S
                w_S = (M_S)/(M_Apy)*1000000
                w_Fe = (M_Fe)/(M_Apy)*1000000
                w_As = (M_As)/(M_Apy)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Fe"] = w_Fe
                self.mineral_chem[mineral]["As"] = w_As
            elif mineral == "Barite":  # BaSO4
                M_Brt = M_Ba + M_S + 4*M_O
                w_O = (4*M_O)/(M_Brt)*1000000
                w_S = (M_S)/(M_Brt)*1000000
                w_Ba = (M_Ba)/(M_Brt)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Ba"] = w_Ba
            elif mineral == "Ilvaite":  # CaFe3(SiO4)2(OH)
                M_Ilvt = M_Ca + 3*M_Fe + 2*(M_Si + 4*M_O) + (M_O + M_H)
                w_H = (M_H)/(M_Ilvt)*1000000
                w_O = (9*M_O)/(M_Ilvt)*1000000
                w_Si = (2*M_Si)/(M_Ilvt)*1000000
                w_Ca = (M_Ca)/(M_Ilvt)*1000000
                w_Fe = (3*M_Fe)/(M_Ilvt)*1000000
                self.mineral_chem[mineral]["H"] = w_H
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Ca"] = w_Ca
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Bornite":  # Cu5FeS4
                M_Bn = 5*M_Cu + M_Fe + 4*M_S
                w_S = (4*M_S)/(M_Bn)*1000000
                w_Fe = (M_Fe)/(M_Bn)*1000000
                w_Cu = (5*M_Cu)/(M_Bn)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Fe"] = w_Fe
                self.mineral_chem[mineral]["Cu"] = w_Cu
            elif mineral == "Calcite":  # CaCO3
                M_Cal = M_Ca + M_C + 3*M_O
                w_C = (M_C)/(M_Cal)*1000000
                w_Ca = (M_Ca)/(M_Cal)*1000000
                self.mineral_chem[mineral]["C"] = w_C
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Chalcopyrite":  # CuFeS2
                M_Ccp = M_Cu + M_Fe + 2*M_S
                w_S = (2*M_S)/(M_Ccp)*1000000
                w_Fe = (M_Fe)/(M_Ccp)*1000000
                w_Cu = (M_Cu)/(M_Ccp)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Fe"] = w_Fe
                self.mineral_chem[mineral]["Cu"] = w_Cu
            elif mineral == "Chromite":  # FeCr2O4
                M = M_Fe + 2*M_Cr + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_Cr = (2*M_Cr)/(M)*1000000
                w_Fe = (M_Fe)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Cr"] = w_Cr
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Enargite":  # Cu3AsS4
                M_En = 3*M_Cu + M_As + 4*M_S
                w_S = (4*M_S)/(M_En)*1000000
                w_Cu = (3*M_Cu)/(M_En)*1000000
                w_As = (M_As)/(M_En)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Cu"] = w_Cu
                self.mineral_chem[mineral]["As"] = w_As
            elif mineral == "Fluorite":  # CaF2
                M_Fl = M_Ca + 2*M_F
                w_F = (2*M_F)/(M_Fl)*1000000
                w_Ca = (M_Ca)/(M_Fl)*1000000
                self.mineral_chem[mineral]["F"] = w_F
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Apatite-Cl":  # Ca5(PO4)3Cl
                M_Ap = 5*M_Ca + 3*(M_P + 4*M_O) + M_Cl
                w_P = (3*M_P)/(M_Ap)*1000000
                w_Cl = (M_Cl)/(M_Ap)*1000000
                w_Ca = (5*M_Ca)/(M_Ap)*1000000
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Cl"] = w_Cl
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Apatite-F":  # Ca5(PO4)3F
                M_Ap = 5*M_Ca + 3*(M_P + 4*M_O) + M_F
                w_F = (M_F)/(M_Ap)*1000000
                w_P = (3*M_P)/(M_Ap)*1000000
                w_Ca = (5*M_Ca)/(M_Ap)*1000000
                self.mineral_chem[mineral]["F"] = w_F
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Apatite-OH":  # Ca5(PO4)3OH
                M_Ap = 5*M_Ca + 3*(M_P + 4*M_O) + (M_O + M_H)
                w_H = (M_H)/(M_Ap)*1000000
                w_P = (3*M_P)/(M_Ap)*1000000
                w_Ca = (5*M_Ca)/(M_Ap)*1000000
                self.mineral_chem[mineral]["H"] = w_H
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Forsterite":  # Mg2SiO4
                M_Ol = 2*M_Mg + M_Si + 4*M_O
                w_Mg = (2*M_Mg)/(M_Ol)*1000000
                w_Si = (M_Si)/(M_Ol)*1000000
                self.mineral_chem[mineral]["Mg"] = w_Mg
                self.mineral_chem[mineral]["Si"] = w_Si
            elif mineral == "Fayalite":  # Fe2SiO4
                M_Ol = 2*M_Fe + M_Si + 4*M_O
                w_Si = (M_Si)/(M_Ol)*1000000
                w_Fe = (2*M_Fe)/(M_Ol)*1000000
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Gahnite":  # ZnAl2O4
                M = M_Zn + 2*M_Al + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_Al = (2*M_Al)/(M)*1000000
                w_Zn = (M_Zn)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Al"] = w_Al
                self.mineral_chem[mineral]["Zn"] = w_Zn
            elif mineral == "Galena":  # PbS
                M_Gn = M_Pb + M_S
                w_S = (M_S)/(M_Gn)*1000000
                w_Pb = (M_Pb)/(M_Gn)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Pb"] = w_Pb
            elif mineral == "Hematite":  # Fe2O3
                M = 2*M_Fe + 3*M_O
                w_O = (3*M_O)/(M)*1000000
                w_Fe = (2*M_Fe)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Tephroite":  # Mn2SiO4
                M_Ol = 2*M_Mn + M_Si + 4*M_O
                w_Si = (M_Si)/(M_Ol)*1000000
                w_Mn = (2*M_Mn)/(M_Ol)*1000000
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Mn"] = w_Mn
            elif mineral == "Albite":  # NaAlSi3O8
                M_Ab = M_Na + M_Al + 3*M_Si + 8*M_O
                w_Na = (M_Na)/(M_Ab)*1000000
                w_Al = (M_Al)/(M_Ab)*1000000
                w_Si = (3*M_Si)/(M_Ab)*1000000
                self.mineral_chem[mineral]["Na"] = w_Na
                self.mineral_chem[mineral]["Al"] = w_Al
                self.mineral_chem[mineral]["Si"] = w_Si
            elif mineral == "Anorthite":  # CaAl2Si2O8
                M_An = M_Ca + 2*(M_Al + M_Si) + 8*M_O
                w_Al = (2*M_Al)/(M_An)*1000000
                w_Si = (2*M_Si)/(M_An)*1000000
                w_Ca = (M_Ca)/(M_An)*1000000
                self.mineral_chem[mineral]["Al"] = w_Al
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Magnetite":  # Fe3O4
                M = 3*M_Fe + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_Fe = (3*M_Fe)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Molybdenite":  # MoS2
                M = M_Mo + 2*M_S
                w_S = (2*M_S)/(M)*1000000
                w_Mo = (M_Mo)/(M)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Mo"] = w_Mo
            elif mineral == "Pyrite":  # FeS2
                M_Py = M_Fe + 2*M_S
                w_S = (2*M_S)/(M_Py)*1000000
                w_Fe = (M_Fe)/(M_Py)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral in ["Orthoclase", "Microcline"]:  # KAlSi3O8
                M_OrMc = M_K + M_Al + 3*M_Si + 8*M_O
                w_Al = (M_Al)/(M_OrMc)*1000000
                w_Si = (3*M_Si)/(M_OrMc)*1000000
                w_K = (M_K)/(M_OrMc)*1000000
                self.mineral_chem[mineral]["Al"] = w_Al
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["K"] = w_K
            elif mineral == "Sphalerite":  # ZnS
                M_Sp = M_Zn + M_S
                w_S = (M_S)/(M_Sp)*1000000
                w_Zn = (M_Zn)/(M_Sp)*1000000
                self.mineral_chem[mineral]["S"] = w_S
                self.mineral_chem[mineral]["Zn"] = w_Zn
            elif mineral == "Zircon":  # ZrSiO4
                M_Zrn = M_Zr + (M_Si + 4*M_O)
                w_Si = (M_Si)/(M_Zrn)*1000000
                w_Zr = (M_Zr)/(M_Zrn)*1000000
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Zr"] = w_Zr
            elif mineral == "Meionite":  # Ca4 Al6 Si6 O24 CO3
                M = 4*M_Ca + 6*M_Al + 6*M_Si + 24*M_O + M_C + 3*M_O
                w_C = (M_C)/(M)*1000000
                w_Al = (6*M_Al)/(M)*1000000
                w_Si = (6*M_Si)/(M)*1000000
                w_Ca = (4*M_Ca)/(M)*1000000
                self.mineral_chem[mineral]["C"] = w_C
                self.mineral_chem[mineral]["Al"] = w_Al
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Marialite":  # Na4 Al3 Si9 O24 Cl
                M = 4*M_Na + 3*M_Al + 9*M_Si + 24*M_O + M_Cl
                w_Na = (4*M_Na)/(M)*1000000
                w_Al = (3*M_Al)/(M)*1000000
                w_Si = (9*M_Si)/(M)*1000000
                w_Cl = (M_Cl)/(M)*1000000
                self.mineral_chem[mineral]["Na"] = w_Na
                self.mineral_chem[mineral]["Al"] = w_Al
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Cl"] = w_Cl
            elif mineral == "Strontianite":  # Sr C O3
                M = M_Sr + M_C + 3*M_O
                w_C = (M_C)/(M)*1000000
                w_O = (3*M_O)/(M)*1000000
                w_Sr = (M_Sr)/(M)*1000000
                self.mineral_chem[mineral]["C"] = w_C
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Sr"] = w_Sr
            elif mineral == "Titanite":  # Ca Ti Si O5
                M = M_Ca + M_Ti + M_Si + 5*M_O
                w_O = (5*M_O)/(M)*1000000
                w_Si = (M_Si)/(M)*1000000
                w_Ca = (M_Ca)/(M)*1000000
                w_Ti = (M_Ti)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Ca"] = w_Ca
                self.mineral_chem[mineral]["Ti"] = w_Ti
            elif mineral == "Aegirine":  # Na Fe Si2 O6
                M = M_Na + M_Fe + 2*M_Si + 6*M_O
                w_O = (6*M_O)/(M)*1000000
                w_Na = (M_Na)/(M)*1000000
                w_Si = (2*M_Si)/(M)*1000000
                w_Fe = (M_Fe)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Na"] = w_Na
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Diopside":  # Mg Ca Si2 O6
                M = M_Mg + M_Ca + 2*M_Si + 6*M_O
                w_O = (6*M_O)/(M)*1000000
                w_Mg = (M_Mg)/(M)*1000000
                w_Si = (2*M_Si)/(M)*1000000
                w_Ca = (M_Ca)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Mg"] = w_Mg
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Ca"] = w_Ca
            elif mineral == "Hedenbergite":  # Fe Ca Si2 O6
                M = M_Fe + M_Ca + 2*M_Si + 6*M_O
                w_O = (6*M_O)/(M)*1000000
                w_Si = (2*M_Si)/(M)*1000000
                w_Ca = (M_Ca)/(M)*1000000
                w_Fe = (M_Fe)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Ca"] = w_Ca
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Ferrosilite":  # Fe2 Si2 O6
                M = 2*M_Fe + 2*M_Si + 6*M_O
                w_O = (6*M_O)/(M)*1000000
                w_Si = (2*M_Si)/(M)*1000000
                w_Fe = (2*M_Fe)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Si"] = w_Si
                self.mineral_chem[mineral]["Fe"] = w_Fe
            elif mineral == "Enstatite":  # Mg2 Si2 O6
                M = 2*M_Mg + 2*M_Si + 6*M_O
                w_O = (6*M_O)/(M)*1000000
                w_Mg = (2*M_Mg)/(M)*1000000
                w_Si = (2*M_Si)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["Mg"] = w_Mg
                self.mineral_chem[mineral]["Si"] = w_Si
            elif mineral == "Monazite-La":  # La P O4
                M = M_La + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_La = (M_La)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["La"] = w_La
            elif mineral == "Monazite-Ce":  # Ce P O4
                M = M_Ce + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_Ce = (M_Ce)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Ce"] = w_Ce
            elif mineral == "Monazite-Pr":  # Pr P O4
                M = M_Pr + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_Pr = (M_Pr)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Pr"] = w_Pr
            elif mineral == "Monazite-Nd":  # Nd P O4
                M = M_Nd + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_Nd = (M_Nd)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Nd"] = w_Nd
            elif mineral == "Monazite-Sm":  # Sm P O4
                M = M_Sm + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_Sm = (M_Sm)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Sm"] = w_Sm
            elif mineral == "Monazite-Eu":  # Eu P O4
                M = M_Eu + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_Eu = (M_Eu)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Eu"] = w_Eu
            elif mineral == "Monazite-Gd":  # Gd P O4
                M = M_Gd + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_Gd = (M_Gd)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Gd"] = w_Gd
            elif mineral == "Monazite-Th":  # Th P O4
                M = M_Th + M_P + 4*M_O
                w_O = (4*M_O)/(M)*1000000
                w_P = (M_P)/(M)*1000000
                w_Th = (M_Th)/(M)*1000000
                self.mineral_chem[mineral]["O"] = w_O
                self.mineral_chem[mineral]["P"] = w_P
                self.mineral_chem[mineral]["Th"] = w_Th
            elif mineral == "Select Mineral":
                pass
            #
            for element, value in self.mineral_chem[mineral].items():
                self.mineral_chem[mineral][element] = round(value, 4)

    #
    def place_mineral_values(self, var_min, header_col):
        #
        lbl_srm_03 = SE(parent=self.parent, row_id=0, column_id=header_col, n_rows=1, n_columns=42, fg=self.green_light,
                        bg=self.green_dark).create_simple_label(text=str(var_min) + " - Element Concentrations (ppm)",
                                                                relief=tk.GROOVE, fontsize="sans 10 bold")
        self.container_elements["SRM"]["Label"].append(lbl_srm_03)
        #
        self.srm_actual[var_min] = {}
        M_H = 1.008
        M_C = 12.011
        M_O = 15.999
        M_F = 18.998
        M_Na = 22.990
        M_Mg = 24.305
        M_Al = 26.982
        M_Si = 28.085
        M_P = 30.974
        M_Cl = 35.450
        M_K = 39.098
        M_Ca = 40.078
        M_Mn = 54.938
        M_Fe = 55.845
        M_Zr = 91.224
        M_Ba = 137.33
        #
        if var_min == "Quartz":  # SiO2
            M_Qz = M_Si + 2*M_O
            w_Si = (M_Si)/(M_Qz)*1000000
            self.srm_actual[var_min]["Si"] = w_Si
        elif var_min == "Arsenopyrite":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
            self.srm_actual[var_min]["As"] = self.mineral_chem[var_min]["As"]
        elif var_min == "Barite":  # BaSO4
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Ba"] = self.mineral_chem[var_min]["Ba"]
        elif var_min == "Ilvaite":  # CaFe3(SiO4)2(OH)
            self.srm_actual[var_min]["H"] = self.mineral_chem[var_min]["H"]
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Ca"] = self.mineral_chem[var_min]["Ca"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Bornite":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
            self.srm_actual[var_min]["Cu"] = self.mineral_chem[var_min]["Cu"]
        elif var_min == "Calcite":  # CaCO3
            M_Cal = M_Ca + M_C + 3*M_O
            w_C = (M_C)/(M_Cal)*1000000
            w_Ca = (M_Ca)/(M_Cal)*1000000
            self.srm_actual[var_min]["C"] = w_C
            self.srm_actual[var_min]["Ca"] = w_Ca
        elif var_min == "Chalcopyrite":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
            self.srm_actual[var_min]["Cu"] = self.mineral_chem[var_min]["Cu"]
        elif var_min == "Chromite":
            self.srm_actual[var_min]["Cr"] = self.mineral_chem[var_min]["Cr"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Sphalerite":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Zn"] = self.mineral_chem[var_min]["Zn"]
        elif var_min == "Enargite":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Cu"] = self.mineral_chem[var_min]["Cu"]
            self.srm_actual[var_min]["As"] = self.mineral_chem[var_min]["As"]
        elif var_min == "Fluorite":  # CaF2
            M_Fl = M_Ca + 2*M_F
            w_F = (2*M_F)/(M_Fl)*1000000
            w_Ca = (M_Ca)/(M_Fl)*1000000
            self.srm_actual[var_min]["F"] = w_F
            self.srm_actual[var_min]["Ca"] = w_Ca
        elif var_min == "Hematite":
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Galena":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Pb"] = self.mineral_chem[var_min]["Pb"]
        elif var_min == "Gahnite":
            self.srm_actual[var_min]["Al"] = self.mineral_chem[var_min]["Al"]
            self.srm_actual[var_min]["Zn"] = self.mineral_chem[var_min]["Zn"]
        elif var_min == "Magnetite":
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Molybdenite":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Mo"] = self.mineral_chem[var_min]["Mo"]
        elif var_min == "Pyrite":
            self.srm_actual[var_min]["S"] = self.mineral_chem[var_min]["S"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Apatite-Cl":  # Ca5(PO4)3Cl
            M_Ap = 5*M_Ca + 3*(M_P + 4*M_O) + M_Cl
            w_P = (3*M_P)/(M_Ap)*1000000
            w_Cl = (M_Cl)/(M_Ap)*1000000
            w_Ca = (5*M_Ca)/(M_Ap)*1000000
            self.srm_actual[var_min]["P"] = w_P
            self.srm_actual[var_min]["Cl"] = w_Cl
            self.srm_actual[var_min]["Ca"] = w_Ca
        elif var_min == "Apatite-F":  # Ca5(PO4)3F
            M_Ap = 5*M_Ca + 3*(M_P + 4*M_O) + M_F
            w_F = (M_F)/(M_Ap)*1000000
            w_P = (3*M_P)/(M_Ap)*1000000
            w_Ca = (5*M_Ca)/(M_Ap)*1000000
            self.srm_actual[var_min]["F"] = w_F
            self.srm_actual[var_min]["P"] = w_P
            self.srm_actual[var_min]["Ca"] = w_Ca
        elif var_min == "Apatite-OH":  # Ca5(PO4)3OH
            M_Ap = 5*M_Ca + 3*(M_P + 4*M_O) + (M_O + M_H)
            w_H = (M_H)/(M_Ap)*1000000
            w_P = (3*M_P)/(M_Ap)*1000000
            w_Ca = (5*M_Ca)/(M_Ap)*1000000
            self.srm_actual[var_min]["H"] = w_H
            self.srm_actual[var_min]["P"] = w_P
            self.srm_actual[var_min]["Ca"] = w_Ca
        elif var_min == "Forsterite":  # Mg2SiO4
            M_Ol = 2*M_Mg + M_Si + 4*M_O
            w_Mg = (2*M_Mg)/(M_Ol)*1000000
            w_Si = (M_Si)/(M_Ol)*1000000
            self.srm_actual[var_min]["Mg"] = w_Mg
            self.srm_actual[var_min]["Si"] = w_Si
        elif var_min == "Fayalite":  # Fe2SiO4
            M_Ol = 2*M_Fe + M_Si + 4*M_O
            w_Si = (M_Si)/(M_Ol)*1000000
            w_Fe = (2*M_Fe)/(M_Ol)*1000000
            self.srm_actual[var_min]["Si"] = w_Si
            self.srm_actual[var_min]["Fe"] = w_Fe
        elif var_min == "Tephroite":  # Mn2SiO4
            M_Ol = 2*M_Mn + M_Si + 4*M_O
            w_Si = (M_Si)/(M_Ol)*1000000
            w_Mn = (2*M_Mn)/(M_Ol)*1000000
            self.srm_actual[var_min]["Si"] = w_Si
            self.srm_actual[var_min]["Mn"] = w_Mn
        elif var_min == "Albite":  # NaAlSi3O8
            M_Ab = M_Na + M_Al + 3*M_Si + 8*M_O
            w_Na = (M_Na)/(M_Ab)*1000000
            w_Al = (M_Al)/(M_Ab)*1000000
            w_Si = (3*M_Si)/(M_Ab)*1000000
            self.srm_actual[var_min]["Na"] = w_Na
            self.srm_actual[var_min]["Al"] = w_Al
            self.srm_actual[var_min]["Si"] = w_Si
        elif var_min == "Anorthite":  # CaAl2Si2O8
            M_An = M_Ca + 2*(M_Al + M_Si) + 8*M_O
            w_Al = (2*M_Al)/(M_An)*1000000
            w_Si = (2*M_Si)/(M_An)*1000000
            w_Ca = (M_Ca)/(M_An)*1000000
            self.srm_actual[var_min]["Al"] = w_Al
            self.srm_actual[var_min]["Si"] = w_Si
            self.srm_actual[var_min]["Ca"] = w_Ca
        elif var_min in ["Orthoclase", "Microcline"]:  # KAlSi3O8
            M_OrMc = M_K + M_Al + 3*M_Si + 8*M_O
            w_Al = (M_Al)/(M_OrMc)*1000000
            w_Si = (3*M_Si)/(M_OrMc)*1000000
            w_K = (M_K)/(M_OrMc)*1000000
            self.srm_actual[var_min]["Al"] = w_Al
            self.srm_actual[var_min]["Si"] = w_Si
            self.srm_actual[var_min]["K"] = w_K
        elif var_min == "Zircon":  # ZrSiO4
            M_Zrn = M_Zr + (M_Si + 4*M_O)
            w_Si = (M_Si)/(M_Zrn)*1000000
            w_Zr = (M_Zr)/(M_Zrn)*1000000
            self.srm_actual[var_min]["Si"] = w_Si
            self.srm_actual[var_min]["Zr"] = w_Zr
        elif var_min == "Meionite":
            self.srm_actual[var_min]["C"] = self.mineral_chem[var_min]["C"]
            self.srm_actual[var_min]["Al"] = self.mineral_chem[var_min]["Al"]
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Ca"] = self.mineral_chem[var_min]["Ca"]
        elif var_min == "Marialite":
            self.srm_actual[var_min]["Na"] = self.mineral_chem[var_min]["Na"]
            self.srm_actual[var_min]["Al"] = self.mineral_chem[var_min]["Al"]
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Cl"] = self.mineral_chem[var_min]["Cl"]
        elif var_min == "Strontianite":
            self.srm_actual[var_min]["C"] = self.mineral_chem[var_min]["C"]
            self.srm_actual[var_min]["Sr"] = self.mineral_chem[var_min]["Sr"]
        elif var_min == "Titanite":
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Ca"] = self.mineral_chem[var_min]["Ca"]
            self.srm_actual[var_min]["Ti"] = self.mineral_chem[var_min]["Ti"]
        elif var_min == "Aegirine":
            self.srm_actual[var_min]["Na"] = self.mineral_chem[var_min]["Na"]
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Diopside":
            self.srm_actual[var_min]["Mg"] = self.mineral_chem[var_min]["Mg"]
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Ca"] = self.mineral_chem[var_min]["Ca"]
        elif var_min == "Hedenbergite":
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Ca"] = self.mineral_chem[var_min]["Ca"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Ferrosilite":
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
            self.srm_actual[var_min]["Fe"] = self.mineral_chem[var_min]["Fe"]
        elif var_min == "Enstatite":
            self.srm_actual[var_min]["Mg"] = self.mineral_chem[var_min]["Mg"]
            self.srm_actual[var_min]["Si"] = self.mineral_chem[var_min]["Si"]
        elif var_min == "Monazite-La":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["La"] = self.mineral_chem[var_min]["La"]
        elif var_min == "Monazite-Ce":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["Ce"] = self.mineral_chem[var_min]["Ce"]
        elif var_min == "Monazite-Pr":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["Pr"] = self.mineral_chem[var_min]["Pr"]
        elif var_min == "Monazite-Nd":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["Nd"] = self.mineral_chem[var_min]["Nd"]
        elif var_min == "Monazite-Sm":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["Sm"] = self.mineral_chem[var_min]["Sm"]
        elif var_min == "Monazite-Eu":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["Eu"] = self.mineral_chem[var_min]["Eu"]
        elif var_min == "Monazite-Gd":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["Gd"] = self.mineral_chem[var_min]["Gd"]
        elif var_min == "Monazite-Th":
            self.srm_actual[var_min]["P"] = self.mineral_chem[var_min]["P"]
            self.srm_actual[var_min]["Th"] = self.mineral_chem[var_min]["Th"]
        #
        for element in self.list_pse:
            if element in self.srm_actual[var_min]:
                self.container_var["SRM"][element].set(self.srm_actual[var_min][element])
            else:
                self.container_var["SRM"][element].set(0.0)

    def select_mineral_is(self, var_min, fluidinclusion=False):
        self.srm_actual[var_min] = {}

        if var_min in self.mineral_chem:
            for key, value in self.mineral_chem[var_min].items():
                self.srm_actual[var_min][key] = value

            if fluidinclusion == False:
                if self.file_loaded == False:
                    self.container_var["isotopes"]["default"].set("Select IS")
                    self.container_var["settings"]["IS Concentration"].set(0.0)
            if len(self.container_var["mineralchemistry"]) > 0:
                self.container_var["mineralchemistry"].clear()
            self.container_var["mineralchemistry"].extend(list(self.mineral_chem[var_min].keys()))
            self.container_var["mineralchemistry"].sort()

            possible_is = []
            for element in self.container_var["mineralchemistry"]:
                for isotope in self.container_lists["ISOTOPES"]:
                    key = re.search(r"(\D+)(\d+)", isotope)
                    if element == key.group(1):
                        possible_is.append(isotope)

            if fluidinclusion:
                list_fluidchemistry = ["H", "Na", "Mg", "Ca", "K", "Cl", "F", "Br", "I", "At"]
                for element in list_fluidchemistry:
                    for isotope in self.container_lists["ISOTOPES"]:
                        key = re.search(r"(\D+)(\d+)", isotope)
                        if element == key.group(1):
                            possible_is.append(isotope)

            if fluidinclusion == False:
                self.opt_is_std_def["menu"].delete(0, "end")
                self.opt_is_smpl_def["menu"].delete(0, "end")

                for index, isotope in enumerate(possible_is):
                    for file_long in self.container_lists["STD"]["Long"]:
                        if index == 0:
                            self.container_optionmenu["STD"][file_long]["menu"].delete(0, "end")

                        self.container_optionmenu["STD"][file_long]["menu"].add_command(
                            label=isotope, command=lambda element=isotope, file=file_long:
                            self.change_std_is(element, file))

                        if self.file_loaded is False:
                            self.container_var["STD"][file_long]["IS"].set("Select IS")
                    for file_long in self.container_lists["SMPL"]["Long"]:
                        if index == 0:
                            self.container_optionmenu["SMPL"][file_long]["menu"].delete(0, "end")

                        self.container_optionmenu["SMPL"][file_long]["menu"].add_command(
                            label=isotope,
                            command=lambda element=isotope, file=file_long, mineral=self.container_var["mineral"].get():
                            self.change_smpl_is(element, file, mineral))

                        if self.file_loaded is False:
                            self.container_var["SMPL"][file_long]["IS"].set("Select IS")

                    self.opt_is_std_def["menu"].add_command(
                        label=isotope, command=lambda element=isotope, mineral=var_min:
                        self.change_std_is_default(element, mineral))
                    self.opt_is_smpl_def["menu"].add_command(
                        label=isotope, command=lambda element=isotope, mineral=var_min:
                        self.change_smpl_is_default(element, mineral))

            self.container_lists["Possible IS"].clear()
            self.container_lists["Possible IS"].extend(possible_is)

            self.mineral_chem["Unknown"] = {}
            for element in self.container_var["mineralchemistry"]:
                for isotope in self.container_lists["ISOTOPES"]:
                    key = re.search(r"(\D+)(\d+)", isotope)
                    if element == key.group(1):
                        self.mineral_chem["Unknown"][element] = self.srm_actual[var_min][element]
                        self.mineral_chem["Unknown"][isotope] = self.srm_actual[var_min][element]

    def onclick(self, var, filename, ratio_mode, event, spikes=False):
        if spikes == False:
            if var.get() in [1, 2, 3, 4, 5]:
                if len(self.container_helper["positions"][filename]) == 2 and len(
                        self.container_helper["indices"][filename]) == 2:
                    self.container_helper["positions"][filename].clear()
                    self.container_helper["indices"][filename].clear()
                #
                x_nearest = min(self.times, key=lambda x: abs(x - event.xdata))
                self.container_helper["positions"][filename].append(x_nearest)
                self.container_helper["indices"][filename].append(self.times[self.times == x_nearest].index[0])
                #
                if len(self.container_helper["positions"][filename]) + len(
                        self.container_helper["indices"][filename]) == 4:
                    if var.get() == 1:  # BG
                        if self.file_type == "STD":
                            if len(self.container_helper["positions"]["BG STD"][filename]) > 0:
                                self.bg_id = self.container_helper["positions"]["BG STD"][filename][-1][4]
                        elif self.file_type == "SMPL":
                            if len(self.container_helper["positions"]["BG SMPL"][filename]) > 0:
                                self.bg_id = self.container_helper["positions"]["BG SMPL"][filename][-1][4]
                        #
                        self.bg_id += 1
                        self.bg_idlist.append(self.bg_id)
                        self.container_helper["limits BG"][self.file]["ID"].append(self.bg_id)
                        self.container_helper["limits BG"][self.file]["type"].append("custom")
                        self.container_helper["positions"]["BG"][filename].append(
                            [round(self.container_helper["positions"][filename][0], 4),
                             round(self.container_helper["positions"][filename][1], 4)])
                        self.container_listboxes[self.file_type][filename]["BG"][0].insert(
                            tk.END, "BG" + str(self.bg_id) + " [" + str(
                                self.container_helper["positions"][filename][0]) + "-" +
                                    str(self.container_helper["positions"][filename][1]) + "]")
                        #
                        if ratio_mode == False:
                            box_bg = self.ax.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.blue_dark)
                            box_bg_ratio = self.ax_ratio.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.blue_dark)
                            #
                            self.container_helper["limits BG"][self.file][str(self.bg_id)] = box_bg
                            self.container_helper["limits BG Ratio"][self.file][str(self.bg_id)] = box_bg_ratio
                            #
                            self.canvas.draw()
                            try:
                                self.canvas_ratio.draw()
                            except:
                                pass
                        else:
                            box_bg = self.ax.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.blue_dark)
                            box_bg_ratio = self.ax_ratio.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.blue_dark)
                            #
                            self.container_helper["limits BG"][self.file][str(self.bg_id)] = box_bg
                            self.container_helper["limits BG Ratio"][self.file][str(self.bg_id)] = box_bg_ratio
                            #
                            self.canvas.draw()
                            self.canvas_ratio.draw()
                        #
                        self.indices_bg = self.container_helper["indices"][filename]
                        #
                        self.container_files[self.file_type][self.filename_short]["BG"][self.bg_id] = {}
                        self.container_files[self.file_type][self.filename_short]["BG"][self.bg_id]["Times"] = [
                            self.container_helper["positions"][filename][0],
                            self.container_helper["positions"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["BG"][self.bg_id]["Positions"] = [
                            self.container_helper["indices"][filename][0],
                            self.container_helper["indices"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["BG"][self.bg_id]["Box"] = box_bg
                        #
                        if self.file_type == "STD":
                            self.container_helper["STD"][filename]["BG"][self.bg_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": [box_bg, box_bg_ratio]}
                            self.container_helper["positions"]["BG STD"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.bg_id])
                        elif self.file_type == "SMPL":
                            self.container_helper["SMPL"][filename]["BG"][self.bg_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": [box_bg, box_bg_ratio]}
                            self.container_helper["positions"]["BG SMPL"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.bg_id])
                    elif var.get() == 2:  # SIG
                        if self.file_type == "STD":
                            if len(self.container_helper["positions"]["SIG STD"][filename]) > 0:
                                self.sig_id = self.container_helper["positions"]["SIG STD"][filename][-1][4]
                        elif self.file_type == "SMPL":
                            if len(self.container_helper["positions"]["SIG SMPL"][filename]) > 0:
                                self.sig_id = self.container_helper["positions"]["SIG SMPL"][filename][-1][4]
                        self.sig_id += 1
                        self.sig_idlist.append(self.sig_id)
                        self.container_helper["limits SIG"][self.file]["ID"].append(self.sig_id)
                        self.container_helper["limits SIG"][self.file]["type"].append("custom")
                        self.container_helper["positions"]["SIG"][filename].append(
                            [round(self.container_helper["positions"][filename][0], 4),
                             round(self.container_helper["positions"][filename][1], 4)])
                        self.container_listboxes[self.file_type][filename]["SIG"][0].insert(
                            tk.END,
                            "SIG" + str(self.sig_id) + " [" + str(self.container_helper["positions"][filename][0]) + "-"
                            + str(self.container_helper["positions"][filename][1]) + "]")
                        #
                        if ratio_mode == False:
                            box_sig = self.ax.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                            self.container_helper["limits SIG"][self.file][str(self.sig_id)] = box_sig
                            self.canvas.draw()
                            #
                            # box_sig_ratio = self.ax_ratio.axvspan(
                            #     self.container_helper["positions"][filename][0],
                            #     self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                            # self.container_helper["limits SIG Ratio"][self.file][str(self.sig_id)] = box_sig_ratio
                            # self.canvas_ratio.draw()
                        else:
                            box_sig_ratio = self.ax_ratio.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                            box_sig = self.ax.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                            #
                            self.container_helper["limits SIG Ratio"][self.file][str(self.sig_id)] = box_sig_ratio
                            self.container_helper["limits SIG"][self.file][str(self.sig_id)] = box_sig
                            #
                            self.canvas_ratio.draw()
                            self.canvas.draw()
                        #
                        self.indices_sig = self.container_helper["indices"][filename]
                        #
                        self.container_files[self.file_type][self.filename_short]["SIG"][self.sig_id] = {}
                        self.container_files[self.file_type][self.filename_short]["SIG"][self.sig_id]["Times"] = [
                            self.container_helper["positions"][filename][0],
                            self.container_helper["positions"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["SIG"][self.sig_id]["Positions"] = [
                            self.container_helper["indices"][filename][0],
                            self.container_helper["indices"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["SIG"][self.sig_id]["Box"] = box_sig
                        #
                        if self.file_type == "STD":
                            self.container_helper["STD"][filename]["SIG"][self.sig_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": [box_sig, box_sig_ratio]}
                            self.container_helper["positions"]["SIG STD"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.sig_id])
                        elif self.file_type == "SMPL":
                            self.container_helper["SMPL"][filename]["SIG"][self.sig_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": [box_sig, box_sig_ratio]}
                            self.container_helper["positions"]["SIG SMPL"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.sig_id])
                    elif var.get() == 3:  # SPK
                        isotope_list = []
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in self.container_helper[self.file_type][filename]["SPK"]:
                                self.container_helper[self.file_type][filename]["SPK"][isotope] = {}
                            if self.container_var["plotting"][isotope][1].get() == 1:
                                isotope_list.append(isotope)
                        for isotope in isotope_list:
                            if len(self.container_helper[self.file_type][filename]["SPK"][isotope]) == 0:
                                self.spk_id = 1
                            else:
                                self.spk_id = int(
                                    len(self.container_helper[self.file_type][filename]["SPK"][isotope]) + 1)
                        isotope = "".join(isotope_list)
                        self.spk_idlist.append(self.spk_id)
                        self.container_helper["limits SPK"][self.file]["ID"].append(self.spk_id)
                        self.container_helper["limits SPK"][self.file]["type"].append("custom")
                        self.container_helper["limits SPK"][self.file]["info"].append([isotope, self.spk_id])
                        self.container_helper["positions"]["SPK"][filename].append(
                            [round(self.container_helper["positions"][filename][0], 4),
                             round(self.container_helper["positions"][filename][1], 4)])
                        #
                        if len(isotope_list) > 1:
                            color_var = self.yellow_dark
                        else:
                            color_var = self.isotope_colors[isotope]
                        self.container_listboxes[self.file_type][filename]["SPK"][0].insert(
                            tk.END, "[" + ", ".join(isotope_list) + "] #" + str(self.spk_id) + " [" + str(
                                self.container_helper["positions"][filename][0]) + "-" + str(
                                self.container_helper["positions"][filename][1]) + "]")
                        #
                        if ratio_mode == False:
                            box_spk = self.ax.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.125, color=color_var)
                            box_spk_ratio = self.ax_ratio.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.125, color=color_var)
                            #
                            self.container_helper["limits SPK"][self.file][str(self.spk_id)] = box_spk
                            self.container_helper["limits SPK Ratio"][self.file][str(self.spk_id)] = box_spk_ratio
                            #
                            self.canvas_ratio.draw()
                            self.canvas.draw()
                        else:
                            box_spk_ratio = self.ax_ratio.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.125, color=color_var)
                            box_spk = self.ax.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.125, color=color_var)
                            #
                            self.container_helper["limits SPK Ratio"][self.file][str(self.spk_id)] = box_spk_ratio
                            self.container_helper["limits SPK"][self.file][str(self.spk_id)] = box_spk
                            #
                            self.canvas_ratio.draw()
                            self.canvas.draw()
                        #
                        self.container_files[self.file_type][self.filename_short]["SPK"][self.spk_id] = {}
                        for isotope in isotope_list:
                            if isotope not in self.spikes_isotopes[self.file_type][filename]:
                                self.spikes_isotopes[self.file_type][filename][isotope] = []
                                self.spikes_isotopes[self.file_type][filename][isotope].append(
                                    [self.container_helper["indices"][filename][0],
                                     self.container_helper["indices"][filename][1]])
                            else:
                                self.spikes_isotopes[self.file_type][filename][isotope].append(
                                    [self.container_helper["indices"][filename][0],
                                     self.container_helper["indices"][filename][1]])
                            #
                            self.container_files[self.file_type][self.filename_short]["SPK"][self.spk_id][
                                "Isotope"] = isotope
                            self.container_files[self.file_type][self.filename_short]["SPK"][self.spk_id][
                                "Times"] = [
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1]]
                            self.container_files[self.file_type][self.filename_short]["SPK"][self.spk_id][
                                "Positions"] = [
                                self.container_helper["indices"][filename][0],
                                self.container_helper["indices"][filename][1]]
                            self.container_files[self.file_type][self.filename_short]["SPK"][self.spk_id][
                                "Box"] = box_spk
                            #
                            if self.file_type == "STD":
                                self.container_helper["STD"][filename]["SPK"][isotope][self.spk_id] = {
                                    "Times": [self.container_helper["positions"][filename][0],
                                              self.container_helper["positions"][filename][1]],
                                    "Positions": [self.container_helper["indices"][filename][0],
                                                  self.container_helper["indices"][filename][1]],
                                    "Object": [box_spk, box_spk_ratio]}
                            elif self.file_type == "SMPL":
                                self.container_helper["SMPL"][filename]["SPK"][isotope][self.spk_id] = {
                                    "Times": [self.container_helper["positions"][filename][0],
                                              self.container_helper["positions"][filename][1]],
                                    "Positions": [self.container_helper["indices"][filename][0],
                                                  self.container_helper["indices"][filename][1]],
                                    "Object": [box_spk, box_spk_ratio]}
                    #
                    elif var.get() == 4:  # MAT
                        if self.file_type == "STD":
                            if len(self.container_helper["positions"]["MAT STD"][filename]) > 0:
                                self.mat_id = self.container_helper["positions"]["MAT STD"][filename][-1][4]
                        elif self.file_type == "SMPL":
                            if len(self.container_helper["positions"]["MAT SMPL"][filename]) > 0:
                                self.mat_id = self.container_helper["positions"]["MAT SMPL"][filename][-1][4]
                        self.mat_id += 1
                        self.mat_idlist.append(self.mat_id)
                        self.container_helper["limits MAT"][self.file]["ID"].append(self.mat_id)
                        self.container_helper["limits MAT"][self.file]["type"].append("custom")
                        self.container_helper["positions"]["MAT"][filename].append(
                            [round(self.container_helper["positions"][filename][0], 4),
                             round(self.container_helper["positions"][filename][1], 4)])
                        self.container_listboxes[self.file_type][filename]["MAT"][0].insert(
                            tk.END,
                            "MAT" + str(self.mat_id) + " [" + str(self.container_helper["positions"][filename][0]) + "-"
                            + str(self.container_helper["positions"][filename][1]) + "]")
                        #
                        # if ratio_mode == False:
                        #     box_mat = self.ax.axvspan(
                        #         self.container_helper["positions"][filename][0],
                        #         self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                        #     self.container_helper["limits MAT"][self.file][str(self.mat_id)] = box_mat
                        #     #
                        #     self.canvas.draw()
                        # else:
                        #     box_mat = self.ax_ratio.axvspan(
                        #         self.container_helper["positions"][filename][0],
                        #         self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                        #     self.container_helper["limits MAT Ratio"][self.file][str(self.mat_id)] = box_mat
                        #     #
                        #     self.canvas_ratio.draw()
                        #
                        box_mat = self.ax.axvspan(
                            self.container_helper["positions"][filename][0],
                            self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                        box_mat_ratio = self.ax_ratio.axvspan(
                            self.container_helper["positions"][filename][0],
                            self.container_helper["positions"][filename][1], alpha=0.25, color=self.brown_dark)
                        self.container_helper["limits MAT"][self.file][str(self.mat_id)] = box_mat
                        self.container_helper["limits MAT Ratio"][self.file][str(self.mat_id)] = box_mat_ratio
                        #
                        self.canvas_ratio.draw()
                        self.canvas.draw()
                        #
                        self.indices_mat = self.container_helper["indices"][filename]
                        #
                        self.container_files[self.file_type][self.filename_short]["MAT"][self.mat_id] = {}
                        self.container_files[self.file_type][self.filename_short]["MAT"][self.mat_id]["Times"] = [
                            self.container_helper["positions"][filename][0],
                            self.container_helper["positions"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["MAT"][self.mat_id]["Positions"] = [
                            self.container_helper["indices"][filename][0],
                            self.container_helper["indices"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["MAT"][self.mat_id]["Box"] = box_mat
                        #
                        if self.file_type == "STD":
                            self.container_helper["STD"][filename]["MAT"][self.mat_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": [box_mat, box_mat_ratio]}
                            self.container_helper["positions"]["MAT STD"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.mat_id])
                        elif self.file_type == "SMPL":
                            self.container_helper["SMPL"][filename]["MAT"][self.mat_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": [box_mat, box_mat_ratio]}
                            self.container_helper["positions"]["MAT SMPL"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.mat_id])
                    #
                    elif var.get() == 5:  # INCL
                        if self.file_type == "STD":
                            if len(self.container_helper["positions"]["INCL STD"][filename]) > 0:
                                self.incl_id = self.container_helper["positions"]["INCL STD"][filename][-1][4]
                        elif self.file_type == "SMPL":
                            if len(self.container_helper["positions"]["INCL SMPL"][filename]) > 0:
                                self.incl_id = self.container_helper["positions"]["INCL SMPL"][filename][-1][4]
                        self.incl_id += 1
                        self.incl_idlist.append(self.incl_id)
                        self.container_helper["limits INCL"][self.file]["ID"].append(self.incl_id)
                        self.container_helper["limits INCL"][self.file]["type"].append("custom")
                        self.container_helper["positions"]["INCL"][filename].append(
                            [round(self.container_helper["positions"][filename][0], 4),
                             round(self.container_helper["positions"][filename][1], 4)])
                        self.container_listboxes[self.file_type][filename]["INCL"][0].insert(
                            tk.END, "INCL" + str(self.incl_id) + " [" + str(
                                self.container_helper["positions"][filename][0]) + "-"
                                    + str(self.container_helper["positions"][filename][1]) + "]")
                        #
                        if ratio_mode == False:
                            box_incl = self.ax.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.slate_grey_dark)
                            self.container_helper["limits INCL"][self.file][str(self.incl_id)] = box_incl
                            #
                            self.canvas.draw()
                        else:
                            box_incl = self.ax_ratio.axvspan(
                                self.container_helper["positions"][filename][0],
                                self.container_helper["positions"][filename][1], alpha=0.25, color=self.slate_grey_dark)
                            self.container_helper["limits INCL Ratio"][self.file][str(self.incl_id)] = box_incl
                            #
                            self.canvas_ratio.draw()
                        #
                        self.indices_incl = self.container_helper["indices"][filename]
                        #
                        self.container_files[self.file_type][self.filename_short]["INCL"][self.incl_id] = {}
                        self.container_files[self.file_type][self.filename_short]["INCL"][self.incl_id]["Times"] = [
                            self.container_helper["positions"][filename][0],
                            self.container_helper["positions"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["INCL"][self.incl_id][
                            "Positions"] = [
                            self.container_helper["indices"][filename][0],
                            self.container_helper["indices"][filename][1]]
                        self.container_files[self.file_type][self.filename_short]["INCL"][self.incl_id][
                            "Box"] = box_incl
                        #
                        if self.file_type == "STD":
                            self.container_helper["STD"][filename]["INCL"][self.incl_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": box_incl}
                            self.container_helper["positions"]["INCL STD"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.incl_id])
                        elif self.file_type == "SMPL":
                            self.container_helper["SMPL"][filename]["INCL"][self.incl_id] = {
                                "Times": [self.container_helper["positions"][filename][0],
                                          self.container_helper["positions"][filename][1]],
                                "Positions": [self.container_helper["indices"][filename][0],
                                              self.container_helper["indices"][filename][1]],
                                "Object": box_incl}
                            self.container_helper["positions"]["INCL SMPL"][filename].append(
                                [self.container_helper["positions"][filename][0],
                                 self.container_helper["positions"][filename][1],
                                 self.container_helper["indices"][filename][0],
                                 self.container_helper["indices"][filename][1],
                                 self.incl_id])
                    #
                    elif var.get() == 0:
                        pass
            else:
                pass
            #
        else:
            if var.get() == 1:
                if len(self.container_helper["positions"][filename]) == 2 and len(
                        self.container_helper["indices"][filename]) == 2:
                    self.container_helper["positions"][filename].clear()
                    self.container_helper["indices"][filename].clear()
                #
                x_nearest = min(self.times, key=lambda x: abs(x - event.xdata))
                self.container_helper["positions"][filename].append(x_nearest)
                self.container_helper["indices"][filename].append(self.times[self.times == x_nearest].index[0])
                #
                if len(self.container_helper["positions"][filename]) + len(
                        self.container_helper["indices"][filename]) == 4:
                    if var.get() == 1:
                        self.se_id += 1
                        self.se_idlist.append(self.se_id)
                        self.positions_se.append([round(self.container_helper["positions"][filename][0], 4),
                                                  round(self.container_helper["positions"][filename][1], 4)])
                        self.lb_se.insert(tk.END, "Spikes" + str(self.se_id) + " [" + str(
                            self.container_helper["positions"][filename][0]) + "-" +
                                          str(self.container_helper["positions"][filename][1]) + "]" + " [" + str(
                            self.container_helper["indices"][filename][0]) + "-" +
                                          str(self.container_helper["indices"][filename][1]) + "]")
                        box_se = self.ax.axvspan(self.container_helper["positions"][filename][0],
                                                 self.container_helper["positions"][filename][1], alpha=0.25,
                                                 color="#fff6a4")
                        self.limits_se[str(self.se_id)] = box_se
                        self.canvas_se.draw()
                    elif var.get() == 0:
                        pass
            else:
                pass

    def update_variables_initial_values(self):
        str_var_01 = self.language_dict["Set start time"][self.var_language]
        str_var_02 = self.language_dict["Set end time"][self.var_language]
        str_var_03 = self.language_dict["Select IS"][self.var_language]
        str_var_04 = self.language_dict["Select oxide"][self.var_language]
        str_var_05 = self.language_dict["Select element"][self.var_language]
        str_var_06 = self.language_dict["Select mineral"][self.var_language]

        self.container_var["settings"]["Time BG Start"].set(str_var_01)
        self.container_var["settings"]["Time BG End"].set(str_var_02)
        self.container_var["settings"]["Time SIG Start"].set(str_var_01)
        self.container_var["settings"]["Time SIG End"].set(str_var_02)
        self.container_var["ma_setting"]["Time BG Start"].set(str_var_01)
        self.container_var["ma_setting"]["Time BG End"].set(str_var_02)
        self.container_var["ma_setting"]["Time MAT Start"].set(str_var_01)
        self.container_var["ma_setting"]["Time MAT End"].set(str_var_02)

        self.container_var["ma_setting"]["Default IS STD"].set(str_var_03)
        self.container_var["ma_setting"]["Default IS SMPL"].set(str_var_03)
        self.container_var["IS"]["Default STD"].set(str_var_03)
        self.container_var["IS"]["Default SMPL"].set(str_var_03)
        self.container_var["General Settings"]["Default IS MA"].set(str_var_03)
        self.container_var["General Settings"]["Default IS FI"].set(str_var_03)
        self.container_var["General Settings"]["Default IS MI"].set(str_var_03)
        self.container_var["IS"]["Default SMPL"].set(str_var_03)

        self.container_var["ma_setting"]["Oxide"].set(str_var_04)

        self.container_var["ma_setting"]["Element"].set(str_var_05)

        self.container_var["ma_setting"]["Mineral"].set(str_var_06)

        keys = ["fi_setting", "mi_setting"]
        for key_setting in keys:
            self.container_var[key_setting]["Time BG Start"].set(str_var_01)
            self.container_var[key_setting]["Time BG End"].set(str_var_02)
            self.container_var[key_setting]["Time MAT Start"].set(str_var_01)
            self.container_var[key_setting]["Time MAT End"].set(str_var_02)
            self.container_var[key_setting]["Time INCL Start"].set(str_var_01)
            self.container_var[key_setting]["Time INCL End"].set(str_var_02)

            self.container_var[key_setting]["IS MAT Default"].set(str_var_03)
            self.container_var[key_setting]["IS INCL Default"].set(str_var_03)
            self.container_var[key_setting]["Salt Correction"]["Default IS"].set(str_var_03)

            self.container_var[key_setting]["Oxide"].set(str_var_04)
            self.container_var[key_setting]["Oxide Inclusion"].set(str_var_04)

    def do_spike_elimination_all_grubbs(self, filetype, spike_elimination_performed=True):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if "Selection" not in self.container_spikes:
            self.container_spikes["Selection"] = {}

        if self.pysills_mode == "MA":
            var_alpha = float(self.container_var[key_setting]["SE Alpha"].get())
            var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())
            if self.container_var["Spike Elimination Method"].get() in ["Grubbs-Test (SILLS)", "Grubbs test"]:
                var_method = 0
            elif self.container_var["Spike Elimination Method"].get() == "Grubbs-Test":
                var_method = 1
            elif self.container_var["Spike Elimination Method"].get() in ["PySILLS Spike Finder", "Whisker analysis"]:
                var_method = 2
        elif self.pysills_mode == "FI":
            var_alpha = float(self.container_var[key_setting]["SE Alpha"].get())
            var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())
            if self.container_var["Spike Elimination Method"].get() in ["Grubbs-Test (SILLS)", "Grubbs test"]:
                var_method = 0
            elif self.container_var["Spike Elimination Method"].get() == "Grubbs-Test":
                var_method = 1
            elif self.container_var["Spike Elimination Method"].get() in ["PySILLS Spike Finder", "Whisker analysis"]:
                var_method = 2
        elif self.pysills_mode == "MI":
            var_alpha = float(self.container_var[key_setting]["SE Alpha"].get())
            var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())
            if self.container_var["Spike Elimination Method"].get() in ["Grubbs-Test (SILLS)", "Grubbs test"]:
                var_method = 0
            elif self.container_var["Spike Elimination Method"].get() == "Grubbs-Test":
                var_method = 1
            elif self.container_var["Spike Elimination Method"].get() in ["PySILLS Spike Finder", "Whisker analysis"]:
                var_method = 2

        if filetype == "STD":
            subwindow_progressbar_spike_elimination, prgbar_spk = self.create_progress_bar_spike_elimination()
            n_files = len(self.container_lists["STD"]["Short"])
            n_isotopes = len(self.container_lists["Measured Isotopes"]["All"])
            n_steps = n_files*n_isotopes
            stepwidth = round(100/n_steps, 2)
            current_step = 0
            self.update_progress(
                parent=subwindow_progressbar_spike_elimination, variable=prgbar_spk, value=current_step)
            self.lbl_prg_spk.configure(text="Spike detection started!", anchor=tk.W)
            for index, file_std in enumerate(self.container_lists["STD"]["Short"]):
                file_long = self.container_lists[filetype]["Long"][index]
                self.lbl_prg_spk.configure(text=file_std)
                if self.container_var[filetype][file_long]["Checkbox"].get() == 1:
                    isotopes_spiked_list = [*self.spikes_isotopes[filetype][file_std]]
                    corrected_isotopes = []
                    not_corrected_isotopes = []
                    self.container_spikes[file_std] = {}

                    if file_std not in self.container_spikes["Selection"]:
                        self.container_spikes["Selection"][file_std] = {}

                    file_isotopes = self.container_lists["Measured Isotopes"][file_std]
                    for isotope in file_isotopes:
                        if bool(self.spikes_isotopes[filetype][file_std]):
                            for isotope_spiked, intervals in self.spikes_isotopes[filetype][file_std].items():

                                if isotope_spiked not in self.container_spikes["Selection"][file_std]:
                                    self.container_spikes["Selection"][file_std][isotope_spiked] = {}

                                if isotope in isotopes_spiked_list:
                                    if isotope not in corrected_isotopes:
                                        corrected_isotopes.append(isotope)
                                        spike_intervals = np.array(intervals)
                                        merged_intervals = ES(variable=spike_intervals).merge_times()
                                        for interval in merged_intervals:
                                            dataset_raw = self.container_measurements["RAW"][file_std][isotope][
                                                          interval[0]:interval[1]]
                                            dataset_complete = self.container_measurements["RAW"][file_std][isotope]
                                            dataset_complete_all = self.container_measurements["RAW"][file_std]
                                            var_threshold = int(self.container_var["Spike Elimination"]["Threshold"][
                                                                    isotope].get())

                                            if spike_elimination_performed == True:
                                                time_start = datetime.datetime.now()
                                                if var_method == 0:
                                                    data_smoothed, indices_outl = GrubbsTestSILLS(
                                                        raw_data=dataset_raw, alpha=var_alpha, threshold=var_threshold,
                                                        start_index=interval[0],
                                                        dataset_complete=dataset_complete).determine_outlier()
                                                elif var_method == 1:
                                                    data_smoothed, indices_outl = ES(
                                                        variable=dataset_raw).do_grubbs_test(
                                                        alpha=var_alpha, dataset_complete=dataset_complete,
                                                        threshold=var_threshold)
                                                elif var_method == 2:
                                                    data_smoothed, indices_outl = OutlierDetection(
                                                        raw_data=dataset_raw, alpha=var_alpha, threshold=var_threshold,
                                                        isotope=isotope,
                                                        dataset_complete=dataset_complete).find_outlier()
                                                time_end = datetime.datetime.now()
                                                time_delta = (time_end - time_start)*1000
                                            else:
                                                data_smoothed = dataset_raw
                                                indices_outl = []

                                            data_improved = data_smoothed.copy()
                                            self.container_measurements["EDITED"][file_std][isotope][
                                                "Uncut"] = data_smoothed

                                            self.container_spikes[file_std][isotope] = {
                                                "Data RAW": self.container_measurements["RAW"][file_std][isotope],
                                                "Data SMOOTHED": data_smoothed, "Data IMPROVED": data_improved,
                                                "Indices": indices_outl,
                                                "Times": self.container_measurements["SELECTED"][file_std]["Time"]}

                                        for var_index in indices_outl:
                                            self.container_spikes["Selection"][file_std][isotope][
                                                var_index] = data_smoothed[var_index]

                                    else:
                                        pass
                                else:
                                    if isotope not in not_corrected_isotopes:
                                        not_corrected_isotopes.append(isotope)
                                        self.container_measurements["EDITED"][file_std][isotope]["Uncut"] = \
                                            self.container_measurements["RAW"][file_std][isotope]
                                    else:
                                        pass
                        else:
                            if isotope not in not_corrected_isotopes:
                                not_corrected_isotopes.append(isotope)
                                if "Uncut" not in self.container_measurements["EDITED"][file_std][isotope]:
                                    self.container_measurements["EDITED"][file_std][isotope]["Uncut"] = None

                                if file_std not in self.container_measurements["RAW"]:
                                    self.build_container_measurements(filetype=filetype, filename_short=file_std)

                                self.container_measurements["EDITED"][file_std][isotope]["Uncut"] = (
                                    self.container_measurements["RAW"][file_std][isotope])

                                self.container_spikes[file_std][isotope] = {
                                    "Data RAW": self.container_measurements["RAW"][file_std][isotope],
                                    "Data SMOOTHED": self.container_measurements["RAW"][file_std][isotope],
                                    "Data IMPROVED": self.container_measurements["RAW"][file_std][isotope],
                                    "Indices": [],
                                    "Times": self.container_measurements["SELECTED"][file_std]["Time"]}
                            else:
                                pass

                        current_step += stepwidth
                        self.update_progress(
                            parent=subwindow_progressbar_spike_elimination, variable=prgbar_spk, value=current_step)
                        self.lbl_prg_spk.configure(
                            text=file_std + " : " + isotope + " - " + str(round(current_step, 1)) + " %", anchor=tk.W)

            # Fill container_spike_values
            self.helper_fill_container_spike_values(mode=filetype)

            current_step += stepwidth
            if current_step >= 100:
                self.lbl_prg_spk.configure(text="Spike detection finished!", anchor=tk.W)
                subwindow_progressbar_spike_elimination.destroy()
        elif filetype == "SMPL":
            list_times = {}
            subwindow_progressbar_spike_elimination, prgbar_spk = self.create_progress_bar_spike_elimination()
            n_files = len(self.container_lists["SMPL"]["Short"])
            n_isotopes = len(self.container_lists["Measured Isotopes"]["All"])
            n_steps = n_files*n_isotopes
            stepwidth = round(100/n_steps, 2)
            current_step = 0
            self.update_progress(
                parent=subwindow_progressbar_spike_elimination, variable=prgbar_spk, value=current_step)
            self.lbl_prg_spk.configure(text="Spike detection started!", anchor=tk.W)

            for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
                list_times[file_smpl] = []
                filename_long = self.container_lists["SMPL"]["Long"][index]
                self.lbl_prg_spk.configure(text=file_smpl)
                if self.container_var[filetype][filename_long]["Checkbox"].get() == 1:
                    isotopes_spiked_list = [*self.spikes_isotopes[filetype][file_smpl]]
                    corrected_isotopes = []
                    not_corrected_isotopes = []
                    self.container_spikes[file_smpl] = {}
                    if len(isotopes_spiked_list) == 0 and "_copy" in file_smpl:
                        file_smpl_original = file_smpl.replace("_copy", "")
                        isotopes_spiked_list = [*self.spikes_isotopes[filetype][file_smpl_original]]
                    if file_smpl not in self.container_spikes["Selection"]:
                        self.container_spikes["Selection"][file_smpl] = {}

                    if self.file_loaded == False:
                        if self.container_icpms["name"] != None:
                            var_skipheader = self.container_icpms["skipheader"]
                            var_skipfooter = self.container_icpms["skipfooter"]
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        else:
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=3, skip_footer=1)
                    else:
                        try:
                            df_data = self.container_measurements["Dataframe"][file_smpl]
                        except:
                            if "_copy" in file_smpl:
                                file_smpl_original = file_smpl.replace("_copy", "")
                                file_smpl = file_smpl_original
                                df_data = self.container_measurements["Dataframe"][file_smpl]
                            else:
                                df_data = self.container_measurements["Dataframe"][file_smpl]
                        # if "_copy" in file_smpl:
                        #     filename_original = file_smpl.replace("_copy", "")
                        #     #file_smpl = filename_original
                        #     df_data = self.container_measurements["Dataframe"][filename_original]
                        # else:
                        #     df_data = self.container_measurements["Dataframe"][file_smpl]

                    list_names = list(df_data.columns.values)
                    list_names.pop(0)
                    df_isotopes = list_names

                    for isotope in df_isotopes:
                        if bool(self.spikes_isotopes[filetype][file_smpl]) == False and "_copy" in file_smpl:
                            file_smpl_original = file_smpl.replace("_copy", "")
                            self.spikes_isotopes[filetype][file_smpl] = self.spikes_isotopes[filetype][
                                file_smpl_original]
                        if bool(self.spikes_isotopes[filetype][file_smpl]):
                            for isotope_spiked, intervals in self.spikes_isotopes[filetype][file_smpl].items():
                                if isotope_spiked not in self.container_spikes["Selection"][file_smpl]:
                                    self.container_spikes["Selection"][file_smpl][isotope_spiked] = {}

                                if isotope in isotopes_spiked_list:
                                    if isotope not in corrected_isotopes:
                                        corrected_isotopes.append(isotope)
                                        spike_intervals = np.array(intervals)
                                        merged_intervals = ES(variable=spike_intervals).merge_times()
                                        for interval in merged_intervals:
                                            if (isotope not in self.container_measurements["RAW"][file_smpl] and
                                                    "_copy" in file_smpl):
                                                file_smpl_original = file_smpl.replace("_copy", "")
                                                dataset_raw = self.container_measurements["RAW"][file_smpl_original][
                                                                  isotope][interval[0]:interval[1]]
                                                self.container_measurements["RAW"][file_smpl][
                                                    isotope] = self.container_measurements["RAW"][file_smpl_original][
                                                    isotope]
                                            else:
                                                dataset_raw = self.container_measurements["RAW"][file_smpl][isotope][
                                                              interval[0]:interval[1]]

                                            dataset_complete = self.container_measurements["RAW"][file_smpl][isotope]
                                            dataset_complete_all = self.container_measurements["RAW"][file_smpl]
                                            var_threshold = int(self.container_var["Spike Elimination"]["Threshold"][
                                                                    isotope].get())

                                            if spike_elimination_performed == True:
                                                time_start = datetime.datetime.now()
                                                if var_method == 0:
                                                    data_smoothed, indices_outl = GrubbsTestSILLS(
                                                        raw_data=dataset_raw, alpha=var_alpha, threshold=var_threshold,
                                                        start_index=interval[0],
                                                        dataset_complete=dataset_complete).determine_outlier()
                                                elif var_method == 1:
                                                    data_smoothed, indices_outl = ES(
                                                        variable=dataset_raw).do_grubbs_test(
                                                        alpha=var_alpha, dataset_complete=dataset_complete,
                                                        threshold=var_threshold)
                                                elif var_method == 2:
                                                    data_smoothed, indices_outl = OutlierDetection(
                                                        raw_data=dataset_raw, alpha=var_alpha, threshold=var_threshold,
                                                        isotope=isotope,
                                                        dataset_complete=dataset_complete).find_outlier()
                                                time_end = datetime.datetime.now()
                                                time_delta = (time_end - time_start)*1000
                                                list_times[file_smpl].append(time_delta.total_seconds())
                                            else:
                                                data_smoothed = dataset_raw
                                                indices_outl = []

                                            data_improved = data_smoothed.copy()
                                            if self.pysills_mode in ["FI", "MI"]:
                                                if self.container_var[key_setting][
                                                    "Spike Elimination Inclusion"].get() == 2:
                                                    length_incl_datasets = len(
                                                        self.container_helper["SMPL"][file_smpl]["INCL"]["Content"])
                                                    if length_incl_datasets > 0:
                                                        for key, items in self.container_helper["SMPL"][file_smpl][
                                                            "INCL"]["Content"].items():
                                                            var_indices = items["Indices"]
                                                            lower_limit = var_indices[0]
                                                            upper_limit = var_indices[1] + 1
                                                            data_raw = self.container_measurements["RAW"][file_smpl][
                                                                isotope]
                                                            if len(indices_outl) > 0:
                                                                for index_outl in indices_outl:
                                                                    if (index_outl >= lower_limit
                                                                            and upper_limit >= index_outl):
                                                                        value_raw = data_raw[index_outl]
                                                                        value_smoothed = data_smoothed[index_outl]
                                                                        data_improved[index_outl] = value_raw
                                                                        value_improved = data_improved[index_outl]
                                                            # values_raw = data_raw[var_indices[0]:var_indices[1] + 1].copy()
                                                            # data_improved[var_indices[0]:var_indices[1] + 1] = values_raw
                                                            # print(isotope, var_indices, indices_outl)
                                                            # for index in range(var_indices[0], var_indices[1] + 1):
                                                            #     value_raw = data_raw[index]
                                                            #     data_improved[index] = value_raw

                                            if (isotope not in self.container_measurements["EDITED"][file_smpl] and
                                                    "_copy" in file_smpl):
                                                self.container_measurements["EDITED"][file_smpl][isotope] = {
                                                    "Uncut": None}
                                                self.container_measurements["EDITED"][file_smpl][isotope][
                                                    "Uncut"] = data_smoothed
                                            else:
                                                self.container_measurements["EDITED"][file_smpl][isotope][
                                                    "Uncut"] = data_smoothed

                                            if ("Time" not in self.container_measurements["SELECTED"][file_smpl] and
                                                    "_copy" in file_smpl):
                                                self.container_measurements["SELECTED"][file_smpl][
                                                    "Time"] = self.container_measurements["SELECTED"][
                                                    file_smpl_original]["Time"]

                                            # if self.container_var[key_setting]["Spike Elimination Inclusion"].get() == 2:
                                            #     if data_smoothed == data_improved and len(indices_outl) > 0:
                                            #         print("The SMOOTHED and IMPROVED datasets are the same. "
                                            #               "That should not be the case!")

                                            self.container_spikes[file_smpl][isotope] = {
                                                "Data RAW": self.container_measurements["RAW"][file_smpl][isotope],
                                                "Data SMOOTHED": data_smoothed, "Data IMPROVED": data_improved, 
                                                "Indices": indices_outl,
                                                "Times": self.container_measurements["SELECTED"][file_smpl]["Time"]}

                                        for var_index in indices_outl:
                                            self.container_spikes["Selection"][file_smpl][isotope][
                                                var_index] = data_smoothed[var_index]
                                    else:
                                        pass
                                else:
                                    if isotope not in not_corrected_isotopes:
                                        not_corrected_isotopes.append(isotope)
                                        self.container_measurements["EDITED"][file_smpl][isotope]["Uncut"] = \
                                            self.container_measurements["RAW"][file_smpl][isotope]
                                    else:
                                        pass
                        else:
                            if isotope not in not_corrected_isotopes:
                                not_corrected_isotopes.append(isotope)

                                if "Uncut" not in self.container_measurements["EDITED"][file_smpl][isotope]:
                                    self.container_measurements["EDITED"][file_smpl][isotope]["Uncut"] = None

                                if file_smpl not in self.container_measurements["RAW"]:
                                    self.build_container_measurements(filetype=filetype, filename_short=file_smpl)

                                self.container_measurements["EDITED"][file_smpl][isotope]["Uncut"] = \
                                    self.container_measurements["RAW"][file_smpl][isotope]

                                self.container_spikes[file_smpl][isotope] = {
                                    "Data RAW": self.container_measurements["RAW"][file_smpl][isotope],
                                    "Data SMOOTHED": self.container_measurements["RAW"][file_smpl][isotope],
                                    "Data IMPROVED": self.container_measurements["RAW"][file_smpl][isotope], 
                                    "Indices": [],
                                    "Times": self.container_measurements["SELECTED"][file_smpl]["Time"]}
                            else:
                                pass

                        current_step += stepwidth
                        self.update_progress(
                            parent=subwindow_progressbar_spike_elimination, variable=prgbar_spk, value=current_step)
                        self.lbl_prg_spk.configure(
                            text=file_smpl + " : " + isotope + " - " + str(round(current_step, 1)) + " %", anchor=tk.W)

            self.helper_fill_container_spike_values(mode=filetype)

            current_step += stepwidth
            if current_step >= 100:
                self.lbl_prg_spk.configure(text="Spike detection finished!", anchor=tk.W)
                subwindow_progressbar_spike_elimination.destroy()

    def single_spike_elimination(self, var_filetype, var_filename_short, var_spike_elimination_performed=True):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.pysills_mode == "MA":
            var_alpha = float(self.container_var[key_setting]["SE Alpha"].get())
            var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())
            if self.container_var["Spike Elimination Method"].get() in ["Grubbs-Test (SILLS)", "Grubbs test"]:
                var_method = 0
            elif self.container_var["Spike Elimination Method"].get() == "Grubbs-Test":
                var_method = 1
            elif self.container_var["Spike Elimination Method"].get() in ["PySILLS Spike Finder", "Whisker analysis"]:
                var_method = 2
        elif self.pysills_mode == "FI":
            var_alpha = float(self.container_var[key_setting]["SE Alpha"].get())
            var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())
            if self.container_var["Spike Elimination Method"].get() in ["Grubbs-Test (SILLS)", "Grubbs test"]:
                var_method = 0
            elif self.container_var["Spike Elimination Method"].get() == "Grubbs-Test":
                var_method = 1
            elif self.container_var["Spike Elimination Method"].get() in ["PySILLS Spike Finder", "Whisker analysis"]:
                var_method = 2
        elif self.pysills_mode == "MI":
            var_alpha = float(self.container_var[key_setting]["SE Alpha"].get())
            var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())
            if self.container_var["Spike Elimination Method"].get() in ["Grubbs-Test (SILLS)", "Grubbs test"]:
                var_method = 0
            elif self.container_var["Spike Elimination Method"].get() == "Grubbs-Test":
                var_method = 1
            elif self.container_var["Spike Elimination Method"].get() in ["PySILLS Spike Finder", "Whisker analysis"]:
                var_method = 2

        list_times = {}
        subwindow_progressbar_spike_elimination, prgbar_spk = self.create_progress_bar_spike_elimination()
        n_files = len(self.container_lists[var_filetype]["Short"])
        n_isotopes = len(self.container_lists["Measured Isotopes"]["All"])
        n_steps = n_files*n_isotopes
        stepwidth = round(100/n_steps, 2)
        current_step = 0
        self.update_progress(parent=subwindow_progressbar_spike_elimination, variable=prgbar_spk, value=current_step)
        self.lbl_prg_spk.configure(text="Spike detection started!", anchor=tk.W)

        list_times[var_filename_short] = []
        index_filename = self.container_lists[var_filetype]["Short"].index(var_filename_short)
        filename_long = self.container_lists[var_filetype]["Long"][index_filename]
        self.lbl_prg_spk.configure(text=var_filename_short)
        if self.container_var[var_filetype][filename_long]["Checkbox"].get() == 1:
            isotopes_spiked_list = [*self.spikes_isotopes[var_filetype][var_filename_short]]
            corrected_isotopes = []
            not_corrected_isotopes = []
            self.container_spikes[var_filename_short] = {}
            if len(isotopes_spiked_list) == 0 and "_copy" in var_filename_short:
                var_filename_short_original = var_filename_short.replace("_copy", "")
                isotopes_spiked_list = [*self.spikes_isotopes[var_filetype][var_filename_short_original]]
            if var_filename_short not in self.container_spikes["Selection"]:
                self.container_spikes["Selection"][var_filename_short] = {}

            if self.file_loaded == False:
                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_data = DE(filename_long=filename_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_data = DE(filename_long=filename_long).get_measurements(
                        delimiter=",", skip_header=3, skip_footer=1)
            else:
                try:
                    df_data = self.container_measurements["Dataframe"][var_filename_short]
                except:
                    if "_copy" in var_filename_short:
                        var_filename_short_original = var_filename_short.replace("_copy", "")
                        var_filename_short = var_filename_short_original
                        df_data = self.container_measurements["Dataframe"][var_filename_short]
                    else:
                        df_data = self.container_measurements["Dataframe"][var_filename_short]

            list_names = list(df_data.columns.values)
            list_names.pop(0)
            df_isotopes = list_names

            for isotope in df_isotopes:
                if bool(self.spikes_isotopes[var_filetype][var_filename_short]) == False and "_copy" in var_filename_short:
                    var_filename_short_original = var_filename_short.replace("_copy", "")
                    self.spikes_isotopes[var_filetype][var_filename_short] = self.spikes_isotopes[var_filetype][
                        var_filename_short_original]
                if bool(self.spikes_isotopes[var_filetype][var_filename_short]):
                    for isotope_spiked, intervals in self.spikes_isotopes[var_filetype][var_filename_short].items():
                        if isotope_spiked not in self.container_spikes["Selection"][var_filename_short]:
                            self.container_spikes["Selection"][var_filename_short][isotope_spiked] = {}

                        if isotope in isotopes_spiked_list:
                            if isotope not in corrected_isotopes:
                                corrected_isotopes.append(isotope)
                                spike_intervals = np.array(intervals)
                                merged_intervals = ES(variable=spike_intervals).merge_times()
                                for interval in merged_intervals:
                                    if (isotope not in self.container_measurements["RAW"][var_filename_short] and
                                            "_copy" in var_filename_short):
                                        var_filename_short_original = var_filename_short.replace("_copy", "")
                                        dataset_raw = self.container_measurements["RAW"][var_filename_short_original][
                                                          isotope][interval[0]:interval[1]]
                                        self.container_measurements["RAW"][var_filename_short][
                                            isotope] = self.container_measurements["RAW"][var_filename_short_original][
                                            isotope]
                                    else:
                                        dataset_raw = self.container_measurements["RAW"][var_filename_short][isotope][
                                                      interval[0]:interval[1]]

                                    dataset_complete = self.container_measurements["RAW"][var_filename_short][isotope]
                                    dataset_complete_all = self.container_measurements["RAW"][var_filename_short]

                                    if var_spike_elimination_performed == True:
                                        time_start = datetime.datetime.now()
                                        if var_method == 0:
                                            data_smoothed, indices_outl = GrubbsTestSILLS(
                                                raw_data=dataset_raw, alpha=var_alpha, threshold=var_threshold,
                                                start_index=interval[0],
                                                dataset_complete=dataset_complete).determine_outlier()
                                        elif var_method == 1:
                                            data_smoothed, indices_outl = ES(
                                                variable=dataset_raw).do_grubbs_test(
                                                alpha=var_alpha, dataset_complete=dataset_complete,
                                                threshold=var_threshold)
                                        elif var_method == 2:
                                            data_smoothed, indices_outl = OutlierDetection(
                                                raw_data=dataset_raw, alpha=var_alpha, threshold=var_threshold,
                                                isotope=isotope,
                                                dataset_complete=dataset_complete).find_outlier()
                                        time_end = datetime.datetime.now()
                                        time_delta = (time_end - time_start)*1000
                                        list_times[var_filename_short].append(time_delta.total_seconds())
                                    else:
                                        data_smoothed = dataset_raw
                                        indices_outl = []

                                    data_improved = data_smoothed.copy()
                                    if self.pysills_mode in ["FI", "MI"]:
                                        if self.container_var[key_setting][
                                            "Spike Elimination Inclusion"].get() == 2 and var_filetype == "SMPL":
                                            length_incl_datasets = len(
                                                self.container_helper["SMPL"][var_filename_short]["INCL"]["Content"])
                                            if length_incl_datasets > 0:
                                                for key, items in self.container_helper["SMPL"][var_filename_short][
                                                    "INCL"]["Content"].items():
                                                    var_indices = items["Indices"]
                                                    lower_limit = var_indices[0]
                                                    upper_limit = var_indices[1] + 1
                                                    data_raw = self.container_measurements["RAW"][var_filename_short][
                                                        isotope]
                                                    if len(indices_outl) > 0:
                                                        for index_outl in indices_outl:
                                                            if (index_outl >= lower_limit
                                                                    and upper_limit >= index_outl):
                                                                value_raw = data_raw[index_outl]
                                                                value_smoothed = data_smoothed[index_outl]
                                                                data_improved[index_outl] = value_raw
                                                                value_improved = data_improved[index_outl]

                                    if (isotope not in self.container_measurements["EDITED"][var_filename_short] and
                                            "_copy" in var_filename_short):
                                        self.container_measurements["EDITED"][var_filename_short][isotope] = {
                                            "Uncut": None}
                                        self.container_measurements["EDITED"][var_filename_short][isotope][
                                            "Uncut"] = data_smoothed
                                    else:
                                        self.container_measurements["EDITED"][var_filename_short][isotope][
                                            "Uncut"] = data_smoothed

                                    if ("Time" not in self.container_measurements["SELECTED"][var_filename_short] and
                                            "_copy" in var_filename_short):
                                        self.container_measurements["SELECTED"][var_filename_short][
                                            "Time"] = self.container_measurements["SELECTED"][
                                            var_filename_short_original]["Time"]

                                    self.container_spikes[var_filename_short][isotope] = {
                                        "Data RAW": self.container_measurements["RAW"][var_filename_short][isotope],
                                        "Data SMOOTHED": data_smoothed, "Data IMPROVED": data_improved,
                                        "Indices": indices_outl,
                                        "Times": self.container_measurements["SELECTED"][var_filename_short]["Time"]}

                                for var_index in indices_outl:
                                    self.container_spikes["Selection"][var_filename_short][isotope][
                                        var_index] = data_smoothed[var_index]
                            else:
                                pass
                        else:
                            if isotope not in not_corrected_isotopes:
                                not_corrected_isotopes.append(isotope)
                                self.container_measurements["EDITED"][var_filename_short][isotope]["Uncut"] = \
                                    self.container_measurements["RAW"][var_filename_short][isotope]
                            else:
                                pass
                else:
                    if isotope not in not_corrected_isotopes:
                        not_corrected_isotopes.append(isotope)

                        if "Uncut" not in self.container_measurements["EDITED"][var_filename_short][isotope]:
                            self.container_measurements["EDITED"][var_filename_short][isotope]["Uncut"] = None

                        if var_filename_short not in self.container_measurements["RAW"]:
                            self.build_container_measurements(filetype=var_filetype, filename_short=var_filename_short)

                        self.container_measurements["EDITED"][var_filename_short][isotope]["Uncut"] = \
                            self.container_measurements["RAW"][var_filename_short][isotope]

                        self.container_spikes[var_filename_short][isotope] = {
                            "Data RAW": self.container_measurements["RAW"][var_filename_short][isotope],
                            "Data SMOOTHED": self.container_measurements["RAW"][var_filename_short][isotope],
                            "Data IMPROVED": self.container_measurements["RAW"][var_filename_short][isotope],
                            "Indices": [],
                            "Times": self.container_measurements["SELECTED"][var_filename_short]["Time"]}
                    else:
                        pass

                current_step += stepwidth
                self.update_progress(
                    parent=subwindow_progressbar_spike_elimination, variable=prgbar_spk, value=current_step)
                self.lbl_prg_spk.configure(
                    text=var_filename_short + " : " + isotope + " - " + str(round(current_step, 1)) + " %", anchor=tk.W)

    def ma_export_calculation_report(self):
        header = ["filename", "ID"]
        n_decimals_concentration = 5
        n_decimals_intensity = 5
        n_decimals_sensitivity = 5
        #
        # Concentration
        report_concentration = {}
        report_concentration["Total STD"] = {}
        report_concentration["Total SMPL"] = {}
        # 1-Sigma-Concentration
        report_concentration_sigma = {}
        report_concentration_sigma["Total STD"] = {}
        report_concentration_sigma["Total SMPL"] = {}
        # Concentration Ratio
        report_concentration_ratio = {}
        report_concentration_ratio["Total STD"] = {}
        report_concentration_ratio["Total SMPL"] = {}
        # Limit of Detection
        report_lod = {}
        report_lod["Total STD"] = {}
        report_lod["Total SMPL"] = {}
        # Intensity
        report_intensity = {}
        report_intensity["Total STD"] = {}
        report_intensity["Total SMPL"] = {}
        # 1-Sigma-Intensity
        report_intensity_sigma = {}
        report_intensity_sigma["Total STD"] = {}
        report_intensity_sigma["Total SMPL"] = {}
        # Intensity Ratio
        report_intensity_ratio = {}
        report_intensity_ratio["Total STD"] = {}
        report_intensity_ratio["Total SMPL"] = {}
        # Analytical Sensitivity
        report_analytical_sensitivity = {}
        report_analytical_sensitivity["Total STD"] = {}
        report_analytical_sensitivity["Total SMPL"] = {}
        # Normalized Sensitivity
        report_normalized_sensitivity = {}
        report_normalized_sensitivity["Total STD"] = {}
        report_normalized_sensitivity["Total SMPL"] = {}
        # Relative Sensitivity Factor
        report_rsf = {}
        report_rsf["Total STD"] = {}
        report_rsf["Total SMPL"] = {}
        #
        for var_filetype in ["STD", "SMPL"]:
            var_key = "Total " + str(var_filetype)
            #
            report_concentration[var_filetype] = {}
            report_concentration[var_key] = {}
            report_concentration[var_key]["filename"] = "All Files"
            #
            report_concentration_sigma[var_filetype] = {}
            report_concentration_sigma[var_key] = {}
            report_concentration_sigma[var_key]["filename"] = "All Files"
            #
            report_concentration_ratio[var_filetype] = {}
            report_concentration_ratio[var_key] = {}
            report_concentration_ratio[var_key]["filename"] = "All Files"
            #
            report_lod[var_filetype] = {}
            report_lod[var_key] = {}
            report_lod[var_key]["filename"] = "All Files"
            #
            report_intensity[var_filetype] = {}
            report_intensity[var_key] = {}
            report_intensity[var_key]["filename"] = "All Files"
            #
            report_intensity_sigma[var_filetype] = {}
            report_intensity_sigma[var_key] = {}
            report_intensity_sigma[var_key]["filename"] = "All Files"
            #
            report_intensity_ratio[var_filetype] = {}
            report_intensity_ratio[var_key] = {}
            report_intensity_ratio[var_key]["filename"] = "All Files"
            #
            report_analytical_sensitivity[var_filetype] = {}
            report_analytical_sensitivity[var_key] = {}
            report_analytical_sensitivity[var_key]["filename"] = "All Files"
            #
            report_normalized_sensitivity[var_filetype] = {}
            report_normalized_sensitivity[var_key] = {}
            report_normalized_sensitivity[var_key]["filename"] = "All Files"
            #
            report_rsf[var_filetype] = {}
            report_rsf[var_key] = {}
            report_rsf[var_key]["filename"] = "All Files"
            #
            for var_datatype in ["SMOOTHED", "RAW"]:
                report_concentration[var_filetype][var_datatype] = {}
                report_concentration_sigma[var_filetype][var_datatype] = {}
                report_concentration_ratio[var_filetype][var_datatype] = {}
                report_lod[var_filetype][var_datatype] = {}
                #
                report_intensity[var_filetype][var_datatype] = {}
                report_intensity_sigma[var_filetype][var_datatype] = {}
                report_intensity_ratio[var_filetype][var_datatype] = {}
                #
                report_analytical_sensitivity[var_filetype][var_datatype] = {}
                report_normalized_sensitivity[var_filetype][var_datatype] = {}
                report_rsf[var_filetype][var_datatype] = {}
                #
                for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                    file_long = self.container_lists[var_filetype]["Long"][index]
                    ## Compositional Results
                    report_concentration[var_filetype][var_datatype][file_short] = {}
                    report_concentration[var_filetype][var_datatype][file_short]["filename"] = file_short
                    report_concentration_sigma[var_filetype][var_datatype][file_short] = {}
                    report_concentration_sigma[var_filetype][var_datatype][file_short]["filename"] = file_short
                    report_concentration_ratio[var_filetype][var_datatype][file_short] = {}
                    report_concentration_ratio[var_filetype][var_datatype][file_short]["filename"] = file_short
                    report_lod[var_filetype][var_datatype][file_short] = {}
                    report_lod[var_filetype][var_datatype][file_short]["filename"] = file_short
                    if var_filetype == "STD":
                        report_concentration[var_filetype][var_datatype][file_short]["ID"] = "---"
                        report_concentration_ratio[var_filetype][var_datatype][file_short]["ID"] = "---"
                        report_lod[var_filetype][var_datatype][file_short]["ID"] = "---"
                    else:
                        report_concentration[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                            var_filetype][file_long]["ID"].get()
                        report_concentration_ratio[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                            var_filetype][file_long]["ID"].get()
                        report_lod[var_filetype][var_datatype][file_short]["ID"] = self.container_var[var_filetype][
                            file_long]["ID"].get()
                    ## Intensity Results
                    report_intensity[var_filetype][var_datatype][file_short] = {}
                    report_intensity[var_filetype][var_datatype][file_short]["filename"] = file_short
                    report_intensity_sigma[var_filetype][var_datatype][file_short] = {}
                    report_intensity_sigma[var_filetype][var_datatype][file_short]["filename"] = file_short
                    report_intensity_ratio[var_filetype][var_datatype][file_short] = {}
                    report_intensity_ratio[var_filetype][var_datatype][file_short]["filename"] = file_short
                    if var_filetype == "STD":
                        report_intensity[var_filetype][var_datatype][file_short]["ID"] = "---"
                        report_intensity_ratio[var_filetype][var_datatype][file_short]["ID"] = "---"
                    else:
                        report_intensity[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                            var_filetype][file_long]["ID"].get()
                        report_intensity_ratio[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                            var_filetype][file_long]["ID"].get()
                    ## Sensitivity Results
                    report_analytical_sensitivity[var_filetype][var_datatype][file_short] = {}
                    report_analytical_sensitivity[var_filetype][var_datatype][file_short]["filename"] = file_short
                    report_normalized_sensitivity[var_filetype][var_datatype][file_short] = {}
                    report_normalized_sensitivity[var_filetype][var_datatype][file_short]["filename"] = file_short
                    report_rsf[var_filetype][var_datatype][file_short] = {}
                    report_rsf[var_filetype][var_datatype][file_short]["filename"] = file_short
                    if var_filetype == "STD":
                        report_analytical_sensitivity[var_filetype][var_datatype][file_short]["ID"] = "---"
                        report_normalized_sensitivity[var_filetype][var_datatype][file_short]["ID"] = "---"
                        report_rsf[var_filetype][var_datatype][file_short]["ID"] = "---"
                    else:
                        report_analytical_sensitivity[var_filetype][var_datatype][file_short][
                            "ID"] = self.container_var[var_filetype][file_long]["ID"].get()
                        report_normalized_sensitivity[var_filetype][var_datatype][file_short][
                            "ID"] = self.container_var[var_filetype][file_long]["ID"].get()
                        report_rsf[var_filetype][var_datatype][file_short]["ID"] = self.container_var[var_filetype][
                            file_long]["ID"].get()
                    #
                    for isotope in self.container_lists["ISOTOPES"]:
                        ## Compositional Results
                        # Concentration
                        if var_filetype == "SMPL":
                            value_i = self.container_concentration[var_filetype][var_datatype][file_short]["MAT"][
                                isotope]
                            value_lod_i = self.container_lod[var_filetype][var_datatype][file_short]["MAT"][isotope]
                        else:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            var_srm_file = self.container_var["STD"][file_long]["SRM"].get()

                            if var_srm_i == var_srm_file:
                                value_i = self.container_concentration[var_filetype][var_datatype][file_short]["MAT"][
                                    isotope]
                                value_lod_i = self.container_lod[var_filetype][var_datatype][file_short]["MAT"][isotope]
                            else:
                                value_i = None

                        if value_i != None:
                            if value_i >= value_lod_i:
                                report_concentration[var_filetype][var_datatype][file_short][isotope] = round(
                                    value_i, n_decimals_concentration)
                            else:
                                report_concentration[var_filetype][var_datatype][file_short][isotope] = round(
                                    -value_i, n_decimals_concentration)
                        else:
                            report_concentration[var_filetype][var_datatype][file_short][isotope] = "---"

                        # 1-Sigma-Concentration
                        value_i = self.container_concentration[var_filetype][var_datatype][file_short]["1 SIGMA MAT"][
                            isotope]
                        report_concentration_sigma[var_filetype][var_datatype][file_short][isotope] = round(
                            value_i, n_decimals_concentration)

                        # Concentration Ratio
                        value_i = self.container_concentration_ratio[var_filetype][var_datatype][file_short]["MAT"][
                            isotope]
                        try:
                            report_concentration_ratio[var_filetype][var_datatype][file_short][
                                isotope] = "{:0.5e}".format(value_i)
                        except:
                            report_concentration_ratio[var_filetype][var_datatype][file_short][isotope] = "---"

                        # Limit of Detection
                        value_i = self.container_lod[var_filetype][var_datatype][file_short]["MAT"][isotope]

                        if value_i != None:
                            report_lod[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_decimals_concentration)
                        else:
                            report_intensity[var_filetype][var_datatype][file_short][isotope] = "---"

                        ## Intensity Results
                        # Intensity
                        if var_filetype == "SMPL":
                            value_i = self.container_intensity_corrected[var_filetype][var_datatype][file_short]["MAT"][
                                isotope]
                        else:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            var_srm_file = self.container_var["STD"][file_long]["SRM"].get()
                            if var_srm_i == var_srm_file:
                                value_i = self.container_intensity_corrected[var_filetype][var_datatype][file_short][
                                    "MAT"][isotope]
                            else:
                                value_i = None
                        if value_i != None:
                            report_intensity[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_decimals_intensity)
                        else:
                            report_intensity[var_filetype][var_datatype][file_short][isotope] = "---"

                        # 1-Sigma-Intensity
                        value_i = self.container_intensity[var_filetype][var_datatype][file_short]["1 SIGMA MAT"][
                            isotope]
                        report_intensity_sigma[var_filetype][var_datatype][file_short][isotope] = round(
                            value_i, n_decimals_intensity)

                        # Intensity Ratio
                        value_i = self.container_intensity_ratio[var_filetype][var_datatype][file_short]["MAT"][isotope]
                        try:
                            report_intensity_ratio[var_filetype][var_datatype][file_short][isotope] = "{:0.5e}".format(
                                value_i)
                        except:
                            report_intensity_ratio[var_filetype][var_datatype][file_short][isotope] = "---"

                        ## Sensitivity Results
                        # Analytical Sensitivity
                        value_i = self.container_analytical_sensitivity[var_filetype][var_datatype][file_short]["MAT"][
                            isotope]
                        try:
                            report_analytical_sensitivity[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_decimals_sensitivity)
                        except:
                            report_analytical_sensitivity[var_filetype][var_datatype][file_short][isotope] = "---"

                        # Normalized Sensitivity
                        if var_filetype == "SMPL":
                            value_i = self.container_normalized_sensitivity[var_filetype][var_datatype][file_short][
                                "MAT"][isotope]
                        else:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            var_srm_file = self.container_var["STD"][file_long]["SRM"].get()
                            if var_srm_i == var_srm_file:
                                value_i = self.container_normalized_sensitivity[var_filetype][var_datatype][file_short][
                                    "MAT"][isotope]
                            else:
                                value_i = None
                        if value_i != None:
                            report_normalized_sensitivity[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_decimals_sensitivity)
                        else:
                            report_normalized_sensitivity[var_filetype][var_datatype][file_short][isotope] = "---"

                        # Relative Sensitivity Factor
                        value_i = self.container_rsf[var_filetype][var_datatype][file_short]["MAT"][isotope]
                        try:
                            report_rsf[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_decimals_sensitivity)
                        except:
                            report_rsf[var_filetype][var_datatype][file_short][isotope] = "---"

        for isotope in self.container_lists["ISOTOPES"]:
            header.append(isotope)
        #
        var_file_extension_pre = self.container_var["General Settings"]["File type"].get()
        if var_file_extension_pre == "*.csv":
            var_file_extension = ".csv"
        elif var_file_extension_pre == "*.txt":
            var_file_extension = ".txt"

        var_delimiter_pre = self.container_var["General Settings"]["Delimiter"].get()
        if var_delimiter_pre == "comma":
            var_delimiter = ","
        elif var_delimiter_pre == "semicolon":
            var_delimiter = ";"

        if self.rb_report.get() == 0:  # All in one
            self.ma_export_report_0(
                report_concentration, report_concentration_sigma, report_concentration_ratio, report_lod,
                report_intensity, report_intensity_sigma, report_intensity_ratio, report_analytical_sensitivity,
                report_normalized_sensitivity, report_rsf, var_file_extension, var_delimiter, header)
        elif self.rb_report.get() == 1:  # STD vs. SMPL
            self.ma_export_report_1(
                report_concentration, report_concentration_sigma, report_concentration_ratio, report_lod,
                report_intensity, report_intensity_sigma, report_intensity_ratio, report_analytical_sensitivity,
                report_normalized_sensitivity, report_rsf, var_file_extension, var_delimiter, header)
        elif self.rb_report.get() == 2:  # RAW vs. SMOOTHED
            self.ma_export_report_2(
                report_concentration, report_concentration_sigma, report_concentration_ratio, report_lod,
                report_intensity, report_intensity_sigma, report_intensity_ratio, report_analytical_sensitivity,
                report_normalized_sensitivity, report_rsf, var_file_extension, var_delimiter, header)

    def ma_export_report_0(
            self, report_concentration, report_concentration_sigma, report_concentration_ratio, report_lod,
            report_intensity, report_intensity_sigma, report_intensity_ratio, report_analytical_sensitivity,
            report_normalized_sensitivity, report_rsf, var_file_extension, var_delimiter, header):
        export_file = filedialog.asksaveasfile(mode="w", defaultextension=var_file_extension)
        filename = export_file.name
        #
        with open(filename, "w", newline="") as report_file:
            writer = csv.DictWriter(report_file, fieldnames=header, delimiter=var_delimiter)
            report_file.write("CALCULATION REPORT\n")
            report_file.write("\n")
            report_file.write("AUTHOR:;" + str(self.container_var["ma_setting"]["Author"].get()) + "\n")
            report_file.write("SOURCE ID:;" + str(self.container_var["ma_setting"]["Source ID"].get()) + "\n")
            report_file.write("\n")
            for var_datatype in ["SMOOTHED", "RAW"]:
                report_file.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file.write("\n")
                for var_filetype in ["SMPL", "STD"]:
                    if var_filetype == "SMPL":
                        report_file.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file.write("COMPOSITIONAL ANALYSIS\n")

                    report_file.write("Concentration\n")  # Concentration
                    report_file.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration[var_filetype][var_datatype][file_short])
                    report_file.write("\n")

                    report_file.write("1-Sigma-Concentration\n")  # 1-Sigma-Concentration
                    report_file.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration_sigma[var_filetype][var_datatype][file_short])
                    report_file.write("\n")

                    if var_filetype == "SMPL":
                        report_file.write("Concentration Ratio\n")  # Concentration Ratio
                        report_file.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_concentration_ratio[var_filetype][var_datatype][file_short])
                        report_file.write("\n")

                        report_file.write("Limit of Detection\n")  # Limit of Detection
                        report_file.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lod[var_filetype][var_datatype][file_short])
                        report_file.write("\n")

                    report_file.write("INTENSITY ANALYSIS\n")

                    report_file.write("Intensity (Sample)\n")  # Intensity
                    report_file.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity[var_filetype][var_datatype][file_short])
                    report_file.write("\n")

                    report_file.write("1-Sigma-Intensity (Sample)\n")  # 1-Sigma-Intensity
                    report_file.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity_sigma[var_filetype][var_datatype][file_short])
                    report_file.write("\n")

                    if var_filetype == "SMPL":
                        report_file.write("Intensity Ratio (Sample)\n")  # Intensity Ratio
                        report_file.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_intensity_ratio[var_filetype][var_datatype][file_short])
                        report_file.write("\n")

                    report_file.write("SENSITIVITY ANALYSIS\n")

                    report_file.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file.write("(1)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])
                    report_file.write("\n")

                    report_file.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file.write("(cps)/(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])
                    report_file.write("\n")

                    if var_filetype == "SMPL":
                        report_file.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                        report_file.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])
                        report_file.write("\n")

    def ma_export_report_1(
            self, report_concentration, report_concentration_sigma, report_concentration_ratio, report_lod,
            report_intensity, report_intensity_sigma, report_intensity_ratio, report_analytical_sensitivity,
            report_normalized_sensitivity, report_rsf, var_file_extension, var_delimiter, header):
        export_file = filedialog.asksaveasfile(mode="w", defaultextension=var_file_extension)
        filename_base = export_file.name
        filename_base_parts = filename_base.split(".")
        filename_std = filename_base_parts[0] + "_std" + var_file_extension
        filename_smpl = filename_base_parts[0] + "_smpl" + var_file_extension

        # Standard Files
        with open(filename_std, "w", newline="") as report_file_std:
            writer = csv.DictWriter(report_file_std, fieldnames=header, delimiter=var_delimiter)
            report_file_std.write("CALCULATION REPORT\n")
            report_file_std.write("\n")
            report_file_std.write("AUTHOR:;" + str(self.container_var["ma_setting"]["Author"].get()) + "\n")
            report_file_std.write("SOURCE ID:;" + str(self.container_var["ma_setting"]["Source ID"].get()) + "\n")
            report_file_std.write("\n")
            for var_datatype in ["SMOOTHED", "RAW"]:
                report_file_std.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_std.write("\n")
                for var_filetype in ["STD"]:
                    if var_filetype == "SMPL":
                        report_file_std.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file_std.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_std.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_std.write("COMPOSITIONAL ANALYSIS\n")

                    report_file_std.write("Concentration\n")  # Concentration
                    report_file_std.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration[var_filetype][var_datatype][file_short])
                    report_file_std.write("\n")

                    report_file_std.write("1-Sigma-Concentration\n")  # 1-Sigma-Concentration
                    report_file_std.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration_sigma[var_filetype][var_datatype][file_short])
                    report_file_std.write("\n")

                    if var_filetype == "SMPL":
                        report_file_std.write("Concentration Ratio\n")  # Concentration Ratio
                        report_file_std.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_concentration_ratio[var_filetype][var_datatype][file_short])
                        report_file_std.write("\n")

                        report_file_std.write("Limit of Detection\n")  # Limit of Detection
                        report_file_std.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lod[var_filetype][var_datatype][file_short])
                        report_file_std.write("\n")

                    report_file_std.write("INTENSITY ANALYSIS\n")

                    report_file_std.write("Intensity (Sample)\n")  # Intensity
                    report_file_std.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity[var_filetype][var_datatype][file_short])
                    report_file_std.write("\n")

                    report_file_std.write("1-Sigma-Intensity (Sample)\n")  # 1-Sigma-Intensity
                    report_file_std.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity_sigma[var_filetype][var_datatype][file_short])
                    report_file_std.write("\n")

                    if var_filetype == "SMPL":
                        report_file_std.write("Intensity Ratio (Sample)\n")  # Intensity Ratio
                        report_file_std.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_intensity_ratio[var_filetype][var_datatype][file_short])
                        report_file_std.write("\n")

                    report_file_std.write("SENSITIVITY ANALYSIS\n")

                    report_file_std.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_std.write("(1)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_std.write("\n")

                    report_file_std.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_std.write("(cps)/(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_std.write("\n")

                    if var_filetype == "SMPL":
                        report_file_std.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                        report_file_std.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])
                        report_file_std.write("\n")
        # Sample Files
        with open(filename_smpl, "w", newline="") as report_file_smpl:
            writer = csv.DictWriter(report_file_smpl, fieldnames=header, delimiter=var_delimiter)
            report_file_smpl.write("CALCULATION REPORT\n")
            report_file_smpl.write("\n")
            report_file_smpl.write("AUTHOR:;" + str(self.container_var["ma_setting"]["Author"].get()) + "\n")
            report_file_smpl.write("SOURCE ID:;" + str(self.container_var["ma_setting"]["Source ID"].get()) + "\n")
            report_file_smpl.write("\n")
            for var_datatype in ["SMOOTHED", "RAW"]:
                report_file_smpl.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_smpl.write("\n")
                for var_filetype in ["SMPL"]:
                    if var_filetype == "SMPL":
                        report_file_smpl.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file_smpl.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_smpl.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_smpl.write("COMPOSITIONAL ANALYSIS\n")

                    report_file_smpl.write("Concentration\n")  # Concentration
                    report_file_smpl.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration[var_filetype][var_datatype][file_short])
                    report_file_smpl.write("\n")

                    report_file_smpl.write("1-SigmaConcentration\n")  # 1-Sigma-Concentration
                    report_file_smpl.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity_sigma[var_filetype][var_datatype][file_short])
                    report_file_smpl.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smpl.write("Concentration Ratio\n")  # Concentration Ratio
                        report_file_smpl.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_concentration_ratio[var_filetype][var_datatype][file_short])
                        report_file_smpl.write("\n")

                        report_file_smpl.write("Limit of Detection\n")  # Limit of Detection
                        report_file_smpl.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lod[var_filetype][var_datatype][file_short])
                        report_file_smpl.write("\n")

                    report_file_smpl.write("INTENSITY ANALYSIS\n")

                    report_file_smpl.write("Intensity (Sample)\n")  # Intensity
                    report_file_smpl.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity[var_filetype][var_datatype][file_short])
                    report_file_smpl.write("\n")

                    report_file_smpl.write("1-Sigma-Intensity (Sample)\n")  # 1-Sigma-Intensity
                    report_file_smpl.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity_sigma[var_filetype][var_datatype][file_short])
                    report_file_smpl.write("\n")

                    report_file_smpl.write("1-Sigma-Intensity (Sample)\n")  # 1-Sigma-Intensity
                    report_file_smpl.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity[var_filetype][var_datatype][file_short])
                    report_file_smpl.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smpl.write("Intensity Ratio (Sample)\n")  # Intensity Ratio
                        report_file_smpl.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_intensity_ratio[var_filetype][var_datatype][file_short])
                        report_file_smpl.write("\n")

                    report_file_smpl.write("SENSITIVITY ANALYSIS\n")

                    report_file_smpl.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_smpl.write("(1)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_smpl.write("\n")

                    report_file_smpl.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_smpl.write("(cps)/(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_smpl.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smpl.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                        report_file_smpl.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])
                        report_file_smpl.write("\n")

        if os.path.exists(filename_base):
            os.remove(filename_base)
        else:
            print("The file does not exist!")

    def ma_export_report_2(
            self, report_concentration, report_concentration_sigma, report_concentration_ratio, report_lod,
            report_intensity, report_intensity_sigma, report_intensity_ratio, report_analytical_sensitivity,
            report_normalized_sensitivity, report_rsf, var_file_extension, var_delimiter, header):
        export_file = filedialog.asksaveasfile(mode="w", defaultextension=var_file_extension)
        filename_base = export_file.name
        filename_base_parts = filename_base.split(".")
        filename_raw = filename_base_parts[0] + "_raw" + var_file_extension
        filename_smoothed = filename_base_parts[0] + "_smoothed" + var_file_extension

        # RAW Data
        with open(filename_raw, "w", newline="") as report_file_raw:
            writer = csv.DictWriter(report_file_raw, fieldnames=header, delimiter=var_delimiter)
            report_file_raw.write("CALCULATION REPORT\n")
            report_file_raw.write("\n")
            report_file_raw.write("AUTHOR:;" + str(self.container_var["ma_setting"]["Author"].get()) + "\n")
            report_file_raw.write("SOURCE ID:;" + str(self.container_var["ma_setting"]["Source ID"].get()) + "\n")
            report_file_raw.write("\n")
            for var_datatype in ["RAW"]:
                report_file_raw.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_raw.write("\n")
                for var_filetype in ["SMPL", "STD"]:
                    if var_filetype == "SMPL":
                        report_file_raw.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file_raw.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_raw.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_raw.write("COMPOSITIONAL ANALYSIS\n")

                    report_file_raw.write("Concentration\n")  # Concentration
                    report_file_raw.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration[var_filetype][var_datatype][file_short])
                    report_file_raw.write("\n")

                    report_file_raw.write("1-Sigma-Concentration\n")  # 1-Sigma-Concentration
                    report_file_raw.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration_sigma[var_filetype][var_datatype][file_short])
                    report_file_raw.write("\n")

                    if var_filetype == "SMPL":
                        report_file_raw.write("Concentration Ratio\n")  # Concentration Ratio
                        report_file_raw.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_concentration_ratio[var_filetype][var_datatype][file_short])
                        report_file_raw.write("\n")

                        report_file_raw.write("Limit of Detection\n")  # Limit of Detection
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lod[var_filetype][var_datatype][file_short])
                        report_file_raw.write("\n")

                    report_file_raw.write("INTENSITY ANALYSIS\n")

                    report_file_raw.write("Intensity (Sample)\n")  # Intensity
                    report_file_raw.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity[var_filetype][var_datatype][file_short])
                    report_file_raw.write("\n")

                    report_file_raw.write("1-Sigma-Intensity (Sample)\n")  # 1-Sigma-Intensity
                    report_file_raw.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity_sigma[var_filetype][var_datatype][file_short])
                    report_file_raw.write("\n")

                    if var_filetype == "SMPL":
                        report_file_raw.write("Intensity Ratio (Sample)\n")  # Intensity Ratio
                        report_file_raw.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_intensity_ratio[var_filetype][var_datatype][file_short])
                        report_file_raw.write("\n")

                    report_file_raw.write("SENSITIVITY ANALYSIS\n")

                    report_file_raw.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_raw.write("(1)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_raw.write("\n")

                    report_file_raw.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_raw.write("(cps)/(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_raw.write("\n")

                    if var_filetype == "SMPL":
                        report_file_raw.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                        report_file_raw.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])
                        report_file_raw.write("\n")
        # SMOOTHED Data
        with open(filename_smoothed, "w", newline="") as report_file_smoothed:
            writer = csv.DictWriter(report_file_smoothed, fieldnames=header, delimiter=var_delimiter)
            report_file_smoothed.write("CALCULATION REPORT\n")
            report_file_smoothed.write("\n")
            report_file_smoothed.write("AUTHOR:;" + str(self.container_var["ma_setting"]["Author"].get()) + "\n")
            report_file_smoothed.write("SOURCE ID:;" + str(self.container_var["ma_setting"]["Source ID"].get()) + "\n")
            report_file_smoothed.write("\n")
            for var_datatype in ["SMOOTHED"]:
                report_file_smoothed.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_smoothed.write("\n")
                for var_filetype in ["SMPL", "STD"]:
                    if var_filetype == "SMPL":
                        report_file_smoothed.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file_smoothed.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_smoothed.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_smoothed.write("COMPOSITIONAL ANALYSIS\n")

                    report_file_smoothed.write("Concentration\n")  # Concentration
                    report_file_smoothed.write("(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_concentration[var_filetype][var_datatype][file_short])
                    report_file_smoothed.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Concentration Ratio\n")  # Concentration Ratio
                        report_file_smoothed.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_concentration_ratio[var_filetype][var_datatype][file_short])
                        report_file_smoothed.write("\n")

                        report_file_smoothed.write("Limit of Detection\n")  # Limit of Detection
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lod[var_filetype][var_datatype][file_short])
                        report_file_smoothed.write("\n")

                    report_file_smoothed.write("INTENSITY ANALYSIS\n")

                    report_file_smoothed.write("Intensity (Sample)\n")  # Intensity
                    report_file_smoothed.write("(cps)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_intensity[var_filetype][var_datatype][file_short])
                    report_file_smoothed.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Intensity Ratio (Sample)\n")  # Intensity Ratio
                        report_file_smoothed.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_intensity_ratio[var_filetype][var_datatype][file_short])
                        report_file_smoothed.write("\n")

                    report_file_smoothed.write("SENSITIVITY ANALYSIS\n")

                    report_file_smoothed.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_smoothed.write("(1)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_smoothed.write("\n")

                    report_file_smoothed.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_smoothed.write("(cps)/(ppm)\n")
                    writer.writeheader()
                    for file_short in self.container_lists[var_filetype]["Short"]:
                        writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])
                    report_file_smoothed.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                        report_file_smoothed.write("(1)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])
                        report_file_smoothed.write("\n")

        if os.path.exists(filename_base):
            os.remove(filename_base)
        else:
            print("The file does not exist!")

    def fi_export_calculation_report(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        header = ["filename", "ID"]

        # Concentration Inclusion
        report_concentration_incl = {}
        report_concentration_incl_1_sigma = {}
        report_concentration_incl["Total STD"] = {}
        report_concentration_incl["Total SMPL"] = {}
        # Concentration Matrix
        report_concentration_mat = {}
        report_concentration_mat_1_sigma = {}
        report_concentration_mat["Total STD"] = {}
        report_concentration_mat["Total SMPL"] = {}
        # Mixed Concentration
        report_concentration_mix = {}
        report_concentration_mix_1_sigma = {}
        report_concentration_mix["Total STD"] = {}
        report_concentration_mix["Total SMPL"] = {}
        # Limit of Detection
        report_lod_incl = {}
        report_lod_incl["Total STD"] = {}
        report_lod_incl["Total SMPL"] = {}
        report_lod_mat = {}
        report_lod_mat["Total STD"] = {}
        report_lod_mat["Total SMPL"] = {}
        # Mixing ratio
        report_mixingratio_a = {}
        report_mixingratio_a["Total STD"] = {}
        report_mixingratio_a["Total SMPL"] = {}
        report_mixingratio_x = {}
        report_mixingratio_x["Total STD"] = {}
        report_mixingratio_x["Total SMPL"] = {}
        # Intensity Inclusion
        report_intensity_incl = {}
        report_intensity_incl["Total STD"] = {}
        report_intensity_incl["Total SMPL"] = {}
        # Intensity Matrix
        report_intensity_mat = {}
        report_intensity_mat["Total STD"] = {}
        report_intensity_mat["Total SMPL"] = {}
        # Intensity Background
        report_intensity_bg = {}
        report_intensity_bg["Total STD"] = {}
        report_intensity_bg["Total SMPL"] = {}
        # Intensity Mix
        report_intensity_mix = {}
        report_intensity_mix["Total STD"] = {}
        report_intensity_mix["Total SMPL"] = {}
        # Analytical Sensitivity
        report_analytical_sensitivity = {}
        report_analytical_sensitivity["Total STD"] = {}
        report_analytical_sensitivity["Total SMPL"] = {}
        # Normalized Sensitivity
        report_normalized_sensitivity = {}
        report_normalized_sensitivity["Total STD"] = {}
        report_normalized_sensitivity["Total SMPL"] = {}
        # Relative Sensitivity Factor
        report_rsf = {}
        report_rsf["Total STD"] = {}
        report_rsf["Total SMPL"] = {}

        for var_filetype in ["STD", "SMPL"]:
            var_key = "Total " + str(var_filetype)

            report_concentration_incl[var_filetype] = {}
            report_concentration_incl[var_key] = {}
            report_concentration_incl_1_sigma[var_filetype] = {}
            report_concentration_incl_1_sigma[var_key] = {}
            report_concentration_incl[var_key]["filename"] = "All Files"

            report_concentration_mat[var_filetype] = {}
            report_concentration_mat[var_key] = {}
            report_concentration_mat_1_sigma[var_filetype] = {}
            report_concentration_mat_1_sigma[var_key] = {}
            report_concentration_mat[var_key]["filename"] = "All Files"

            report_concentration_mix[var_filetype] = {}
            report_concentration_mix[var_key] = {}
            report_concentration_mix_1_sigma[var_filetype] = {}
            report_concentration_mix_1_sigma[var_key] = {}
            report_concentration_mix[var_key]["filename"] = "All Files"

            report_lod_incl[var_filetype] = {}
            report_lod_incl[var_key] = {}
            report_lod_incl[var_key]["filename"] = "All Files"

            report_lod_mat[var_filetype] = {}
            report_lod_mat[var_key] = {}
            report_lod_mat[var_key]["filename"] = "All Files"

            report_mixingratio_a[var_filetype] = {}
            report_mixingratio_a[var_key] = {}
            report_mixingratio_a[var_key]["filename"] = "All Files"

            report_mixingratio_x[var_filetype] = {}
            report_mixingratio_x[var_key] = {}
            report_mixingratio_x[var_key]["filename"] = "All Files"

            report_intensity_incl[var_filetype] = {}
            report_intensity_incl[var_key] = {}
            report_intensity_incl[var_key]["filename"] = "All Files"

            report_intensity_mat[var_filetype] = {}
            report_intensity_mat[var_key] = {}
            report_intensity_mat[var_key]["filename"] = "All Files"

            report_intensity_bg[var_filetype] = {}
            report_intensity_bg[var_key] = {}
            report_intensity_bg[var_key]["filename"] = "All Files"

            report_intensity_mix[var_filetype] = {}
            report_intensity_mix[var_key] = {}
            report_intensity_mix[var_key]["filename"] = "All Files"

            report_analytical_sensitivity[var_filetype] = {}
            report_analytical_sensitivity[var_key] = {}
            report_analytical_sensitivity[var_key]["filename"] = "All Files"

            report_normalized_sensitivity[var_filetype] = {}
            report_normalized_sensitivity[var_key] = {}
            report_normalized_sensitivity[var_key]["filename"] = "All Files"

            report_rsf[var_filetype] = {}
            report_rsf[var_key] = {}
            report_rsf[var_key]["filename"] = "All Files"

            for var_datatype in ["SMOOTHED", "RAW"]:
                report_concentration_incl[var_filetype][var_datatype] = {}
                report_concentration_incl_1_sigma[var_filetype][var_datatype] = {}
                report_concentration_mat[var_filetype][var_datatype] = {}
                report_concentration_mat_1_sigma[var_filetype][var_datatype] = {}
                report_concentration_mix[var_filetype][var_datatype] = {}
                report_concentration_mix_1_sigma[var_filetype][var_datatype] = {}
                report_lod_incl[var_filetype][var_datatype] = {}
                report_lod_mat[var_filetype][var_datatype] = {}
                report_mixingratio_a[var_filetype][var_datatype] = {}
                report_mixingratio_x[var_filetype][var_datatype] = {}

                report_intensity_incl[var_filetype][var_datatype] = {}
                report_intensity_mat[var_filetype][var_datatype] = {}
                report_intensity_bg[var_filetype][var_datatype] = {}
                report_intensity_mix[var_filetype][var_datatype] = {}

                report_analytical_sensitivity[var_filetype][var_datatype] = {}
                report_normalized_sensitivity[var_filetype][var_datatype] = {}
                report_rsf[var_filetype][var_datatype] = {}

                for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                    file_long = self.container_lists[var_filetype]["Long"][index]
                    file_isotopes = self.container_lists["Measured Isotopes"][file_short]

                    if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                        report_concentration_incl[var_filetype][var_datatype][file_short] = {}
                        report_concentration_incl[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_concentration_incl_1_sigma[var_filetype][var_datatype][file_short] = {}
                        report_concentration_incl_1_sigma[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_concentration_mat[var_filetype][var_datatype][file_short] = {}
                        report_concentration_mat[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short] = {}
                        report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_concentration_mix[var_filetype][var_datatype][file_short] = {}
                        report_concentration_mix[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_concentration_mix_1_sigma[var_filetype][var_datatype][file_short] = {}
                        report_concentration_mix_1_sigma[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_lod_incl[var_filetype][var_datatype][file_short] = {}
                        report_lod_incl[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_lod_mat[var_filetype][var_datatype][file_short] = {}
                        report_lod_mat[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_mixingratio_a[var_filetype][var_datatype][file_short] = {}
                        report_mixingratio_a[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_mixingratio_x[var_filetype][var_datatype][file_short] = {}
                        report_mixingratio_x[var_filetype][var_datatype][file_short]["filename"] = file_short

                        if var_filetype == "STD":
                            report_concentration_incl[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_concentration_incl_1_sigma[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_concentration_mat[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_concentration_mix[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_concentration_mix_1_sigma[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_lod_incl[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_lod_mat[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_mixingratio_a[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_mixingratio_x[var_filetype][var_datatype][file_short]["ID"] = "---"
                        else:
                            report_concentration_incl[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_concentration_incl_1_sigma[var_filetype][var_datatype][file_short][
                                "ID"] = self.container_var[var_filetype][file_long]["ID"].get()
                            report_concentration_mat[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short][
                                "ID"] = self.container_var[var_filetype][file_long]["ID"].get()
                            report_concentration_mix[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_concentration_mix_1_sigma[var_filetype][var_datatype][file_short][
                                "ID"] = self.container_var[var_filetype][file_long]["ID"].get()
                            report_lod_incl[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_lod_mat[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_mixingratio_a[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_mixingratio_x[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()

                        report_intensity_incl[var_filetype][var_datatype][file_short] = {}
                        report_intensity_incl[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_intensity_mat[var_filetype][var_datatype][file_short] = {}
                        report_intensity_mat[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_intensity_bg[var_filetype][var_datatype][file_short] = {}
                        report_intensity_bg[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_intensity_mix[var_filetype][var_datatype][file_short] = {}
                        report_intensity_mix[var_filetype][var_datatype][file_short]["filename"] = file_short

                        if var_filetype == "STD":
                            report_intensity_incl[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_intensity_mat[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_intensity_bg[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_intensity_mix[var_filetype][var_datatype][file_short]["ID"] = "---"
                        else:
                            report_intensity_incl[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_intensity_mat[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_intensity_bg[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_intensity_mix[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()

                        report_analytical_sensitivity[var_filetype][var_datatype][file_short] = {}
                        report_analytical_sensitivity[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_normalized_sensitivity[var_filetype][var_datatype][file_short] = {}
                        report_normalized_sensitivity[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_rsf[var_filetype][var_datatype][file_short] = {}
                        report_rsf[var_filetype][var_datatype][file_short]["filename"] = file_short

                        if var_filetype == "STD":
                            report_analytical_sensitivity[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_normalized_sensitivity[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_rsf[var_filetype][var_datatype][file_short]["ID"] = "---"
                        else:
                            report_analytical_sensitivity[var_filetype][var_datatype][file_short][
                                "ID"] = self.container_var[var_filetype][file_long]["ID"].get()
                            report_normalized_sensitivity[var_filetype][var_datatype][file_short][
                                "ID"] = self.container_var[var_filetype][file_long]["ID"].get()
                            report_rsf[var_filetype][var_datatype][file_short]["ID"] = self.container_var[var_filetype][
                                file_long]["ID"].get()

                        for isotope in file_isotopes:
                            ## COMPOSITIONAL ANALYSIS
                            # Concentration Inclusion
                            if var_filetype == "SMPL":
                                value_i = self.container_concentration[var_filetype][var_datatype][file_short]["INCL"][
                                    isotope]
                                lod_i = self.container_lod[var_filetype][var_datatype][file_short]["INCL"][isotope]
                                value_sigma_i = self.container_concentration[var_filetype][var_datatype][file_short][
                                    "1 SIGMA INCL"][isotope]
                            else:
                                value_i = 0.0
                                lod_i = 0.0
                                value_sigma_i = 0.0

                            n_digits = 5

                            if value_i >= lod_i:
                                value_i = value_i
                            else:
                                value_i *= -1

                            report_concentration_incl[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)
                            report_concentration_incl_1_sigma[var_filetype][var_datatype][file_short][isotope] = round(
                                value_sigma_i, n_digits)

                            # Concentration Matrix
                            if var_filetype == "STD":
                                var_srm_i = self.container_var["SRM"][isotope].get()
                                var_srm_file = self.container_var["STD"][file_long]["SRM"].get()
                            value_i = self.container_concentration[var_filetype][var_datatype][file_short]["MAT"][
                                isotope]
                            lod_i = self.container_lod[var_filetype][var_datatype][file_short]["MAT"][isotope]
                            n_digits = 5

                            if value_i >= lod_i:
                                value_i = value_i
                            else:
                                value_i *= -1

                            if var_filetype == "SMPL":
                                value_sigma_i = self.container_concentration[var_filetype][var_datatype][file_short][
                                    "1 SIGMA MAT"][isotope]
                                report_concentration_mat[var_filetype][var_datatype][file_short][isotope] = round(
                                    value_i, n_digits)
                                report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short][isotope] = round(
                                    value_sigma_i, n_digits)

                            else:
                                if var_srm_i == var_srm_file:
                                    report_concentration_mat[var_filetype][var_datatype][file_short][isotope] = round(
                                        value_i, n_digits)
                                else:
                                    report_concentration_mat[var_filetype][var_datatype][file_short][isotope] = "undefined"

                            # Concentration Mixed
                            if var_filetype == "SMPL":
                                value_i = self.container_mixed_concentration[var_filetype][var_datatype][file_short][
                                    isotope]
                            else:
                                value_i = 0.0

                            n_digits = 5
                            report_concentration_mix[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            # Limit of Detection (Inclusion)
                            if var_filetype == "SMPL":
                                value_i = self.container_lod[var_filetype][var_datatype][file_short]["INCL"][isotope]
                            else:
                                value_i = 0.0

                            n_digits = 5
                            report_lod_incl[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            # Limit of Detection (Matrix)
                            value_i = self.container_lod[var_filetype][var_datatype][file_short]["MAT"][isotope]
                            n_digits = 5
                            report_lod_mat[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            # Mixing Ratio (Factor a)
                            if var_filetype == "SMPL":
                                value_i = self.container_mixed_concentration_ratio[var_filetype][var_datatype][file_short][
                                    isotope]
                            else:
                                value_i = 0.0

                            report_mixingratio_a[var_filetype][var_datatype][file_short][isotope] = "{:0.5e}".format(
                                value_i)

                            # Mixing Ratio (Factor x)
                            if var_filetype == "SMPL":
                                value_i = self.container_mixing_ratio[var_filetype][var_datatype][file_short][isotope]
                            else:
                                value_i = 0.0

                            report_mixingratio_x[var_filetype][var_datatype][file_short][isotope] = "{:0.5e}".format(
                                value_i)

                            ## INTENSITY ANALYSIS
                            # Intensity Inclusion
                            if var_filetype == "SMPL":
                                value_i = self.container_intensity_corrected[var_filetype][var_datatype][file_short][
                                    "INCL"][isotope]
                            else:
                                value_i = 0.0

                            n_digits = 5
                            report_intensity_incl[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            # Intensity Matrix
                            value_i = self.container_intensity_corrected[var_filetype][var_datatype][file_short]["MAT"][
                                isotope]
                            n_digits = 5
                            report_intensity_mat[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            # Intensity Background
                            value_i = self.container_intensity_corrected[var_filetype][var_datatype][file_short]["BG"][
                                isotope]
                            n_digits = 5
                            report_intensity_bg[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            # Intensity Mixed
                            if var_filetype == "SMPL":
                                value_i = self.container_intensity_mix[var_filetype][var_datatype][file_short][isotope]
                            else:
                                value_i = 0.0

                            n_digits = 5
                            report_intensity_mix[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            ## SENSITIVITY ANALYSIS
                            # Analytical Sensitivity
                            value_i = self.container_analytical_sensitivity[var_filetype][var_datatype][file_short]["MAT"][
                                isotope]

                            if var_filetype == "STD" and index == 0:
                                helper_std = {}
                                helper_std[isotope] = []
                                var_srm_i = self.container_var["SRM"][isotope].get()
                                for index, filename_short in enumerate(self.container_lists["STD"]["Short"]):
                                    filename_long = self.container_lists["STD"]["Long"][index]
                                    var_srm_file = self.container_var["STD"][filename_long]["SRM"].get()
                                    if var_srm_file == var_srm_i:
                                        value_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                            filename_short]["MAT"][isotope]
                                        helper_std[isotope].append(value_i)

                            n_digits = 5

                            if value_i != None:
                                report_analytical_sensitivity[var_filetype][var_datatype][file_short][isotope] = round(
                                    value_i, n_digits)
                            else:
                                report_analytical_sensitivity[var_filetype][var_datatype][file_short][isotope] = "undefined"

                            # Normalized Sensitivity
                            value_i = self.container_normalized_sensitivity[var_filetype][var_datatype][file_short]["MAT"][
                                isotope]
                            n_digits = 5
                            report_normalized_sensitivity[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_digits)

                            # Relative Sensitivity Factor
                            value_i = self.container_rsf[var_filetype][var_datatype][file_short]["MAT"][isotope]
                            report_rsf[var_filetype][var_datatype][file_short][isotope] = "{:0.5e}".format(value_i)

        for isotope in self.container_lists["ISOTOPES"]:
            header.append(isotope)

        var_file_extension_pre = self.container_var["General Settings"]["File type"].get()
        if var_file_extension_pre == "*.csv":
            var_file_extension = ".csv"
        elif var_file_extension_pre == "*.txt":
            var_file_extension = ".txt"

        var_delimiter_pre = self.container_var["General Settings"]["Delimiter"].get()
        if var_delimiter_pre == "comma":
            var_delimiter = ","
        elif var_delimiter_pre == "semicolon":
            var_delimiter = ";"

        if self.rb_report.get() == 0:  # All in one
            self.fi_export_report_0(
                report_concentration_incl, report_concentration_incl_1_sigma, report_concentration_mat,
                report_concentration_mat_1_sigma, report_concentration_mix, report_mixingratio_a,
                report_mixingratio_x, report_lod_incl, report_lod_mat, report_intensity_incl, report_intensity_mat,
                report_intensity_bg, report_intensity_mix, report_analytical_sensitivity, report_normalized_sensitivity,
                report_rsf, var_file_extension, var_delimiter, header)
        elif self.rb_report.get() == 1:  # STD vs. SMPL
            self.fi_export_report_1(
                report_concentration_incl, report_concentration_incl_1_sigma, report_concentration_mat,
                report_concentration_mat_1_sigma, report_concentration_mix, report_mixingratio_a,
                report_mixingratio_x, report_lod_incl, report_lod_mat, report_intensity_incl, report_intensity_mat,
                report_intensity_bg, report_intensity_mix, report_analytical_sensitivity, report_normalized_sensitivity,
                report_rsf, var_file_extension, var_delimiter, header)
        elif self.rb_report.get() == 2:  # RAW vs. SMOOTHED
            self.fi_export_report_2(
                report_concentration_incl, report_concentration_incl_1_sigma, report_concentration_mat,
                report_concentration_mat_1_sigma, report_concentration_mix, report_mixingratio_a,
                report_mixingratio_x, report_lod_incl, report_lod_mat, report_intensity_incl, report_intensity_mat,
                report_intensity_bg, report_intensity_mix, report_analytical_sensitivity, report_normalized_sensitivity,
                report_rsf, var_file_extension, var_delimiter, header)

    def fi_export_report_0(
            self, report_concentration_incl, report_concentration_incl_1_sigma, report_concentration_mat,
            report_concentration_mat_1_sigma, report_concentration_mix, report_mixingratio_a,
            report_mixingratio_x, report_lod_incl, report_lod_mat, report_intensity_incl, report_intensity_mat,
            report_intensity_bg, report_intensity_mix, report_analytical_sensitivity, report_normalized_sensitivity,
            report_rsf, var_file_extension, var_delimiter, header):
        export_file = filedialog.asksaveasfile(mode="w", defaultextension=var_file_extension)
        filename = export_file.name

        with open(filename, "w", newline="") as report_file:
            writer = csv.DictWriter(report_file, fieldnames=header, delimiter=var_delimiter)
            report_file.write("CALCULATION REPORT\n")
            report_file.write("\n")
            report_file.write("AUTHOR:;" + str(self.container_var["ma_setting"]["Author"].get()) + "\n")
            report_file.write("SOURCE ID:;" + str(self.container_var["ma_setting"]["Source ID"].get()) + "\n")
            report_file.write("\n")

            for var_datatype in ["SMOOTHED", "RAW"]:
                report_file.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file.write("\n")

                for var_filetype in ["SMPL", "STD"]:
                    if var_filetype == "SMPL":
                        report_file.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file.write("STANDARD FILES\n")

                    var_key = "Total " + str(var_filetype)
                    report_file.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file.write("COMPOSITIONAL ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file.write("Composition (Inclusion)\n")  # Concentration Inclusion
                        report_file.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl[var_filetype][var_datatype][file_short])

                        report_file.write("\n")

                        report_file.write("1-Sigma Composition (Inclusion)\n")  # Concentration Inclusion (1-Sigma)
                        report_file.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl_1_sigma[var_filetype][var_datatype][
                                                    file_short])

                        report_file.write("\n")

                        report_file.write("Limit of Detection (Inclusion)\n")  # Limit of Detection (Inclusion)
                        report_file.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_lod_incl[var_filetype][var_datatype][file_short])

                        report_file.write("\n")

                    report_file.write("Composition (Matrix)\n")  # Concentration Matrix
                    report_file.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_concentration_mat[var_filetype][var_datatype][file_short])

                    report_file.write("\n")

                    if var_filetype == "SMPL":
                        report_file.write("1-Sigma Composition (Matrix)\n")  # Concentration Matrix (1-Sigma)
                        report_file.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_mat_1_sigma[var_filetype][var_datatype][
                                                    file_short])

                    report_file.write("\n")

                    report_file.write("Limit of Detection (Matrix)\n")  # Limit of Detection (Matrix)
                    report_file.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_lod_mat[var_filetype][var_datatype][file_short])

                    report_file.write("\n")

                    if var_filetype == "SMPL":
                        report_file.write("Composition (Mixed)\n")  # Concentration Mixed
                        report_file.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_mix[var_filetype][var_datatype][file_short])

                        report_file.write("\n")

                    if var_filetype == "SMPL":
                        report_file.write("Mixing Ratio a\n")  # Mixing Ratio a
                        report_file.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_a[var_filetype][var_datatype][file_short])

                        report_file.write("\n")

                        report_file.write("Mixing Ratio x\n")  # Mixing Ratio x
                        report_file.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_x[var_filetype][var_datatype][file_short])

                        report_file.write("\n")

                    report_file.write("INTENSITY ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file.write("Intensity (Inclusion)\n")  # Intensity Inclusion
                        report_file.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_incl[var_filetype][var_datatype][file_short])

                        report_file.write("\n")

                    report_file.write("Intensity (Matrix)\n")  # Intensity Matrix
                    report_file.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_mat[var_filetype][var_datatype][file_short])

                    report_file.write("\n")

                    report_file.write("Intensity (Background)\n")  # Intensity Background
                    report_file.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_bg[var_filetype][var_datatype][file_short])

                    report_file.write("\n")

                    if var_filetype == "SMPL":
                        report_file.write("Intensity (Mixed)\n")  # Intensity Mixed
                        report_file.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_mix[var_filetype][var_datatype][file_short])

                        report_file.write("\n")

                    report_file.write("SENSITIVITY ANALYSIS\n")
                    report_file.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])

                    report_file.write("\n")

                    report_file.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file.write("(cps)/(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])

                    report_file.write("\n")

                    report_file.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                    report_file.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])

                    report_file.write("\n")

    def fi_export_report_1(
            self, report_concentration_incl, report_concentration_incl_1_sigma, report_concentration_mat,
            report_concentration_mat_1_sigma, report_concentration_mix, report_mixingratio_a,
            report_mixingratio_x, report_lod_incl, report_lod_mat, report_intensity_incl, report_intensity_mat,
            report_intensity_bg, report_intensity_mix, report_analytical_sensitivity, report_normalized_sensitivity,
            report_rsf, var_file_extension, var_delimiter, header):
        export_file = filedialog.asksaveasfile(mode="w", defaultextension=var_file_extension)
        filename_base = export_file.name
        filename_base_parts = filename_base.split(".")
        filename_std = filename_base_parts[0] + "_std" + var_file_extension
        filename_smpl = filename_base_parts[0] + "_smpl" + var_file_extension
        export_file.close()

        # Standard Files
        with open(filename_std, "w", newline="") as report_file_std:
            writer = csv.DictWriter(report_file_std, fieldnames=header, delimiter=var_delimiter)
            report_file_std.write("CALCULATION REPORT\n")
            report_file_std.write("\n")
            report_file_std.write("AUTHOR:;" + str(self.container_var["fi_setting"]["Author"].get()) + "\n")
            report_file_std.write("SOURCE ID:;" + str(self.container_var["fi_setting"]["Source ID"].get()) + "\n")
            report_file_std.write("\n")
            for var_datatype in ["SMOOTHED", "RAW"]:
                report_file_std.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_std.write("\n")
                for var_filetype in ["STD"]:
                    report_file_std.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_std.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_std.write("COMPOSITIONAL ANALYSIS\n")
                    report_file_std.write("Composition (Matrix)\n")  # Concentration Matrix
                    report_file_std.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_concentration_mat[var_filetype][var_datatype][file_short])

                    report_file_std.write("\n")

                    report_file_std.write("Limit of Detection (Matrix)\n")  # Limit of Detection (Matrix)
                    report_file_std.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_lod_mat[var_filetype][var_datatype][file_short])

                    report_file_std.write("\n")

                    report_file_std.write("INTENSITY ANALYSIS\n")
                    report_file_std.write("Intensity (Matrix)\n")  # Intensity Matrix
                    report_file_std.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_mat[var_filetype][var_datatype][file_short])

                    report_file_std.write("\n")

                    report_file_std.write("Intensity (Background)\n")  # Intensity Background
                    report_file_std.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_bg[var_filetype][var_datatype][file_short])

                    report_file_std.write("\n")

                    report_file_std.write("SENSITIVITY ANALYSIS\n")
                    report_file_std.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_std.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_std.write("\n")

                    report_file_std.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_std.write("(cps)/(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_std.write("\n")

                    report_file_std.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                    report_file_std.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])

                    report_file_std.write("\n")

        # Sample Files
        with open(filename_smpl, "w", newline="") as report_file_smpl:
            writer = csv.DictWriter(report_file_smpl, fieldnames=header, delimiter=var_delimiter)
            report_file_smpl.write("CALCULATION REPORT\n")
            report_file_smpl.write("\n")
            report_file_smpl.write("AUTHOR:;" + str(self.container_var["fi_setting"]["Author"].get()) + "\n")
            report_file_smpl.write("SOURCE ID:;" + str(self.container_var["fi_setting"]["Source ID"].get()) + "\n")
            report_file_smpl.write("\n")
            for var_datatype in ["SMOOTHED", "RAW"]:
                report_file_smpl.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_smpl.write("\n")
                for var_filetype in ["SMPL"]:
                    if var_filetype == "SMPL":
                        report_file_smpl.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file_smpl.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_smpl.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_smpl.write("COMPOSITIONAL ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file_smpl.write("Composition (Inclusion)\n")  # Concentration Inclusion
                        report_file_smpl.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl[var_filetype][var_datatype][file_short])

                        report_file_smpl.write("\n")

                        report_file_smpl.write("1-Sigma Composition (Inclusion)\n")  # Concentration Inclusion (1-Sigma)
                        report_file_smpl.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl_1_sigma[var_filetype][var_datatype][
                                                    file_short])

                        report_file_smpl.write("\n")

                        report_file_smpl.write("Limit of Detection (Inclusion)\n")  # Limit of Detection (Inclusion)
                        report_file_smpl.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_lod_incl[var_filetype][var_datatype][file_short])

                        report_file_smpl.write("\n")

                    report_file_smpl.write("Composition (Matrix)\n")  # Concentration Matrix
                    report_file_smpl.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_concentration_mat[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

                    report_file_smpl.write("1-Sigma Composition (Matrix)\n")  # Concentration Matrix (1-Sigma)
                    report_file_smpl.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

                    report_file_smpl.write("Limit of Detection (Matrix)\n")  # Limit of Detection (Matrix)
                    report_file_smpl.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_lod_mat[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smpl.write("Composition (Mixed)\n")  # Concentration Mixed
                        report_file_smpl.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_mix[var_filetype][var_datatype][file_short])

                        report_file_smpl.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smpl.write("Mixing Ratio a\n")  # Mixing Ratio a
                        report_file_smpl.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_a[var_filetype][var_datatype][file_short])

                        report_file_smpl.write("\n")

                        report_file_smpl.write("Mixing Ratio x\n")  # Mixing Ratio x
                        report_file_smpl.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_x[var_filetype][var_datatype][file_short])

                        report_file_smpl.write("\n")

                    report_file_smpl.write("INTENSITY ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file_smpl.write("Intensity (Inclusion)\n")  # Intensity Inclusion
                        report_file_smpl.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_incl[var_filetype][var_datatype][file_short])

                        report_file_smpl.write("\n")

                    report_file_smpl.write("Intensity (Matrix)\n")  # Intensity Matrix
                    report_file_smpl.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_mat[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

                    report_file_smpl.write("Intensity (Background)\n")  # Intensity Background
                    report_file_smpl.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_bg[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smpl.write("Intensity (Mixed)\n")  # Intensity Mixed
                        report_file_smpl.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_mix[var_filetype][var_datatype][file_short])

                        report_file_smpl.write("\n")

                    report_file_smpl.write("SENSITIVITY ANALYSIS\n")
                    report_file_smpl.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_smpl.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

                    report_file_smpl.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_smpl.write("(cps)/(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

                    report_file_smpl.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                    report_file_smpl.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])

                    report_file_smpl.write("\n")

        if os.path.exists(filename_base):
            os.remove(filename_base)
        else:
            print("The file does not exist!")

    def fi_export_report_2(
            self, report_concentration_incl, report_concentration_incl_1_sigma, report_concentration_mat,
            report_concentration_mat_1_sigma, report_concentration_mix, report_mixingratio_a,
            report_mixingratio_x, report_lod_incl, report_lod_mat, report_intensity_incl, report_intensity_mat,
            report_intensity_bg, report_intensity_mix, report_analytical_sensitivity, report_normalized_sensitivity,
            report_rsf, var_file_extension, var_delimiter, header):
        export_file = filedialog.asksaveasfile(mode="w", defaultextension=var_file_extension)
        filename_base = export_file.name
        filename_base_parts = filename_base.split(".")
        filename_raw = filename_base_parts[0] + "_raw" + var_file_extension
        filename_smoothed = filename_base_parts[0] + "_smoothed" + var_file_extension
        export_file.close()

        # RAW Data
        with open(filename_raw, "w", newline="") as report_file_raw:
            writer = csv.DictWriter(report_file_raw, fieldnames=header, delimiter=var_delimiter)
            report_file_raw.write("CALCULATION REPORT\n")
            report_file_raw.write("\n")
            report_file_raw.write("AUTHOR:;" + str(self.container_var["fi_setting"]["Author"].get()) + "\n")
            report_file_raw.write("SOURCE ID:;" + str(self.container_var["fi_setting"]["Source ID"].get()) + "\n")
            report_file_raw.write("\n")
            for var_datatype in ["RAW"]:
                report_file_raw.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_raw.write("\n")
                for var_filetype in ["SMPL", "STD"]:
                    if var_filetype == "SMPL":
                        report_file_raw.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file_raw.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_raw.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_raw.write("COMPOSITIONAL ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file_raw.write("Composition (Inclusion)\n")  # Concentration Inclusion
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                        report_file_raw.write("1-Sigma Composition (Inclusion)\n")  # Concentration Inclusion (1-Sigma)
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl_1_sigma[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                        report_file_raw.write("Limit of Detection (Inclusion)\n")  # Limit of Detection (Inclusion)
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_lod_incl[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                    report_file_raw.write("Composition (Matrix)\n")  # Concentration Matrix
                    report_file_raw.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_concentration_mat[var_filetype][var_datatype][file_short])

                    report_file_raw.write("\n")

                    if var_filetype == "SMPL":
                        report_file_raw.write("1-Sigma Composition (Matrix)\n")  # Concentration Matrix (1-Sigma)
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                    report_file_raw.write("Limit of Detection (Matrix)\n")  # Limit of Detection (Matrix)
                    report_file_raw.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_lod_mat[var_filetype][var_datatype][file_short])

                    report_file_raw.write("\n")

                    if var_filetype == "SMPL":
                        report_file_raw.write("Composition (Mixed)\n")  # Concentration Mixed
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_mix[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                    if var_filetype == "SMPL":
                        report_file_raw.write("Mixing Ratio a\n")  # Mixing Ratio a
                        report_file_raw.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_a[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                        report_file_raw.write("Mixing Ratio x\n")  # Mixing Ratio x
                        report_file_raw.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_x[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                    report_file_raw.write("INTENSITY ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file_raw.write("Intensity (Inclusion)\n")  # Intensity Inclusion
                        report_file_raw.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_incl[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                    report_file_raw.write("Intensity (Matrix)\n")  # Intensity Matrix
                    report_file_raw.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_mat[var_filetype][var_datatype][file_short])

                    report_file_raw.write("\n")

                    report_file_raw.write("Intensity (Background)\n")  # Intensity Background
                    report_file_raw.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_bg[var_filetype][var_datatype][file_short])

                    report_file_raw.write("\n")

                    if var_filetype == "SMPL":
                        report_file_raw.write("Intensity (Mixed)\n")  # Intensity Mixed
                        report_file_raw.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_mix[var_filetype][var_datatype][file_short])

                        report_file_raw.write("\n")

                    report_file_raw.write("SENSITIVITY ANALYSIS\n")
                    report_file_raw.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_raw.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_raw.write("\n")

                    report_file_raw.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_raw.write("(cps)/(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_raw.write("\n")

                    report_file_raw.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                    report_file_raw.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])

                    report_file_raw.write("\n")

        # SMOOTHED Data
        with open(filename_smoothed, "w", newline="") as report_file_smoothed:
            writer = csv.DictWriter(report_file_smoothed, fieldnames=header, delimiter=var_delimiter)
            report_file_smoothed.write("CALCULATION REPORT\n")
            report_file_smoothed.write("\n")
            report_file_smoothed.write("AUTHOR:;" + str(self.container_var["ma_setting"]["Author"].get()) + "\n")
            report_file_smoothed.write("SOURCE ID:;" + str(self.container_var["ma_setting"]["Source ID"].get()) + "\n")
            report_file_smoothed.write("\n")
            for var_datatype in ["SMOOTHED"]:
                report_file_smoothed.write("DATA TYPE:;" + str(var_datatype) + str(" DATA") + "\n")
                report_file_smoothed.write("\n")
                for var_filetype in ["SMPL", "STD"]:
                    if var_filetype == "SMPL":
                        report_file_smoothed.write("SAMPLE FILES\n")
                    elif var_filetype == "STD":
                        report_file_smoothed.write("STANDARD FILES\n")
                    var_key = "Total " + str(var_filetype)
                    report_file_smoothed.write("\n")

                    ## COMPOSITIONAL ANALYSIS
                    report_file_smoothed.write("COMPOSITIONAL ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Composition (Inclusion)\n")  # Concentration Inclusion
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                        report_file_smoothed.write("1-Sigma Composition (Inclusion)\n")  # Concentration Inclusion (1-Sigma)
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_incl_1_sigma[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                        report_file_smoothed.write("Limit of Detection (Inclusion)\n")  # Limit of Detection (Inclusion)
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_lod_incl[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                    report_file_smoothed.write("Composition (Matrix)\n")  # Concentration Matrix
                    report_file_smoothed.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_concentration_mat[var_filetype][var_datatype][file_short])

                    report_file_smoothed.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smoothed.write("1-Sigma Composition (Matrix)\n")  # Concentration Matrix (1-Sigma)
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_mat_1_sigma[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                    report_file_smoothed.write("Limit of Detection (Matrix)\n")  # Limit of Detection (Matrix)
                    report_file_smoothed.write("(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_lod_mat[var_filetype][var_datatype][file_short])

                    report_file_smoothed.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Composition (Mixed)\n")  # Concentration Mixed
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_concentration_mix[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Mixing Ratio a\n")  # Mixing Ratio a
                        report_file_smoothed.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_a[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                        report_file_smoothed.write("Mixing Ratio x\n")  # Mixing Ratio x
                        report_file_smoothed.write("(1)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_mixingratio_x[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                    report_file_smoothed.write("INTENSITY ANALYSIS\n")
                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Intensity (Inclusion)\n")  # Intensity Inclusion
                        report_file_smoothed.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_incl[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                    report_file_smoothed.write("Intensity (Matrix)\n")  # Intensity Matrix
                    report_file_smoothed.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_mat[var_filetype][var_datatype][file_short])

                    report_file_smoothed.write("\n")

                    report_file_smoothed.write("Intensity (Background)\n")  # Intensity Background
                    report_file_smoothed.write("(cps)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_intensity_bg[var_filetype][var_datatype][file_short])

                    report_file_smoothed.write("\n")

                    if var_filetype == "SMPL":
                        report_file_smoothed.write("Intensity (Mixed)\n")  # Intensity Mixed
                        report_file_smoothed.write("(cps)\n")
                        writer.writeheader()

                        for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                            file_long = self.container_lists[var_filetype]["Long"][index]
                            if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                                writer.writerow(report_intensity_mix[var_filetype][var_datatype][file_short])

                        report_file_smoothed.write("\n")

                    report_file_smoothed.write("SENSITIVITY ANALYSIS\n")
                    report_file_smoothed.write("Analytical Sensitivity\n")  # Analytical Sensitivity
                    report_file_smoothed.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_analytical_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_smoothed.write("\n")

                    report_file_smoothed.write("Normalized Sensitivity\n")  # Normalized Sensitivity
                    report_file_smoothed.write("(cps)/(ppm)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_normalized_sensitivity[var_filetype][var_datatype][file_short])

                    report_file_smoothed.write("\n")

                    report_file_smoothed.write("Relative Sensitivity Factor\n")  # Relative Sensitivity Factor
                    report_file_smoothed.write("(1)\n")
                    writer.writeheader()

                    for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                        file_long = self.container_lists[var_filetype]["Long"][index]
                        if self.container_var[var_filetype][file_long]["Checkbox"].get() == 1:
                            writer.writerow(report_rsf[var_filetype][var_datatype][file_short])

                    report_file_smoothed.write("\n")

        if os.path.exists(filename_base):
            os.remove(filename_base)
        else:
            print("The file does not exist!")

    def save_project(self):
        save_file = filedialog.asksaveasfile(mode="w", defaultextension=".csv")
        # Save information about the project
        self.save_project_information_in_file(save_file=save_file)
        # Save information about 'Standard Files Setup'
        self.save_standard_file_information_in_file(save_file=save_file)
        # Save information about 'Sample Files Setup'
        self.save_sample_file_information_in_file(save_file=save_file)
        # Save information about 'Measured Isotopes'
        self.save_measured_isotopes_in_file(save_file=save_file)

        if self.pysills_mode in ["FI", "MI"]:
            # Save information about 'Inclusion Setup'
            self.save_inclusion_information_in_file(save_file=save_file)
            if self.pysills_mode == "FI":
                # Save information about 'PyPitzer'
                self.save_pypitzer_settings_in_file(save_file=save_file)

            # Save information about 'Quantification Setup (Matrix-Only Tracer)'
            self.save_quantification_method_matrix_only_in_file(save_file=save_file)
            # Save information about 'Quantification Setup (Second Internal Standard)'
            self.save_quantification_method_second_internal_in_file(save_file=save_file)
            if self.pysills_mode == "FI":
                # Save information about 'Geometric Approach (Halter2002)'
                self.save_quantification_method_halter2002(save_file=save_file)
                # Save information about 'Geometric Approach (Borisova2021)'
                self.save_quantification_method_borisova2021(save_file=save_file)

        # Save information about 'Sample/Matrix Setup'
        self.save_mineralphase_information_in_file(save_file=save_file)
        # Save information about 'Dwell Time Settings'
        self.save_dwell_time_information_in_file(save_file=save_file)
        # Save information about 'Interval Settings'
        self.save_interval_information_in_file(save_file=save_file)
        # Save information about 'Spike Elimination'
        self.save_spike_elimination_information_in_file(save_file=save_file)
        # Save information about the experimental input data
        self.save_experimental_data_in_file(save_file=save_file)
        # END
        save_file.write("END")
        save_file.close()

    def save_project_information_in_file(self, save_file):
        if self.pysills_mode == "MA":
            info_mode = "Mineral Analysis"
            info_key = "ma_setting"
        elif self.pysills_mode == "FI":
            info_mode = "Fluid Inclusion Analysis"
            info_key = "fi_setting"
        elif self.pysills_mode == "MI":
            info_mode = "Melt Inclusion Analysis"
            info_key = "mi_setting"

        save_file.write("PROJECT INFORMATION" + "\n")
        save_file.write(str(info_mode) + "\n")

        info_author = self.container_var[info_key]["Author"].get()
        info_source = self.container_var[info_key]["Source ID"].get()
        info_carrier_gas = self.container_var["LASER"].get()
        info_icpms = self.var_opt_icp.get()

        str_proj = str(info_author) + ";" + str(info_source) + ";" + str(info_carrier_gas) + ";" + str(info_icpms)
        str_proj += "\n"

        save_file.write(str_proj)
        save_file.write("\n")

    def save_standard_file_information_in_file(self, save_file):
        save_file.write("STANDARD FILES" + "\n")

        for index, filename_short in enumerate(self.container_lists["STD"]["Short"]):
            filename_long = self.container_lists["STD"]["Long"][index]

            if filename_long in self.container_var["STD"]:
                info_srm = self.container_var["STD"][filename_long]["SRM"].get()
                info_cb_state = self.container_var["STD"][filename_long]["Checkbox"].get()
                info_sign_color = self.container_var["STD"][filename_long]["Sign Color"].get()
                info_acquisition = self.container_var["acquisition times"]["STD"][filename_short].get()
            else:
                info_srm = "Select SRM"
                info_cb_state = 1
                info_sign_color = self.sign_red
                info_acquisition = "00:00:00"

            str_std = (str(filename_short) + ";" + str(info_srm) + ";" + str(info_cb_state) + ";" +
                       str(info_sign_color) + ";" + str(info_acquisition))

            str_std += "\n"
            save_file.write(str_std)
        save_file.write("\n")

    def save_sample_file_information_in_file(self, save_file):
        save_file.write("SAMPLE FILES" + "\n")

        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]

            if filename_long in self.container_var["SMPL"]:
                info_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
                info_assemblage = self.container_var["SMPL"][filename_long]["ID"].get()
                info_cb_state = self.container_var["SMPL"][filename_long]["Checkbox"].get()
                info_sign_color = self.container_var["SMPL"][filename_long]["Sign Color"].get()
                info_acquisition = self.container_var["acquisition times"]["SMPL"][filename_short].get()
                info_oxide = self.container_var["SMPL"][filename_long]["Matrix Setup"]["Oxide"]["Name"].get()
                info_totalamount = self.container_var["Oxides Quantification"]["Total Amounts"][filename_short].get()
                info_totalamount_incl = self.container_var["Oxides Quantification INCL"]["Total Amounts"][
                    filename_short].get()
            else:
                info_is = "Select IS"
                info_assemblage = "A"
                info_cb_state = 1
                info_sign_color = self.sign_red
                info_acquisition = "00:00:00"
                info_oxide = "Select Oxide"
                info_totalamount = "100.0"
                info_totalamount_incl = "100.0"

            str_smpl = (str(filename_short) + ";" + str(info_is) + ";" + str(info_assemblage) + ";" + str(info_cb_state)
                        + ";" + str(info_sign_color) + ";" + str(info_acquisition) + ";" + str(info_oxide) + ";"
                        + str(info_totalamount) + ";" + str(info_totalamount_incl))

            str_smpl += "\n"
            save_file.write(str_smpl)
        save_file.write("\n")

    def save_measured_isotopes_in_file(self, save_file):
        save_file.write("ISOTOPES" + "\n")

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            if isotope.isdigit():
                pass
            else:
                info_srm = self.container_var["SRM"][isotope].get()

                str_iso = str(isotope) + ";" + str(info_srm)
                str_iso += "\n"

                save_file.write(str_iso)

        save_file.write("\n")

        if len(self.container_lists["Selected Oxides"]["All"]) > 0:
            for oxide in self.container_lists["Selected Oxides"]["All"]:
                str_oxide = str(oxide)
                str_oxide += "\n"

                save_file.write(str_oxide)

            save_file.write("\n")

    def save_inclusion_information_in_file(self, save_file):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        save_file.write("INCLUSION SETTINGS" + "\n")

        info_method = self.container_var[key_setting]["Inclusion Setup Selection"].get()

        str_incl = str("Method") + ";" + str(info_method) + "\n"
        save_file.write(str_incl)
        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            try:
                info_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
                info_concentration = self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].get()
                info_salinity = self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                    filename_short].get()
            except:
                info_is = "Select IS"
                info_concentration = 0.0
                info_salinity = 0.0

            str_incl = (str(filename_short) + ";" + str(info_is) + ";" + str(info_concentration) + ";"
                        + str(info_salinity))

            str_incl += "\n"
            save_file.write(str_incl)

        save_file.write("\n")

    def save_pypitzer_settings_in_file(self, save_file):
        save_file.write("PYPITZER SETTINGS" + "\n")

        str_cations = "Cations" + ";"
        str_anions = "Anions" + ";"
        str_isotopes = "Isotopes" + ";"

        for index, cation in enumerate(self.container_lists["Selected Cations"]):
            if index < len(self.container_lists["Selected Cations"]) - 1:
                str_cations += cation + ";"
            else:
                str_cations += cation + "\n"

        for index, anion in enumerate(self.container_lists["Selected Anions"]):
            if index < len(self.container_lists["Selected Anions"]) - 1:
                str_anions += anion + ";"
            else:
                str_anions += anion + "\n"

        for index, isotope in enumerate(list(self.helper_checkbuttons["Isotopes"].keys())):
            if self.helper_checkbuttons["Isotopes"][isotope].get() == 1:
                if index < len(list(self.helper_checkbuttons["Isotopes"].keys())) - 1:
                    str_isotopes += isotope + ";"
                else:
                    str_isotopes += isotope + "\n"

        str_isotopes = str_isotopes[:-1]
        str_isotopes += "\n"

        save_file.write(str_cations)
        save_file.write(str_anions)
        save_file.write(str_isotopes)

        for index, filename_smpl_long in enumerate(self.container_lists["SMPL"]["Long"]):
            filename_smpl_short = self.container_lists["SMPL"]["Short"][index]
            try:
                var_last_compound = self.container_var["SMPL"][filename_smpl_long]["Last compound"].get()
                var_melting_temperature = self.container_var["SMPL"][filename_smpl_long]["Melting temperature"].get()
            except:
                var_last_compound = "Undefined"
                var_melting_temperature = "Undefined"
            str_file = filename_smpl_short + ";" + var_last_compound + ";" + var_melting_temperature + "\n"

            save_file.write(str_file)

        save_file.write("\n")

    def save_quantification_method_matrix_only_in_file(self, save_file):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        save_file.write("QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)" + "\n")

        info_method = self.container_var[key_setting]["Quantification Method"].get()
        info_method_incl = self.container_var[key_setting]["Inclusion Intensity Calculation"].get()

        str_method = str("Method") + ";" + str(info_method) + ";" + str(info_method_incl) + "\n"
        save_file.write(str_method)
        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            try:
                info_amount = self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Amount"].get()
                info_matrix = self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Matrix"].get()
                info_isotope = self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Name"].get()
                info_concentration = self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Value"].get()
            except:
                info_amount = 0.0
                info_matrix = "Select Matrix"
                info_isotope = "Select Isotope"
                info_concentration = 0.0

            str_method = (str(filename_short) + ";" + str(info_amount) + ";" + str(info_matrix) + ";"
                          + str(info_isotope) + ";" + str(info_concentration) + "\n")

            save_file.write(str_method)

        save_file.write("\n")

    def save_quantification_method_second_internal_in_file(self, save_file):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        save_file.write("QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)" + "\n")

        info_method = self.container_var[key_setting]["Quantification Method"].get()
        info_method_incl = self.container_var[key_setting]["Inclusion Intensity Calculation"].get()

        str_method = str("Method") + ";" + str(info_method) + ";" + str(info_method_incl) + "\n"
        save_file.write(str_method)
        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            try:
                info_isotope = self.container_var["SMPL"][filename_long]["Second Internal Standard"]["Name"].get()
                info_concentration = self.container_var["SMPL"][filename_long]["Second Internal Standard"][
                    "Value"].get()
            except:
                info_isotope = "Select Isotope"
                info_concentration = 0.0
            str_method = str(filename_short) + ";" + str(info_isotope) + ";" + str(info_concentration) + "\n"
            save_file.write(str_method)

        save_file.write("\n")

    def save_quantification_method_halter2002(self, save_file):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        save_file.write("QUANTIFICATION SETTINGS (HALTER2002)" + "\n")
        info_method = self.container_var[key_setting]["Inclusion Intensity Calculation"].get()
        str_method = str("Method") + ";" + str(info_method) + "\n"
        save_file.write(str_method)

        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]

            try:
                val_a_i = self.container_var["SMPL"][filename_long]["Halter2002"]["a"].get()
                val_b_i = self.container_var["SMPL"][filename_long]["Halter2002"]["b"].get()
                val_rho_host_i = self.container_var["SMPL"][filename_long]["Halter2002"]["rho(host)"].get()
                val_rho_incl_i = self.container_var["SMPL"][filename_long]["Halter2002"]["rho(incl)"].get()
                val_r_i = self.container_var["SMPL"][filename_long]["Halter2002"]["R"].get()
            except:
                val_a_i = "Undefined"
                val_b_i = "Undefined"
                val_rho_host_i = "Undefined"
                val_rho_incl_i = "Undefined"
                val_r_i = "Undefined"

            str_i = (str(filename_short) + ";" + str(val_a_i) + ";" + str(val_b_i) + ";" + str(val_rho_host_i) +
                     ";" + str(val_rho_incl_i) + ";" + str(val_r_i) + "\n")
            save_file.write(str_i)

        save_file.write("\n")

    def save_quantification_method_borisova2021(self, save_file):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        save_file.write("QUANTIFICATION SETTINGS (BORISOVA2021)" + "\n")
        info_method = self.container_var[key_setting]["Inclusion Intensity Calculation"].get()
        str_method = str("Method") + ";" + str(info_method) + "\n"
        save_file.write(str_method)

        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]

            try:
                val_r_host_i = self.container_var["SMPL"][filename_long]["Borisova2021"]["R(host)"].get()
                val_r_incl_i = self.container_var["SMPL"][filename_long]["Borisova2021"]["R(incl)"].get()
                val_rho_host_i = self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(host)"].get()
                val_rho_incl_i = self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(incl)"].get()
            except:
                val_r_host_i = "Undefined"
                val_r_incl_i = "Undefined"
                val_rho_host_i = "Undefined"
                val_rho_incl_i = "Undefined"

            str_i = (str(filename_short) + ";" + str(val_r_host_i) + ";" + str(val_r_incl_i) + ";" +
                     str(val_rho_host_i) + ";" + str(val_rho_incl_i) + "\n")
            save_file.write(str_i)

        save_file.write("\n")

    def save_mineralphase_information_in_file(self, save_file):
        if self.pysills_mode == "MA":
            info_title = "SAMPLE SETTINGS"
        elif self.pysills_mode == "FI":
            info_title = "MATRIX SETTINGS"
        elif self.pysills_mode == "MI":
            info_title = "MATRIX SETTINGS"

        save_file.write(str(info_title) + "\n")
        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            if filename_long in self.container_var["SMPL"]:
                if self.pysills_mode == "MA":
                    info_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
                    info_concentration = self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].get()
                else:
                    info_is = self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Name"].get()
                    info_concentration = self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"][
                        "Concentration"].get()
            else:
                info_is = "Select IS"
                info_concentration = "1000000"

            str_smpl_is = str(filename_short) + ";" + str(info_is) + ";" + str(info_concentration) + "\n"

            save_file.write(str_smpl_is)

        save_file.write("\n")

    def save_dwell_time_information_in_file(self, save_file):
        save_file.write("DWELL TIME SETTINGS" + "\n")

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            if isotope.isdigit():
                pass
            else:
                info_dwell = self.container_var["dwell_times"]["Entry"][isotope].get()
                str_dwell = str(isotope) + ";" + str(info_dwell) + "\n"
                save_file.write(str_dwell)

        save_file.write("\n")

    def save_interval_information_in_file(self, save_file):
        save_file.write("INTERVAL SETTINGS" + "\n")

        for index, filename_short in enumerate(self.container_lists["STD"]["Short"]):
            str_intervals = str(filename_short) + ";" + "STD" + "\n"
            if filename_short in self.container_helper["STD"]:
                for key, item in self.container_helper["STD"][filename_short]["BG"]["Content"].items():
                    info_id = key
                    info_times = item["Times"]
                    info_indices = item["Indices"]

                    str_intervals += "BG" + ";" + str(info_id) + ";" + str(info_times) + ";" + str(info_indices) + "\n"

                for key, item in self.container_helper["STD"][filename_short]["MAT"]["Content"].items():
                    info_id = key
                    info_times = item["Times"]
                    info_indices = item["Indices"]

                    str_intervals += "MAT" + ";" + str(info_id) + ";" + str(info_times) + ";" + str(info_indices) + "\n"

                save_file.write(str_intervals)

        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            str_intervals = str(filename_short) + ";" + "SMPL" + "\n"

            if filename_short in self.container_helper["SMPL"]:
                for key, item in self.container_helper["SMPL"][filename_short]["BG"]["Content"].items():
                    info_id = key
                    info_times = item["Times"]
                    info_indices = item["Indices"]

                    str_intervals += "BG" + ";" + str(info_id) + ";" + str(info_times) + ";" + str(info_indices) + "\n"

                for key, item in self.container_helper["SMPL"][filename_short]["MAT"]["Content"].items():
                    info_id = key
                    info_times = item["Times"]
                    info_indices = item["Indices"]

                    str_intervals += "MAT" + ";" + str(info_id) + ";" + str(info_times) + ";" + str(info_indices) + "\n"

                if self.pysills_mode in ["FI", "MI"]:
                    for key, item in self.container_helper["SMPL"][filename_short]["INCL"]["Content"].items():
                        info_id = key
                        info_times = item["Times"]
                        info_indices = item["Indices"]

                        str_intervals += "INCL" + ";" + str(info_id) + ";" + str(info_times) + ";" + str(
                            info_indices) + "\n"

                save_file.write(str_intervals)

        save_file.write("\n")

    def save_spike_elimination_information_in_file(self, save_file):
        if self.pysills_mode == "MA":
            mode_key = "ma_setting"
        elif self.pysills_mode == "FI":
            mode_key = "fi_setting"
        elif self.pysills_mode == "MI":
            mode_key = "mi_setting"

        save_file.write("SPIKE ELIMINATION" + "\n")

        info_std_state = self.container_var["Spike Elimination"]["STD"]["State"]
        info_smpl_state = self.container_var["Spike Elimination"]["SMPL"]["State"]
        info_method = self.container_var["Spike Elimination Method"].get()
        info_alpha = self.container_var[mode_key]["SE Alpha"].get()
        info_threshold = self.container_var[mode_key]["SE Threshold"].get()

        if self.pysills_mode == "MA":
            str_spike = (str("STD") + ";" + str(info_std_state) + ";" + str("SMPL") + ";" + str(info_smpl_state) + ";"
                         + str(info_method) + ";" + str(info_alpha) + ";" + str(info_threshold) + "\n")
        else:
            info_inclusion_consideration = self.container_var[mode_key]["Spike Elimination Inclusion"].get()

            str_spike = (str("STD") + ";" + str(info_std_state) + ";" + str("SMPL") + ";" + str(info_smpl_state) + ";"
                         + str(info_inclusion_consideration) + ";" + str(info_method) + ";" + str(info_alpha) + ";"
                         + str(info_threshold) + "\n")

        save_file.write(str_spike)

        for var_file, dataset_isotopes in self.container_spike_values.items():
            str_spike_file = var_file + "\n"
            save_file.write(str_spike_file)
            for var_isotope, dataset_values in dataset_isotopes.items():
                str_spike_isotope = str(var_isotope) + ";"
                for var_id, val_id in dataset_values["Save"].items():
                    str_spike_isotope += str(var_id) + ";" + str(val_id) + ";"
                str_spike_isotope = str_spike_isotope[:-1]
                str_spike_isotope += "\n"
                save_file.write(str_spike_isotope)

        save_file.write("\n")

    def save_experimental_data_in_file(self, save_file):
        save_file.write("EXPERIMENTAL DATA" + "\n")

        for filetype in ["STD", "SMPL"]:
            if filetype == "STD":
                save_file.write("Standard Files" + "\n")
            else:
                save_file.write("Sample Files" + "\n")
            for index, filename_short in enumerate(self.container_lists[filetype]["Short"]):
                if filename_short in self.container_var["acquisition times"][filetype]:
                    info_acquisition = self.container_var["acquisition times"][filetype][filename_short].get()
                    filename_long = self.container_lists[filetype]["Long"][index]
                    save_file.write(str(filename_short) + "\n")
                    save_file.write("Acquisition" + ";" + str(info_acquisition) + "\n")
                    file_header = "Time" + ";"
                    file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                    for isotope in file_isotopes:
                        file_header += str(isotope) + ";"
                    save_file.write(str(file_header) + "\n")

                    if self.file_loaded == False:
                        if self.container_icpms["name"] != None:
                            var_skipheader = self.container_icpms["skipheader"]
                            var_skipfooter = self.container_icpms["skipfooter"]
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        else:
                            df_data = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=3, skip_footer=1)
                    else:
                        df_data = self.container_measurements["Dataframe"][filename_short]

                    dataset_time = list(DE().get_times(dataframe=df_data))
                    for index_line, time_value in enumerate(dataset_time):
                        file_content_line = str(time_value) + ";"
                        for isotope in file_isotopes:
                            file_content_line += str(df_data[isotope][index_line]) + ";"
                        save_file.write(str(file_content_line) + "\n")
                    save_file.write("\n")

    def open_project_part_01(self, key_setting, index_container, loaded_lines):
        ## PROJECT INFORMATION
        for i in range(index_container["PROJECT INFORMATION"] + 2, index_container["STANDARD FILES"] - 1):
            line_std = str(loaded_lines[i].strip())
            splitted_std = line_std.split(";")

            self.container_var[key_setting]["Author"].set(splitted_std[0])
            self.container_var[key_setting]["Source ID"].set(splitted_std[1])
            self.container_var["LASER"].set(splitted_std[2])
            try:
                self.var_opt_icp.set(splitted_std[3])
            except:
                self.var_opt_icp.set("Select ICP-MS")

    def open_project_part_02(self, key_setting, index_container, loaded_lines):
        ## STANDARD FILES
        for i in range(index_container["STANDARD FILES"] + 1, index_container["SAMPLE FILES"] - 1):
            line_std = str(loaded_lines[i].strip())
            splitted_std = line_std.split(";")

            var_file_long = splitted_std[0]
            var_file_short = splitted_std[0].split("/")[-1]

            self.container_spikes[var_file_short] = {}

            self.container_files["STD"][var_file_short] = {"SRM": tk.StringVar()}
            self.container_var["STD"][var_file_long] = {
                "IS Data": {"IS": tk.StringVar(), "Concentration": tk.StringVar()},
                "Checkbox": tk.IntVar(), "Sign Color": tk.StringVar(), "SRM": tk.StringVar()}

            self.container_var["acquisition times"]["STD"][var_file_short] = tk.StringVar()

            self.lb_std.insert(tk.END, str(var_file_short))
            self.list_std.append(var_file_long)
            self.container_lists["STD"]["Long"].append(var_file_long)
            self.container_lists["STD"]["Short"].append(var_file_short)
            self.container_var["STD"][var_file_long]["SRM"].set(splitted_std[1])
            self.container_var["STD"][var_file_long]["Checkbox"].set(splitted_std[2])

            try:
                self.container_var["STD"][var_file_long]["Sign Color"].set(splitted_std[3])
            except:
                self.container_var["STD"][var_file_long]["Sign Color"].set(self.sign_red)

            self.container_var["acquisition times"]["STD"][var_file_short].set(splitted_std[4])

            analysis_mode = key_setting[:2]
            if analysis_mode == "ma":
                self.ma_current_file_std = self.list_std[0]
            elif analysis_mode == "fi":
                self.fi_current_file_std = self.list_std[0]
            elif analysis_mode == "mi":
                self.mi_current_file_std = self.list_std[0]

    def open_project_part_03(self, key_setting, index_container, loaded_lines):
        ## SAMPLE FILES
        analysis_mode = key_setting[:2]
        for i in range(index_container["SAMPLE FILES"] + 1, index_container["ISOTOPES"] - 1):
            line_smpl = str(loaded_lines[i].strip())
            splitted_data_smpl = line_smpl.split(";")
            var_file_long = splitted_data_smpl[0]
            var_file_short = splitted_data_smpl[0].split("/")[-1]

            self.container_spikes[var_file_short] = {}

            self.container_var["SMPL"][var_file_long] = {
                "IS Data": {"IS": tk.StringVar(), "Concentration": tk.StringVar()},
                "Checkbox": tk.IntVar(), "ID": tk.StringVar(), "Sign Color": tk.StringVar()}
            self.container_var["SMPL"][var_file_long]["Matrix Setup"] = {
                "IS": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                "Oxide": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                "Element": {"Name": tk.StringVar(), "Concentration": tk.StringVar()}}

            self.container_var["acquisition times"]["SMPL"][var_file_short] = tk.StringVar()
            self.container_var["Oxides Quantification"]["Total Amounts"][var_file_short] = tk.StringVar()
            self.container_var["Oxides Quantification INCL"]["Total Amounts"][var_file_short] = tk.StringVar()

            self.lb_smpl.insert(tk.END, str(var_file_short))
            self.list_smpl.append(var_file_long)
            self.container_lists["SMPL"]["Long"].append(var_file_long)
            self.container_lists["SMPL"]["Short"].append(var_file_short)
            self.container_var["SMPL"][var_file_long]["Checkbox"].get()

            if analysis_mode == "ma":
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].set("Select IS")
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Concentration"].set("0.0")
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["Oxide"]["Name"].set("Select Oxide")
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["Oxide"]["Concentration"].set("100.0")
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["Element"]["Name"].set("Select Element")
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["Element"]["Concentration"].set("100.0")
            elif analysis_mode in ["fi", "mi"]:
                self.container_var["SMPL"][var_file_long]["IS Data"] = {
                    "IS": tk.StringVar(), "Concentration": tk.StringVar(),
                    "RAW": {"IS": tk.StringVar(), "Concentration": tk.StringVar()},
                    "SMOOTHED": {"IS": tk.StringVar(), "Concentration": tk.StringVar()}}

                self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].set("Select IS")
                self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].set("0.0")
                self.container_var["SMPL"][var_file_long]["IS Data"]["RAW"]["IS"].set("Select IS")
                self.container_var["SMPL"][var_file_long]["IS Data"]["RAW"]["Concentration"].set("0.0")
                self.container_var["SMPL"][var_file_long]["IS Data"]["SMOOTHED"]["IS"].set("Select IS")
                self.container_var["SMPL"][var_file_long]["IS Data"]["SMOOTHED"]["Concentration"].set("0.0")

            self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].set(splitted_data_smpl[1])

            if analysis_mode == "ma":
                self.ma_current_file_smpl = self.list_smpl[0]
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].set(splitted_data_smpl[1])
            elif analysis_mode == "fi":
                self.fi_current_file_smpl = self.list_smpl[0]
            elif analysis_mode == "mi":
                self.mi_current_file_smpl = self.list_smpl[0]

            self.container_var["SMPL"][var_file_long]["ID"].set(splitted_data_smpl[2])
            self.container_var["SMPL"][var_file_long]["Checkbox"].set(splitted_data_smpl[3])
            self.container_var["SMPL"][var_file_long]["Sign Color"].set(splitted_data_smpl[4])
            self.container_var["acquisition times"]["SMPL"][var_file_short].set(splitted_data_smpl[5])

            if len(splitted_data_smpl[6]) > 0:
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["Oxide"]["Name"].set(splitted_data_smpl[6])
            else:
                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["Oxide"]["Name"].set("Select Oxide")

            if len(splitted_data_smpl[7]) > 0:
                self.container_var["Oxides Quantification"]["Total Amounts"][var_file_short].set(splitted_data_smpl[7])
            else:
                self.container_var["Oxides Quantification"]["Total Amounts"][var_file_short].set("100.0")

            if len(splitted_data_smpl) == 9:
                if len(splitted_data_smpl[8]) > 0:
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][var_file_short].set(
                        splitted_data_smpl[8])
                else:
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][var_file_short].set("100.0")
            else:
                self.container_var["Oxides Quantification INCL"]["Total Amounts"][var_file_short].set("100.0")

    def open_project_part_04(self, key_setting, index_container, loaded_lines):
        ## ISOTOPES
        analysis_mode = key_setting[:2]

        if analysis_mode == "ma":
            title_next = "SAMPLE SETTINGS"
        else:
            title_next = "INCLUSION SETTINGS"

        for i in range(index_container["ISOTOPES"] + 1, index_container[title_next] - 1):
            line_std = str(loaded_lines[i].strip())
            splitted_lines = line_std.split(";")
            if len(splitted_lines) > 1:
                isotope = splitted_lines[0]
                self.container_var["SRM"][isotope] = tk.StringVar()
                self.container_lists["ISOTOPES"].append(isotope)
                self.container_var["SRM"][isotope].set(splitted_lines[1])
            else:
                oxide = splitted_lines[0]
                if len(oxide) > 0:
                    self.container_lists["Selected Oxides"]["All"].append(oxide)

    def open_project_part_05(self, key_setting, index_container, loaded_lines):
        ## SAMPLE/MATRIX SETTINGS
        analysis_mode = key_setting[:2]

        if analysis_mode == "ma":
            title_0 = "SAMPLE SETTINGS"
            title_1 = "DWELL TIME SETTINGS"
        elif analysis_mode == "fi":
            title_0 = "INCLUSION SETTINGS"

            if self.without_pypitzer == False:
                title_1 = "PYPITZER SETTINGS"
            else:
                title_1 = "QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)"
        elif analysis_mode == "mi":
            title_0 = "INCLUSION SETTINGS"
            title_1 = "QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)"

        for i in range(index_container[title_0] + 1, index_container[title_1] - 1):
            line_std = str(loaded_lines[i].strip())
            splitted_lines = line_std.split(";")

            if len(splitted_lines) == 2:
                self.container_var[key_setting]["Inclusion Setup Selection"] = tk.IntVar()
                self.container_var[key_setting]["Inclusion Setup Selection"].set(splitted_lines[1])

            if len(splitted_lines) > 2:
                info_file = splitted_lines[0]
                info_file_short = info_file.split("/")[-1]
                info_isotope = splitted_lines[1]
                info_concentration = splitted_lines[2]

                self.container_var["SMPL"][info_file]["IS Data"]["IS"].set(info_isotope)
                self.container_var["SMPL"][info_file]["IS Data"]["Concentration"].set(info_concentration)
                self.container_var["SMPL"][info_file]["Matrix Setup"]["IS"]["Name"].set(info_isotope)
                self.container_var["SMPL"][info_file]["Matrix Setup"]["IS"]["Concentration"].set(info_concentration)

                if analysis_mode == "fi":
                    info_salinity = splitted_lines[3]

                    self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                        info_file_short] = tk.StringVar()
                    self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                        info_file_short].set(info_salinity)

    def open_project_part_06(self, key_setting, index_container, loaded_lines):
        ## DWELL TIME SETTINGS
        for i in range(index_container["DWELL TIME SETTINGS"] + 1, index_container["INTERVAL SETTINGS"] - 1):
            line_std = str(loaded_lines[i].strip())
            splitted_lines = line_std.split(";")

            isotope = splitted_lines[0]
            self.container_var["dwell_times"]["Entry"][isotope] = tk.StringVar()
            self.container_var["dwell_times"]["Entry"][isotope].set(splitted_lines[1])

    def open_project_part_07(self, key_setting, index_container, loaded_lines):
        ## INTERVAL SETTINGS
        analysis_mode = key_setting[:2]
        for i in range(index_container["INTERVAL SETTINGS"] + 1, index_container["SPIKE ELIMINATION"] - 1):
            line_std = str(loaded_lines[i].strip())
            splitted_lines = line_std.split(";")

            if splitted_lines[1] in ["STD", "SMPL"]:
                var_filetype = splitted_lines[1]
                var_file_long = splitted_lines[0]
                var_file_short = splitted_lines[0].split("/")[-1]

                if analysis_mode == "ma":
                    self.container_helper[var_filetype][var_file_short] = {
                        "BG": {"Content": {}, "Indices": []},
                        "MAT": {"Content": {}, "Indices": []}}
                else:
                    self.container_helper[var_filetype][var_file_short] = {
                        "BG": {"Content": {}, "Indices": []},
                        "MAT": {"Content": {}, "Indices": []},
                        "INCL": {"Content": {}, "Indices": []}}
            else:
                if splitted_lines[0] == "BG":
                    var_id = int(splitted_lines[1])
                    var_times = splitted_lines[2]
                    var_indices = splitted_lines[3]

                    key_times = re.search(r"\[(\d+\.\d+)(\,\s+)(\d+\.\d+)\]", var_times)
                    key_indices = re.search(r"\[(\d+)(\,\s+)(\d+)\]", var_indices)
                    helper_times = [float(key_times.group(1)), float(key_times.group(3))]
                    helper_indices = [int(key_indices.group(1)), int(key_indices.group(3))]
                    helper_times.sort()
                    helper_indices.sort()
                    self.container_helper[var_filetype][var_file_short]["BG"]["ID"] = var_id
                    self.container_helper[var_filetype][var_file_short]["BG"]["Content"][var_id] = {}
                    self.container_helper[var_filetype][var_file_short]["BG"]["Content"][var_id][
                        "Times"] = helper_times
                    self.container_helper[var_filetype][var_file_short]["BG"]["Content"][var_id][
                        "Indices"] = helper_indices

                    self.container_helper[var_filetype][var_file_short]["BG"]["Indices"].append(var_id)

                elif splitted_lines[0] == "MAT":
                    var_id = int(splitted_lines[1])
                    var_times = splitted_lines[2]
                    var_indices = splitted_lines[3]

                    key_times = re.search(r"\[(\d+\.\d+)(\,\s+)(\d+\.\d+)\]", var_times)
                    key_indices = re.search(r"\[(\d+)(\,\s+)(\d+)\]", var_indices)

                    helper_times = [float(key_times.group(1)), float(key_times.group(3))]
                    helper_indices = [int(key_indices.group(1)), int(key_indices.group(3))]
                    helper_times.sort()
                    helper_indices.sort()
                    self.container_helper[var_filetype][var_file_short]["MAT"]["ID"] = var_id
                    self.container_helper[var_filetype][var_file_short]["MAT"]["Content"][var_id] = {}
                    self.container_helper[var_filetype][var_file_short]["MAT"]["Content"][var_id][
                        "Times"] = helper_times
                    self.container_helper[var_filetype][var_file_short]["MAT"]["Content"][var_id][
                        "Indices"] = helper_indices

                    self.container_helper[var_filetype][var_file_short]["MAT"]["Indices"].append(var_id)

                elif splitted_lines[0] == "INCL":
                    var_id = int(splitted_lines[1])
                    var_times = splitted_lines[2]
                    var_indices = splitted_lines[3]

                    key_times = re.search(r"\[(\d+\.\d+)(\,\s+)(\d+\.\d+)\]", var_times)
                    key_indices = re.search(r"\[(\d+)(\,\s+)(\d+)\]", var_indices)
                    helper_times = [float(key_times.group(1)), float(key_times.group(3))]
                    helper_indices = [int(key_indices.group(1)), int(key_indices.group(3))]
                    helper_times.sort()
                    helper_indices.sort()
                    self.container_helper[var_filetype][var_file_short]["INCL"]["ID"] = var_id
                    self.container_helper[var_filetype][var_file_short]["INCL"]["Content"][var_id] = {}
                    self.container_helper[var_filetype][var_file_short]["INCL"]["Content"][var_id][
                        "Times"] = helper_times
                    self.container_helper[var_filetype][var_file_short]["INCL"]["Content"][var_id][
                        "Indices"] = helper_indices

                    self.container_helper[var_filetype][var_file_short]["INCL"]["Indices"].append(var_id)

            if splitted_lines[0] == "BG":
                self.container_helper[var_filetype][var_file_short]["BG"]["ID"] = len(
                    self.container_helper[var_filetype][var_file_short]["BG"]["Content"])
            elif splitted_lines[0] == "MAT":
                self.container_helper[var_filetype][var_file_short]["MAT"]["ID"] = len(
                    self.container_helper[var_filetype][var_file_short]["MAT"]["Content"])
            elif splitted_lines[0] == "INCL":
                self.container_helper[var_filetype][var_file_short]["INCL"]["ID"] = len(
                    self.container_helper[var_filetype][var_file_short]["INCL"]["Content"])

    def open_project_part_08(self, key_setting, index_container, loaded_lines):
        ## SPIKE ELIMINATION
        analysis_mode = key_setting[:2]
        index = 0
        if self.old_file:
            final_line = index_container["END"] - 1
        else:
            final_line = index_container["EXPERIMENTAL DATA"] - 1

        for i in range(index_container["SPIKE ELIMINATION"] + 1, final_line):
            line_std = str(loaded_lines[i].strip())
            splitted_lines = line_std.split(";")

            if index == 0:
                self.container_var["Spike Elimination"]["STD"]["State"] = bool(splitted_lines[1])
                self.container_var["Spike Elimination"]["SMPL"]["State"] = bool(splitted_lines[3])

                if analysis_mode == "ma":
                    if splitted_lines[4] in ["Grubbs-Test", "Grubbs-Test (SILLS)"]:
                        splitted_lines[4] = "Grubbs test"

                    self.container_var["Spike Elimination Method"].set(splitted_lines[4])
                    self.container_var[key_setting]["SE Alpha"].set(splitted_lines[5])
                    self.container_var[key_setting]["SE Threshold"].set(int(splitted_lines[6]))
                else:
                    if splitted_lines[5] in ["Grubbs-Test", "Grubbs-Test (SILLS)"]:
                        splitted_lines[5] = "Grubbs test"

                    self.container_var[key_setting]["Spike Elimination Inclusion"].set(splitted_lines[4])
                    self.container_var["Spike Elimination Method"].set(splitted_lines[5])
                    self.container_var[key_setting]["SE Alpha"].set(splitted_lines[6])
                    self.container_var[key_setting]["SE Threshold"].set(int(splitted_lines[7]))

                index += 1
            else:
                if len(splitted_lines) == 1:
                    var_file = splitted_lines[0]
                    if var_file not in self.container_spike_values:
                        self.container_spike_values[var_file] = {}
                if len(splitted_lines) > 1:
                    var_isotope = splitted_lines[0]
                    list_values = splitted_lines[1:]
                    if var_isotope not in self.container_spike_values[var_file]:
                        self.container_spike_values[var_file][var_isotope] = {
                            "RAW": [], "SMOOTHED": [], "Current": [], "Save": {}}

                    for var_index in range(0, len(list_values), 2):
                        var_id = int(list_values[var_index])
                        val_id = float(list_values[var_index + 1])
                        self.container_spike_values[var_file][var_isotope]["Save"][var_id] = val_id

    def open_project_part_09(self, key_setting, index_container, loaded_lines, filename):
        ## EXPERIMENTAL DATA
        if self.old_file == False:
            helper_indices = {}
            for index, i in enumerate(range(index_container["EXPERIMENTAL DATA"] + 1, index_container["END"] - 1)):
                line_std = str(loaded_lines[i].strip())
                splitted_lines = line_std.split(";")
                if len(splitted_lines) == 1:
                    if splitted_lines[0] not in ["Standard Files", "Sample Files", ""]:
                        if splitted_lines[0] not in helper_indices:
                            helper_indices[splitted_lines[0]] = [i + 2]
                        if index > 1:
                            helper_indices[last_file].append(i - 2)
                        last_file = splitted_lines[0]

            if index > 1:
                helper_indices[last_file].append(i)

            for key, data in helper_indices.items():
                filename_short = key
                header_names = ["Time"]
                header_names.extend(self.container_lists["ISOTOPES"])
                dataframe = pd.read_csv(
                    filename, sep=";", header=0, skiprows=data[0], nrows=data[1] - data[0], usecols=header_names,
                    engine="python")

                dataframe_blank = dataframe.loc[dataframe.isnull().all(1)]
                if len(dataframe_blank) > 0:
                    first_blank_index = dataframe_blank.index[0]
                    dataframe = dataframe[:first_blank_index]
                var_columns = dataframe.columns

                for column in var_columns:
                    if (list(dataframe[var_columns[0]])[-1] == ",,"
                            or list(dataframe[var_columns[0]])[-1] == ";;"):
                        dataframe[column] = dataframe[column][:-1].astype(float)
                    else:
                        dataframe[column] = dataframe[column].astype(float)
                df_isotopes = DE().get_isotopes(dataframe=dataframe)

                times = DE().get_times(dataframe=dataframe)
                self.container_lists["Measured Isotopes"][key] = df_isotopes

                if key not in self.container_lists["Measured Elements"]:
                    self.container_lists["Measured Elements"][key] = {}

                for isotope in df_isotopes:
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)
                    if element not in self.container_lists["Measured Elements"][key]:
                        self.container_lists["Measured Elements"][key][element] = [isotope]
                    else:
                        if isotope not in self.container_lists["Measured Elements"][key][element]:
                            self.container_lists["Measured Elements"][key][element].append(isotope)
                    if element not in self.container_lists["Measured Elements"]["All"]:
                        self.container_lists["Measured Elements"]["All"].append(element)

                if "Dataframe" not in self.container_measurements:
                    self.container_measurements["Dataframe"] = {}
                if key not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][key] = dataframe

                if key not in self.container_measurements["RAW"]:
                    self.container_measurements["RAW"][key] = {}
                    self.container_measurements["EDITED"][key] = {}
                    self.container_measurements["SELECTED"][key] = {}
                self.container_measurements["RAW"][key]["Time"] = times.tolist()
                self.container_measurements["EDITED"][key]["Time"] = times.tolist()
                self.container_measurements["SELECTED"][key]["Time"] = times.tolist()

                for isotope in df_isotopes:
                    self.container_measurements["RAW"][key][isotope] = dataframe[isotope].tolist()
                    self.container_measurements["EDITED"][key][isotope] = {}

                    if "RAW" not in self.container_measurements["SELECTED"][key]:
                        self.container_measurements["SELECTED"][key]["RAW"] = {}

                    if "SMOOTHED" not in self.container_measurements["SELECTED"][key]:
                        self.container_measurements["SELECTED"][key]["SMOOTHED"] = {}

                    self.container_measurements["SELECTED"][key]["RAW"][isotope] = {}
                    self.container_measurements["SELECTED"][key]["SMOOTHED"][isotope] = {}

                    data_raw = self.container_measurements["RAW"][filename_short][isotope]
                    data_smoothed = data_raw.copy()
                    data_improved = data_raw.copy()
                    data_indices = []
                    data_times = self.container_measurements["SELECTED"][filename_short]["Time"]

                    if filename_short in self.container_spike_values:
                        if isotope in self.container_spike_values[filename_short]:
                            for index, value in self.container_spike_values[filename_short][isotope]["Save"].items():
                                data_indices.append(index)
                                data_improved[index] = value

                    self.container_spikes[filename_short][isotope] = {
                        "Data RAW": data_raw, "Data SMOOTHED": data_smoothed, "Data IMPROVED": data_improved,
                        "Indices": data_indices, "Times": data_times}

    def open_project(self):
        if len(self.container_lists["Measured Isotopes"]["All"]) > 0:
            print("We are sorry but it is currently necessary to restart PySILLS before another project can be opened. "
                  "This issue will be fixed in the future.")
            self.parent.bell()
        else:
            subwindow_progressbar, prgbar = self.create_progress_bar_spike_elimination()
            current_step = 0
            self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
            self.lbl_prg_spk.configure(text="Opening project started!", anchor=tk.W)

            filename = filedialog.askopenfilename()

            try:
                file_loaded = open(str(filename), "r")
                loaded_lines = file_loaded.readlines()
                n_lines = len(loaded_lines)

                if ",,\n" in loaded_lines:
                    loaded_lines = [sub.replace(",,\n", "") for sub in loaded_lines]
                elif ";;\n" in loaded_lines:
                    loaded_lines = [sub.replace(";;\n", "") for sub in loaded_lines]

                n_settings = 0
                strings = ["PROJECT INFORMATION", "STANDARD FILES"]
                index_container = {}

                while n_settings < len(strings):
                    index_container[strings[n_settings]] = 0
                    index = 0
                    flag = 0
                    for line in open(str(filename), "r"):
                        if strings[n_settings] in line:
                            flag = 1
                            break
                        else:
                            index += 1
                    if flag == 0:
                        pass
                    else:
                        index_container[strings[n_settings]] += index
                        n_settings += 1

                for i in range(index_container["PROJECT INFORMATION"] + 1, index_container["STANDARD FILES"] - 1):
                    line_std = str(loaded_lines[i].strip())
                    splitted_line = line_std.split(";")
                    var_mode = splitted_line[0]
                    if var_mode == "Mineral Analysis":
                        key_setting = "ma_setting"
                        self.pysills_mode = "MA"
                        self.var_rb_mode.set(0)
                    elif var_mode == "Fluid Inclusion Analysis":
                        key_setting = "fi_setting"
                        self.pysills_mode = "FI"
                        self.var_rb_mode.set(1)
                    elif var_mode == "Melt Inclusion Analysis":
                        key_setting = "mi_setting"
                        self.pysills_mode = "MI"
                        self.var_rb_mode.set(2)
                    break
                self.select_experiment(var_rb=self.var_rb_mode)

                n_settings = 0
                if "EXPERIMENTAL DATA\n" in loaded_lines or "EXPERIMENTAL DATA" in loaded_lines:
                    if self.pysills_mode == "MA":
                        strings = ["PROJECT INFORMATION", "STANDARD FILES", "SAMPLE FILES", "ISOTOPES",
                                   "SAMPLE SETTINGS", "DWELL TIME SETTINGS", "INTERVAL SETTINGS", "SPIKE ELIMINATION",
                                   "EXPERIMENTAL DATA", "END"]
                    else:
                        if ("PYPITZER SETTINGS\n" in loaded_lines and "QUANTIFICATION SETTINGS (HALTER2002)\n"
                                in loaded_lines and "QUANTIFICATION SETTINGS (BORISOVA2021)\n" in loaded_lines):
                            strings = ["PROJECT INFORMATION", "STANDARD FILES", "SAMPLE FILES", "ISOTOPES",
                                       "INCLUSION SETTINGS", "PYPITZER SETTINGS",
                                       "QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)",
                                       "QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)",
                                       "QUANTIFICATION SETTINGS (HALTER2002)", "QUANTIFICATION SETTINGS (BORISOVA2021)",
                                       "MATRIX SETTINGS", "DWELL TIME SETTINGS", "INTERVAL SETTINGS",
                                       "SPIKE ELIMINATION", "EXPERIMENTAL DATA", "END"]
                        else:
                            strings = ["PROJECT INFORMATION", "STANDARD FILES", "SAMPLE FILES", "ISOTOPES",
                                       "INCLUSION SETTINGS", "QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)",
                                       "QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)", "MATRIX SETTINGS",
                                       "DWELL TIME SETTINGS", "INTERVAL SETTINGS", "SPIKE ELIMINATION",
                                       "EXPERIMENTAL DATA", "END"]
                            self.without_pypitzer = True
                else:
                    if self.pysills_mode == "MA":
                        strings = ["PROJECT INFORMATION", "STANDARD FILES", "SAMPLE FILES", "ISOTOPES",
                                   "SAMPLE SETTINGS", "DWELL TIME SETTINGS", "INTERVAL SETTINGS", "SPIKE ELIMINATION",
                                   "END"]
                    else:
                        strings = ["PROJECT INFORMATION", "STANDARD FILES", "SAMPLE FILES", "ISOTOPES",
                                   "INCLUSION SETTINGS", "PYPITZER SETTINGS",
                                   "QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)",
                                   "QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)",
                                   "QUANTIFICATION SETTINGS (HALTER2002)", "QUANTIFICATION SETTINGS (BORISOVA2021)",
                                   "MATRIX SETTINGS", "DWELL TIME SETTINGS", "INTERVAL SETTINGS", "SPIKE ELIMINATION",
                                   "END"]
                    self.old_file = True

                index_container = {}
                while n_settings < len(strings):
                    index_container[strings[n_settings]] = 0
                    index = 0
                    flag = 0
                    for line in open(str(filename), "r"):
                        if strings[n_settings] in line:
                            flag = 1
                            break
                        else:
                            index += 1
                    if flag == 0:
                        pass
                    else:
                        index_container[strings[n_settings]] += index
                        n_settings += 1

                time_start = datetime.datetime.now()

                current_step = 10
                self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                self.lbl_prg_spk.configure(text="Initialization", anchor=tk.W)

                if self.pysills_mode == "MA":
                    self.open_project_part_01(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 20
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## STANDARD FILES
                    self.open_project_part_02(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 30
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## SAMPLE FILES
                    self.open_project_part_03(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 40
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## ISOTOPES
                    self.open_project_part_04(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 50
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## SAMPLE/MATRIX SETTINGS
                    self.open_project_part_05(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 60
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## DWELL TIME SETTINGS
                    self.open_project_part_06(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 70
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## INTERVAL SETTINGS
                    self.open_project_part_07(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 80
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## SPIKE ELIMINATION
                    self.open_project_part_08(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 90
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) +" %", anchor=tk.W)
                    ## EXPERIMENTAL DATA
                    self.open_project_part_09(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines,
                        filename=filename)
                    current_step = 100
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text="Opening project finished!", anchor=tk.W)

                    if current_step >= 100:
                        self.lbl_prg_spk.configure(text="Opening project finished!", anchor=tk.W)
                        subwindow_progressbar.destroy()
                elif self.pysills_mode == "FI":
                    ## PROJECT INFORMATION
                    self.open_project_part_01(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 20
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## STANDARD FILES
                    self.open_project_part_02(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 30
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## SAMPLE FILES
                    self.open_project_part_03(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 40
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## ISOTOPES
                    self.open_project_part_04(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 50
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## INCLUSION SETTINGS
                    self.open_project_part_05(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 60
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## PYPITZER SETTINGS
                    if self.without_pypitzer == False:
                        for i in range(index_container["PYPITZER SETTINGS"] + 1,
                                       index_container["QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)"] - 1):
                            line_data = str(loaded_lines[i].strip())
                            splitted_data = line_data.split(";")

                            if splitted_data[0] == "Cations":
                                self.container_lists["Selected Cations"].extend(splitted_data[1:])
                            elif splitted_data[0] == "Anions":
                                self.container_lists["Selected Anions"].extend(splitted_data[1:])
                            elif splitted_data[0] == "Isotopes":
                                for isotope in splitted_data[1:]:
                                    self.helper_checkbuttons["Isotopes"][isotope] = tk.IntVar()
                                    self.helper_checkbuttons["Isotopes"][isotope].set(1)
                            elif splitted_data[0] in self.container_lists["SMPL"]["Short"]:
                                for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                                    var_last_compound = splitted_data[1]
                                    var_melting_temperature = splitted_data[2]

                                    self.container_var["SMPL"][filename_smpl_long]["Last compound"] = tk.StringVar()
                                    self.container_var["SMPL"][filename_smpl_long][
                                        "Melting temperature"] = tk.StringVar()
                                    self.container_var["SMPL"][filename_smpl_long]["Last compound"].set(
                                        var_last_compound)
                                    self.container_var["SMPL"][filename_smpl_long]["Melting temperature"].set(
                                        var_melting_temperature)
                    current_step = 63
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)
                    index = 0
                    for i in range(index_container["QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)"] + 1,
                                   index_container["QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)"] - 1):
                        line_data = str(loaded_lines[i].strip())
                        splitted_data = line_data.split(";")
                        #
                        if index == 0:
                            self.container_var[key_setting]["Quantification Method"] = tk.IntVar()
                            self.container_var[key_setting]["Quantification Method"].set(splitted_data[1])

                            if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                            if len(splitted_data) == 3:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(
                                    int(splitted_data[2]))
                            else:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(0)
                        else:
                            info_file = splitted_data[0]
                            info_amount = splitted_data[1]
                            info_matrix = splitted_data[2]
                            info_isotope = splitted_data[3]
                            info_concentration = splitted_data[4]
                            #
                            self.container_var["SMPL"][info_file]["Host Only Tracer"] = {
                                "Name": tk.StringVar(), "Value": tk.StringVar(), "Matrix": tk.StringVar(),
                                "Amount": tk.StringVar()}
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Amount"].set(info_amount)
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Matrix"].set(info_matrix)
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Name"].set(info_isotope)
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Value"].set(info_concentration)
                        #
                        index += 1

                    current_step = 66
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)
                    index = 0
                    if self.without_pypitzer == False:
                        keyword = "QUANTIFICATION SETTINGS (HALTER2002)"
                    else:
                        keyword = "MATRIX SETTINGS"

                    for i in range(index_container["QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)"] + 1,
                                   index_container[keyword] - 1):
                        line_data = str(loaded_lines[i].strip())
                        splitted_data = line_data.split(";")
                        #
                        if index == 0:
                            self.container_var[key_setting]["Quantification Method"] = tk.IntVar()
                            self.container_var[key_setting]["Quantification Method"].set(splitted_data[1])

                            if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                            if len(splitted_data) == 3:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(
                                    int(splitted_data[2]))
                            else:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(0)
                        else:
                            if len(splitted_data) == 3:
                                info_file = splitted_data[0]
                                info_isotope = splitted_data[1]
                                info_concentration = splitted_data[2]

                                self.container_var["SMPL"][info_file]["Second Internal Standard"] = {
                                    "Name": tk.StringVar(), "Value": tk.StringVar()}
                                self.container_var["SMPL"][info_file]["Second Internal Standard"]["Name"].set(
                                    info_isotope)
                                self.container_var["SMPL"][info_file]["Second Internal Standard"]["Value"].set(
                                    info_concentration)
                        #
                        index += 1

                    current_step = 69
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (HALTER2002)
                    index = 0
                    if self.without_pypitzer == False:
                        for i in range(index_container["QUANTIFICATION SETTINGS (HALTER2002)"] + 1,
                                       index_container["QUANTIFICATION SETTINGS (BORISOVA2021)"] - 1):
                            line_data = str(loaded_lines[i].strip())
                            splitted_data = line_data.split(";")

                            if index == 0:
                                val_method = int(splitted_data[1])
                                if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                    self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(val_method)
                            else:
                                filename_short = splitted_data[0]
                                index_filename = self.container_lists["SMPL"]["Short"].index(filename_short)
                                filename_long = self.container_lists["SMPL"]["Long"][index_filename]
                                val_a_i = splitted_data[1]
                                val_b_i = splitted_data[2]
                                val_rho_host_i = splitted_data[3]
                                val_rho_incl_i = splitted_data[4]
                                val_r_i = splitted_data[5]
                                if "Halter2002" not in self.container_var["SMPL"][filename_long]:
                                    self.container_var["SMPL"][filename_long]["Halter2002"] = {
                                        "a": tk.StringVar(), "b": tk.StringVar(), "rho(host)": tk.StringVar(),
                                        "rho(incl)": tk.StringVar(), "R": tk.StringVar()}
                                self.container_var["SMPL"][filename_long]["Halter2002"]["a"].set(val_a_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["b"].set(val_b_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["rho(host)"].set(val_rho_host_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["rho(incl)"].set(val_rho_incl_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["R"].set(val_r_i)

                            index += 1

                    current_step = 72
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (BORISOVA2021)
                    index = 0
                    if self.without_pypitzer == False:
                        for i in range(index_container["QUANTIFICATION SETTINGS (BORISOVA2021)"] + 1,
                                       index_container["MATRIX SETTINGS"] - 1):
                            line_data = str(loaded_lines[i].strip())
                            splitted_data = line_data.split(";")

                            if index == 0:
                                val_method = int(splitted_data[1])
                                if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                    self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(val_method)
                            else:
                                filename_short = splitted_data[0]
                                index_filename = self.container_lists["SMPL"]["Short"].index(filename_short)
                                filename_long = self.container_lists["SMPL"]["Long"][index_filename]
                                val_r_host_i = splitted_data[1]
                                val_r_incl_i = splitted_data[2]
                                val_rho_host_i = splitted_data[3]
                                val_rho_incl_i = splitted_data[4]
                                if "Borisova2021" not in self.container_var["SMPL"][filename_long]:
                                    self.container_var["SMPL"][filename_long]["Borisova2021"] = {
                                        "R(host)": tk.StringVar(), "R(incl)": tk.StringVar(),
                                        "rho(host)": tk.StringVar(), "rho(incl)": tk.StringVar()}
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["R(host)"].set(val_r_host_i)
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["R(incl)"].set(val_r_incl_i)
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(host)"].set(
                                    val_rho_host_i)
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(incl)"].set(
                                    val_rho_incl_i)

                            index += 1

                    current_step = 75
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## MATRIX SETTINGS
                    for i in range(index_container["MATRIX SETTINGS"] + 1,
                                   index_container["DWELL TIME SETTINGS"] - 1):
                        line_std = str(loaded_lines[i].strip())
                        splitted_std = line_std.split(";")

                        info_file = splitted_std[0]
                        info_isotope = splitted_std[1]
                        info_concentration = splitted_std[2]

                        if "Matrix Setup" not in self.container_var["SMPL"][info_file]:
                            self.container_var["SMPL"][info_file]["Matrix Setup"] = {
                                "IS": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                                "Oxide": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                                "Element": {"Name": tk.StringVar(), "Concentration": tk.StringVar()}}
                        self.container_var["SMPL"][info_file]["Matrix Setup"]["IS"]["Name"].set(info_isotope)
                        self.container_var["SMPL"][info_file]["Matrix Setup"]["IS"]["Concentration"].set(
                            info_concentration)

                    current_step = 78
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## DWELL TIME SETTINGS
                    self.open_project_part_06(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 81
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## INTERVAL SETTINGS
                    self.open_project_part_07(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 84
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## SPIKE ELIMINATION
                    self.open_project_part_08(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 87
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## EXPERIMENTAL DATA
                    self.open_project_part_09(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines,
                        filename=filename)
                    current_step = 100
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text="Opening project finished!", anchor=tk.W)

                    if current_step >= 100:
                        self.lbl_prg_spk.configure(text="Opening project finished!", anchor=tk.W)
                        subwindow_progressbar.destroy()
                elif self.pysills_mode == "MI":
                    ## PROJECT INFORMATION
                    self.open_project_part_01(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 20
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## STANDARD FILES
                    self.open_project_part_02(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 30
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## SAMPLE FILES
                    self.open_project_part_03(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 40
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## ISOTOPES
                    self.open_project_part_04(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 50
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## INCLUSION SETTINGS
                    self.open_project_part_05(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 60
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## PYPITZER SETTINGS
                    if self.without_pypitzer == False:
                        for i in range(index_container["PYPITZER SETTINGS"] + 1,
                                       index_container["QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)"] - 1):
                            line_data = str(loaded_lines[i].strip())
                            splitted_data = line_data.split(";")

                            if splitted_data[0] == "Cations":
                                self.container_lists["Selected Cations"].extend(splitted_data[1:])
                            elif splitted_data[0] == "Anions":
                                self.container_lists["Selected Anions"].extend(splitted_data[1:])
                            elif splitted_data[0] == "Isotopes":
                                for isotope in splitted_data[1:]:
                                    self.helper_checkbuttons["Isotopes"][isotope] = tk.IntVar()
                                    self.helper_checkbuttons["Isotopes"][isotope].set(1)
                            elif splitted_data[0] in self.container_lists["SMPL"]["Short"]:
                                for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                                    var_last_compound = splitted_data[1]
                                    var_melting_temperature = splitted_data[2]

                                    self.container_var["SMPL"][filename_smpl_long]["Last compound"] = tk.StringVar()
                                    self.container_var["SMPL"][filename_smpl_long][
                                        "Melting temperature"] = tk.StringVar()
                                    self.container_var["SMPL"][filename_smpl_long]["Last compound"].set(
                                        var_last_compound)
                                    self.container_var["SMPL"][filename_smpl_long]["Melting temperature"].set(
                                        var_melting_temperature)

                    current_step = 63
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)
                    index = 0
                    for i in range(index_container["QUANTIFICATION SETTINGS (MATRIX-ONLY TRACER)"] + 1,
                                   index_container["QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)"] - 1):
                        line_data = str(loaded_lines[i].strip())
                        splitted_data = line_data.split(";")
                        #
                        if index == 0:
                            self.container_var[key_setting]["Quantification Method"] = tk.IntVar()
                            self.container_var[key_setting]["Quantification Method"].set(splitted_data[1])

                            if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                            if len(splitted_data) == 3:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(
                                    int(splitted_data[2]))
                            else:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(0)
                        else:
                            info_file = splitted_data[0]
                            info_amount = splitted_data[1]
                            info_matrix = splitted_data[2]
                            info_isotope = splitted_data[3]
                            info_concentration = splitted_data[4]
                            #
                            self.container_var["SMPL"][info_file]["Host Only Tracer"] = {
                                "Name": tk.StringVar(), "Value": tk.StringVar(), "Matrix": tk.StringVar(),
                                "Amount": tk.StringVar()}
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Amount"].set(info_amount)
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Matrix"].set(info_matrix)
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Name"].set(info_isotope)
                            self.container_var["SMPL"][info_file]["Host Only Tracer"]["Value"].set(info_concentration)
                        #
                        index += 1

                    current_step = 66
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)
                    index = 0
                    if self.without_pypitzer == False:
                        keyword = "QUANTIFICATION SETTINGS (HALTER2002)"
                    else:
                        keyword = "MATRIX SETTINGS"

                    for i in range(index_container["QUANTIFICATION SETTINGS (SECOND INTERNAL STANDARD)"] + 1,
                                   index_container[keyword] - 1):
                        line_data = str(loaded_lines[i].strip())
                        splitted_data = line_data.split(";")
                        #
                        if index == 0:
                            self.container_var[key_setting]["Quantification Method"] = tk.IntVar()
                            self.container_var[key_setting]["Quantification Method"].set(splitted_data[1])

                            if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                            if len(splitted_data) == 3:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(
                                    int(splitted_data[2]))
                            else:
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(0)
                        else:
                            info_file = splitted_data[0]
                            info_isotope = splitted_data[1]
                            info_concentration = splitted_data[2]
                            #
                            self.container_var["SMPL"][info_file]["Second Internal Standard"] = {
                                "Name": tk.StringVar(), "Value": tk.StringVar()}
                            self.container_var["SMPL"][info_file]["Second Internal Standard"]["Name"].set(info_isotope)
                            self.container_var["SMPL"][info_file]["Second Internal Standard"]["Value"].set(
                                info_concentration)
                        #
                        index += 1

                    current_step = 69
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (HALTER2002)
                    index = 0
                    if self.without_pypitzer == False:
                        for i in range(index_container["QUANTIFICATION SETTINGS (HALTER2002)"] + 1,
                                       index_container["QUANTIFICATION SETTINGS (BORISOVA2021)"] - 1):
                            line_data = str(loaded_lines[i].strip())
                            splitted_data = line_data.split(";")

                            if index == 0:
                                val_method = int(splitted_data[1])
                                if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                    self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(val_method)
                            else:
                                filename_short = splitted_data[0]
                                index_filename = self.container_lists["SMPL"]["Short"].index(filename_short)
                                filename_long = self.container_lists["SMPL"]["Long"][index_filename]
                                val_a_i = splitted_data[1]
                                val_b_i = splitted_data[2]
                                val_rho_host_i = splitted_data[3]
                                val_rho_incl_i = splitted_data[4]
                                val_r_i = splitted_data[5]
                                if "Halter2002" not in self.container_var["SMPL"][filename_long]:
                                    self.container_var["SMPL"][filename_long]["Halter2002"] = {
                                        "a": tk.StringVar(), "b": tk.StringVar(), "rho(host)": tk.StringVar(),
                                        "rho(incl)": tk.StringVar(), "R": tk.StringVar()}
                                self.container_var["SMPL"][filename_long]["Halter2002"]["a"].set(val_a_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["b"].set(val_b_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["rho(host)"].set(val_rho_host_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["rho(incl)"].set(val_rho_incl_i)
                                self.container_var["SMPL"][filename_long]["Halter2002"]["R"].set(val_r_i)

                            index += 1

                    current_step = 72
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## QUANTIFICATION SETTINGS (BORISOVA2021)
                    index = 0
                    if self.without_pypitzer == False:
                        for i in range(index_container["QUANTIFICATION SETTINGS (BORISOVA2021)"] + 1,
                                       index_container["MATRIX SETTINGS"] - 1):
                            line_data = str(loaded_lines[i].strip())
                            splitted_data = line_data.split(";")

                            if index == 0:
                                val_method = int(splitted_data[1])
                                if "Inclusion Intensity Calculation" not in self.container_var[key_setting]:
                                    self.container_var[key_setting]["Inclusion Intensity Calculation"] = tk.IntVar()
                                self.container_var[key_setting]["Inclusion Intensity Calculation"].set(val_method)
                            else:
                                filename_short = splitted_data[0]
                                index_filename = self.container_lists["SMPL"]["Short"].index(filename_short)
                                filename_long = self.container_lists["SMPL"]["Long"][index_filename]
                                val_r_host_i = splitted_data[1]
                                val_r_incl_i = splitted_data[2]
                                val_rho_host_i = splitted_data[3]
                                val_rho_incl_i = splitted_data[4]
                                if "Borisova2021" not in self.container_var["SMPL"][filename_long]:
                                    self.container_var["SMPL"][filename_long]["Borisova2021"] = {
                                        "R(host)": tk.StringVar(), "R(incl)": tk.StringVar(),
                                        "rho(host)": tk.StringVar(), "rho(incl)": tk.StringVar()}
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["R(host)"].set(val_r_host_i)
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["R(incl)"].set(val_r_incl_i)
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(host)"].set(
                                    val_rho_host_i)
                                self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(incl)"].set(
                                    val_rho_incl_i)

                            index += 1

                    current_step = 75
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## MATRIX SETTINGS
                    for i in range(index_container["MATRIX SETTINGS"] + 1,
                                   index_container["DWELL TIME SETTINGS"] - 1):
                        line_std = str(loaded_lines[i].strip())
                        splitted_std = line_std.split(";")

                        info_file = splitted_std[0]
                        info_isotope = splitted_std[1]
                        info_concentration = splitted_std[2]

                        if "Matrix Setup" not in self.container_var["SMPL"][info_file]:
                            self.container_var["SMPL"][info_file]["Matrix Setup"] = {
                                "IS": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                                "Oxide": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                                "Element": {"Name": tk.StringVar(), "Concentration": tk.StringVar()}}
                        self.container_var["SMPL"][info_file]["Matrix Setup"]["IS"]["Name"].set(info_isotope)
                        self.container_var["SMPL"][info_file]["Matrix Setup"]["IS"]["Concentration"].set(
                            info_concentration)

                    current_step = 78
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## DWELL TIME SETTINGS
                    self.open_project_part_06(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 81
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## INTERVAL SETTINGS
                    self.open_project_part_07(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 84
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## SPIKE ELIMINATION
                    self.open_project_part_08(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines)
                    current_step = 87
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text=str(current_step) + " %", anchor=tk.W)
                    ## EXPERIMENTAL DATA
                    self.open_project_part_09(
                        key_setting=key_setting, index_container=index_container, loaded_lines=loaded_lines,
                        filename=filename)
                    current_step = 100
                    self.update_progress(parent=subwindow_progressbar, variable=prgbar, value=current_step)
                    self.lbl_prg_spk.configure(text="Opening project finished!", anchor=tk.W)

                    if current_step >= 100:
                        self.lbl_prg_spk.configure(text="Opening project finished!", anchor=tk.W)
                        subwindow_progressbar.destroy()

                # Initialization
                time_start = datetime.datetime.now()
                self.file_loaded = True
                self.demo_mode = False

                if self.old_file == True and self.var_opt_icp.get() == "Select ICP-MS":
                    self.container_icpms["name"] = None
                else:
                    self.select_icp_ms(var_opt=self.var_opt_icp)

                if self.pysills_mode == "MA":
                    self.ma_settings()
                elif self.pysills_mode == "FI":
                    self.fi_settings()
                elif self.pysills_mode == "MI":
                    self.mi_settings()

                time_end = datetime.datetime.now()
                time_delta = (time_end - time_start)*1000
                print(f"Process time (opening project - part 'Initialization'):", time_delta.total_seconds(), "ms")
            except FileNotFoundError:
                print("File not found!")

    def convert_true_false_string(self, var_str):
        d = {"True": True, "False": False}
        return d.get(var_str, var_str)

    def delete_csv(self, var_lb, var_list):
        if var_lb == self.lb_std:
            var_list = self.list_std
        elif var_lb == self.lb_smpl:
            var_list = self.list_smpl
        item = var_lb.curselection()
        var_list.remove(var_list[item[0]])
        var_lb.delete(tk.ANCHOR)
        #
        if var_lb == self.lb_std:
            del self.container_lists["STD"]["Long"][item[0]]
            del self.container_lists["STD"]["Short"][item[0]]
        elif var_lb == self.lb_smpl:
            del self.container_lists["SMPL"]["Long"][item[0]]
            del self.container_lists["SMPL"]["Short"][item[0]]

    def restart_pysills(self):
        self.parent.destroy()
        root = tk.Tk()
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        PySILLS(parent=root, var_screen_width=screen_width, var_screen_height=screen_height)
        root.mainloop()

    ####################
    ## DATA PROCESSING #
    ####################
    def open_csv(self, datatype):
        if datatype == "STD":
            if "Default_STD_01.csv" in self.list_std:
                self.list_std.clear()
            var_list = self.list_std
            var_listbox = self.lb_std
        elif datatype == "SMPL":
            if "Default_SMPL_01.csv" in self.list_smpl:
                self.list_smpl.clear()
            var_list = self.list_smpl
            var_listbox = self.lb_smpl

        filename = filedialog.askopenfilenames(
            parent=self.parent,
            filetypes=(("LA-ICP-MS files", "*.csv *.FIN2 *.xl *.txt"), ("csv files", "*.csv"), ("FIN2 files", "*.FIN2"),
                       ("xl files", "*.xl"), ("txt files", "*.txt"), ("all files", "*.*")), initialdir=os.getcwd())

        # if "mat" in filename[0]:
        #     mat = scipy.io.loadmat(filename[0])

        for i in filename:
            if i not in var_list:
                var_list.append(i)
                file_parts = i.split("/")
                var_listbox.insert(tk.END, file_parts[-1])
                str_filename_long = i
                str_filename_short = file_parts[-1]

                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_exmpl = DE(filename_long=str_filename_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_exmpl = DE(filename_long=str_filename_long).get_measurements(
                        delimiter=",", skip_header=3, skip_footer=1)

                if "Dataframe" not in self.container_measurements:
                    self.container_measurements["Dataframe"] = {}
                if str_filename_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][str_filename_short] = df_exmpl

                self.times = DE().get_times(dataframe=df_exmpl)
                df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
                self.container_lists["Measured Isotopes"][str_filename_short] = df_isotopes
                file_isotopes = df_isotopes

                self.add_needed_variables_for_later_added_files(
                    filename_long=str_filename_long, filename_short=str_filename_short, filetype=datatype,
                    file_isotopes=file_isotopes)

                if (self.container_icpms["name"] != None and
                        self.container_icpms["name"] not in ["PerkinElmer Syngistix"]):
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    var_timestamp = self.container_icpms["timestamp"]
                    var_icpms = self.container_icpms["name"]

                    dates, times = Data(filename=str_filename_long).import_as_list(
                        skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp,
                        icpms=var_icpms)
                elif self.container_icpms["name"] == "PerkinElmer Syngistix":
                    create_time = os.path.getctime(str_filename_long)
                    create_date = datetime.datetime.fromtimestamp(create_time)
                    times = [[str(create_date.hour), str(create_date.minute), str(create_date.second)]]
                    dates = [str(create_date.year), str(create_date.month), str(create_date.day)]
                else:
                    dates, times = Data(filename=str_filename_long).import_as_list(
                        skip_header=3, skip_footer=1, timestamp=2,
                        icpms="Agilent 7900s")

                if str_filename_short not in self.container_var["acquisition times"][datatype]:
                    self.container_var["acquisition times"][datatype][str_filename_short] = tk.StringVar()
                    self.container_var["acquisition times"][datatype][str_filename_short].set(
                        times[0][0] + ":" + times[0][1] + ":" + times[0][2])

        self.demo_mode = False

    def create_dwell_time_window(self):
        str_title = self.language_dict["Dwell Time Settings"][self.var_language]
        str_lbl_01 = self.language_dict["Dwell times (in s)"][self.var_language]
        str_lbl_02 = self.language_dict["Default settings"][self.var_language]
        ## Window Settings
        window_dwell = tk.Toplevel(self.parent)
        window_dwell.title(str_title)
        window_dwell.geometry("300x450+0+0")
        window_dwell.resizable(False, False)
        window_dwell["bg"] = self.bg_colors["Super Dark"]

        window_width = 300
        window_height = 450
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        for x in range(n_columns):
            tk.Grid.columnconfigure(window_dwell, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(window_dwell, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            window_dwell.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            window_dwell.grid_columnconfigure(i, minsize=column_min)

        ## Labels
        lbl_01 = SE(
            parent=window_dwell, row_id=0, column_id=0, n_rows=1, n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=window_dwell, row_id=1, column_id=0, n_rows=1, n_columns=7, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Dark"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")

        self.container_elements["dwell_times"]["Label"].extend([lbl_01, lbl_02])

        if self.container_var["dwell_times"]["Entry"]["Default"].get() != "0.002":
            var_text = self.container_var["dwell_times"]["Entry"]["Default"].get()
        else:
            var_text = "0.002"

        entr_dwell = SE(
            parent=window_dwell, row_id=1, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["dwell_times"]["Entry"]["Default"], text_default=var_text,
            command=lambda event, var_isotope=None, mode="Default":
            self.change_dwell_times(var_isotope, mode, event))

        self.container_elements["dwell_times"]["Entry"].append(entr_dwell)

        ## TREEVIEWS
        frm_dwell = SE(
            parent=window_dwell, row_id=2, column_id=0, n_rows=15, n_columns=14, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()
        vsb_dwell = ttk.Scrollbar(master=frm_dwell, orient="vertical")
        text_dwell = tk.Text(
            master=frm_dwell, width=30, height=25, yscrollcommand=vsb_dwell.set, bg=self.bg_colors["Very Light"])
        vsb_dwell.config(command=text_dwell.yview)
        vsb_dwell.pack(side="right", fill="y")
        text_dwell.pack(side="left", fill="both", expand=True)

        for var_isotope in self.container_lists["Measured Isotopes"]["All"]:
            lbl_i = tk.Label(
                frm_dwell, text=var_isotope, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_dwell.window_create("end", window=lbl_i)
            text_dwell.insert("end", "\t")

            entr_i = tk.Entry(
                frm_dwell, textvariable=self.container_var["dwell_times"]["Entry"][var_isotope],
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                highlightbackground=self.bg_colors["Very Light"], width=12)
            text_dwell.window_create("insert", window=entr_i)
            text_dwell.insert("end", "\n")

            if var_isotope not in self.container_var["Spike Elimination"]["Threshold"]:
                self.container_var["Spike Elimination"]["Threshold"][var_isotope] = tk.StringVar()

    def change_dwell_times(self, var_isotope, mode, event):
        if mode == "Default":
            value = self.container_var["dwell_times"]["Entry"]["Default"].get()
            for isotope in self.container_lists["ISOTOPES"]:
                self.container_var["dwell_times"]["Entry"][isotope].set(value)
        elif mode == "Specific":
            value = self.container_var["dwell_times"]["Entry"][var_isotope].get()
            self.container_var["dwell_times"]["Entry"][var_isotope].set(value)

    def create_spike_elimination_threshold_window(self):
        """Check-up window to control the spike elimination threshold setup."""
        ## Window Settings
        window_width = 300
        window_height = 600
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_se_threshold = tk.Toplevel(self.parent)
        subwindow_se_threshold.title("Spike Elimination")
        subwindow_se_threshold.geometry(var_geometry)
        subwindow_se_threshold.resizable(False, False)
        subwindow_se_threshold["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_se_threshold, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_se_threshold, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_se_threshold.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_se_threshold.grid_columnconfigure(i, minsize=column_min)

        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]

        var_row_start = 0
        var_column_start = 0
        var_header_n = 14
        int_category_n = 8

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_se_threshold, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Spike Elimination - Threshold Setup", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_01 = SE(
            parent=subwindow_se_threshold, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Default threshold value", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_02 = SE(
            parent=subwindow_se_threshold, row_id=var_row_start + 2, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Isotope-specific threshold value", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        ## ENTRIES
        entr_01 = SE(
            parent=subwindow_se_threshold, row_id=var_row_start + 1, column_id=int_category_n, n_rows=1,
            n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(var=var_threshold, text_default=var_threshold.get())

        ## BUTTONS
        btn_03 = SE(
            parent=subwindow_se_threshold, row_id=n_rows - 2, column_id=var_header_n - int_category_n, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Update values", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="specific": self.calculate_threshold_spike_elimination(mode))

        ## TREEVIEWS
        frm_se_threshold = SE(
            parent=subwindow_se_threshold, row_id=var_row_start + 3, column_id=var_column_start, n_rows=n_rows - 5,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_se_threshold = ttk.Scrollbar(master=frm_se_threshold, orient="vertical")
        text_se_threshold = tk.Text(
            master=frm_se_threshold, width=30, height=25, yscrollcommand=vsb_se_threshold.set,
            bg=self.bg_colors["Very Light"])
        vsb_se_threshold.config(command=text_se_threshold.yview)
        vsb_se_threshold.pack(side="right", fill="y")
        text_se_threshold.pack(side="left", fill="both", expand=True)

        for index, var_isotope in enumerate(self.container_lists["Measured Isotopes"]["All"]):
            if index == 0:
                lbl_i = tk.Label(
                    frm_se_threshold, text="Isotope" + "\t" + "Dwell time" + "\t" + "Threshold",
                    bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
                text_se_threshold.window_create("end", window=lbl_i)
                text_se_threshold.insert("end", "\n")

                lbl_i = tk.Label(
                    frm_se_threshold, text=var_isotope, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
                text_se_threshold.window_create("end", window=lbl_i)
                text_se_threshold.insert("end", "\t")

                if var_isotope not in self.container_var["Spike Elimination"]["Threshold"]:
                    self.container_var["Spike Elimination"]["Threshold"][var_isotope] = tk.StringVar()
                    self.container_var["Spike Elimination"]["Threshold"][var_isotope].set(var_threshold.get())

                entr_i = tk.Entry(
                    frm_se_threshold, textvariable=self.container_var["dwell_times"]["Entry"][var_isotope],
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=self.bg_colors["Very Light"], width=12)
                text_se_threshold.window_create("insert", window=entr_i)
                text_se_threshold.insert("end", "\t")

                entr_i = tk.Entry(
                    frm_se_threshold, textvariable=self.container_var["Spike Elimination"]["Threshold"][var_isotope],
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=self.bg_colors["Very Light"], width=12)
                text_se_threshold.window_create("insert", window=entr_i)
                text_se_threshold.insert("end", "\n")
            else:
                lbl_i = tk.Label(
                    frm_se_threshold, text=var_isotope, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
                text_se_threshold.window_create("end", window=lbl_i)
                text_se_threshold.insert("end", "\t")

                if var_isotope not in self.container_var["Spike Elimination"]["Threshold"]:
                    self.container_var["Spike Elimination"]["Threshold"][var_isotope] = tk.StringVar()
                    self.container_var["Spike Elimination"]["Threshold"][var_isotope].set(var_threshold.get())

                entr_i = tk.Entry(
                    frm_se_threshold, textvariable=self.container_var["dwell_times"]["Entry"][var_isotope],
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=self.bg_colors["Very Light"], width=12)
                text_se_threshold.window_create("insert", window=entr_i)
                text_se_threshold.insert("end", "\t")

                entr_i = tk.Entry(
                    frm_se_threshold, textvariable=self.container_var["Spike Elimination"]["Threshold"][var_isotope],
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=self.bg_colors["Very Light"], width=12)
                text_se_threshold.window_create("insert", window=entr_i)
                text_se_threshold.insert("end", "\n")

    def detect_signal_interval(self, mode="BG"):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        data_interval_detection = {}
        data_calc = {}

        list_files = []
        list_files.extend(self.container_lists["STD"]["Long"])
        if self.pysills_mode == "MA" or mode == "BG":
            list_files.extend(self.container_lists["SMPL"]["Long"])

        for file_long in list_files:
            file_short = file_long.split("/")[-1]
            if self.file_loaded == False:
                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_data = DE(filename_long=file_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_data = DE(filename_long=file_long).get_measurements(
                        delimiter=",", skip_header=3, skip_footer=1)
                dataset_time = list(DE().get_times(dataframe=df_data))
            else:
                if "Time" not in self.container_measurements["RAW"][file_short] and "_copy" in file_short:
                    file_short_original = file_short.replace("_copy", "")
                    self.container_measurements["RAW"][file_short]["Time"] = self.container_measurements["RAW"][
                        file_short_original]["Time"]
                dataset_time = self.container_measurements["RAW"][file_short]["Time"]
                df_data = self.container_measurements["RAW"][file_short]

            condition = False
            index_isotope = 0
            if file_long in self.container_lists["STD"]["Long"]:
                var_srm_file = self.container_var["STD"][file_long]["SRM"].get()
                index = self.container_lists["STD"]["Long"].index(file_long)
                file_short = self.container_lists["STD"]["Short"][index]

                for element, value in sorted(
                        self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                    if element in self.container_lists["Measured Elements"][file_short]:
                        isotope_is = self.container_lists["Measured Elements"][file_short][element][0]
                    break
            else:
                isotope_is = self.container_var["SMPL"][file_long]["IS Data"]["IS"].get()

            if isotope_is == "Select IS":
                file_dummy = file_long
                file_dummy_short = file_dummy.split("/")[-1]
                if self.file_loaded == False:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_data_dummy = DE(filename_long=file_dummy).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_data_dummy = DE(filename_long=file_dummy).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                else:
                    df_data_dummy = self.container_measurements["RAW"][file_dummy_short]

                max_values = {"Last": 0}
                for isotope in list(df_data_dummy.keys())[1:]:
                    dataset_isotope = list(df_data[isotope])
                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        if np.mean(dataset_isotope) > max_values["Last"]:
                            max_values.clear()
                            max_values[isotope] = np.mean(dataset_isotope)
                            max_values["Last"] = np.mean(dataset_isotope)
                    else:
                        if np.median(dataset_isotope) > max_values["Last"]:
                            max_values.clear()
                            max_values[isotope] = np.median(dataset_isotope)
                            max_values["Last"] = np.median(dataset_isotope)

                del max_values["Last"]
                isotope_is = list(max_values.keys())[0]
            else:
                max_values = {"Last": 0}

                for isotope in list(df_data.keys())[1:]:
                    dataset_isotope = list(df_data[isotope])
                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        if np.mean(dataset_isotope) > max_values["Last"]:
                            max_values.clear()
                            max_values[isotope] = np.mean(dataset_isotope)
                            max_values["Last"] = np.mean(dataset_isotope)
                    else:
                        if np.median(dataset_isotope) > max_values["Last"]:
                            max_values.clear()
                            max_values[isotope] = np.median(dataset_isotope)
                            max_values["Last"] = np.median(dataset_isotope)

                del max_values["Last"]
                isotope_is = list(max_values.keys())[0]

            n_loops = 0
            while condition == False:
                n = 0
                if file_short not in data_interval_detection:
                    data_interval_detection[file_short] = {"BG": {"Start": None, "End": None, "Index": None},
                                                           "MAT": {"Start": None, "End": None, "Index": None}}
                    data_calc[file_short] = {"Time": [], "Cumulative Average": [], "Change": [], "Ratio": []}

                dataset_isotope = list(df_data[isotope_is])
                condition_2 = False
                index_2 = 10
                while condition_2 == False:
                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        mean_first10 = np.mean(dataset_isotope[:index_2])
                    else:
                        mean_first10 = np.median(dataset_isotope[:index_2])

                    if mean_first10 > 0:
                        condition_2 = True
                    else:
                        index_2 += 1

                for index, value_time in enumerate(dataset_time):
                    data_calc[file_short]["Time"].append(value_time)

                    if index > 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            value_cumulavg = np.mean(dataset_isotope[:index + 1])
                        else:
                            value_cumulavg = np.median(dataset_isotope[:index + 1])
                        data_calc[file_short]["Cumulative Average"].append(value_cumulavg)
                        value_change = value_cumulavg - data_calc[file_short]["Cumulative Average"][-2]
                        data_calc[file_short]["Change"].append(value_change)
                        value_ratio = value_cumulavg/mean_first10
                        data_calc[file_short]["Ratio"].append(value_ratio)
                    elif index == 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            value_cumulavg = np.mean(dataset_isotope[:index])
                        else:
                            value_cumulavg = np.median(dataset_isotope[:index])
                        data_calc[file_short]["Cumulative Average"].append(value_cumulavg)
                        value_change = value_cumulavg - data_calc[file_short]["Cumulative Average"][0]
                        data_calc[file_short]["Change"].append(value_change)
                        value_ratio = value_cumulavg/mean_first10
                        data_calc[file_short]["Ratio"].append(value_ratio)
                    elif index == 0:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            value_cumulavg = np.mean(dataset_isotope[0])
                        else:
                            value_cumulavg = np.median(dataset_isotope[0])
                        data_calc[file_short]["Cumulative Average"].append(value_cumulavg)
                        value_change = 0.0
                        data_calc[file_short]["Change"].append(value_change)
                        value_ratio = value_cumulavg/mean_first10
                        data_calc[file_short]["Ratio"].append(value_ratio)

                    if value_ratio > 20 and data_interval_detection[file_short]["BG"]["End"] == None:
                        offset_bg_start = self.container_var["General Settings"]["BG Offset Start"].get()
                        offset_bg_end = self.container_var["General Settings"]["BG Offset End"].get()
                        offset_mat_start = self.container_var["General Settings"]["MAT Offset Start"].get()

                        data_interval_detection[file_short]["BG"]["Start"] = dataset_time[offset_bg_start]

                        index_time = dataset_time.index(value_time)
                        data_interval_detection[file_short]["BG"]["End"] = dataset_time[index_time - offset_bg_end]
                        data_interval_detection[file_short]["MAT"]["Start"] = dataset_time[
                            index_time + offset_mat_start]

                        index_start = dataset_time.index(dataset_time[offset_bg_start])
                        index_end = dataset_time.index(dataset_time[index_time - offset_bg_end])
                        data_interval_detection[file_short]["BG"]["Index"] = [index_start, index_end]

                        index_start_mat = dataset_time.index(dataset_time[index_time + offset_mat_start])

                    if value_change < 0 and index > 0.5*len(dataset_time) \
                            and data_interval_detection[file_short]["MAT"]["End"] == None:
                        offset_mat_end = self.container_var["General Settings"]["MAT Offset End"].get()

                        index_time = dataset_time.index(value_time)
                        data_interval_detection[file_short]["MAT"]["End"] = dataset_time[index_time - offset_mat_end]

                        index_end = dataset_time.index(dataset_time[index_time - offset_mat_end])
                        data_interval_detection[file_short]["MAT"]["Index"] = [index_start_mat, index_end]

                for key1, value1 in data_interval_detection[file_short].items():
                    if key1 == mode:
                        for key2, value2 in value1.items():
                            if value2 != None:
                                n += 1

                if n == 3:
                    condition = True
                else:
                    index_isotope += 1

                n_loops += 1

                if n_loops == 100:
                    break

        if mode == "BG":
            if self.pysills_mode == "MA":
                self.container_var[key_setting]["Time BG Start"].set("auto-detection used")
                self.container_var[key_setting]["Time BG End"].set("auto-detection used")
            else:
                if self.pysills_mode == "FI":
                    self.container_var[key_setting]["Time BG Start"].set("auto-detection used")
                    self.container_var[key_setting]["Time BG End"].set("auto-detection used")
                else:
                    if n_loops == 100:
                        self.container_var[key_setting]["Time BG Start"].set("auto-detection not successful")
                        self.container_var[key_setting]["Time BG End"].set("auto-detection not successful")
                    else:
                        self.container_var[key_setting]["Time BG Start"].set("auto-detection used")
                        self.container_var[key_setting]["Time BG End"].set("auto-detection used")

            self.autodetection_bg = True
        elif mode == "MAT":
            if self.pysills_mode == "MA":
                self.container_var[key_setting]["Time MAT Start"].set("auto-detection used")
                self.container_var[key_setting]["Time MAT End"].set("auto-detection used")
            elif self.pysills_mode == "FI":
                self.container_var[key_setting]["Time MAT Start"].set("auto-detection used")
                self.container_var[key_setting]["Time MAT End"].set("auto-detection used")
            elif self.pysills_mode == "MI":
                self.container_var[key_setting]["Time MAT Start"].set("auto-detection used")
                self.container_var[key_setting]["Time MAT End"].set("auto-detection used")

            self.autodetection_sig = True

        if n_loops < 1000:
            for filename, dataset in data_interval_detection.items():
                if filename in self.container_lists["STD"]["Short"]:
                    filetype = "STD"

                    if self.pysills_mode == "MA":
                        self.temp_lines_checkup2[filetype][filename] = 0
                elif filename in self.container_lists["SMPL"]["Short"]:
                    filetype = "SMPL"

                    if self.pysills_mode == "MA":
                        self.temp_lines_checkup2[filetype][filename] = 0

                var_index = self.container_lists[filetype]["Short"].index(filename)
                filename_long = self.container_lists[filetype]["Long"][var_index]

                t_start = dataset[mode]["Start"]
                t_end = dataset[mode]["End"]
                index_start = dataset[mode]["Index"][0]
                index_end = dataset[mode]["Index"][1]

                self.container_helper[filetype][filename][mode]["Content"][1] = {
                    "Times": [t_start, t_end], "Indices": [index_start, index_end], "Object": None}
                self.container_helper[filetype][filename][mode]["ID"] += 1
                self.container_helper[filetype][filename][mode]["Indices"].append(1)

                self.container_var[filetype][filename_long]["Frame"].config(background=self.sign_yellow, bd=1)
                self.container_var[filetype][filename_long]["Sign Color"].set(self.sign_yellow)

                if self.pysills_mode == "MA":
                    self.temp_lines_checkup2[filetype][filename] = 0
                    self.show_time_signal_diagram_checker(var_setting_key=key_setting)
                elif self.pysills_mode == "FI":
                    self.temp_lines_checkup2[filetype][filename] = 0
                    self.show_time_signal_diagram_checker(var_setting_key=key_setting)
                elif self.pysills_mode == "MI":
                    self.temp_lines_checkup2[filetype][filename] = 0
                    self.show_time_signal_diagram_checker(var_setting_key=key_setting)

    def checkup_oxides(self):
        """Check-up window to control the 100 wt.% oxides setup."""
        ## Window Settings
        window_width = 1660
        window_height = 725
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_checkup_oxides = tk.Toplevel(self.parent)
        subwindow_checkup_oxides.title("Check-Up - 100 wt.% oxides")
        subwindow_checkup_oxides.geometry(var_geometry)
        subwindow_checkup_oxides.resizable(False, False)
        subwindow_checkup_oxides["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_checkup_oxides, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_checkup_oxides, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_checkup_oxides.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_checkup_oxides.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 10
        int_category_n = 8

        ## FRAMES
        frm_01 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 1, column_id=var_column_start, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_02 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 1, column_id=var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_03 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 1, column_id=2*var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_04 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 1, column_id=3*var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_05 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 1, column_id=4*var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_06 = SE(
            parent=subwindow_checkup_oxides, row_id=15, column_id=var_column_start, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_07 = SE(
            parent=subwindow_checkup_oxides, row_id=15, column_id=var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_08 = SE(
            parent=subwindow_checkup_oxides, row_id=15, column_id=2*var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_09 = SE(
            parent=subwindow_checkup_oxides, row_id=15, column_id=3*var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_10 = SE(
            parent=subwindow_checkup_oxides, row_id=15, column_id=4*var_header_n, n_rows=12,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        frm_11 = SE(
            parent=subwindow_checkup_oxides, row_id=13, column_id=var_column_start, n_rows=1,
            n_columns=5*var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_12 = SE(
            parent=subwindow_checkup_oxides, row_id=27, column_id=var_column_start, n_rows=1,
            n_columns=5*var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_13 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 15, column_id=5*var_header_n + 1, n_rows=3,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_14 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 2, column_id=5*var_header_n + 1, n_rows=2,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_15 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 5, column_id=5*var_header_n + 1, n_rows=2,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_16 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 9, column_id=5*var_header_n + 1, n_rows=2,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_17 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 2,
            column_id=5*var_header_n + int(1.5*var_header_n) + 2, n_rows=11, n_columns=int(1.5*var_header_n),
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(relief=tk.FLAT)
        frm_18 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 15,
            column_id=5*var_header_n + int(1.5*var_header_n) + 2, n_rows=11, n_columns=int(1.5*var_header_n),
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(relief=tk.FLAT)

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Alkali metals", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_02 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start, column_id=var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Alkaline earth metals", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_03 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start, column_id=2*var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Transition metals", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_04 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start, column_id=3*var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Other metals", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_05 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start, column_id=4*var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Metalloids", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_06 = SE(
            parent=subwindow_checkup_oxides, row_id=14, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Lanthanides", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_07 = SE(
            parent=subwindow_checkup_oxides, row_id=14, column_id=var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Actinides", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_08 = SE(
            parent=subwindow_checkup_oxides, row_id=14, column_id=2*var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Non-metals", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_09 = SE(
            parent=subwindow_checkup_oxides, row_id=14, column_id=3*var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Halogens", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_10 = SE(
            parent=subwindow_checkup_oxides, row_id=14, column_id=4*var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Noble gases", relief=tk.FLAT, fontsize="sans 12 bold")
        lbl_11 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Setup - Oxide ratios", relief=tk.FLAT, fontsize="sans 12 bold", anchor=tk.W)
        lbl_11a = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 1, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Matrix/Sample", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_11b = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 2, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="FeO/(FeO + Fe2O3)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_11c = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 3, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="MnO/(MnO + Mn2O3)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_11d = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 4, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Inclusion", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_11e = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 5, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="FeO/(FeO + Fe2O3)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_11f = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 6, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="MnO/(MnO + Mn2O3)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_12 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 8, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Setup - Reference element", relief=tk.FLAT, fontsize="sans 12 bold", anchor=tk.W)
        lbl_12a = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 9, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Matrix quantification", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_12b = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 10, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Inclusion quantification", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_13 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 12, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Setup - Oxide selection", relief=tk.FLAT, fontsize="sans 12 bold", anchor=tk.W)
        lbl_13a = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 13, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Select all oxides", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_13b = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 14, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Deselect all oxides", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_13c = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 15, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Rock-forming elements", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_13d = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 16, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Guess the composition", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_14 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start, column_id=5*var_header_n + int(1.5*var_header_n) + 2,
            n_rows=1, n_columns=int(1.5*var_header_n), fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Setup - Files", relief=tk.FLAT, fontsize="sans 12 bold", anchor=tk.W)
        lbl_14a = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 1,
            column_id=5*var_header_n + int(1.5*var_header_n) + 2, n_rows=1, n_columns=int_category_n,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Matrix/Sample", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_14b = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 14,
            column_id=5*var_header_n + int(1.5*var_header_n) + 2, n_rows=1, n_columns=int_category_n,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Inclusion", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_15 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 17, column_id=5*var_header_n + 1, n_rows=1,
            n_columns=int(1.5*var_header_n), fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Run 100 wt.% oxides calculation for", relief=tk.FLAT, fontsize="sans 12 bold", anchor=tk.W)

        ## BUTTONS
        btn_01 = SE(
            parent=subwindow_checkup_oxides, row_id=13, column_id=int(0.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_02 = SE(
            parent=subwindow_checkup_oxides, row_id=13, column_id=int(1.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_03 = SE(
            parent=subwindow_checkup_oxides, row_id=13, column_id=int(2.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_04 = SE(
            parent=subwindow_checkup_oxides, row_id=13, column_id=int(3.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_05 = SE(
            parent=subwindow_checkup_oxides, row_id=13, column_id=int(4.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_06 = SE(
            parent=subwindow_checkup_oxides, row_id=27, column_id=int(0.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_07 = SE(
            parent=subwindow_checkup_oxides, row_id=27, column_id=int(1.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_08 = SE(
            parent=subwindow_checkup_oxides, row_id=27, column_id=int(2.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_09 = SE(
            parent=subwindow_checkup_oxides, row_id=27, column_id=int(3.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_10 = SE(
            parent=subwindow_checkup_oxides, row_id=27, column_id=int(4.5*var_header_n), n_rows=1,
            n_columns=int(0.5*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select all", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_13a = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 13, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Run", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.select_all_oxides)
        btn_13b = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 14, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Run", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.deselect_all_oxides)
        btn_13c = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 15, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Select", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.select_main_rockforming_elements)
        btn_13d = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 16, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Run", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_13d.configure(state="disabled")

        ## ENTRIES
        var_entr_mat_fe = self.container_var["Oxides Quantification"]["Ratios"]["Fe-Ratio"]
        var_entr_mat_mn = self.container_var["Oxides Quantification"]["Ratios"]["Mn-Ratio"]
        var_entr_incl_fe = self.container_var["Oxides Quantification INCL"]["Ratios"]["Fe-Ratio"]
        var_entr_incl_mn = self.container_var["Oxides Quantification INCL"]["Ratios"]["Mn-Ratio"]

        entr_mat_fe = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 2, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_mat_fe, text_default=var_entr_mat_fe.get())
        entr_mat_mn = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 3, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_mat_mn, text_default=var_entr_mat_mn.get())

        entr_incl_fe = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 5, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_incl_fe, text_default=var_entr_incl_fe.get())
        entr_incl_mn = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 6, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_incl_mn, text_default=var_entr_incl_mn.get())

        if self.pysills_mode in ["MA", "FI"]:
            entr_incl_fe.configure(state="disabled")
            entr_incl_mn.configure(state="disabled")

        ## TREEVIEWS
        list_mat_isotopes = self.container_lists["Measured Isotopes"]["All"].copy()
        list_incl_isotopes = self.container_lists["Measured Isotopes"]["All"].copy()
        # File setup (matrix/sample)
        vsb_17 = ttk.Scrollbar(master=frm_17, orient="vertical")
        text_17 = tk.Text(
            master=frm_17, width=30, height=25, yscrollcommand=vsb_17.set, bg=self.bg_colors["Very Light"])
        vsb_17.config(command=text_17.yview)
        vsb_17.pack(side="right", fill="y")
        text_17.pack(side="left", fill="both", expand=True)

        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_17, text=filename_short, bg=self.bg_colors["Very Light"],
                             fg=self.bg_colors["Dark Font"])
            text_17.window_create("end", window=lbl_i)
            text_17.insert("end", "\t")

            if filename_short not in self.container_var["Oxides Quantification"]["Total Amounts"]:
                self.container_var["Oxides Quantification"]["Total Amounts"][filename_short] = tk.StringVar()
                self.container_var["Oxides Quantification"]["Total Amounts"][filename_short].set("100.0")

            entr_i = tk.Entry(
                frm_17, textvariable=self.container_var["Oxides Quantification"]["Total Amounts"][filename_short],
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                highlightbackground=self.bg_colors["Very Light"], width=6)
            text_17.window_create("insert", window=entr_i)
            text_17.insert("end", "\t")

            if self.pysills_mode == "MA":
                var_opt_ref_i = self.container_var["SMPL"][filename_long]["IS Data"]["IS"]
            else:
                var_opt_ref_i = self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Name"]

            opt_ref_i = tk.OptionMenu(frm_17, var_opt_ref_i, *list_mat_isotopes)
            opt_ref_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_ref_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)
            text_17.window_create("end", window=opt_ref_i)
            text_17.insert("end", " \n")

        # File setup (inclusion)
        vsb_18 = ttk.Scrollbar(master=frm_18, orient="vertical")
        text_18 = tk.Text(
            master=frm_18, width=30, height=25, yscrollcommand=vsb_18.set, bg=self.bg_colors["Very Light"])
        vsb_18.config(command=text_18.yview)
        vsb_18.pack(side="right", fill="y")
        text_18.pack(side="left", fill="both", expand=True)

        if self.pysills_mode == "MI":
            for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
                filename_long = self.container_lists["SMPL"]["Long"][index]
                lbl_i = tk.Label(frm_18, text=filename_short, bg=self.bg_colors["Very Light"],
                                 fg=self.bg_colors["Dark Font"])
                text_18.window_create("end", window=lbl_i)
                text_18.insert("end", "\t")

                if filename_short not in self.container_var["Oxides Quantification INCL"]["Total Amounts"]:
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][filename_short] = tk.StringVar()
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][filename_short].set("100.0")

                entr_i = tk.Entry(
                    frm_18, textvariable=self.container_var["Oxides Quantification INCL"]["Total Amounts"][
                        filename_short], fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"], width=6)

                text_18.window_create("insert", window=entr_i)
                text_18.insert("end", "\t")

                var_opt_ref_i = self.container_var["SMPL"][filename_long]["IS Data"]["IS"]

                opt_ref_i = tk.OptionMenu(frm_18, var_opt_ref_i, *list_mat_isotopes)
                opt_ref_i["menu"].config(
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                    activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
                opt_ref_i.config(
                    bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                    activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                    highlightthickness=0)
                text_18.window_create("end", window=opt_ref_i)
                text_18.insert("end", " \n")

        list_major_oxides = [
            "SiO2", "Al2O3", "FeO", "Fe2O3", "CaO", "Na2O", "MgO", "K2O", "TiO2", "P2O5", "MnO", "Mn2O3", "SO3"]
        # Alkali metals
        vsb_01 = ttk.Scrollbar(master=frm_01, orient="vertical")
        text_01 = tk.Text(
            master=frm_01, width=30, height=25, yscrollcommand=vsb_01.set, bg=self.bg_colors["Very Light"])
        vsb_01.config(command=text_01.yview)
        vsb_01.pack(side="right", fill="y")
        text_01.pack(side="left", fill="both", expand=True)
        counter_01 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["Li", "Na", "K", "Rb", "Cs", "Fr"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]

                    cb_i = tk.Checkbutton(
                        master=frm_01, text=oxide, fg=self.bg_colors["Dark Font"],
                        bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                    text_01.window_create("end", window=cb_i)
                    text_01.insert("end", "\n")
                    counter_01 += 1
                    if element not in self.container_lists["Possible Oxides"]:
                        self.container_lists["Possible Oxides"][element] = []

                    if oxide not in self.container_lists["Possible Oxides"]["All"]:
                        self.container_lists["Possible Oxides"]["All"].append(oxide)
                    if oxide not in self.container_lists["Possible Oxides"][element]:
                        self.container_lists["Possible Oxides"][element].append(oxide)

        # Alkaline earth metals
        vsb_02 = ttk.Scrollbar(master=frm_02, orient="vertical")
        text_02 = tk.Text(
            master=frm_02, width=30, height=25, yscrollcommand=vsb_02.set, bg=self.bg_colors["Very Light"])
        vsb_02.config(command=text_02.yview)
        vsb_02.pack(side="right", fill="y")
        text_02.pack(side="left", fill="both", expand=True)
        counter_02 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["Be", "Mg", "Ca", "Sr", "Ba", "Ra"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]

                    cb_i = tk.Checkbutton(
                        master=frm_02, text=oxide, fg=self.bg_colors["Dark Font"],
                        bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                    text_02.window_create("end", window=cb_i)
                    text_02.insert("end", "\n")
                    counter_02 += 1
                    if element not in self.container_lists["Possible Oxides"]:
                        self.container_lists["Possible Oxides"][element] = []

                    if oxide not in self.container_lists["Possible Oxides"]["All"]:
                        self.container_lists["Possible Oxides"]["All"].append(oxide)
                    if oxide not in self.container_lists["Possible Oxides"][element]:
                        self.container_lists["Possible Oxides"][element].append(oxide)

        # Transition metals
        vsb_03 = ttk.Scrollbar(master=frm_03, orient="vertical")
        text_03 = tk.Text(
            master=frm_03, width=30, height=25, yscrollcommand=vsb_03.set, bg=self.bg_colors["Very Light"])
        vsb_03.config(command=text_03.yview)
        vsb_03.pack(side="right", fill="y")
        text_03.pack(side="left", fill="both", expand=True)
        counter_03 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Y", "Zr", "Nb", "Mo", "Tc", "Ru",
                           "Rh", "Pd", "Ag", "Cd", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Rf", "Db",
                           "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_03, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_03.window_create("end", window=cb_i)
                        text_03.insert("end", "\n")
                        counter_03 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        # Other metals
        vsb_04 = ttk.Scrollbar(master=frm_04, orient="vertical")
        text_04 = tk.Text(
            master=frm_04, width=30, height=25, yscrollcommand=vsb_04.set, bg=self.bg_colors["Very Light"])
        vsb_04.config(command=text_04.yview)
        vsb_04.pack(side="right", fill="y")
        text_04.pack(side="left", fill="both", expand=True)
        counter_04 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["Al", "Ga", "In", "Sn", "Tl", "Pb", "Bi", "Nh", "Fl", "Mc", "Lv"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_04, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_04.window_create("end", window=cb_i)
                        text_04.insert("end", "\n")
                        counter_04 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        # Metalloids
        vsb_05 = ttk.Scrollbar(master=frm_05, orient="vertical")
        text_05 = tk.Text(
            master=frm_05, width=30, height=25, yscrollcommand=vsb_05.set, bg=self.bg_colors["Very Light"])
        vsb_05.config(command=text_05.yview)
        vsb_05.pack(side="right", fill="y")
        text_05.pack(side="left", fill="both", expand=True)
        counter_05 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["B", "Si", "Ge", "As", "Sb", "Te", "Po"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_05, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_05.window_create("end", window=cb_i)
                        text_05.insert("end", "\n")
                        counter_05 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        # Lanthanides
        vsb_06 = ttk.Scrollbar(master=frm_06, orient="vertical")
        text_06 = tk.Text(
            master=frm_06, width=30, height=25, yscrollcommand=vsb_06.set, bg=self.bg_colors["Very Light"])
        vsb_06.config(command=text_06.yview)
        vsb_06.pack(side="right", fill="y")
        text_06.pack(side="left", fill="both", expand=True)
        counter_06 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_06, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_06.window_create("end", window=cb_i)
                        text_06.insert("end", "\n")
                        counter_06 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        # Actinides
        vsb_07 = ttk.Scrollbar(master=frm_07, orient="vertical")
        text_07 = tk.Text(
            master=frm_07, width=30, height=25, yscrollcommand=vsb_07.set, bg=self.bg_colors["Very Light"])
        vsb_07.config(command=text_07.yview)
        vsb_07.pack(side="right", fill="y")
        text_07.pack(side="left", fill="both", expand=True)
        counter_07 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_07, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_07.window_create("end", window=cb_i)
                        text_07.insert("end", "\n")
                        counter_07 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        # Non-metals
        vsb_08 = ttk.Scrollbar(master=frm_08, orient="vertical")
        text_08 = tk.Text(
            master=frm_08, width=30, height=25, yscrollcommand=vsb_08.set, bg=self.bg_colors["Very Light"])
        vsb_08.config(command=text_08.yview)
        vsb_08.pack(side="right", fill="y")
        text_08.pack(side="left", fill="both", expand=True)
        counter_08 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["H", "C", "N", "O", "P", "S", "Se"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_08, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_08.window_create("end", window=cb_i)
                        text_08.insert("end", "\n")
                        counter_08 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        # Halogens
        vsb_09 = ttk.Scrollbar(master=frm_09, orient="vertical")
        text_09 = tk.Text(
            master=frm_09, width=30, height=25, yscrollcommand=vsb_09.set, bg=self.bg_colors["Very Light"])
        vsb_09.config(command=text_09.yview)
        vsb_09.pack(side="right", fill="y")
        text_09.pack(side="left", fill="both", expand=True)
        counter_09 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["F", "Cl", "Br", "I", "At", "Ts"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_09, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_09.window_create("end", window=cb_i)
                        text_09.insert("end", "\n")
                        counter_09 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        # Noble gases
        vsb_10 = ttk.Scrollbar(master=frm_10, orient="vertical")
        text_10 = tk.Text(
            master=frm_10, width=30, height=25, yscrollcommand=vsb_10.set, bg=self.bg_colors["Very Light"])
        vsb_10.config(command=text_10.yview)
        vsb_10.pack(side="right", fill="y")
        text_10.pack(side="left", fill="both", expand=True)
        counter_10 = 0
        for index, element in enumerate(self.container_lists["Measured Elements"]["All"]):
            if element in ["He", "Ne", "Ar", "Kr", "Xe", "Rn", "Og"]:
                for oxide in self.chemistry_oxides_sorted[element]:
                    bool_problem = False
                    if oxide in list_major_oxides:
                        var_cb = self.container_var["Oxides Quantification"]["Major"][oxide]
                    else:
                        if oxide in self.container_var["Oxides Quantification"]["Minor"]:
                            var_cb = self.container_var["Oxides Quantification"]["Minor"][oxide]
                        else:
                            bool_problem = True

                    if bool_problem == False:
                        cb_i = tk.Checkbutton(
                            master=frm_10, text=oxide, fg=self.bg_colors["Dark Font"],
                            bg=self.bg_colors["Very Light"], variable=var_cb,
                            command=lambda var_checkbox=var_cb, key_oxide=oxide:
                            self.select_oxide2(var_checkbox, key_oxide))
                        text_10.window_create("end", window=cb_i)
                        text_10.insert("end", "\n")
                        counter_10 += 1
                        if element not in self.container_lists["Possible Oxides"]:
                            self.container_lists["Possible Oxides"][element] = []

                        if oxide not in self.container_lists["Possible Oxides"]["All"]:
                            self.container_lists["Possible Oxides"]["All"].append(oxide)
                        if oxide not in self.container_lists["Possible Oxides"][element]:
                            self.container_lists["Possible Oxides"][element].append(oxide)

        if counter_01 == 0:
            btn_01.configure(state="disabled")
        if counter_02 == 0:
            btn_02.configure(state="disabled")
        if counter_03 == 0:
            btn_03.configure(state="disabled")
        if counter_04 == 0:
            btn_04.configure(state="disabled")
        if counter_05 == 0:
            btn_05.configure(state="disabled")
        if counter_06 == 0:
            btn_06.configure(state="disabled")
        if counter_07 == 0:
            btn_07.configure(state="disabled")
        if counter_08 == 0:
            btn_08.configure(state="disabled")
        if counter_09 == 0:
            btn_09.configure(state="disabled")
        if counter_10 == 0:
            btn_10.configure(state="disabled")

        ## OPTION MENUS
        var_opt_mat_isotope = tk.StringVar()
        var_opt_mat_isotope.set("Select isotope")
        var_opt_incl_isotope = tk.StringVar()
        var_opt_incl_isotope.set("Select isotope")

        opt_mat_isotope = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 9, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=var_opt_mat_isotope, option_list=list_mat_isotopes, text_set=var_opt_mat_isotope.get(),
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=var_opt_incl_isotope, mode="MAT": self.select_reference_isotope(var_opt, mode))
        opt_mat_isotope["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_mat_isotope.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        opt_incl_isotope = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 10, column_id=5*var_header_n + 1 + int_category_n,
            n_rows=1, n_columns=int(0.75*var_header_n), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=var_opt_incl_isotope, option_list=list_incl_isotopes, text_set=var_opt_incl_isotope.get(),
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=var_opt_incl_isotope, mode="INCL": self.select_reference_isotope(var_opt, mode))
        opt_incl_isotope["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_incl_isotope.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        if self.pysills_mode in ["MA", "FI"]:
            opt_incl_isotope.configure(state="disabled")

        ## CHECKBOXES
        cb_01 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 18, column_id=5*var_header_n + 1,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=int(1.5*var_header_n),
            bg=self.bg_colors["Light"]).create_simple_checkbox(
            var_cb=self.oxide_calculation_mat, text="Matrix/Sample", set_sticky="nesw", own_color=True)
        cb_02 = SE(
            parent=subwindow_checkup_oxides, row_id=var_row_start + 19, column_id=5*var_header_n + 1,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=int(1.5*var_header_n),
            bg=self.bg_colors["Light"]).create_simple_checkbox(
            var_cb=self.oxide_calculation_incl, text="Inclusion", set_sticky="nesw", own_color=True)

        if self.pysills_mode in ["MA", "FI"]:
            cb_02.configure(state="disabled")

    def select_oxide2(self, var_checkbox, key_oxide):
        if var_checkbox.get() == 1:
            if key_oxide not in self.container_lists["Selected Oxides"]["All"]:
                self.container_lists["Selected Oxides"]["All"].append(key_oxide)
        else:
            if key_oxide in self.container_lists["Selected Oxides"]["All"]:
                self.container_lists["Selected Oxides"]["All"].remove(key_oxide)

    def select_main_rockforming_elements(self):
        list_oxides = ["SiO2", "TiO2", "Al2O3", "Fe2O3", "FeO", "Mn2O3", "MnO", "MgO", "CaO", "Na2O", "K2O", "P2O5"]
        self.container_lists["Selected Oxides"]["All"].clear()
        for oxide, variable in self.container_var["Oxides Quantification"]["Major"].items():
            if oxide in list_oxides and oxide in self.container_lists["Possible Oxides"]["All"]:
                variable.set(1)
                if oxide not in self.container_lists["Selected Oxides"]["All"]:
                    self.container_lists["Selected Oxides"]["All"].append(oxide)
        for oxide, variable in self.container_var["Oxides Quantification"]["Minor"].items():
            if oxide in list_oxides and oxide in self.container_lists["Possible Oxides"]["All"]:
                variable.set(1)
                if oxide not in self.container_lists["Selected Oxides"]["All"]:
                    self.container_lists["Selected Oxides"]["All"].append(oxide)

    def select_reference_isotope(self, var_opt, mode="MAT"):
        for index, filename_long in enumerate(self.container_lists["SMPL"]["Long"]):
            if mode == "MAT":
                if self.pysills_mode == "MA":
                    self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set(var_opt)
                else:
                    self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Name"].set(var_opt)
            else:
                self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set(var_opt)

    def select_all_oxides(self):
        self.container_lists["Selected Oxides"]["All"].clear()
        for oxide, variable in self.container_var["Oxides Quantification"]["Major"].items():
            if oxide in self.container_lists["Possible Oxides"]["All"]:
                variable.set(1)
                if oxide not in self.container_lists["Selected Oxides"]["All"]:
                    self.container_lists["Selected Oxides"]["All"].append(oxide)
        for oxide, variable in self.container_var["Oxides Quantification"]["Minor"].items():
            if oxide in self.container_lists["Possible Oxides"]["All"]:
                variable.set(1)
                if oxide not in self.container_lists["Selected Oxides"]["All"]:
                    self.container_lists["Selected Oxides"]["All"].append(oxide)

    def deselect_all_oxides(self):
        self.container_lists["Selected Oxides"]["All"].clear()
        for oxide, variable in self.container_var["Oxides Quantification"]["Major"].items():
            if oxide in self.container_lists["Possible Oxides"]["All"]:
                variable.set(0)
        for oxide, variable in self.container_var["Oxides Quantification"]["Minor"].items():
            if oxide in self.container_lists["Possible Oxides"]["All"]:
                variable.set(0)

    def checkup_internal_standard(self):
        """Check-up window to control the internal standard setup."""
        ## Window Settings
        window_width = 840
        window_height = 400
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_checkup_is = tk.Toplevel(self.parent)
        subwindow_checkup_is.title("Check-Up - Internal standard")
        subwindow_checkup_is.geometry(var_geometry)
        subwindow_checkup_is.resizable(False, False)
        subwindow_checkup_is["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_checkup_is, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_checkup_is, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_checkup_is.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_checkup_is.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 20
        int_category_n = 6

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_checkup_is, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Internal standard (sample/matrix)", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_checkup_is, row_id=var_row_start, column_id=var_header_n + 1, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Internal standard (inclusion)", relief=tk.FLAT, fontsize="sans 10 bold")

        ## TREEVIEWS
        list_is_mat = self.container_lists["Measured Isotopes"]["All"]
        list_is_incl = self.container_lists["Measured Isotopes"]["All"]

        frm_mat = SE(
            parent=subwindow_checkup_is, row_id=var_row_start + 1, column_id=var_column_start, n_rows=n_rows - 3,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_mat = ttk.Scrollbar(master=frm_mat, orient="vertical")
        text_mat = tk.Text(
            master=frm_mat, width=30, height=25, yscrollcommand=vsb_mat.set, bg=self.bg_colors["Very Light"])
        vsb_mat.config(command=text_mat.yview)
        vsb_mat.pack(side="right", fill="y")
        text_mat.pack(side="left", fill="both", expand=True)

        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(
                frm_mat, text=filename_short, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_mat.window_create("end", window=lbl_i)
            text_mat.insert("end", "\t")

            if self.pysills_mode == "MA":
                var_opt_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"]
                var_entr_is = self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"]
            else:
                var_opt_is = self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Name"]
                var_entr_is = self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Concentration"]

            opt_is_i = tk.OptionMenu(
                frm_mat, var_opt_is, *list_is_mat)
            opt_is_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_is_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
            text_mat.window_create("end", window=opt_is_i)
            text_mat.insert("end", "\t")

            var_opt_is_mat_i = tk.StringVar()
            var_entr_is_mat_i = tk.StringVar()
            var_opt_is_mat_i.set("Select isotope")
            var_entr_is_mat_i.set("0.0")

            entr_i = tk.Entry(
                frm_mat, textvariable=var_entr_is, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"],
                highlightthickness=0, highlightbackground=self.bg_colors["Very Light"], width=12)
            text_mat.window_create("insert", window=entr_i)
            text_mat.insert("end", "\n")

        frm_incl = SE(
            parent=subwindow_checkup_is, row_id=var_row_start + 1, column_id=var_header_n + 1, n_rows=n_rows - 3,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_incl = ttk.Scrollbar(master=frm_incl, orient="vertical")
        text_incl = tk.Text(
            master=frm_incl, width=30, height=25, yscrollcommand=vsb_incl.set, bg=self.bg_colors["Very Light"])
        vsb_incl.config(command=text_incl.yview)
        vsb_incl.pack(side="right", fill="y")
        text_incl.pack(side="left", fill="both", expand=True)

        if self.pysills_mode != "MA":
            for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
                filename_long = self.container_lists["SMPL"]["Long"][index]
                lbl_i = tk.Label(
                    frm_incl, text=filename_short, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
                text_incl.window_create("end", window=lbl_i)
                text_incl.insert("end", "\t")

                var_opt_is_incl_i = tk.StringVar()
                var_entr_is_incl_i = tk.StringVar()
                var_opt_is_incl_i.set("Select isotope")
                var_entr_is_incl_i.set("0.0")

                opt_is_i = tk.OptionMenu(
                    frm_incl, self.container_var["SMPL"][filename_long]["IS Data"]["IS"], *list_is_incl)
                opt_is_i["menu"].config(
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                    activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
                opt_is_i.config(
                    bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                    activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
                text_incl.window_create("end", window=opt_is_i)
                text_incl.insert("end", "\t")

                entr_i = tk.Entry(
                    frm_incl, textvariable=self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"],
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=self.bg_colors["Very Light"], width=12)
                text_incl.window_create("insert", window=entr_i)
                text_incl.insert("end", "\n")

        ## OPTION MENUS
        self.var_opt_is_mat_default = tk.StringVar()
        self.var_opt_is_incl_default = tk.StringVar()
        self.var_opt_is_mat_default.set("Select isotope")
        self.var_opt_is_incl_default.set("Select isotope")

        opt_is_mat = SE(
            parent=subwindow_checkup_is, row_id=n_rows - 2, column_id=var_header_n - 2*int_category_n, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.var_opt_is_mat_default, option_list=list_is_mat, text_set=self.var_opt_is_mat_default.get(),
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.var_opt_is_mat_default: self.change_default_is(var_opt))
        opt_is_mat["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_is_mat.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        if self.pysills_mode != "MA":
            opt_is_incl = SE(
                parent=subwindow_checkup_is, row_id=n_rows - 2, column_id=2*var_header_n + 1 - 2*int_category_n,
                n_rows=1, n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_option_isotope(
                var_iso=self.var_opt_is_incl_default, option_list=list_is_incl,
                text_set=self.var_opt_is_incl_default.get(), fg_active=self.bg_colors["Dark Font"],
                bg_active=self.accent_color,
                command=lambda var_opt=self.var_opt_is_mat_default, mode="INCL": self.change_default_is(var_opt, mode))
            opt_is_incl["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            opt_is_incl.config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, highlightthickness=0)

        ## ENTRIES
        self.var_entr_is_mat_default = tk.StringVar()
        self.var_entr_is_incl_default = tk.StringVar()
        self.var_entr_is_mat_default.set("0.0")
        self.var_entr_is_incl_default.set("0.0")

        entr_is_mat = SE(
            parent=subwindow_checkup_is, row_id=n_rows - 2, column_id=var_header_n - int_category_n, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.var_entr_is_mat_default, text_default=self.var_entr_is_mat_default.get())
        entr_is_mat.bind(
            "<Return>", lambda event, var_entr=self.var_entr_is_mat_default, mode="MAT":
            self.change_default_is_value(var_entr, mode, event))

        if self.pysills_mode != "MA":
            entr_is_incl = SE(
                parent=subwindow_checkup_is, row_id=n_rows - 2, column_id=2*var_header_n + 1 - int_category_n, n_rows=1,
                n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["White"]).create_simple_entry(
                var=self.var_entr_is_incl_default, text_default=self.var_entr_is_incl_default.get())
            entr_is_incl.bind(
                "<Return>", lambda event, var_entr=self.var_entr_is_incl_default, mode="INCL":
                self.change_default_is_value(var_entr, mode, event))

        ## INITIALIZATION
        try:
            self.srm_isotopes
        except:
            self.srm_isotopes = {}
            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                self.srm_isotopes[isotope] = {}
                var_srm = self.container_var["SRM"][isotope].get()
                key_element = re.search(r"(\D+)(\d+)", isotope)
                var_element = key_element.group(1)
                self.srm_isotopes[isotope]["SRM"] = var_srm
                if var_element in self.srm_actual[var_srm]:
                    self.srm_isotopes[isotope]["Concentration"] = self.srm_actual[var_srm][var_element]
                else:
                    self.srm_isotopes[isotope]["Concentration"] = 0.0

    def change_default_is(self, var_opt, mode="MAT"):
        if mode == "MAT":
            for index, filename_long in enumerate(self.container_lists["SMPL"]["Long"]):
                if self.pysills_mode == "MA":
                    self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set(var_opt)
                else:
                    self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Name"].set(var_opt)
        else:
            for index, filename_long in enumerate(self.container_lists["SMPL"]["Long"]):
                self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set(var_opt)

    def change_default_is_value(self, var_entr, mode, event):
        val_entr = var_entr.get()
        if mode == "MAT":
            for index, filename_long in enumerate(self.container_lists["SMPL"]["Long"]):
                if self.pysills_mode == "MA":
                    self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].set(val_entr)
                else:
                    self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Concentration"].set(val_entr)
        else:
            for index, filename_long in enumerate(self.container_lists["SMPL"]["Long"]):
                self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].set(val_entr)

    def change_is_value_default(self, var_entr, event):
        for file_smpl in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].set(var_entr.get())

    def change_is_setup(self, var_is, var_file=None, mode="Default"):
        if mode == "Default":
            try:
                value_is = self.mineral_chem["Unknown"][var_is]
            except:
                value_is = 0.0

            self.container_var["IS SMPL Default"].set(value_is)

            for file in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file]["IS Data"]["IS"].set(var_is)
                self.container_var["SMPL"][file]["IS Data"]["Concentration"].set(value_is)

                file_short = file.split("/")[-1]
                if file_short not in self.container_files["SMPL"]:
                    self.container_files["SMPL"][file_short] = {
                        "IS": tk.StringVar(), "IS Concentration": tk.StringVar()}
                    self.container_files["SMPL"][file_short]["IS"].set(var_is)
                    self.container_files["SMPL"][file_short]["IS Concentration"].set(value_is)
                else:
                    self.container_files["SMPL"][file_short]["IS"].set(var_is)
                    self.container_files["SMPL"][file_short]["IS Concentration"].set(value_is)

        else:
            try:
                value_is = self.mineral_chem["Unknown"][var_is]
            except:
                value_is = 0.0

            self.container_var["SMPL"][var_file]["IS Data"]["IS"].set(var_is)
            self.container_var["SMPL"][var_file]["IS Data"]["Concentration"].set(value_is)

            file_short = var_file.split("/")[-1]

            if file_short not in self.container_files["SMPL"]:
                self.container_files["SMPL"][file_short] = {
                    "IS": tk.StringVar(), "IS Concentration": tk.StringVar()}
                self.container_files["SMPL"][file_short]["IS"].set(var_is)
                self.container_files["SMPL"][file_short]["IS Concentration"].set(value_is)
            else:
                self.container_files["SMPL"][file_short]["IS"].set(var_is)
                self.container_files["SMPL"][file_short]["IS Concentration"].set(value_is)

            #self.container_var["SMPL"][var_file]["IS"].set(var_is)

    def srm_window(self):
        ## Window Settings
        window_width = 860
        window_height = 625
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        window_srm = tk.Toplevel(self.parent)
        window_srm.title("SRM and Mineral Composition Data")
        window_srm.geometry(var_geometry)
        window_srm.resizable(False, False)
        window_srm["bg"] = self.green_light
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(window_srm, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(window_srm, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            window_srm.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            window_srm.grid_columnconfigure(i, minsize=column_min)
        #
        ###########################################################
        #
        ## Frames
        frm_01 = SE(
            parent=window_srm, row_id=0, column_id=0, n_rows=n_rows, n_columns=9,
            fg=self.green_light, bg=self.green_dark).create_frame(relief=tk.FLAT)
        #
        ## Labels
        lbl_01 = SE(
            parent=window_srm, row_id=0, column_id=0, n_rows=1, n_columns=9, fg=self.green_light,
            bg=self.green_dark).create_simple_label(
            text="Select SRM", relief=tk.GROOVE, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=window_srm, row_id=2, column_id=0, n_rows=1, n_columns=9, fg=self.green_light,
            bg=self.green_dark).create_simple_label(
            text="Select Mineral", relief=tk.GROOVE, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=window_srm, row_id=0, column_id=10, n_rows=1, n_columns=32, fg=self.green_light,
            bg=self.green_dark).create_simple_label(
            text="Periodic Table of the Elements", relief=tk.GROOVE, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=window_srm, row_id=n_rows - 4, column_id=0, n_rows=4, n_columns=9, fg=self.green_dark,
            bg=self.red_dark).create_simple_label(
            text="CAUTION!\n The mineral composition\n data reflects only the\n ideal composition of\n pure endmembers",
            relief=tk.GROOVE, fontsize="sans 10 bold")
        #
        ## Option Menues
        list_srm = np.sort(self.list_srm)
        opt_srm = SE(
            parent=window_srm, row_id=1, column_id=0, n_rows=1, n_columns=9, fg=self.green_dark,
            bg=self.green_medium).create_simple_optionmenu(
            var_opt=self.container_var["srm_window"]["Option Menu"]["SRM"], var_default="Select SRM",
            var_list=list_srm, fg_active=self.green_dark, bg_active=self.red_dark,
            command=lambda var_opt=self.container_var["srm_window"]["Option Menu"]["SRM"]:
            self.change_option_srm_window(var_opt))
        #
        list_minerals = np.sort(self.mineral_list)
        opt_mineral = SE(
            parent=window_srm, row_id=3, column_id=0, n_rows=1, n_columns=9, fg=self.green_dark,
            bg=self.green_medium).create_simple_optionmenu(
            var_opt=self.container_var["srm_window"]["Option Menu"]["Mineral"], var_default="Select Mineral",
            var_list=list_minerals, fg_active=self.green_dark, bg_active=self.red_dark,
            command=lambda var_opt=self.container_var["srm_window"]["Option Menu"]["Mineral"]:
            self.change_option_srm_window(var_opt))
        #
        ## Labels and Entries
        start_column_pse = 10
        for index, element in enumerate(self.list_pse):
            if 0 <= index < 23:
                lbl_i = SE(
                    parent=window_srm, row_id=index + 1, column_id=start_column_pse, n_rows=1, n_columns=3,
                    fg=self.green_light, bg=self.green_medium).create_simple_label(
                    text=str(index + 1) + " " + element, relief=tk.GROOVE, fontsize="sans 10 bold", anchor="w")
                #
                if element not in self.container_var["srm_window"]["Entry"]:
                    self.container_var["srm_window"]["Entry"][element] = tk.StringVar()
                #
                entr_i = SE(
                    parent=window_srm, row_id=index + 1, column_id=start_column_pse + 3, n_rows=1, n_columns=5,
                    fg=self.green_light, bg=self.green_dark).create_simple_entry(
                    var=self.container_var["srm_window"]["Entry"][element], text_default="0.0", command=None)
            elif 23 <= index < 46:
                lbl_i = SE(
                    parent=window_srm, row_id=index + 1 - 23, column_id=start_column_pse + 8, n_rows=1, n_columns=3,
                    fg=self.green_light, bg=self.green_medium).create_simple_label(
                    text=str(index + 1) + " " + element, relief=tk.GROOVE, fontsize="sans 10 bold", anchor="w")
                #
                if element not in self.container_var["srm_window"]["Entry"]:
                    self.container_var["srm_window"]["Entry"][element] = tk.StringVar()
                #
                entr_i = SE(
                    parent=window_srm, row_id=index + 1 - 23, column_id=start_column_pse + 11, n_rows=1, n_columns=5,
                    fg=self.green_light, bg=self.green_dark).create_simple_entry(
                    var=self.container_var["srm_window"]["Entry"][element], text_default="0.0", command=None)
            elif 46 <= index < 69:
                lbl_i = SE(
                    parent=window_srm, row_id=index + 1 - 46, column_id=start_column_pse + 16, n_rows=1, n_columns=3,
                    fg=self.green_light, bg=self.green_medium).create_simple_label(
                    text=str(index + 1) + " " + element, relief=tk.GROOVE, fontsize="sans 10 bold", anchor="w")
                #
                if element not in self.container_var["srm_window"]["Entry"]:
                    self.container_var["srm_window"]["Entry"][element] = tk.StringVar()
                #
                entr_i = SE(
                    parent=window_srm, row_id=index + 1 - 46, column_id=start_column_pse + 19, n_rows=1, n_columns=5,
                    fg=self.green_light, bg=self.green_dark).create_simple_entry(
                    var=self.container_var["srm_window"]["Entry"][element], text_default="0.0", command=None)
            elif 69 <= index < 92:
                lbl_i = SE(
                    parent=window_srm, row_id=index + 1 - 69, column_id=start_column_pse + 24, n_rows=1, n_columns=3,
                    fg=self.green_light, bg=self.green_medium).create_simple_label(
                    text=str(index + 1) + " " + element, relief=tk.GROOVE, fontsize="sans 10 bold", anchor="w")
                #
                if element not in self.container_var["srm_window"]["Entry"]:
                    self.container_var["srm_window"]["Entry"][element] = tk.StringVar()
                #
                entr_i = SE(
                    parent=window_srm, row_id=index + 1 - 69, column_id=start_column_pse + 27, n_rows=1, n_columns=5,
                    fg=self.green_light, bg=self.green_dark).create_simple_entry(
                    var=self.container_var["srm_window"]["Entry"][element], text_default="0.0", command=None)

    #
    def change_option_srm_window(self, var_opt):
        self.srm_values = {}
        self.srm_values[var_opt] = {}
        #
        if var_opt in self.list_srm:
            self.container_var["srm_window"]["Option Menu"]["Mineral"].set("Select Mineral")
            #
            ESRM().place_srm_values(srm_name=var_opt, srm_dict=self.srm_values)
            #
            for element in self.list_pse:
                if element in self.srm_values[var_opt].keys():
                    self.container_var["srm_window"]["Entry"][element].set(self.srm_values[var_opt][element])
                else:
                    self.container_var["srm_window"]["Entry"][element].set("0.0")
            #
        elif var_opt in self.mineral_list:
            self.container_var["srm_window"]["Option Menu"]["SRM"].set("Select SRM")
            #
            for element in self.list_pse:
                if element in self.mineral_chem[var_opt].keys():
                    self.container_var["srm_window"]["Entry"][element].set(self.mineral_chem[var_opt][element])
                else:
                    self.container_var["srm_window"]["Entry"][element].set("0.0")

    def create_srm_data_list(self):
        for var_srm in self.list_srm:
            self.container_lists["SRM Data"][var_srm] = {}
            ESRM().place_srm_values(srm_name=var_srm, srm_dict=self.container_lists["SRM Data"])

        for var_srm in self.list_srm:
            data_srm = self.container_lists["SRM Data"][var_srm]
            for element in self.list_pse:
                if element not in self.container_lists["SRM Data"]:
                    self.container_lists["SRM Data"][element] = {}

                if element in data_srm:
                    self.container_lists["SRM Data"][element][var_srm] = data_srm[element]

    def subwindow_general_settings(self):
        ## Window Settings
        window_width = 700
        window_height = 550
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_generalsettings = tk.Toplevel(self.parent)
        subwindow_generalsettings.title("General Settings")
        subwindow_generalsettings.geometry(var_geometry)
        subwindow_generalsettings.resizable(False, False)
        subwindow_generalsettings["bg"] = self.bg_colors["Super Dark"]

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_generalsettings, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_generalsettings, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_generalsettings.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_generalsettings.grid_columnconfigure(i, minsize=column_min)

        ###########################################################
        start_row = 0
        start_column = 0

        ## Labels
        str_lbl_01 = self.language_dict["Project Information"][self.var_language]
        str_lbl_02 = self.language_dict["Calculation Accuracy"][self.var_language]
        str_lbl_03 = self.language_dict["Sensitivity Drift"][self.var_language]
        str_lbl_04 = self.language_dict["Limit of Detection"][self.var_language]
        str_lbl_05 = self.language_dict["Offset Automatic Interval Detection"][self.var_language]
        str_lbl_06 = self.language_dict["Colormap"][self.var_language]
        str_lbl_07 = self.language_dict["Report File"][self.var_language]
        str_lbl_08 = self.language_dict["Plotting Setup"][self.var_language]
        str_lbl_09 = self.language_dict["Language Selection"][self.var_language]
        str_lbl_10 = self.language_dict["Data Processing"][self.var_language]
        str_lbl_11 = "Dwell times"
        str_lbl_12 = "Default value"

        lbl_01 = SE(
            parent=subwindow_generalsettings, row_id=2, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_generalsettings, row_id=5, column_id=start_column, n_rows=2, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Standard Reference\n Material (SRM)", relief=tk.FLAT, fontsize="sans 10 bold")
        # lbl_04 = SE(
        #     parent=subwindow_generalsettings, row_id=8, column_id=start_column, n_rows=2, n_columns=9,
        #     fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
        #     text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")
        # lbl_05 = SE(
        #     parent=subwindow_generalsettings, row_id=0, column_id=start_column + 10, n_rows=2, n_columns=16,
        #     fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
        #     text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_06 = SE(
            parent=subwindow_generalsettings, row_id=0, column_id=11, n_rows=1, n_columns=13,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_07 = SE(
            parent=subwindow_generalsettings, row_id=5, column_id=11, n_rows=2, n_columns=13,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_05, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_08 = SE(
            parent=subwindow_generalsettings, row_id=9, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_06, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_09 = SE(
            parent=subwindow_generalsettings, row_id=18, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_07, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_10 = SE(
            parent=subwindow_generalsettings, row_id=11, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_08, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_11 = SE(
            parent=subwindow_generalsettings, row_id=0, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_09, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_11 = SE(
            parent=subwindow_generalsettings, row_id=13, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_10, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_11 = SE(
            parent=subwindow_generalsettings, row_id=9, column_id=11, n_rows=1, n_columns=13,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_11, relief=tk.FLAT, fontsize="sans 10 bold")

        self.gui_elements["general_settings"]["Label"]["General"].extend(
            [lbl_01, lbl_02, lbl_06, lbl_07, lbl_08, lbl_09, lbl_10, lbl_11])

        lbl_11a = SE(
            parent=subwindow_generalsettings, row_id=10, column_id=11, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_12, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01a = SE(
            parent=subwindow_generalsettings, row_id=3, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Default Author", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02a = SE(
            parent=subwindow_generalsettings, row_id=7, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Default SRM", relief=tk.FLAT, fontsize="sans 10 bold")
        # lbl_05a = SE(
        #     parent=subwindow_generalsettings, row_id=2, column_id=start_column + 10, n_rows=1, n_columns=16,
        #     fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
        #     text="Transform time values into ...", relief=tk.GROOVE, fontsize="sans 10 bold")
        lbl_06a = SE(
            parent=subwindow_generalsettings, row_id=1, column_id=11, n_rows=1, n_columns=13,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Calculation formula from ...", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_07a = SE(
            parent=subwindow_generalsettings, row_id=7, column_id=11, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Background", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_07b = SE(
            parent=subwindow_generalsettings, row_id=8, column_id=11, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Main signal", relief=tk.FLAT, fontsize="sans 10 bold")
        # lbl_08a = SE(
        #     parent=subwindow_generalsettings, row_id=2, column_id=start_column + 27, n_rows=1, n_columns=10,
        #     fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
        #     text="Isotopes", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_09a = SE(
            parent=subwindow_generalsettings, row_id=19, column_id=start_column, n_rows=1, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="File type", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_09b = SE(
            parent=subwindow_generalsettings, row_id=20, column_id=start_column, n_rows=1, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Delimiter", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_10a = SE(
            parent=subwindow_generalsettings, row_id=12, column_id=start_column, n_rows=1, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Line width", relief=tk.FLAT, fontsize="sans 10 bold")

        self.gui_elements["general_settings"]["Label"]["General"].extend(
            [lbl_01a, lbl_02a, lbl_06a, lbl_07a, lbl_07b, lbl_09a, lbl_09b, lbl_10a])

        ## Entries
        entr_11a = SE(
            parent=subwindow_generalsettings, row_id=10, column_id=18, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["dwell_times"]["Entry"]["Default"],
            text_default=self.container_var["dwell_times"]["Entry"]["Default"].get(), command=None)
        entr_01a = SE(
            parent=subwindow_generalsettings, row_id=4, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["General Settings"]["Default Author"],
            text_default=self.container_var["General Settings"]["Default Author"].get(), command=None)
        entr_07a = SE(
            parent=subwindow_generalsettings, row_id=7, column_id=18, n_rows=1, n_columns=3,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["General Settings"]["BG Offset Start"],
            text_default=self.container_var["General Settings"]["BG Offset Start"].get(), command=None)
        entr_07b = SE(
            parent=subwindow_generalsettings, row_id=7, column_id=21, n_rows=1, n_columns=3,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["General Settings"]["BG Offset End"],
            text_default=self.container_var["General Settings"]["BG Offset End"].get(), command=None)
        entr_07c = SE(
            parent=subwindow_generalsettings, row_id=8, column_id=18, n_rows=1, n_columns=3,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["General Settings"]["MAT Offset Start"],
            text_default=self.container_var["General Settings"]["MAT Offset Start"].get(), command=None)
        entr_07d = SE(
            parent=subwindow_generalsettings, row_id=8, column_id=21, n_rows=1, n_columns=3,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["General Settings"]["MAT Offset End"],
            text_default=self.container_var["General Settings"]["MAT Offset End"].get(), command=None)
        entr_10a = SE(
            parent=subwindow_generalsettings, row_id=12, column_id=5, n_rows=1, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["General Settings"]["Line width"],
            text_default=self.container_var["General Settings"]["Line width"].get(),
            command=lambda event, var_entr=self.container_var["General Settings"]["Line width"]:
            self.check_lw_value(var_entr, event))

        self.gui_elements["general_settings"]["Entry"]["General"].extend(
            [entr_01a, entr_07a, entr_07b, entr_07c, entr_07d, entr_10a])

        ## Option Menus
        list_srm = list(np.sort(self.list_srm))
        list_srm.insert(0, "Select SRM")
        list_colormaps = [
            "turbo", "rainbow", "gist_rainbow", "jet", "nipy_spectral", "gnuplot", "gist_earth", "ocean", "hsv",
            "seismic", "coolwarm", "Spectral", "copper", "hot", "cool", "viridis", "plasma", "inferno", "magma",
            "cividis", "brg"]
        list_languages = ["English", "German", "Spanish", "Italian", "French", "Chinese", "Greek", "Russian"]
        list_colormaps.sort()
        list_filetypes = ["*.csv", "*.txt"]
        list_filetypes.sort()
        list_delimiter = ["comma", "semicolon"]
        list_delimiter.sort()
        list_languages.sort()

        opt_srm = SE(
            parent=subwindow_generalsettings, row_id=8, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["Default SRM"],
            var_default=self.container_var["General Settings"]["Default SRM"].get(), var_list=list_srm,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color)
        opt_colormaps = SE(
            parent=subwindow_generalsettings, row_id=10, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["Colormap"],
            var_default=self.container_var["General Settings"]["Colormap"].get(), var_list=list_colormaps,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["General Settings"]["Colormap"]: self.change_colormap(var_opt))
        opt_filetype = SE(
            parent=subwindow_generalsettings, row_id=19, column_id=5, n_rows=1, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["File type"],
            var_default=self.container_var["General Settings"]["File type"].get(), var_list=list_filetypes,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["General Settings"]["File type"]: self.change_filetype(var_opt))
        opt_delimiter = SE(
            parent=subwindow_generalsettings, row_id=20, column_id=5, n_rows=1, n_columns=5,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["Delimiter"],
            var_default=self.container_var["General Settings"]["Delimiter"].get(), var_list=list_delimiter,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["General Settings"]["Delimiter"]: self.change_delimiter(var_opt))
        opt_language = SE(
            parent=subwindow_generalsettings, row_id=1, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["Language"],
            var_default=self.container_var["General Settings"]["Language"].get(), var_list=list_languages,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color)
        # opt_language["menu"].entryconfig("German", state="disable")
        opt_language["menu"].entryconfig("Italian", state="disable")
        opt_language["menu"].entryconfig("Spanish", state="disable")
        opt_language["menu"].entryconfig("French", state="disable")
        opt_language["menu"].entryconfig("Chinese", state="disable")
        opt_language["menu"].entryconfig("Greek", state="disable")
        opt_language["menu"].entryconfig("Russian", state="disable")

        self.gui_elements["general_settings"]["Option Menu"]["General"].extend(
            [opt_srm, opt_colormaps, opt_filetype, opt_delimiter, opt_language])

        ## Radiobuttons
        # rb_04a = SE(
        #     parent=subwindow_generalsettings, row_id=10, column_id=start_column, n_rows=1, n_columns=9,
        #     fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
        #     var_rb=self.container_var["General Settings"]["Calculation Accuracy"], value_rb=0,
        #     color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS",
        #     sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        # rb_04b = SE(
        #     parent=subwindow_generalsettings, row_id=11, column_id=start_column, n_rows=1, n_columns=9,
        #     fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
        #     var_rb=self.container_var["General Settings"]["Calculation Accuracy"], value_rb=1,
        #     color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="PySILLS",
        #     sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        # rb_05a = SE(
        #     parent=subwindow_generalsettings, row_id=3, column_id=start_column + 10, n_rows=1, n_columns=16,
        #     fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
        #     var_rb=self.container_var["General Settings"]["Sensitivity Drift"], value_rb=0,
        #     color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="seconds",
        #     sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        # rb_05b = SE(
        #     parent=subwindow_generalsettings, row_id=4, column_id=start_column + 10, n_rows=1, n_columns=16,
        #     fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
        #     var_rb=self.container_var["General Settings"]["Sensitivity Drift"], value_rb=1,
        #     color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="decimal numbers", sticky="nesw",
        #     relief=tk.FLAT, font="sans 10 bold")
        #
        rb_06a = SE(
            parent=subwindow_generalsettings, row_id=2, column_id=11, n_rows=1, n_columns=13,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["General Settings"]["LOD Selection"], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Pettke et al. (2012)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_06b = SE(
            parent=subwindow_generalsettings, row_id=3, column_id=11, n_rows=1, n_columns=13,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["General Settings"]["LOD Selection"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Longerich et al. (1996)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        rb_06b = SE(
            parent=subwindow_generalsettings, row_id=14, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Desired Average"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Arithmetic Mean",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_06b = SE(
            parent=subwindow_generalsettings, row_id=15, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Desired Average"], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Median",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        rb_07a = SE(
            parent=subwindow_generalsettings, row_id=16, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Interval Processing"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Average of every interval",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_07b = SE(
            parent=subwindow_generalsettings, row_id=17, column_id=start_column, n_rows=1, n_columns=10,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Interval Processing"], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Stack all intervals into one",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_07a.configure(state="disabled")
        rb_07b.configure(state="disabled")
        self.gui_elements["general_settings"]["Radiobutton"]["General"].extend(
            [rb_06a, rb_06b])
        #
        ## Buttons
        btn_01 = SE(
            parent=subwindow_generalsettings, row_id=19, column_id=25, n_rows=2, n_columns=9,
            fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Save Settings", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.confirm_general_settings)

        self.gui_elements["general_settings"]["Button"]["General"].extend([btn_01])

        self.check_lw_value(var_entr=self.container_var["General Settings"]["Line width"], event="")

    def check_lw_value(self, var_entr, event):
        if float(var_entr.get()) < 0:
            var_entr.set("0.5")
        elif float(var_entr.get()) > 2:
            var_entr.set("2.0")

    def change_colormap(self, var_opt):
        self.container_var["General Settings"]["Colormap"].set(var_opt)

    def change_filetype(self, var_opt):
        self.container_var["General Settings"]["File type"].set(var_opt)

    def change_delimiter(self, var_opt):
        self.container_var["General Settings"]["Delimiter"].set(var_opt)

    def confirm_general_settings(self):
        path_pysills = os.path.dirname(os.path.realpath(__file__))
        path_pysills = self.path_pysills
        filename = os.path.join(self.path_pysills_main, "user_settings.txt")
        with open(filename, "w") as file_settings:
            file_settings.write("GENERAL SETTINGS" + ";\n")
            for key, value in self.container_var["General Settings"].items():
                str_key = str(key) + ";" + str(value.get()) + ";\n"
                file_settings.write(str_key)
            str_key = str("Dwell Times") + ";" + str(self.container_var["dwell_times"]["Entry"]["Default"].get()) + ";\n"
            file_settings.write(str_key)

    def check_srm_settings(self):
        str_title = self.language_dict["Check-Up - Standard Reference Material"][self.var_language]
        str_lbl_01 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_02 = self.language_dict["Isotopes"][self.var_language]
        str_lbl_03 = self.language_dict["SRM values"][self.var_language]
        str_lbl_04 = self.language_dict["Name"][self.var_language]
        str_lbl_05 = self.language_dict["SRM"][self.var_language]
        str_lbl_06 = self.language_dict["Concentration (ppm)"][self.var_language]
        str_lbl_07 = self.language_dict["Element"][self.var_language]

        ## Window Settings
        window_width = 640
        window_height = 575
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_srm_checkup = tk.Toplevel(self.parent)
        subwindow_srm_checkup.title(str_title)
        subwindow_srm_checkup.geometry(var_geometry)
        subwindow_srm_checkup.resizable(False, False)
        subwindow_srm_checkup["bg"] = self.bg_colors["Very Dark"]

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_srm_checkup, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_srm_checkup, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_srm_checkup.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_srm_checkup.grid_columnconfigure(i, minsize=column_min)

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

        start_column = 0
        start_row = 0

        ## LABELS
        lbl_std = SE(
            parent=subwindow_srm_checkup, row_id=start_row, column_id=start_column, n_rows=1, n_columns=17,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_smpl = SE(
            parent=subwindow_srm_checkup, row_id=start_row + 11, column_id=start_column, n_rows=1, n_columns=17,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_smpl = SE(
            parent=subwindow_srm_checkup, row_id=start_row, column_id=start_column + 18, n_rows=1, n_columns=13,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold")

        ## TREEVIEW
        tv_std = SE(
            parent=subwindow_srm_checkup, row_id=start_row + 1, column_id=start_column, n_rows=10, n_columns=17,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_treeview(
            n_categories=2, text_n=[str_lbl_04, str_lbl_05], width_n=["120", "220"], individual=True)

        list_srm = ["Select SRM"]
        for index, var_file in enumerate(self.container_lists["STD"]["Long"]):
            parts = var_file.split("/")
            file_std = parts[-1]
            var_srm_file_i = self.container_var["STD"][var_file]["SRM"].get()
            #
            if var_srm_file_i not in list_srm:
                list_srm.append(var_srm_file_i)
            #
            entry_std = [file_std, var_srm_file_i]
            #
            tv_std.insert("", tk.END, values=entry_std)

        if len(list_srm) > 1:
            list_srm.remove("Select SRM")

        tv_isotope = SE(
            parent=subwindow_srm_checkup, row_id=start_row + 12, column_id=start_column, n_rows=10, n_columns=17,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=3, text_n=[str_lbl_04, str_lbl_05, str_lbl_06], width_n=["70", "130", "140"],
            individual=True)

        for index, isotope in enumerate(self.container_lists["ISOTOPES"]):
            var_srm_i = self.container_var["SRM"][isotope].get()

            key_element = re.search(r"(\D+)(\d+)", isotope)
            element = key_element.group(1)
            if element in self.srm_actual[var_srm_i]:
                var_isotope_concentration = self.srm_actual[var_srm_i][element]
            else:
                var_isotope_concentration = 0.0

            entry_isotope = [isotope, var_srm_i, var_isotope_concentration]

            tv_isotope.insert("", tk.END, values=entry_isotope)

        tv_srm = SE(
            parent=subwindow_srm_checkup, row_id=start_row + 2, column_id=start_column + 18, n_rows=20, n_columns=13,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=2, text_n=[str_lbl_07, str_lbl_06], width_n=["100", "160"], individual=True)

        ## Option Menus
        var_opt_srm = tk.StringVar()
        if self.container_var["SRM"]["default"][0].get() != "Select SRM":
            var_opt_srm.set(self.container_var["SRM"]["default"][0].get())
        else:
            var_opt_srm.set("Select SRM")

        opt_srm = SE(
            parent=subwindow_srm_checkup, row_id=start_row + 1, column_id=start_column + 18, n_rows=1, n_columns=13,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_optionmenu(
            var_opt=var_opt_srm, var_default=var_opt_srm.get(), var_list=list_srm,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=var_opt_srm, var_tv=tv_srm: self.change_srm_checkup(var_opt, var_tv))

        ## INITIALIZATION
        self.change_srm_checkup(var_opt=var_opt_srm.get(), var_tv=tv_srm)

    def change_srm_checkup(self, var_opt, var_tv):
        if len(var_tv.get_children()) > 0:
            for item in var_tv.get_children():
                var_tv.delete(item)
        #
        if var_opt != "Select SRM":
            for element in np.sort(list(self.srm_actual[var_opt].keys())):
                entry_isotope = [element, self.srm_actual[var_opt][element]]
                #
                var_tv.insert("", tk.END, values=entry_isotope)

    #
    def check_interval_settings(self):
        ## Window Settings
        window_width = 1080
        window_height = 825
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        subwindow_intervals = tk.Toplevel(self.parent)
        subwindow_intervals.title("Check-Up - Calculation Intervals")
        subwindow_intervals.geometry(var_geometry)
        subwindow_intervals.resizable(False, False)
        subwindow_intervals["bg"] = self.bg_colors["Very Dark"]
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_intervals, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_intervals, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            subwindow_intervals.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_intervals.grid_columnconfigure(i, minsize=column_min)
        #
        if self.pysills_mode == "MA":
            accent_bg = self.colors_ma["Dark"]
            accent_fg = self.colors_ma["Light Font"]
            accent_btn_bg = self.colors_ma["Medium"]
            accent_btn_fg = self.colors_ma["Dark Font"]
            var_categories = ["Filename", "Category", "ID", "Start", "End"]
            var_widths = ["160", "90", "90", "90", "90"]
        elif self.pysills_mode == "FI":
            accent_bg = self.accent_color
            accent_fg = self.colors_fi["Light Font"]
            accent_btn_bg = self.colors_fi["Medium"]
            accent_btn_fg = self.colors_fi["Dark Font"]
            var_categories = ["Filename", "Category", "ID", "Start", "End"]
            var_widths = ["160", "90", "90", "90", "90"]
        elif self.pysills_mode == "MI":
            accent_bg = self.colors_mi["Dark"]
            accent_fg = self.colors_mi["Light Font"]
            accent_btn_bg = self.colors_mi["Medium"]
            accent_btn_fg = self.colors_mi["Dark Font"]
            var_categories = ["Name", "BG(start)", "BG(end)", "MAT(start)", "MAT(end)", "INCL(start)", "INCL(end)"]
            var_widths = ["120", "67", "67", "67", "67", "67", "67"]
        elif self.pysills_mode == "OA":
            accent_bg = self.bg_colors["Dark"]
            accent_fg = self.bg_colors["Light Font"]
            accent_btn_bg = self.bg_colors["Medium"]
            accent_btn_fg = self.bg_colors["Dark Font"]
        #
        ################################################################################################################
        #
        start_column = 0
        start_row = 0
        #
        ## FRAMES
        frm_00 = SE(
            parent=subwindow_intervals, row_id=start_row, column_id=start_column + 26,
            n_rows=n_rows, n_columns=n_columns - 26, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)
        #
        ## FIGURES
        fig_checkup_std = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        fig_checkup_smpl = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        #
        canvas_std = FigureCanvasTkAgg(fig_checkup_std, master=subwindow_intervals)
        canvas_std.get_tk_widget().grid(
            row=start_row + 1, column=start_column + 26, rowspan=15, columnspan=27, sticky="nesw")
        canvas_smpl = FigureCanvasTkAgg(fig_checkup_smpl, master=subwindow_intervals)
        canvas_smpl.get_tk_widget().grid(
            row=start_row + 17, column=start_column + 26, rowspan=15, columnspan=27, sticky="nesw")
        #
        self.container_checkup["STD"].append(canvas_std)
        self.container_checkup["SMPL"].append(canvas_smpl)
        self.temp_figure_checkup = {"STD": fig_checkup_std, "SMPL": fig_checkup_smpl}
        self.temp_canvas_checkup = {"STD": canvas_std, "SMPL": canvas_smpl}
        self.temp_axes_checkup = {"STD": {}, "SMPL": {}}
        self.temp_lines_checkup = {"STD": {}, "SMPL": {}}
        #
        ## LABELS
        lbl_std = SE(
            parent=subwindow_intervals, row_id=start_row, column_id=start_column, n_rows=1, n_columns=26,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Standard Files", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_smpl = SE(
            parent=subwindow_intervals, row_id=start_row + 16, column_id=start_column, n_rows=1, n_columns=26,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold")
        #
        ## BUTTONS
        btn_std_01 = SE(
            parent=subwindow_intervals, row_id=start_row, column_id=start_column + 26, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Previous Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="STD", mode="Back", var_fig=fig_checkup_std:
            self.change_graph_checkup(filetype, mode, var_fig))
        btn_std_02 = SE(
            parent=subwindow_intervals, row_id=start_row, column_id=start_column + 32, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Next Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="STD", var_fig=fig_checkup_std: self.change_graph_checkup(filetype, var_fig))
        #
        if self.pysills_mode == "MA":
            btn_std_03 = SE(
                parent=subwindow_intervals, row_id=start_row, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda var_filename_long=self.ma_current_file_std, var_filetype="STD", checkup_mode=True:
                self.ma_check_specific_file(var_filename_long, var_filetype, checkup_mode))
            #
        elif self.pysills_mode == "FI":
            btn_std_03 = SE(
                parent=subwindow_intervals, row_id=start_row, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda var_file=self.fi_current_file_std, var_type="STD", checkup_mode=True:
                self.fi_check_specific_file(var_file, var_type, checkup_mode))
            #
        elif self.pysills_mode == "MI":
            btn_std_03 = SE(
                parent=subwindow_intervals, row_id=start_row, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda var_file=self.mi_current_file_std, var_type="STD", checkup_mode=True:
                self.mi_check_specific_file(var_file, var_type, checkup_mode))
        #
        btn_smpl_01 = SE(
            parent=subwindow_intervals, row_id=start_row + 16, column_id=start_column + 26, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Previous Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="SMPL", mode="Back", var_fig=fig_checkup_smpl:
            self.change_graph_checkup(filetype, mode, var_fig))
        btn_smpl_02 = SE(
            parent=subwindow_intervals, row_id=start_row + 16, column_id=start_column + 32, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Next Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="SMPL", var_fig=fig_checkup_smpl: self.change_graph_checkup(filetype, var_fig))
        if self.pysills_mode == "MA":
            btn_smpl_03 = SE(
                parent=subwindow_intervals, row_id=start_row + 16, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda var_filename_long=self.ma_current_file_smpl, var_filetype="SMPL", checkup_mode=True:
                self.ma_check_specific_file(var_filename_long, var_filetype, checkup_mode))
        elif self.pysills_mode == "FI":
            btn_smpl_03 = SE(
                parent=subwindow_intervals, row_id=start_row + 16, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda var_file=self.fi_current_file_smpl, var_type="SMPL", checkup_mode=True:
                self.fi_check_specific_file(var_file, var_type, checkup_mode))
        elif self.pysills_mode == "MI":
            btn_smpl_03 = SE(
                parent=subwindow_intervals, row_id=start_row + 16, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda var_file=self.mi_current_file_smpl, var_type="SMPL", checkup_mode=True:
                self.mi_check_specific_file(var_file, var_type, checkup_mode))
        #
        ## TREEVIEW
        #
        tv_std = SE(
            parent=subwindow_intervals, row_id=start_row + 1, column_id=start_column, n_rows=15, n_columns=26,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=len(var_categories), text_n=var_categories, width_n=var_widths, individual=True)
        #
        if self.pysills_mode == "MA":
            for file_std in self.container_lists["STD"]["Short"]:
                for category in ["BG", "MAT"]:
                    if len(self.container_helper["STD"][file_std][category]["Content"]) > 0:
                        for var_id, var_content in self.container_helper["STD"][file_std][category]["Content"].items():
                            if category == "BG":
                                times = var_content["Times"]
                            else:
                                times = var_content["Times"]
                            #
                            entry_std = [file_std, category, var_id, times[0], times[1]]
                            tv_std.insert("", tk.END, values=entry_std)
                        #
                    else:
                        var_id = 0
                        times = ["undefined", "undefined"]
                        #
                        entry_std = [file_std, category, var_id, times[0], times[1]]
                        tv_std.insert("", tk.END, values=entry_std)
                        #
                self.temp_axes_checkup["STD"][file_std] = fig_checkup_std.add_subplot(label=file_std)
                self.temp_lines_checkup["STD"][file_std] = 0
            #
        else:
            for file_std in self.container_lists["STD"]["Short"]:
                for category in ["BG", "MAT"]:
                    if len(self.container_helper["STD"][file_std][category]["Content"]) > 0:
                        for var_id, var_content in self.container_helper["STD"][file_std][category]["Content"].items():
                            if category == "BG":
                                times = var_content["Times"]
                            else:
                                times = var_content["Times"]
                            #
                            entry_std = [file_std, category, var_id, times[0], times[1]]
                            tv_std.insert("", tk.END, values=entry_std)
                        #
                    else:
                        var_id = 0
                        times = ["undefined", "undefined"]
                        #
                        entry_std = [file_std, category, var_id, times[0], times[1]]
                        tv_std.insert("", tk.END, values=entry_std)
                        #
                self.temp_axes_checkup["STD"][file_std] = fig_checkup_std.add_subplot(label=file_std)
                self.temp_lines_checkup["STD"][file_std] = 0
        #
        tv_smpl = SE(
            parent=subwindow_intervals, row_id=start_row + 17, column_id=start_column, n_rows=15, n_columns=26,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=len(var_categories), text_n=var_categories, width_n=var_widths, individual=True)
        #
        if self.pysills_mode == "MA":
            for file_smpl in self.container_lists["SMPL"]["Short"]:
                for category in ["BG", "MAT"]:
                    if len(self.container_helper["SMPL"][file_smpl][category]["Content"]) > 0:
                        for var_id, var_content in self.container_helper["SMPL"][file_smpl][category][
                            "Content"].items():
                            if category == "BG":
                                times = var_content["Times"]
                            else:
                                times = var_content["Times"]
                            #
                            entry_smpl = [file_smpl, category, var_id, times[0], times[1]]
                            tv_smpl.insert("", tk.END, values=entry_smpl)
                        #
                    else:
                        var_id = 0
                        times = ["undefined", "undefined"]
                        #
                        entry_smpl = [file_smpl, category, var_id, times[0], times[1]]
                        tv_smpl.insert("", tk.END, values=entry_smpl)
                        #
                self.temp_axes_checkup["SMPL"][file_smpl] = fig_checkup_smpl.add_subplot(label=file_smpl)
                self.temp_lines_checkup["SMPL"][file_smpl] = 0
            #
        else:
            for file_smpl in self.container_lists["SMPL"]["Short"]:
                for category in ["BG", "MAT", "INCL"]:
                    if len(self.container_helper["SMPL"][file_smpl][category]["Content"]) > 0:
                        for var_id, var_content in self.container_helper["SMPL"][file_smpl][category][
                            "Content"].items():
                            if category == "BG":
                                times = var_content["Times"]
                            else:
                                times = var_content["Times"]
                            #
                            entry_smpl = [file_smpl, category, var_id, times[0], times[1]]
                            tv_smpl.insert("", tk.END, values=entry_smpl)
                        #
                    else:
                        var_id = 0
                        times = ["undefined", "undefined"]
                        #
                        entry_smpl = [file_smpl, category, var_id, times[0], times[1]]
                        tv_smpl.insert("", tk.END, values=entry_smpl)
                        #
                self.temp_axes_checkup["SMPL"][file_smpl] = fig_checkup_smpl.add_subplot(label=file_smpl)
                self.temp_lines_checkup["SMPL"][file_smpl] = 0
        #
        ## INITIALIZATION
        self.change_graph_checkup(filetype="STD", initialization=True, var_fig=fig_checkup_std)
        self.change_graph_checkup(filetype="SMPL", initialization=True, var_fig=fig_checkup_smpl)

    #
    def check_acquisition_times(self):
        ## Window Settings
        window_width = 520
        window_height = 825
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_aquisition_times = tk.Toplevel(self.parent)
        subwindow_aquisition_times.title("Check-Up - Acquisition  Times")
        subwindow_aquisition_times.geometry(var_geometry)
        subwindow_aquisition_times.resizable(False, False)
        subwindow_aquisition_times["bg"] = self.bg_colors["Very Dark"]

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_aquisition_times, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_aquisition_times, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_aquisition_times.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_aquisition_times.grid_columnconfigure(i, minsize=column_min)

        start_column = 0
        start_row = 0

        ## LABELS
        lbl_std = SE(
            parent=subwindow_aquisition_times, row_id=start_row, column_id=start_column, n_rows=1, n_columns=16,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Standard Files", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_smpl = SE(
            parent=subwindow_aquisition_times, row_id=start_row + 16, column_id=start_column, n_rows=1, n_columns=16,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold")

        ## ENTRY
        self.var_entr_std_time = tk.StringVar()
        self.var_entr_std_time.set("00:00:00")

        entr_std = SE(
            parent=subwindow_aquisition_times, row_id=start_row + 1, column_id=start_column + 17, n_rows=2,
            n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.var_entr_std_time, text_default=self.var_entr_std_time.get(),
            command=lambda event, filetype="STD": self.change_value_acquisition(filetype, event))

        self.var_entr_smpl_time = tk.StringVar()
        self.var_entr_smpl_time.set("00:00:00")

        entr_smpl = SE(
            parent=subwindow_aquisition_times, row_id=start_row + 17, column_id=start_column + 17, n_rows=2,
            n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.var_entr_smpl_time, text_default=self.var_entr_smpl_time.get(),
            command=lambda event, filetype="SMPL": self.change_value_acquisition(filetype, event))

        ## TREEVIEWS
        self.tv_std = SE(
            parent=subwindow_aquisition_times, row_id=start_row + 1, column_id=start_column, n_rows=14, n_columns=15,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=2, text_n=["Filename", "Acquisition Time"],
            width_n=["150", "150"], individual=True)

        scb_v = ttk.Scrollbar(subwindow_aquisition_times, orient="vertical")
        scb_h = ttk.Scrollbar(subwindow_aquisition_times, orient="horizontal")
        self.tv_std.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
        scb_v.config(command=self.tv_std.yview)
        scb_h.config(command=self.tv_std.xview)
        scb_v.grid(row=start_row + 1, column=start_column + 15, rowspan=14, columnspan=1, sticky="ns")
        scb_h.grid(row=start_row + 15, column=start_column, rowspan=1, columnspan=15, sticky="ew")

        for index, var_file in enumerate(self.container_lists["STD"]["Long"]):
            parts = var_file.split("/")
            file_std = parts[-1]
            var_file_short = file_std

            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]

            if self.file_loaded == False:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                var_time = self.container_var["acquisition times"]["STD"][var_file_short].get()
                parts_time = var_time.split(":")
                times = parts_time

            if index == 0:
                if self.file_loaded == False:
                    t_start_0 = datetime.timedelta(
                        hours=int(times[0][0]), minutes=int(times[0][1]), seconds=int(times[0][2]))
                    t_start = datetime.timedelta(
                        hours=int(times[0][0]), minutes=int(times[0][1]), seconds=int(times[0][2]))
                else:
                    t_start_0 = datetime.timedelta(
                        hours=int(times[0]), minutes=int(times[1]), seconds=int(times[2]))
                    t_start = datetime.timedelta(
                        hours=int(times[0]), minutes=int(times[1]), seconds=int(times[2]))
            else:
                if self.file_loaded == False:
                    t_start = datetime.timedelta(
                        hours=int(times[0][0]), minutes=int(times[0][1]), seconds=int(times[0][2]))
                else:
                    t_start = datetime.timedelta(
                        hours=int(times[0]), minutes=int(times[1]), seconds=int(times[2]))

            t_delta_0 = (t_start - t_start_0).total_seconds()
            self.container_lists["Acquisition Times Delta"][file_std] = t_delta_0

            if file_std not in self.container_var["acquisition times"]["STD"]:
                self.container_var["acquisition times"]["STD"][file_std] = tk.StringVar()
                self.container_var["acquisition times"]["STD"][file_std].set(
                    times[0][0] + ":" + times[0][1] + ":" + times[0][2])

            entry_std = [file_std, self.container_var["acquisition times"]["STD"][file_std].get()]
            self.tv_std.insert("", tk.END, values=entry_std)

        self.tv_smpl = SE(
            parent=subwindow_aquisition_times, row_id=start_row + 17, column_id=start_column, n_rows=14, n_columns=15,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=2, text_n=["Filename", "Acquisition Time"],
            width_n=["150", "150"], individual=True)

        scb_v = ttk.Scrollbar(subwindow_aquisition_times, orient="vertical")
        scb_h = ttk.Scrollbar(subwindow_aquisition_times, orient="horizontal")
        self.tv_smpl.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
        scb_v.config(command=self.tv_smpl.yview)
        scb_h.config(command=self.tv_smpl.xview)
        scb_v.grid(row=start_row + 17, column=start_column + 15, rowspan=14, columnspan=1, sticky="ns")
        scb_h.grid(row=start_row + 31, column=start_column, rowspan=1, columnspan=15, sticky="ew")

        for index, var_file in enumerate(self.container_lists["SMPL"]["Long"]):
            parts = var_file.split("/")
            file_smpl = parts[-1]
            var_file_short = file_smpl

            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]

            if self.file_loaded == False:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                var_time = self.container_var["acquisition times"]["SMPL"][var_file_short].get()
                parts_time = var_time.split(":")
                times = parts_time

            if self.file_loaded == False:
                t_start = datetime.timedelta(hours=int(times[0][0]), minutes=int(times[0][1]), seconds=int(times[0][2]))
            else:
                t_start = datetime.timedelta(hours=int(times[0]), minutes=int(times[1]), seconds=int(times[2]))
            t_delta_0 = (t_start - t_start_0).total_seconds()
            self.container_lists["Acquisition Times Delta"][file_smpl] = t_delta_0

            if file_smpl not in self.container_var["acquisition times"]["SMPL"]:
                self.container_var["acquisition times"]["SMPL"][file_smpl] = tk.StringVar()
                if self.file_loaded == False:
                    self.container_var["acquisition times"]["SMPL"][file_smpl].set(
                        times[0][0] + ":" + times[0][1] + ":" + times[0][2])
                else:
                    self.container_var["acquisition times"]["SMPL"][file_smpl].set(
                        times[0] + ":" + times[1] + ":" + times[2])

            entry_smpl = [file_smpl, self.container_var["acquisition times"]["SMPL"][file_smpl].get()]
            self.tv_smpl.insert("", tk.END, values=entry_smpl)

    def calculate_acquisition_time_deltas(self):
        for index, var_file in enumerate(self.container_lists["STD"]["Long"]):
            parts = var_file.split("/")
            file_std = parts[-1]
            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]

            if self.file_loaded == False:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                var_time = self.container_var["acquisition times"]["STD"][file_std].get()
                parts_time = var_time.split(":")
                times = parts_time

            if times[0] == "unknown" and self.file_loaded == True:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)

            if len(times) == 2:
                data_times = times[0]
            else:
                data_times = times

            if index == 0:
                if self.container_var["General Settings"]["Sensitivity Drift"].get() == 0:
                    if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                        t_start_0 = datetime.timedelta(
                            hours=int(data_times[0]), minutes=int(data_times[1]), seconds=int(data_times[2]))
                    else:
                        t_start_0 = datetime.timedelta(
                            hours=int(data_times[0]), minutes=int(data_times[1]), seconds=int("00"))
                else:
                    t_start_0 = int(data_times[0]) + int(data_times[1])/60

            if self.container_var["General Settings"]["Sensitivity Drift"].get() == 0:
                if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                    t_start = datetime.timedelta(
                        hours=int(data_times[0]), minutes=int(data_times[1]), seconds=int(data_times[2]))
                else:
                    t_start = datetime.timedelta(
                        hours=int(data_times[0]), minutes=int(data_times[1]), seconds=int("00"))
            else:
                t_start = int(data_times[0]) + int(data_times[1])/60

            if self.container_var["General Settings"]["Sensitivity Drift"].get() == 0:
                t_delta_0 = (t_start - t_start_0).total_seconds()
            else:
                t_delta_0 = t_start - t_start_0

            self.container_lists["Acquisition Times Delta"][file_std] = t_delta_0

        for index, var_file in enumerate(self.container_lists["SMPL"]["Long"]):
            parts = var_file.split("/")
            file_smpl = parts[-1]
            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]

            if self.file_loaded == False:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                var_time = self.container_var["acquisition times"]["SMPL"][file_smpl].get()
                parts_time = var_time.split(":")
                times = parts_time

            if times[0] == "unknown" and self.file_loaded == True:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)

            if len(times) == 2:
                data_times = times[0]
            else:
                data_times = times

            if self.container_var["General Settings"]["Sensitivity Drift"].get() == 0:
                if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                    t_start = datetime.timedelta(
                        hours=int(data_times[0]), minutes=int(data_times[1]), seconds=int(data_times[2]))
                else:
                    t_start = datetime.timedelta(
                        hours=int(data_times[0]), minutes=int(data_times[1]), seconds=int("00"))
            else:
                t_start = int(data_times[0]) + int(data_times[1])/60

            if self.container_var["General Settings"]["Sensitivity Drift"].get() == 0:
                t_delta_0 = (t_start - t_start_0).total_seconds()
            else:
                t_delta_0 = t_start - t_start_0

            self.container_lists["Acquisition Times Delta"][file_smpl] = t_delta_0

    def check_imported_files(self):
        ## Window Settings
        window_width = 1080
        window_height = 825
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        subwindow_imported_files = tk.Toplevel(self.parent)
        subwindow_imported_files.title("Check-Up - Imported Files")
        subwindow_imported_files.geometry(var_geometry)
        subwindow_imported_files.resizable(False, False)
        subwindow_imported_files["bg"] = self.bg_colors["Very Dark"]
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_imported_files, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_imported_files, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            subwindow_imported_files.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_imported_files.grid_columnconfigure(i, minsize=column_min)
        #
        if self.pysills_mode == "MA":
            accent_bg = self.colors_ma["Dark"]
            accent_fg = self.colors_ma["Light Font"]
            accent_btn_bg = self.colors_ma["Medium"]
            accent_btn_fg = self.colors_ma["Dark Font"]
        elif self.pysills_mode == "FI":
            accent_bg = self.accent_color
            accent_fg = self.colors_fi["Light Font"]
            accent_btn_bg = self.colors_fi["Medium"]
            accent_btn_fg = self.colors_fi["Dark Font"]
        elif self.pysills_mode == "MI":
            accent_bg = self.colors_mi["Dark"]
            accent_fg = self.colors_mi["Light Font"]
            accent_btn_bg = self.colors_mi["Medium"]
            accent_btn_fg = self.colors_mi["Dark Font"]
        elif self.pysills_mode == "OA":
            accent_bg = self.bg_colors["Dark"]
            accent_fg = self.bg_colors["Light Font"]
            accent_btn_bg = self.bg_colors["Medium"]
            accent_btn_fg = self.bg_colors["Dark Font"]
        #
        ###########################################################
        #
        start_column = 0
        start_row = 0
        #
        ## FRAMES
        frm_00 = SE(
            parent=subwindow_imported_files, row_id=start_row, column_id=start_column + 26,
            n_rows=n_rows, n_columns=n_columns - 26, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)
        #
        ## LABELS
        lbl_std = SE(
            parent=subwindow_imported_files, row_id=start_row, column_id=start_column, n_rows=1, n_columns=26,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Standard Files", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_smpl = SE(
            parent=subwindow_imported_files, row_id=start_row + 16, column_id=start_column, n_rows=1, n_columns=26,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold")
        #
        ## FIGURES
        fig_checkup_std = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        fig_checkup_smpl = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        #
        canvas_std = FigureCanvasTkAgg(fig_checkup_std, master=subwindow_imported_files)
        canvas_std.get_tk_widget().grid(
            row=start_row + 1, column=start_column + 26, rowspan=15, columnspan=28, sticky="nesw")
        canvas_smpl = FigureCanvasTkAgg(fig_checkup_smpl, master=subwindow_imported_files)
        canvas_smpl.get_tk_widget().grid(
            row=start_row + 17, column=start_column + 26, rowspan=15, columnspan=28, sticky="nesw")
        #
        self.container_checkup["STD"].append(canvas_std)
        self.container_checkup["SMPL"].append(canvas_smpl)
        self.temp_figure_checkup = {"STD": fig_checkup_std, "SMPL": fig_checkup_smpl}
        self.temp_canvas_checkup = {"STD": canvas_std, "SMPL": canvas_smpl}
        self.temp_axes_checkup = {"STD": {}, "SMPL": {}}
        self.temp_lines_checkup = {"STD": {}, "SMPL": {}}
        #
        ## BUTTONS
        btn_std_01 = SE(
            parent=subwindow_imported_files, row_id=start_row, column_id=start_column + 26, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Previous Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="STD", mode="Back", var_fig=fig_checkup_std:
            self.change_graph_checkup(filetype, mode, var_fig))
        btn_std_02 = SE(
            parent=subwindow_imported_files, row_id=start_row, column_id=start_column + 32, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Next Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="STD", var_fig=fig_checkup_std: self.change_graph_checkup(filetype, var_fig))
        btn_smpl_01 = SE(
            parent=subwindow_imported_files, row_id=start_row + 16, column_id=start_column + 26, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Previous Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="SMPL", mode="Back", var_fig=fig_checkup_smpl:
            self.change_graph_checkup(filetype, mode, var_fig))
        btn_smpl_02 = SE(
            parent=subwindow_imported_files, row_id=start_row + 16, column_id=start_column + 32, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Next Graph", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype="SMPL", var_fig=fig_checkup_smpl: self.change_graph_checkup(filetype, var_fig))
        #
        ## TREEVIEW
        tv_std = SE(
            parent=subwindow_imported_files, row_id=start_row + 1, column_id=start_column, n_rows=15, n_columns=26,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=6, text_n=["Name", "N Isotopes", "t(start)", "t(end)", "t(day)", "date"],
            width_n=["120", "80", "80", "80", "80", "80"], individual=True)
        #
        for index, var_file in enumerate(self.container_lists["STD"]["Long"]):
            parts = var_file.split("/")
            file_std = parts[-1]
            var_file_short = parts[-1]
            if self.file_loaded == False:
                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=3, skip_footer=1)
            else:
                df_data = self.container_measurements["Dataframe"][var_file_short]

            # if self.container_icpms["name"] != None:
            #     var_skipheader = self.container_icpms["skipheader"]
            #     var_skipfooter = self.container_icpms["skipfooter"]
            #     df_data = DE(filename_long=var_file).get_measurements(
            #         delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            # else:
            #     df_data = DE(filename_long=var_file).get_measurements(
            #         delimiter=",", skip_header=3, skip_footer=1)
            dataset_time = list(DE().get_times(dataframe=df_data))
            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]

            if self.file_loaded == False:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                var_time = self.container_var["acquisition times"]["STD"][var_file_short].get()
                parts_time = var_time.split(":")
                times = parts_time

            if self.file_loaded == False:
                entry_std = [file_std, len(list(df_data.keys())[1:]), dataset_time[0], dataset_time[-1],
                             times[0][0] + ":" + times[0][1] + ":" + times[0][2],
                             dates[0][0] + "/" + dates[0][1] + "/" + dates[0][2]]
            else:
                entry_std = [file_std, len(list(df_data.keys())[1:]), dataset_time[0], dataset_time[-1],
                             times[0] + ":" + times[1] + ":" + times[2]]

            tv_std.insert("", tk.END, values=entry_std)
            #
            self.temp_axes_checkup["STD"][file_std] = fig_checkup_std.add_subplot(label=file_std)
            self.temp_lines_checkup["STD"][file_std] = 0
        #
        tv_smpl = SE(
            parent=subwindow_imported_files, row_id=start_row + 17, column_id=start_column, n_rows=15, n_columns=26,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=6, text_n=["Name", "N Isotopes", "t(start)", "t(end)", "t(day)", "date"],
            width_n=["120", "80", "80", "80", "80", "80"], individual=True)
        #
        for index, var_file in enumerate(self.container_lists["SMPL"]["Long"]):
            parts = var_file.split("/")
            file_smpl = parts[-1]
            var_file_short = parts[-1]
            if self.file_loaded == False:
                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=3, skip_footer=1)
            else:
                df_data = self.container_measurements["Dataframe"][var_file_short]

            dataset_time = list(DE().get_times(dataframe=df_data))
            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            var_timestamp = self.container_icpms["timestamp"]
            var_icpms = self.container_icpms["name"]
            if self.file_loaded == False:
                dates, times = Data(filename=var_file).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
            else:
                var_time = self.container_var["acquisition times"]["SMPL"][var_file_short].get()
                parts_time = var_time.split(":")
                times = parts_time

            if self.file_loaded == False:
                entry_smpl = [file_smpl, len(list(df_data.keys())[1:]), dataset_time[0], dataset_time[-1],
                              times[0][0] + ":" + times[0][1] + ":" + times[0][2],
                              dates[0][0] + "/" + dates[0][1] + "/" + dates[0][2]]
            else:
                entry_smpl = [file_smpl, len(list(df_data.keys())[1:]), dataset_time[0], dataset_time[-1],
                              times[0] + ":" + times[1] + ":" + times[2]]

            tv_smpl.insert("", tk.END, values=entry_smpl)
            #
            self.temp_axes_checkup["SMPL"][file_smpl] = fig_checkup_smpl.add_subplot(label=file_smpl)
            self.temp_lines_checkup["SMPL"][file_smpl] = 0
        #
        ## INITIALIZATION
        self.change_graph_checkup(filetype="STD", initialization=True, var_fig=fig_checkup_std)
        self.change_graph_checkup(filetype="SMPL", initialization=True, var_fig=fig_checkup_smpl)

    #
    def change_graph_checkup(self, filetype, var_fig, mode="Next", initialization=False):
        counter_key = "Counter " + str(filetype)
        #
        for key, axis_item in self.temp_axes_checkup[filetype].items():
            axis_item.axis("off")
            axis_item.set_visible(False)
        #
        self.temp_canvas_checkup[filetype].draw()
        #
        if initialization == False:
            n_files = len(self.container_lists[filetype]["Long"])
            #
            if mode == "Next":
                if self.container_checkup[counter_key] < n_files - 1:
                    self.container_checkup[counter_key] += 1
                else:
                    self.container_checkup[counter_key] = 0
            else:
                if self.container_checkup[counter_key] > 0:
                    self.container_checkup[counter_key] -= 1
                else:
                    self.container_checkup[counter_key] = n_files - 1
        #
        var_file = self.container_lists[filetype]["Long"][self.container_checkup[counter_key]]
        #
        parts = var_file.split("/")
        var_file_short = parts[-1]
        var_fig = self.temp_figure_checkup[filetype]
        #
        if filetype == "STD":
            self.fi_current_file_std = var_file
        elif filetype == "SMPL":
            self.fi_current_file_smpl = var_file
        #
        if self.temp_lines_checkup[filetype][var_file_short] == 0:
            if self.file_loaded == False:
                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=3, skip_footer=1)
            else:
                df_data = self.container_measurements["Dataframe"][var_file_short]

            dataset_time = list(DE().get_times(dataframe=df_data))
            x_max = max(dataset_time)
            icp_measurements = np.array([[df_data[isotope] for isotope in self.container_lists["ISOTOPES"]]])
            y_max = np.amax(icp_measurements)
            #
            ## DIAGRAMS
            ax = var_fig.add_subplot(label=np.random.uniform())
            self.temp_axes_checkup[filetype][var_file_short] = ax
            #
            for isotope in self.container_lists["ISOTOPES"]:
                ln = ax.plot(dataset_time, df_data[isotope], label=isotope, color=self.isotope_colors[isotope],
                             linewidth=1, visible=True)
            #
            if self.pysills_mode in ["FI", "MI"]:
                var_check_bg = self.container_helper[filetype][var_file_short]["BG"]["Content"]
            else:
                var_check_bg = self.container_helper[filetype][var_file_short]["BG"]["Content"]
            #
            if len(var_check_bg) > 0:
                if self.pysills_mode in ["FI", "MI"]:
                    for var_id, var_content in self.container_helper[filetype][var_file_short]["BG"]["Content"].items():
                        times_bg = var_content["Times"]
                        #
                        box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.35, color=self.colors_intervals["BG"])
                else:
                    for var_id, var_content in self.container_helper[filetype][var_file_short]["BG"]["Content"].items():
                        times_bg = var_content["Times"]
                        #
                        box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.35, color=self.colors_intervals["BG"])
                    # times_bg = self.container_helper[filetype][var_file_short]["BG"][1]["Times"]
                    # #
                    # box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.5, color=self.colors_intervals["BG"])
            #
            if self.pysills_mode == "MA":
                signal_key = "MAT"
                var_check_sig = self.container_helper[filetype][var_file_short][signal_key]["Content"]
                # signal_key = "SIG"
                # var_check_sig = self.container_helper[filetype][var_file_short][signal_key]
            else:
                signal_key = "MAT"
                var_check_sig = self.container_helper[filetype][var_file_short][signal_key]["Content"]
            #
            if len(var_check_sig) > 0:
                if self.pysills_mode in ["FI"]:
                    for var_id, var_content in self.container_helper[filetype][var_file_short][signal_key][
                        "Content"].items():
                        times_sig = var_content["Times"]
                        var_color = self.colors_intervals["MAT"]
                        #
                        box_sig = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                elif self.pysills_mode in ["MI"]:
                    for var_id, var_content in self.container_helper[filetype][var_file_short][signal_key][
                        "Content"].items():
                        times_sig = self.container_helper[filetype][var_file_short][signal_key]["Content"][1]["Times"]
                        var_color = self.colors_intervals["MAT"]
                        #
                        box_sig = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                else:
                    for var_id, var_content in self.container_helper[filetype][var_file_short][signal_key][
                        "Content"].items():
                        times_sig = var_content["Times"]
                        var_color = self.colors_intervals["MAT"]
                        #
                        box_sig = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                    # times_sig = times_sig = self.container_helper[filetype][var_file_short][signal_key][1]["Times"]
                    # var_color = self.colors_intervals["SIG"]
                    # #
                    # box_sig = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
            #
            if self.pysills_mode == "MA":
                inclusion_key = "INCL"
                var_check_incl = []
            else:
                inclusion_key = "INCL"
                var_check_incl = self.container_helper[filetype][var_file_short][inclusion_key]["Content"]
            #
            if len(var_check_incl) > 0:
                if self.pysills_mode in ["FI"]:
                    for var_id, var_content in self.container_helper[filetype][var_file_short][inclusion_key][
                        "Content"].items():
                        times_sig = var_content["Times"]
                        #
                        box_sig = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35,
                                             color=self.colors_intervals["INCL"])
                elif self.pysills_mode in ["MI"]:
                    for var_id, var_content in self.container_helper[filetype][var_file_short][inclusion_key][
                        "Content"].items():
                        times_sig = self.container_helper[filetype][var_file_short][inclusion_key]["Content"][1][
                            "Times"]
                        #
                        box_sig = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35,
                                             color=self.colors_intervals["INCL"])
            #
            ax.grid(True)
            ax.set_yscale("log")
            ax.set_xlim(left=0, right=x_max)
            ax.set_xticks(np.arange(0, x_max, 20))
            ax.set_ylim(bottom=100, top=1.5*y_max)
            ax.grid(which="major", linestyle="-", linewidth=1)
            ax.minorticks_on()
            ax.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
            ax.set_axisbelow(True)
            ax.set_title(var_file_short, fontsize=9)
            ax.set_xlabel("Time (s)", labelpad=0.5, fontsize=8)
            ax.set_ylabel("Signal (cps)", labelpad=0.5, fontsize=8)
            ax.xaxis.set_tick_params(labelsize=8)
            ax.yaxis.set_tick_params(labelsize=8)
            #
            var_fig.subplots_adjust(bottom=0.125, top=0.925, left=0.1125, right=0.95)
            #
            self.temp_canvas_checkup[filetype].draw()
            #
            self.temp_lines_checkup[filetype][var_file_short] = 1
            #
        else:
            self.temp_axes_checkup[filetype][var_file_short].axis("on")
            self.temp_axes_checkup[filetype][var_file_short].set_visible(True)
            #
            self.temp_canvas_checkup[filetype].draw()

    def change_value_acquisition(self, filetype, event):
        if filetype == "STD":
            selected_item = self.tv_std.selection()[0]
            index = int(str(selected_item)[-1]) - 1
            new_time = self.var_entr_std_time.get()
            var_file = self.container_lists[filetype]["Short"][index]
            #
            self.tv_std.item(item=selected_item, text=var_file, values=(var_file, new_time))
        else:
            selected_item = self.tv_smpl.selection()[0]
            index = int(str(selected_item)[-1]) - 1
            new_time = self.var_entr_smpl_time.get()
            var_file = self.container_lists[filetype]["Short"][index]
            #
            self.tv_smpl.item(item=selected_item, text=var_file, values=(var_file, new_time))
        #
        self.container_var["acquisition times"][filetype][var_file].set(new_time)

    ########################################################################################################################
    ### EXTRAS #############################################################################################################
    ########################################################################################################################
    def ma_extras(self):
        """Main window of additional analysis tools for a mineral analysis project."""
        ## Window Settings
        window_width = 500
        window_height = 400
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_ma_extras = tk.Toplevel(self.parent)
        self.subwindow_ma_extras.title("MINERAL ANALYSIS - Extras")
        self.subwindow_ma_extras.geometry(var_geometry)
        self.subwindow_ma_extras.resizable(False, False)
        self.subwindow_ma_extras["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_ma_extras, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_ma_extras, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_ma_extras.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_ma_extras.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 12
        int_category_n = 8

        # Initialization
        for var_filetype in ["STD", "SMPL"]:
            for var_file_short in self.container_lists[var_filetype]["Short"]:
                self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)

        var_filetype = "None"
        var_file_short = "None"
        var_file_long = "None"
        var_focus = "None"

        for var_datatype in ["RAW", "SMOOTHED"]:
            # Intensity Analysis
            self.get_intensity(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_focus=var_focus, mode="All")

            if self.container_var["General Settings"]["Desired Average"].get() == 1:
                str_averagetype = "arithmetic mean"
            else:
                str_averagetype = "median"

            IQ(dataframe=None, project_type=self.pysills_mode,
               results_container=self.container_intensity_corrected["STD"][var_datatype]).get_averaged_intensities(
                data_container=self.container_intensity_corrected["STD"][var_datatype],
                average_type=str_averagetype)

            self.ma_get_intensity_ratio(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, var_focus=var_focus, mode="All")
            # Sensitivity Analysis
            self.get_analytical_sensitivity(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, mode="All")
            results_is = self.determine_possible_is(filetype="ALL")
            IQ(dataframe=None, project_type=self.pysills_mode,
               results_container=self.container_intensity_ratio).get_intensity_ratio(
                data_container=self.container_intensity_corrected, dict_is=results_is, datatype=var_datatype)
            # Compositional Analysis
            self.ma_get_concentration(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, mode="All")
            SQ(dataframe_01=self.container_intensity_corrected, dataframe_02=self.container_concentration,
               results_container=self.container_normalized_sensitivity).get_normalized_sensitivity(
                datatype=var_datatype, data_sensitivity=self.container_analytical_sensitivity, dict_is=results_is)
            self.ma_get_rsf(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, mode="All")
            self.ma_get_concentration_ratio(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, mode="All")
            self.ma_get_lod(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, mode="All")

        # LABELS
        lbl_01 = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Mineral classification", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001a = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001b = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 2, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (element ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001c = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 3, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001d = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 4, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxide ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001e = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 5, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001f = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 6, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_02 = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start, column_id=var_header_n, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Geothermometry", relief=tk.FLAT, fontsize="sans 10 bold")

        lbl_002 = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 1, column_id=var_header_n, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ti-in-Quartz", relief=tk.FLAT, fontsize="sans 10 bold")

        # BUTTONS
        btn_001a = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 1, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Elements": self.diagram_xy(mode))
        btn_001b = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 2, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Element ratios": self.diagram_xy(mode))
        btn_001c = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 3, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxides": self.diagram_xy(mode))
        btn_001d = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 4, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxide ratios": self.diagram_xy(mode))
        btn_001e = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 5, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_001f = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 6, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])

        if len(self.container_lists["Selected Oxides"]["All"]) == 0:
            btn_001c.configure(state="disabled")
            btn_001d.configure(state="disabled")

        btn_001e.configure(state="disabled")
        btn_001f.configure(state="disabled")

        btn_002 = SE(
            parent=self.subwindow_ma_extras, row_id=var_row_start + 1, column_id=var_header_n + int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.geothermometry_titanium_in_quartz)

    def geothermometry_titanium_in_quartz(self):
        """Window for the Titanium-in-Quartz thermometry."""
        ## Window Settings
        window_width = 800
        window_height = 400
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_geothermometry_ti_in_qz = tk.Toplevel(self.parent)
        self.subwindow_geothermometry_ti_in_qz.title("Geothermometry - Titanium-in-Quartz")
        self.subwindow_geothermometry_ti_in_qz.geometry(var_geometry)
        self.subwindow_geothermometry_ti_in_qz.resizable(False, False)
        self.subwindow_geothermometry_ti_in_qz["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_geothermometry_ti_in_qz, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_geothermometry_ti_in_qz, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_geothermometry_ti_in_qz.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_geothermometry_ti_in_qz.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 12
        int_category_n = 12

        # LABELS
        lbl_01 = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Titanium-in-Quartz Thermometry", relief=tk.FLAT, fontsize="sans 10 bold")

        lbl_02 = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start + 6, column_id=var_column_start,
            n_rows=1, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Additional Settings", relief=tk.FLAT, fontsize="sans 10 bold")

        lbl_03 = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start,
            column_id=var_column_start + var_header_n + 1, n_rows=1, n_columns=var_header_n + 14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Results", relief=tk.FLAT, fontsize="sans 10 bold")

        # BUTTONS
        btn_03 = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start + 5, column_id=var_row_start, n_rows=1,
            n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Run", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.run_geothermometer_titanium_in_quartz)
        btn_03 = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start + 5, column_id=6, n_rows=1,
            n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Export Results", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])

        # RADIOBUTTONS
        rb_001 = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start + 1, column_id=var_column_start,
            n_rows=1, n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["Geothermometry"]["Titanium in Quartz"], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="TitaniQ - after Wark (2006)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        ## TREEVIEW
        self.tv_results_ti_in_qz = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start + 1,
            column_id=var_column_start + var_header_n + 1, n_rows=14, n_columns=var_header_n + 14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=5, text_n=["Filename", "Data Type", "C(ppm)", "T(°C)", "T(K)"],
            width_n=["150", "100", "90", "90", "90"], individual=True)

        for index, str_filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            entry_results = [str_filename_short, "-", "-"]
            self.tv_results_ti_in_qz.insert("", tk.END, values=entry_results)
            file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]
            self.list_ti_isotopes = []

            for isotope in file_isotopes:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if element == "Ti":
                    self.list_ti_isotopes.append(isotope)

            for isotope_ti in self.list_ti_isotopes:
                entry_results = [isotope_ti, "-", "-"]
                self.tv_results_ti_in_qz.insert("", tk.END, values=entry_results)

    def run_geothermometer_titanium_in_quartz(self):
        if self.container_var["Geothermometry"]["Titanium in Quartz"].get() == 0:
            # TitaniQ
            self.calculate_temperature_titaniq()

    def calculate_temperature_titaniq(self):
        if len(self.tv_results_ti_in_qz.get_children()) > 0:
            for item in self.tv_results_ti_in_qz.get_children():
                self.tv_results_ti_in_qz.delete(item)

        for index, str_filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            entry_results = [str_filename_short, "-", "-"]
            self.tv_results_ti_in_qz.insert("", tk.END, values=entry_results)
            for datatype in ["RAW", "SMOOTHED"]:
                for isotope_ti in self.list_ti_isotopes:
                    val_concentration_ti = round(self.container_concentration["SMPL"][datatype][str_filename_short][
                                                     "MAT"][isotope_ti], 4)
                    val_temperature_i_celsius = -3765/(np.log(val_concentration_ti) - 5.69) - 273.15
                    val_temperature_i_kelvin = val_temperature_i_celsius + 273.15
                    entry_results = [isotope_ti, datatype, round(val_concentration_ti, 4),
                                     round(val_temperature_i_celsius, 2), round(val_temperature_i_kelvin, 2)]
                    self.tv_results_ti_in_qz.insert("", tk.END, values=entry_results)

    def fi_extras(self, init=False):
        """Main window of additional analysis tools for a fluid inclusion analysis project."""
        ## Window Settings
        window_width = 660
        window_height = 225
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_fi_extras = tk.Toplevel(self.parent)
        self.subwindow_fi_extras.title("FLUID INCLUSION ANALYSIS - Extras")
        self.subwindow_fi_extras.geometry(var_geometry)
        self.subwindow_fi_extras.resizable(False, False)
        self.subwindow_fi_extras["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_fi_extras, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_fi_extras, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_fi_extras.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_fi_extras.grid_columnconfigure(i, minsize=column_min)

        ## Initialization
        if init:
            for var_filetype in ["STD", "SMPL"]:
                for var_file_short in self.container_lists[var_filetype]["Short"]:
                    self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)

                if (self.container_var["Spike Elimination"]["STD"]["State"] == False and
                        self.container_var["Spike Elimination"]["SMPL"]["State"] == False):
                    list_datatype = ["RAW"]
                else:
                    list_datatype = ["RAW", "SMOOTHED"]

            var_filetype = "None"
            var_file_short = "None"
            var_file_long = "None"
            var_focus = "None"

            for var_datatype in list_datatype:
                if len(self.container_spikes) > 0:
                    # Intensity Results
                    self.get_intensity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_focus=var_focus, mode="All")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_focus=var_focus, mode="All")
                    self.fi_get_intensity_mix(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short, mode="All")
                    # Sensitivity Results
                    self.get_analytical_sensitivity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, mode="All")
                    results_is = self.determine_possible_is(filetype="ALL")
                    IQ(dataframe=None, project_type=self.pysills_mode,
                       results_container=self.container_intensity_ratio).get_intensity_ratio(
                        data_container=self.container_intensity_corrected, dict_is=results_is, datatype=var_datatype)
                    self.fi_get_rsf(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    # Concentration Results
                    self.fi_get_concentration2(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    self.fi_get_normalized_sensitivity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    self.fi_get_concentration_ratio(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    self.get_lod(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=None, mode="All")
                    self.fi_get_mixed_concentration_ratio(
                        var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long,
                        mode="All")
                    self.fi_get_mixing_ratio(
                        var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long,
                        mode="All")
                    self.fi_get_concentration_mixed(var_datatype=var_datatype, var_file_short=var_file_short,
                                                    mode="All")

        var_row_start = 0
        var_column_start = 0
        var_header_n = 16
        int_category_n = 12

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Matrix classification", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_02 = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start, column_id=var_header_n + 1, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Fluid classification", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001a = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001b = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 2, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (element ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001c = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 3, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001d = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 4, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxide ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001e = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 5, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001f = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 6, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002a = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 1, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002b = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 2, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (element ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002c = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 3, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002d = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 4, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxide ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002e = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 5, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002f = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 6, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002g = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 7, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Halogen ratios", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        # BUTTONS
        btn_001a = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 1, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Elements": self.diagram_xy(mode))
        btn_001b = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 2, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Element ratios": self.diagram_xy(mode))
        btn_001c = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 3, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxides": self.diagram_xy(mode))
        btn_001d = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 4, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxide ratios": self.diagram_xy(mode))
        btn_001e = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 5, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_001f = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 6, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])

        if len(self.container_lists["Selected Oxides"]["All"]) == 0:
            btn_001c.configure(state="disabled")
            btn_001d.configure(state="disabled")

        btn_001e.configure(state="disabled")
        btn_001f.configure(state="disabled")

        btn_002a = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 1, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Elements", focus="INCL": self.diagram_xy(mode, focus))
        btn_002b = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 2, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Element ratios", focus="INCL": self.diagram_xy(mode, focus))
        btn_002c = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 3, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxides", focus="INCL": self.diagram_xy(mode, focus))
        btn_002d = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 4, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxide ratios", focus="INCL": self.diagram_xy(mode, focus))
        btn_002e = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 5, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_002f = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 6, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_002g = SE(
            parent=self.subwindow_fi_extras, row_id=var_row_start + 7, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda init=True: self.halogen_ratios_diagram(init))

        if len(self.container_lists["Selected Oxides"]["All"]) == 0:
            btn_002c.configure(state="disabled")
            btn_002d.configure(state="disabled")

        btn_002e.configure(state="disabled")
        btn_002f.configure(state="disabled")

    def mi_extras(self, init=False):
        """Main window of additional analysis tools for a melt inclusion analysis project."""
        ## Window Settings
        window_width = 660
        window_height = 225
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_mi_extras = tk.Toplevel(self.parent)
        self.subwindow_mi_extras.title("MELT INCLUSION ANALYSIS - Extras")
        self.subwindow_mi_extras.geometry(var_geometry)
        self.subwindow_mi_extras.resizable(False, False)
        self.subwindow_mi_extras["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_mi_extras, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_mi_extras, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_mi_extras.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_mi_extras.grid_columnconfigure(i, minsize=column_min)

        ## Initialization
        if init:
            for var_filetype in ["STD", "SMPL"]:
                for var_file_short in self.container_lists[var_filetype]["Short"]:
                    self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)

                if (self.container_var["Spike Elimination"]["STD"]["State"] == False and
                        self.container_var["Spike Elimination"]["SMPL"]["State"] == False):
                    list_datatype = ["RAW"]
                else:
                    list_datatype = ["RAW", "SMOOTHED"]

            var_filetype = "None"
            var_file_short = "None"
            var_file_long = "None"
            var_focus = "None"

            for var_datatype in list_datatype:
                if len(self.container_spikes) > 0:
                    # Intensity Results
                    self.get_intensity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_focus=var_focus, mode="All")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_focus=var_focus, mode="All")
                    self.fi_get_intensity_mix(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short, mode="All")
                    # Sensitivity Results
                    self.get_analytical_sensitivity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, mode="All")
                    results_is = self.determine_possible_is(filetype="ALL")
                    IQ(dataframe=None, project_type=self.pysills_mode,
                       results_container=self.container_intensity_ratio).get_intensity_ratio(
                        data_container=self.container_intensity_corrected, dict_is=results_is, datatype=var_datatype)
                    self.fi_get_rsf(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    # Concentration Results
                    self.fi_get_concentration2(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    self.fi_get_normalized_sensitivity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    self.fi_get_concentration_ratio(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=var_focus, mode="All")
                    self.get_lod(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, var_focus=None, mode="All")
                    self.fi_get_mixed_concentration_ratio(
                        var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long,
                        mode="All")
                    self.fi_get_mixing_ratio(
                        var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long,
                        mode="All")
                    self.fi_get_concentration_mixed(var_datatype=var_datatype, var_file_short=var_file_short,
                                                    mode="All")

        var_row_start = 0
        var_column_start = 0
        var_header_n = 16
        int_category_n = 12

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Matrix classification", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_02 = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start, column_id=var_header_n + 1, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Fluid classification", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001a = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001b = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 2, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (element ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001c = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 3, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001d = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 4, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxide ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001e = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 5, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001f = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 6, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002a = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 1, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002b = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 2, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (element ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002c = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 3, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002d = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 4, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="x-y diagram (oxide ratios)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002e = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 5, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (elements)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_002f = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 6, column_id=var_header_n + 1, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="Ternary diagram (oxides)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        # BUTTONS
        btn_001a = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 1, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Elements": self.diagram_xy(mode))
        btn_001b = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 2, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Element ratios": self.diagram_xy(mode))
        btn_001c = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 3, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxides": self.diagram_xy(mode))
        btn_001d = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 4, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxide ratios": self.diagram_xy(mode))
        btn_001e = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 5, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_001f = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 6, column_id=int_category_n,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])

        if len(self.container_lists["Selected Oxides"]["All"]) == 0:
            btn_001c.configure(state="disabled")
            btn_001d.configure(state="disabled")

        btn_001e.configure(state="disabled")
        btn_001f.configure(state="disabled")

        btn_002a = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 1, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Elements", focus="INCL": self.diagram_xy(mode, focus))
        btn_002b = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 2, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Element ratios", focus="INCL": self.diagram_xy(mode, focus))
        btn_002c = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 3, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxides", focus="INCL": self.diagram_xy(mode, focus))
        btn_002d = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 4, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Oxide ratios", focus="INCL": self.diagram_xy(mode, focus))
        btn_002e = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 5, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_002f = SE(
            parent=self.subwindow_mi_extras, row_id=var_row_start + 6, column_id=var_header_n + int_category_n + 1,
            n_rows=1, n_columns=var_header_n - int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text="Setup", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])

        if len(self.container_lists["Selected Oxides"]["All"]) == 0:
            btn_002c.configure(state="disabled")
            btn_002d.configure(state="disabled")

        btn_002e.configure(state="disabled")
        btn_002f.configure(state="disabled")

    def diagram_xy(self, mode, focus="MAT", init=False):
        ## Window Settings
        window_width = 1000
        window_height = 600
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_diagram_xy = tk.Toplevel(self.parent)

        if self.pysills_mode == "MA":
            subwindow_diagram_xy.title("MINERAL ANALYSIS - Extras")
        elif self.pysills_mode == "FI":
            subwindow_diagram_xy.title("FLUID INCLUSION ANALYSIS - Extras")
        elif self.pysills_mode == "MI":
            subwindow_diagram_xy.title("MELT INCLUSION ANALYSIS - Extras")

        subwindow_diagram_xy.geometry(var_geometry)
        subwindow_diagram_xy.resizable(False, False)
        subwindow_diagram_xy["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_diagram_xy, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_diagram_xy, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_diagram_xy.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_diagram_xy.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 16
        int_category_n = 8

        ## LABELS
        if focus == "MAT":
            lbl_01 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.accent_color).create_simple_label(
                text="Matrix analysis", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        elif focus == "INCL":
            lbl_01 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.accent_color).create_simple_label(
                text="Inclusion analysis", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        self.oxides_xy = False

        if mode == "Elements":
            lbl_02 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Elements", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        elif mode == "Element ratios":
            lbl_02 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Element ratios", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        elif mode == "Oxides":
            lbl_02 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Oxides", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
            self.oxides_xy = True
        elif mode == "Oxide ratios":
            lbl_02 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 1, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Oxide ratios", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
            self.oxides_xy = True

        if "ratios" in mode:
            lbl_02 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 3, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="with respect to", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
            lbl_03 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 4, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Results", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        else:
            lbl_03 = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 3, column_id=var_column_start, n_rows=1,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Results", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        ## OPTION MENUS
        self.container_var["x-y diagram"]["x"].set("Select x")
        self.container_var["x-y diagram"]["y"].set("Select y")
        self.container_var["x-y diagram"]["z"].set("Select z")

        if self.oxides_xy == False:
            list_options = self.container_lists["Measured Isotopes"]["All"]
        else:
            if len(self.container_lists["Selected Oxides"]["All"]) > 0:
                list_options = self.container_lists["Selected Oxides"]["All"]

        opt_x = SE(
            parent=subwindow_diagram_xy, row_id=var_row_start + 2, column_id=var_column_start, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["x-y diagram"]["x"], option_list=list_options,
            text_set=self.container_var["x-y diagram"]["x"].get(), fg_active=self.bg_colors["Dark Font"],
            bg_active=self.accent_color,
            command=lambda var_x=self.container_var["x-y diagram"]["x"], var_y=self.container_var["x-y diagram"]["y"],
                           var_focus=focus: self.change_xy_diagram(var_x, var_y, var_focus))
        opt_x["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_x.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        opt_y = SE(
            parent=subwindow_diagram_xy, row_id=var_row_start + 2, column_id=var_column_start + int_category_n,
            n_rows=1, n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["x-y diagram"]["y"], option_list=list_options,
            text_set=self.container_var["x-y diagram"]["y"].get(), fg_active=self.bg_colors["Dark Font"],
            bg_active=self.accent_color,
            command=lambda var_x=self.container_var["x-y diagram"]["x"], var_y=self.container_var["x-y diagram"]["y"],
                           var_focus=focus: self.change_xy_diagram(var_x, var_y, var_focus))
        opt_y["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_y.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        if "ratios" in mode:
            opt_z = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 3, column_id=var_column_start + int_category_n,
                n_rows=1, n_columns=int_category_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_option_isotope(
                var_iso=self.container_var["x-y diagram"]["z"], option_list=list_options,
                text_set=self.container_var["x-y diagram"]["z"].get(), fg_active=self.bg_colors["Dark Font"],
                bg_active=self.accent_color,
                command=lambda var_x=self.container_var["x-y diagram"]["x"],
                               var_y=self.container_var["x-y diagram"]["y"], var_focus=focus, var_z=True:
                self.change_xy_diagram(var_x, var_y, var_focus, var_z))
            opt_z["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            opt_z.config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, highlightthickness=0)

        ## TREEVIEWS
        if "ratios" in mode:
            self.tv_results_xy = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 5, column_id=var_column_start, n_rows=n_rows - 6,
                n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
                n_categories=3, text_n=["File", "x", "y"], width_n=["120", "100", "100"], individual=True)
        else:
            self.tv_results_xy = SE(
                parent=subwindow_diagram_xy, row_id=var_row_start + 4, column_id=var_column_start, n_rows=n_rows - 5,
                n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
                n_categories=3, text_n=["File", "x", "y"], width_n=["120", "100", "100"], individual=True)

        ## FRAMES
        frm_01 = SE(
            parent=subwindow_diagram_xy, row_id=var_row_start, column_id=var_header_n + 1, n_rows=n_rows,
            n_columns=n_columns - var_header_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()

        ## DIAGRAMS
        self.create_xy_diagram(
            parent=subwindow_diagram_xy, var_row_start=var_row_start, var_column_start=var_header_n + 1,
            n_rows=n_rows, n_columns=n_columns - var_header_n - 1, init=True)

    def change_xy_diagram(self, var_x, var_y, var_focus, var_z=False, init=False):
        var_opt_x = self.container_var["x-y diagram"]["x"].get()
        var_opt_y = self.container_var["x-y diagram"]["y"].get()

        if var_opt_x != "Select x" and var_opt_y != "Select y":
            if len(self.tv_results_xy.get_children()) > 0:
                for item in self.tv_results_xy.get_children():
                    self.tv_results_xy.delete(item)

            self.ax_diagram_xy.clear()
            for index, str_filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
                if self.oxides_xy == True:
                    isotope_x = self.container_oxides[var_opt_x]["Isotopes"][0]
                    isotope_y = self.container_oxides[var_opt_y]["Isotopes"][0]
                    factor_x = 1
                    factor_y = 1

                    if "Fe" in isotope_x:
                        r = float(self.container_var["Oxides Quantification"]["Ratios"]["Fe-Ratio"].get())
                        if "Fe2O3" == var_opt_x:
                            factor_x = 1 - r
                        else:
                            factor_x = r
                    elif "Mn" in isotope_x:
                        r = float(self.container_var["Oxides Quantification"]["Ratios"]["Mn-Ratio"].get())
                        if "Mn2O3" == var_opt_x:
                            factor_x = 1 - r
                        else:
                            factor_x = r

                    if "Fe" in isotope_y:
                        r = float(self.container_var["Oxides Quantification"]["Ratios"]["Fe-Ratio"].get())
                        if "Fe2O3" == var_opt_y:
                            factor_y = 1 - r
                        else:
                            factor_y = r
                    elif "Mn" in isotope_y:
                        r = float(self.container_var["Oxides Quantification"]["Ratios"]["Mn-Ratio"].get())
                        if "Mn2O3" == var_opt_y:
                            factor_y = 1 - r
                        else:
                            factor_y = r

                    concentration_x = round(factor_x*self.container_concentration["SMPL"]["RAW"][str_filename_short][
                        var_focus][isotope_x], 4)
                    concentration_y = round(factor_y*self.container_concentration["SMPL"]["RAW"][str_filename_short][
                        var_focus][isotope_y], 4)
                else:
                    concentration_x = round(self.container_concentration["SMPL"]["RAW"][str_filename_short][var_focus][
                                                var_opt_x], 4)
                    concentration_y = round(self.container_concentration["SMPL"]["RAW"][str_filename_short][var_focus][
                                                var_opt_y], 4)

                if self.oxides_xy == True:
                    factor_x = 1/self.conversion_factors[var_opt_x]
                    factor_y = 1/self.conversion_factors[var_opt_y]
                    concentration_x = round(concentration_x/factor_x, 4)
                    concentration_y = round(concentration_y/factor_y, 4)

                if self.container_var["x-y diagram"]["z"].get() != "Select z":
                    var_z = True

                if var_z == True:
                    var_opt_z = self.container_var["x-y diagram"]["z"].get()
                    if self.oxides_xy == True:
                        isotope_z = self.container_oxides[var_opt_z]["Isotopes"][0]
                        concentration_z = round(self.container_concentration["SMPL"]["RAW"][str_filename_short][
                                                    var_focus][isotope_z], 4)
                        factor_z = 1/self.conversion_factors[var_opt_z]
                        concentration_z = round(concentration_z/factor_z, 4)
                    else:
                        concentration_z = round(self.container_concentration["SMPL"]["RAW"][str_filename_short][
                                                    var_focus][var_opt_z], 4)
                    if concentration_z > 0:
                        ratio_x = "{:0.4e}".format(concentration_x/concentration_z)
                        ratio_y = "{:0.4e}".format(concentration_y/concentration_z)
                    else:
                        ratio_x = np.nan
                        ratio_y = np.nan

                    entry_results = [str_filename_short, ratio_x, ratio_y]
                else:
                    entry_results = [str_filename_short, concentration_x, concentration_y]

                self.tv_results_xy.insert("", tk.END, values=entry_results)

                if var_z == True:
                    if np.nan not in [ratio_x, ratio_y]:
                        self.ax_diagram_xy.scatter(ratio_x, ratio_y, s=85, color=self.accent_color,
                                                   edgecolor="black", alpha=0.75)
                else:
                    self.ax_diagram_xy.scatter(concentration_x, concentration_y, s=85, color=self.accent_color,
                                               edgecolor="black", alpha=0.75)

            self.ax_diagram_xy.grid()

            if var_z == True:
                self.ax_diagram_xy.set_xlabel("C("+str(var_opt_x)+")/C("+str(var_opt_z)+") (1)")
                self.ax_diagram_xy.set_ylabel("C("+str(var_opt_y)+")/C("+str(var_opt_z)+") (1)")
            else:
                self.ax_diagram_xy.set_xlabel("C("+str(var_opt_x)+") (ppm)")
                self.ax_diagram_xy.set_ylabel("C("+str(var_opt_y)+") (ppm)")

            self.ax_diagram_xy.set_axisbelow(True)

            self.canvas_diagram_xy.draw()

    def create_xy_diagram(self, parent, var_row_start, var_column_start, n_rows, n_columns, init=False):
        self.fig_diagram_xy = Figure(figsize=(10,5), tight_layout=True, facecolor=self.bg_colors["Very Light"])

        self.canvas_diagram_xy = FigureCanvasTkAgg(self.fig_diagram_xy, master=parent)
        self.canvas_diagram_xy.get_tk_widget().grid(
            row=var_row_start, column=var_column_start, rowspan=n_rows - 1, columnspan=n_columns,
            sticky="nesw")

        self.toolbarFrame_diagram_xy = tk.Frame(master=parent)
        self.toolbarFrame_diagram_xy.grid(
            row=n_rows - 1, column=var_column_start, rowspan=1, columnspan=n_columns, sticky="ew")

        self.toolbar_diagram_xy = NavigationToolbar2Tk(self.canvas_diagram_xy, self.toolbarFrame_diagram_xy)
        self.toolbar_diagram_xy.config(
            bg=self.bg_colors["Very Light"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
            highlightcolor=self.bg_colors["Dark Font"], bd=0)
        self.toolbar_diagram_xy._message_label.config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_diagram_xy.winfo_children()[-2].config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])

        ax = self.fig_diagram_xy.add_subplot(label=np.random.uniform())

        ax.grid()
        ax.set_xlabel("C(x) (ppm)")
        ax.set_ylabel("C(y) (ppm)")
        ax.set_axisbelow(True)

        self.ax_diagram_xy = ax

    def halogen_ratios_diagram(self, init=False):
        ## Window Settings
        window_width = 800
        window_height = 600
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_halogen_ratios = tk.Toplevel(self.parent)
        subwindow_halogen_ratios.title("FLUID INCLUSION ANALYSIS - Extras")
        subwindow_halogen_ratios.geometry(var_geometry)
        subwindow_halogen_ratios.resizable(False, False)
        subwindow_halogen_ratios["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_halogen_ratios, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_halogen_ratios, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_halogen_ratios.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_halogen_ratios.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 10
        int_category_n = 6

        self.helper_scatter_points = {}

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_halogen_ratios, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="File manager", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        ## TABLES
        frm_01 = SE(
            parent=subwindow_halogen_ratios, row_id=var_row_start + 1, column_id=var_column_start,
            n_rows=n_rows - 2, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()
        vsb_01 = ttk.Scrollbar(master=frm_01, orient="vertical")
        text_01 = tk.Text(
            master=frm_01, width=30, height=25, yscrollcommand=vsb_01.set, bg=self.bg_colors["Very Light"])
        vsb_01.config(command=text_01.yview)
        vsb_01.pack(side="right", fill="y")
        text_01.pack(side="left", fill="both", expand=True)

        self.helper_halogen_ratios = {"Checkboxes": {}, "Results": {}}
        for filename_short in self.container_lists["SMPL"]["Short"]:
            if filename_short not in self.helper_halogen_ratios:
                self.helper_halogen_ratios[filename_short] = tk.IntVar()
                self.helper_halogen_ratios[filename_short].set(1)

            if filename_short not in self.helper_scatter_points:
                self.helper_scatter_points[filename_short] = []

            str_filename_short = filename_short
            cb_i = tk.Checkbutton(
                master=frm_01, text=filename_short, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"],
                variable=self.helper_halogen_ratios[filename_short],
                command=lambda filename_short=str_filename_short: self.select_file_halogen_ratio(filename_short))
            self.helper_halogen_ratios["Checkboxes"][filename_short] = cb_i
            text_01.window_create("end", window=cb_i)
            text_01.insert("end", "\n")

        ## INITIALIZATION
        frm_02= SE(
            parent=subwindow_halogen_ratios, row_id=var_row_start, column_id=var_header_n,
            n_rows=n_rows, n_columns=n_columns - var_header_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()

        self.create_halogen_ratio_diagram(
            parent=subwindow_halogen_ratios, var_row_start=var_row_start, var_header_n=var_header_n, n_rows=n_rows,
            n_columns=n_columns)

        if init == True:
            for filename_short in self.container_lists["SMPL"]["Short"]:
                self.select_file_halogen_ratio(filename_short, initialization=init)

    def create_halogen_ratio_diagram(self, parent, var_row_start, var_header_n, n_rows, n_columns):
        self.fig_halogen_ratios = Figure(figsize=(10,5), tight_layout=True, facecolor=self.bg_colors["Very Light"])

        self.canvas_halogen_ratios = FigureCanvasTkAgg(self.fig_halogen_ratios, master=parent)
        self.canvas_halogen_ratios.get_tk_widget().grid(
            row=var_row_start, column=var_header_n, rowspan=n_rows - 2, columnspan=n_columns - var_header_n,
            sticky="nesw")

        self.toolbarFrame_halogen_ratios = tk.Frame(master=parent)
        self.toolbarFrame_halogen_ratios.grid(
            row=n_rows - 2, column=var_header_n, rowspan=1, columnspan=n_columns - var_header_n, sticky="ew")

        self.toolbar_halogen_ratios = NavigationToolbar2Tk(self.canvas_halogen_ratios, self.toolbarFrame_halogen_ratios)
        self.toolbar_halogen_ratios.config(
            bg=self.bg_colors["Very Light"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
            highlightcolor=self.bg_colors["Dark Font"], bd=0)
        self.toolbar_halogen_ratios._message_label.config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_halogen_ratios.winfo_children()[-2].config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])

        ax = self.fig_halogen_ratios.add_subplot(label=np.random.uniform())
        ax2 = ax.twiny()

        ax.set_xscale("log")
        ax2.set_xscale("log")
        ax.set_yscale("log")
        ax.set_xlim(4*10**(-1), 3*10**5)
        ax.set_ylim(1*10**(-2), 3*10**2)
        ax2.set_xlim(7*10**(4), 1*10**-1)
        ax.grid()

        ax.set_xlabel("I/Cl ($\\mu$mol)")
        ax.set_ylabel("Br/Cl (mmol)")
        ax2.set_xlabel("Br/I (mol)")
        ax.set_title("Halogen systematics of natural fluid inclusions")

        data_icl = self.create_iodine_chlorine_ratio()
        data_brcl = self.create_bromine_chlorine_ratio()

        data_icl = data_icl*10**6
        data_brcl = data_brcl*10**3

        data_halite = [0.788390, 0.098038]
        data_sylvite = [0.774990, 0.392940]
        data_seawater = [0.751910, 1.522500]

        data_x_set = [0.75828, 1.5245, 2.3861, 3.0648, 3.2736, 3.4056, 3.6857, 4.0955, 4.4324, 4.6723, 5.0566, 5.9229,
                      6.8467, 6.6686, 6.4101, 6.3262]
        data_y_set = [1.522500, 1.522500, 1.522500, 1.522500, 1.7425, 1.9953, 2.4781, 3.4068, 4.289, 5.1147, 6.4391,
                      6.6159, 6.7976, 7.9973, 9.4087, 10.275]

        data_icl2 = np.linspace(data_seawater[0], 10**6, 7500)

        a_lower = 0.5*10**(-3)
        a_upper = 2.5*10**(-3)
        a_upper2 = 2.5*10**(-3)
        b = data_seawater[1]

        x = data_icl[:len(data_brcl)]

        ax.scatter(data_halite[0], data_halite[1], marker="D", s=67, color="lightgrey", edgecolor="black",
                   label="Halite", zorder=2)
        ax.scatter(data_sylvite[0], data_sylvite[1], marker="s", s=67, color="lightgrey", edgecolor="black",
                   label="Sylvite", zorder=2)
        ax.scatter(data_seawater[0], data_seawater[1], marker="*", s=175, color="lightgrey", edgecolor="black",
                   label="Seawater", zorder=2)

        ax.fill_between(data_icl2, a_upper*data_icl2 + b, a_lower*data_icl2 + b, color="0.75", alpha=0.25, zorder=0)
        ax.plot(data_icl2, a_lower*data_icl2 + b, linestyle="dotted", color="black", linewidth=2, alpha=0.75, zorder=1,
                label="Br/I=0.5")
        ax.plot(data_icl2, a_upper*data_icl2 + b, linestyle="dashed", color="black", linewidth=2, alpha=0.75, zorder=1,
                label="Br/I=2.5")

        ax.plot(data_x_set, data_y_set, linestyle="solid", color="black", linewidth=2, alpha=1, zorder=1, label="SET")

        ax.plot(data_icl, data_icl*10**(3), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(2), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(1), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(0), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(-1), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(-2), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(-3), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(-4), linestyle="dashed", color="grey", alpha=0.5)
        ax.plot(data_icl, data_icl*10**(-5), linestyle="dashed", color="grey", alpha=0.5)

        ax.set_axisbelow(True)

        ax.legend(loc="lower right", fontsize="small", framealpha=1.0)
        self.ax_halogen_ratio = ax

    def create_iodine_chlorine_ratio(self):
        start_data = np.linspace(0.01, 1, 100)
        factor_data = [10**x for x in range(1, 6)]
        new_data = list(start_data)

        for value_start in start_data:
            for factor in factor_data:
                value = factor*value_start*10**(-6)
                new_data.append(value)
        final_data = np.sort(new_data)

        return final_data

    def create_bromine_chlorine_ratio(self):
        start_data = np.linspace(0.01, 1, 100)
        factor_data = [10**x for x in range(1, 3)]
        new_data = list(start_data)

        for value_start in start_data:
            for factor in factor_data:
                value = factor*value_start*10**(-3)
                new_data.append(value)
        final_data = np.sort(new_data)

        return final_data

    def iodine_to_bromine(self, x):
        return x

    def rad2deg(self, x):
        return x*180/np.pi

    def select_file_halogen_ratio(self, filename_short, initialization=False):
        molar_mass_cl = self.chemistry_data["Cl"]
        molar_mass_br = self.chemistry_data["Br"]
        molar_mass_i = self.chemistry_data["I"]
        conversion_cl = 1/(molar_mass_cl)
        conversion_br = 1/(molar_mass_br)
        conversion_i = 1/(molar_mass_i)

        if self.helper_halogen_ratios[filename_short].get() == 1 or initialization == True:
            if ("Cl" in self.container_lists["Measured Elements"] and
                    "Br" in self.container_lists["Measured Elements"] and
                    "I" in self.container_lists["Measured Elements"]):
                elements_list = ["Cl", "Br", "I"]
                isotopes_dict = {"Cl": [], "Br": [], "I": []}
                for element in elements_list:
                    isotopes_list = self.container_lists["Measured Elements"][filename_short][element]
                    isotopes_dict[element] = isotopes_list

                helper_icl = []
                helper_brcl = []
                for isotope_cl in isotopes_dict["Cl"]:
                    concentration_cl = conversion_cl*self.container_concentration["SMPL"]["SMOOTHED"][filename_short][
                        "INCL"][isotope_cl]
                    for isotope_i in isotopes_dict["I"]:
                        concentration_i = conversion_i*self.container_concentration["SMPL"]["SMOOTHED"][filename_short][
                            "INCL"][isotope_i]
                        val_icl = (concentration_i/concentration_cl)*10**6
                        helper_icl.append(val_icl)
                        for isotope_br in isotopes_dict["Br"]:
                            concentration_br = conversion_br*self.container_concentration["SMPL"]["SMOOTHED"][
                                filename_short]["INCL"][isotope_br]
                            val_brcl = (concentration_br/concentration_cl)*10**3
                            helper_brcl.append(val_brcl)
                            if 0.0 not in [val_icl, val_brcl]:
                                sct = self.ax_halogen_ratio.scatter(
                                    val_icl, val_brcl, s=50, color=self.accent_color, edgecolor="black", zorder=2,
                                    alpha=0.75)
                                self.helper_scatter_points[filename_short].append(sct)
                            else:
                                self.helper_halogen_ratios[filename_short].set(0)
                                self.helper_halogen_ratios["Checkboxes"][filename_short].configure(state="disabled")
            else:
                if "I" not in self.container_lists["Measured Elements"]:
                    elements_list = ["Cl", "Br"]
                    isotopes_dict = {"Cl": [], "Br": []}
                    for element in elements_list:
                        isotopes_list = self.container_lists["Measured Elements"][filename_short][element]
                        isotopes_dict[element] = isotopes_list

                    helper_icl = []
                    helper_brcl = []
                    for isotope_cl in isotopes_dict["Cl"]:
                        concentration_cl = conversion_cl*self.container_concentration["SMPL"]["SMOOTHED"][
                            filename_short]["INCL"][isotope_cl]
                        concentration_i = conversion_i*100
                        val_icl = (concentration_i/concentration_cl)*10**6
                        helper_icl.append(val_icl)
                        for isotope_br in isotopes_dict["Br"]:
                            concentration_br = conversion_br*self.container_concentration["SMPL"]["SMOOTHED"][
                                filename_short]["INCL"][isotope_br]
                            val_brcl = (concentration_br/concentration_cl)*10**3
                            helper_brcl.append(val_brcl)
                            if 0.0 not in [val_icl, val_brcl]:
                                sct = self.ax_halogen_ratio.scatter(
                                    val_icl, val_brcl, s=50, color=self.accent_color, edgecolor="black", zorder=2,
                                    alpha=0.75)
                                self.helper_scatter_points[filename_short].append(sct)
                            else:
                                self.helper_halogen_ratios[filename_short].set(0)
                                self.helper_halogen_ratios["Checkboxes"][filename_short].configure(state="disabled")
        else:
            for sct_item in self.helper_scatter_points[filename_short]:
                sct_item.set_visible(False)

        self.canvas_halogen_ratios.draw()

    ####################################################################################################################
    # MINERAL ANALYSIS #################################################################################################
    ####################################################################################################################
    def ma_settings(self):
        """Main settings window of a mineral analysis project."""
        if self.file_system_need_update:
            path2 = os.getcwd()
            path = self.path_pysills
            parent = os.path.dirname(path)

            if self.demo_mode:
                self.var_opt_icp.set("Agilent 7900s")
                self.select_icp_ms(var_opt=self.var_opt_icp)
                ma_demo_files = {"ALL": [], "STD": [], "SMPL": []}

                try:
                    folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")
                    folder_path = folder_path.replace("\\", "/")
                    demo_files = os.listdir(path=folder_path)
                except:
                    if "pysills" not in self.path_pysills_main:
                        folder_path = os.path.join(self.path_pysills_main, "pysills", "lib", "demo_files")
                    else:
                        folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")

                    if self.var_os == "win32":
                        folder_path = folder_path.replace("\\", "/")

                    demo_files = os.listdir(path=folder_path)

                for file in demo_files:
                    if file.startswith("demo_ma"):
                        #folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")
                        #folder_path = self.path_pysills_main + str(r"/lib/demo_files/")
                        path_complete = os.path.join(folder_path, file)
                        if "_copy" not in path_complete:
                            path_raw = pathlib.PureWindowsPath(path_complete)
                            ma_demo_files["ALL"].append(str(path_raw.as_posix()))

                ma_demo_files["ALL"].sort()
                ma_demo_files["STD"].extend(ma_demo_files["ALL"][:3])
                ma_demo_files["STD"].extend(ma_demo_files["ALL"][-3:])
                ma_demo_files["SMPL"].extend(ma_demo_files["ALL"][3:-4])

                self.list_std = ma_demo_files["STD"]
                self.list_smpl = ma_demo_files["SMPL"]

            if len(self.list_std) > 0:
                self.ma_current_file_std = self.list_std[0]

            if len(self.list_smpl) > 0:
                self.ma_current_file_smpl = self.list_smpl[0]

            for file_std in self.list_std:
                file_parts = file_std.split("/")
                if file_std not in self.container_lists["STD"]["Long"]:
                    self.container_lists["STD"]["Long"].append(file_std)
                    self.container_lists["STD"]["Short"].append(file_parts[-1])
                if self.demo_mode:
                    self.lb_std.insert(tk.END, file_parts[-1])

                for item in ["Quickview", "File Setup", "Results Intensity", "Results Concentration",
                             "Results Sensitivity", "SE STD", "SE SMPL"]:
                    self.container_var["Subwindows"][self.pysills_mode][item] = {}

            for file_smpl in self.list_smpl:
                file_parts = file_smpl.split("/")
                if file_smpl not in self.container_lists["SMPL"]["Long"]:
                    self.container_lists["SMPL"]["Long"].append(file_smpl)
                    self.container_lists["SMPL"]["Short"].append(file_parts[-1])
                if self.demo_mode:
                    self.lb_smpl.insert(tk.END, file_parts[-1])

            for file_std in self.list_std:
                file_parts = file_std.split("/")
                if self.file_loaded == False:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_exmpl = DE(filename_long=file_std).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_exmpl = DE(filename_long=file_std).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                else:
                    if "Dataframe" in self.container_measurements:
                        file_parts = file_std.split("/")
                        df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]
                    else:
                        if self.container_icpms["name"] != None:
                            var_skipheader = self.container_icpms["skipheader"]
                            var_skipfooter = self.container_icpms["skipfooter"]
                            df_exmpl = DE(filename_long=file_std).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        else:
                            df_exmpl = DE(filename_long=file_std).get_measurements(
                                delimiter=",", skip_header=3, skip_footer=1)

                self.times = DE().get_times(dataframe=df_exmpl)
                df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
                self.container_lists["ISOTOPES"] = df_isotopes
                self.container_lists["Measured Isotopes"][file_parts[-1]] = df_isotopes
                self.container_lists["Measured Isotopes"]["All"] = self.container_lists["ISOTOPES"]

                for isotope in self.container_lists["Measured Isotopes"][file_parts[-1]]:
                    if isotope.isdigit():
                        print("There is a problem with an isotope that is probably just a number. "
                              "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                        self.container_lists["Measured Isotopes"][file_parts[-1]].remove(isotope)
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        if key_element != None:
                            element = key_element.group(1)
                            if element not in self.container_lists["Measured Elements"]["All"]:
                                self.container_lists["Measured Elements"]["All"].append(element)

            for file_smpl in self.list_smpl:
                file_parts = file_smpl.split("/")
                if self.file_loaded == False:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_exmpl = DE(filename_long=file_smpl).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_exmpl = DE(filename_long=file_smpl).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                else:
                    if "Dataframe" in self.container_measurements:
                        file_parts = file_smpl.split("/")
                        df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]
                    else:
                        if self.container_icpms["name"] != None:
                            var_skipheader = self.container_icpms["skipheader"]
                            var_skipfooter = self.container_icpms["skipfooter"]
                            df_exmpl = DE(filename_long=file_smpl).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        else:
                            df_exmpl = DE(filename_long=file_smpl).get_measurements(
                                delimiter=",", skip_header=3, skip_footer=1)

                self.times = DE().get_times(dataframe=df_exmpl)
                df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
                self.container_lists["ISOTOPES"] = df_isotopes
                self.container_lists["Measured Isotopes"][file_parts[-1]] = df_isotopes
                self.container_lists["Measured Isotopes"]["All"] = self.container_lists["ISOTOPES"]

                for isotope in self.container_lists["Measured Isotopes"][file_parts[-1]]:
                    if isotope.isdigit():
                        print("There is a problem with an isotope that is probably just a number. "
                              "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                        self.container_lists["Measured Isotopes"][file_parts[-1]].remove(isotope)
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        if key_element != None:
                            element = key_element.group(1)
                            if element not in self.container_lists["Measured Elements"]["All"]:
                                self.container_lists["Measured Elements"]["All"].append(element)

            if "Dataframe" not in self.container_measurements:
                self.container_measurements["Dataframe"] = {}

            if file_parts[-1] not in self.container_measurements["Dataframe"]:
                self.container_measurements["Dataframe"][file_parts[-1]] = df_exmpl

            self.times = DE().get_times(dataframe=df_exmpl)
            df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
            self.container_lists["ISOTOPES"] = df_isotopes
            self.container_lists["Measured Isotopes"][file_parts[-1]] = df_isotopes
            self.container_lists["Measured Isotopes"]["All"] = self.container_lists["ISOTOPES"]

            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                if isotope.isdigit():
                    print("There is a problem with an isotope (->", isotope, "<-) that is probably just a number. "
                          "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                else:
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    if key_element != None:
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"]["All"]:
                            self.container_lists["Measured Elements"]["All"].append(element)

            for filename_short in self.container_lists["STD"]["Short"]:
                self.container_lists["Measured Elements"][filename_short] = {}
                self.container_lists["Measured Isotopes"][filename_short] = df_isotopes
                for isotope in self.container_lists["Measured Isotopes"][filename_short]:
                    if isotope.isdigit():
                        pass
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"][filename_short]:
                            self.container_lists["Measured Elements"][filename_short][element] = [isotope]
                        else:
                            if isotope not in self.container_lists["Measured Elements"][filename_short][element]:
                                self.container_lists["Measured Elements"][filename_short][element].append(isotope)

            for filename_short in self.container_lists["SMPL"]["Short"]:
                self.container_lists["Measured Elements"][filename_short] = {}
                self.container_lists["Measured Isotopes"][filename_short] = df_isotopes
                for isotope in self.container_lists["Measured Isotopes"][filename_short]:
                    if isotope.isdigit():
                        pass
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"][filename_short]:
                            self.container_lists["Measured Elements"][filename_short][element] = [isotope]
                        else:
                            if isotope not in self.container_lists["Measured Elements"][filename_short][element]:
                                self.container_lists["Measured Elements"][filename_short][element].append(isotope)

            self.define_isotope_colors()

        ## Window Settings
        window_width = 1300
        window_height = 950
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        str_title_window = self.language_dict["MINERAL ANALYSIS - Setup"][self.var_language]
        self.subwindow_ma_settings = tk.Toplevel(self.parent)
        self.subwindow_ma_settings.title(str_title_window)
        self.subwindow_ma_settings.geometry(var_geometry)
        self.subwindow_ma_settings.resizable(False, False)
        self.subwindow_ma_settings["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_ma_settings, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_ma_settings, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_ma_settings.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_ma_settings.grid_columnconfigure(i, minsize=column_min)

        ## INITIALIZATION
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            if isotope.isdigit():
                pass
            else:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)

                if element not in self.container_lists["Elements"]:
                    self.container_lists["Elements"].append(element)
                if element not in self.container_lists["Measured Elements"]:
                    self.container_lists["Measured Elements"][element] = []
                if isotope not in self.container_lists["Measured Elements"][element]:
                    self.container_lists["Measured Elements"][element].append(isotope)

                if isotope not in self.container_var["Spike Elimination"]["Threshold"]:
                    self.container_var["Spike Elimination"]["Threshold"][isotope] = tk.StringVar()
                    self.container_var["Spike Elimination"]["Threshold"][isotope].set(var_threshold.get())

        ## Static
        # Build section 'Project Information'
        var_project_information = {"Row start": 0, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_project_information(var_geometry_info=var_project_information)
        # Build section 'Standard Reference Material'
        var_standard_reference_material = {"Row start": 3, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_standard_reference_material(var_geometry_info=var_standard_reference_material)
        # Build section 'Matrix Settings'
        var_sample_settings = {"Row start": 6, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_sample_settings(var_geometry_info=var_sample_settings)
        # Build section 'Assemblage Setup'
        var_assemblage_setup = {"Row start": 8, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_assemblage_setup(var_geometry_info=var_assemblage_setup)
        # Build section 'Dwell Time Setup'
        var_dwell_time_setup = {"Row start": 10, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_dwell_time_setup(var_geometry_info=var_dwell_time_setup)
        # Build section 'Calculation Window (Background) Setup'
        var_calculation_window_bg_setup = {"Row start": 12, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_calculation_window_bg(var_geometry_info=var_calculation_window_bg_setup)
        # Build section 'Calculation Window (Sample) Setup'
        var_calculation_window_smpl_setup = {"Row start": 16, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_calculation_window_smpl(var_geometry_info=var_calculation_window_smpl_setup)
        # Build section 'Spike Elimination Setup'
        var_spike_elimination_setup = {"Row start": 20, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_spike_elimination_setup(var_geometry_info=var_spike_elimination_setup)
        # Build section 'Check-Up'
        var_checkup = {"Row start": 26, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_checkup_feature(var_geometry_info=var_checkup)
        # Build section 'Acquisition Times'
        var_acquisition_times_check = {"Row start": 17, "Column start": 46, "N rows": 1, "N columns": 18}
        self.place_acquisition_times_check(var_geometry_info=var_acquisition_times_check)
        # Build section 'Standard Files'
        var_standard_files = {"Row start": 0, "Column start": 19, "N rows": 15, "N columns": 26}
        self.place_standard_files_table(var_geometry_info=var_standard_files)
        # Build section 'Sample Files'
        var_sample_files = {"Row start": 17, "Column start": 19, "N rows": 18, "N columns": 26}
        self.place_sample_files_table(var_geometry_info=var_sample_files)
        # Build section 'Time-Signal Diagram Checker'
        self.define_isotope_colors()
        var_time_signal_diagram_check = {"Row start": 25, "Column start": 46, "N rows": 1, "N columns": 18}
        self.place_time_signal_plot_checker(var_geometry_info=var_time_signal_diagram_check)
        # Build section 'Measured Isotopes'
        var_measured_isotopes = {"Row start": 1, "Column start": 46, "N rows": 15, "N columns": 18}
        self.place_measured_isotopes_overview(var_geometry_info=var_measured_isotopes)

        ## INITIALIZATION
        self.calculate_threshold_spike_elimination()
        self.select_spike_elimination(
            var_opt=self.container_var["Spike Elimination Method"].get(),
            start_row=var_spike_elimination_setup["Row start"], mode="MA")

        if self.file_loaded:
            list_files = []
            list_files_std = self.container_lists["STD"]["Short"].copy()
            list_files_smpl = self.container_lists["SMPL"]["Short"].copy()
            list_files.extend(list_files_std)
            list_files.extend(list_files_smpl)
            for filename_short in list_files:
                if filename_short in self.container_spikes:
                    if len(self.container_spikes[filename_short]) > 0:
                        pass
                    else:
                        if self.copied_file == False:
                            if self.container_var["Spike Elimination"]["STD"]["State"]:
                                if self.container_var["Spike Elimination Method"].get() in [
                                    "Grubbs-Test (SILLS)", "Grubbs-Test", "PySILLS Spike Finder", "Grubbs test",
                                    "Whisker analysis"]:
                                    var_method = "Grubbs"
                                    self.spike_elimination_all(filetype="STD", algorithm=var_method)
                            if self.container_var["Spike Elimination"]["SMPL"]["State"]:
                                if self.container_var["Spike Elimination Method"].get() in [
                                    "Grubbs-Test (SILLS)", "Grubbs-Test", "PySILLS Spike Finder", "Grubbs test",
                                    "Whisker analysis"]:
                                    var_method = "Grubbs"
                                    self.spike_elimination_all(filetype="SMPL", algorithm=var_method)
                        else:
                            if filename_short in list_files_std:
                                filetype = "STD"
                            elif filename_short in list_files_smpl:
                                filetype = "SMPL"

                            self.single_spike_elimination(var_filetype=filetype, var_filename_short=filename_short)
                else:
                    self.container_spikes[filename_short] = {}
        else:
            self.ma_select_srm_default(var_opt=self.container_var["SRM"]["default"][0].get())
            self.ma_select_srm_default(var_opt=self.container_var["SRM"]["default"][1].get(), mode="ISOTOPES")
            self.ma_select_id_default(var_opt=self.container_var["ID"]["Default SMPL"].get())

        self.build_srm_database()
        self.file_system_need_update = False
        self.btn_save_project.configure(state="normal")

    def place_project_information(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Project Information'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        # Labels
        str_lbl_01 = self.language_dict["Project Information"][self.var_language]
        str_lbl_02 = self.language_dict["Author"][self.var_language]
        str_lbl_03 = self.language_dict["Source ID"][self.var_language]

        lbl_01 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01a = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold")

        # Entries
        self.container_var[var_setting_key]["Author"].set(
            self.container_var["General Settings"]["Default Author"].get())
        var_entr_01a_default = self.container_var[var_setting_key]["Author"].get()
        var_entr_01b_default = self.container_var[var_setting_key]["Source ID"].get()

        entr_01a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[var_setting_key]["Author"], text_default=var_entr_01a_default)
        entr_01b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_category_n, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[var_setting_key]["Source ID"], text_default=var_entr_01b_default)

    def place_standard_reference_material(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Standard Reference Material'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        # Labels
        str_lbl_01 = self.language_dict["Standard Reference Material (SRM)"][self.var_language]
        str_lbl_02 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_03 = self.language_dict["Isotopes"][self.var_language]

        lbl_02 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n - 4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n - 4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold")

        # Option Menus
        if self.container_var["SRM"]["default"][0].get() != "Select SRM":
            var_text_std = self.container_var["SRM"]["default"][0].get()
        else:
            if self.container_var["General Settings"]["Default SRM"].get() != "Select SRM":
                var_text_std = self.container_var["General Settings"]["Default SRM"].get()
            else:
                var_text_std = "Select SRM"

        self.container_var["SRM"]["default"][0].set(var_text_std)

        if self.container_var["SRM"]["default"][1].get() != "Select SRM":
            var_text_iso = self.container_var["SRM"]["default"][1].get()
        else:
            if self.container_var["General Settings"]["Default SRM"].get() != "Select SRM":
                var_text_iso = self.container_var["General Settings"]["Default SRM"].get()
            else:
                var_text_iso = "Select SRM"

        self.container_var["SRM"]["default"][1].set(var_text_iso)

        opt_02a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n - 4, n_rows=var_row_n,
            n_columns=var_category_n - 2, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_srm(
            var_srm=self.container_var["SRM"]["default"][0], text_set=var_text_std,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            option_list=self.container_lists["SRM Library"],
            command=lambda var_srm=self.container_var["SRM"]["default"][0]: self.change_srm_default(var_srm))
        opt_02a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_02a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        opt_02b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_category_n - 4, n_rows=var_row_n,
            n_columns=var_category_n - 2, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_srm(
            var_srm=self.container_var["SRM"]["default"][1], text_set=var_text_iso,
            fg_active=self.bg_colors["Dark Font"], option_list=self.container_lists["SRM Library"],
            bg_active=self.accent_color, command=lambda var_srm=self.container_var["SRM"]["default"][1]:
            self.change_srm_default(var_srm, key="isotope"))
        opt_02b["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_02b.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

    def place_sample_settings(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Sample Settings'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
            str_lbl_01 = self.language_dict["Sample Settings"][self.var_language]
            str_btn_01 = self.language_dict["Setup"][self.var_language]
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
            str_lbl_01 = self.language_dict["Matrix Settings"][self.var_language]
            str_btn_01 = self.language_dict["Setup"][self.var_language]
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"
            str_lbl_01 = self.language_dict["Matrix Settings"][self.var_language]
            str_btn_01 = self.language_dict["Setup"][self.var_language]

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        # Labels
        lbl_03 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")

        # Buttons
        btn_03a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_header_n - 9, n_rows=var_row_n,
            n_columns=var_header_n - 9, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.mineral_matrix_quantification)

        # Option Menu
        str_default_method = self.container_var["Quantification Mineral"]["Method"].get()
        list_methods = ["Internal Standard", "100 wt.% Oxides"]

        opt_03a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n - 9, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Quantification Mineral"]["Method"], option_list=list_methods,
            text_set=str_default_method, fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color)
        opt_03a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
        opt_03a.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)

    def mineral_matrix_quantification(self, focus="MAT"):
        # Window Settings
        window_width = 480
        window_height = 175
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        if self.pysills_mode == "MA":
            str_title_window = "Sample Quantification"
            str_title_window = self.language_dict["Sample Settings"][self.var_language]
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            str_title_window = "Matrix Quantification"
            str_title_window = self.language_dict["Matrix Settings"][self.var_language]
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            if focus == "MAT":
                str_title_window = "Matrix Quantification"
                str_title_window = self.language_dict["Matrix Settings"][self.var_language]
            else:
                str_title_window = "Inclusion Quantification"
                str_title_window = self.language_dict["Inclusion Settings"][self.var_language]
            var_setting_key = "mi_setting"

        self.subwindow_mineral_matrix_quantification = tk.Toplevel(self.parent)
        self.subwindow_mineral_matrix_quantification.title(str_title_window)
        self.subwindow_mineral_matrix_quantification.geometry(var_geometry)
        self.subwindow_mineral_matrix_quantification.resizable(False, False)
        self.subwindow_mineral_matrix_quantification["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_mineral_matrix_quantification, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_mineral_matrix_quantification, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_mineral_matrix_quantification.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_mineral_matrix_quantification.grid_columnconfigure(i, minsize=column_min)

        if focus == "MAT":
            str_method = self.container_var["Quantification Mineral"]["Method"].get()
        else:
            str_method = "100 wt.% Oxides"

        var_row_start = 0
        var_column_start = 0
        var_row_n = 1
        var_header_n = 11

        if str_method == "Internal Standard":
            # LABELS
            str_lbl_01 = self.language_dict["Internal Standard Setup"][self.var_language]
            str_lbl_02 = self.language_dict["Oxide Calculation"][self.var_language]
            str_lbl_03 = self.language_dict["Element Calculation"][self.var_language]
            str_lbl_04 = self.language_dict["Experimental Data"][self.var_language]
            str_lbl_05 = self.language_dict["Custom Data"][self.var_language]
            str_lbl_06 = self.language_dict["Mineral Calculation"][self.var_language]
            str_btn_01 = self.language_dict["Setup"][self.var_language]

            lbl_01 = SE(
                parent=self.subwindow_mineral_matrix_quantification, row_id=var_row_start, column_id=var_column_start,
                n_rows=var_row_n, n_columns=2*var_header_n + 1, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
            # RADIOBUTTONS
            rb_01a = SE(
                parent=self.subwindow_mineral_matrix_quantification, row_id=var_row_start + 1,
                column_id=var_column_start, n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=1,
                color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text=str_lbl_02,
                sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
            rb_01b = SE(
                parent=self.subwindow_mineral_matrix_quantification, row_id=var_row_start + 2,
                column_id=var_column_start, n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=2,
                color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text=str_lbl_03,
                sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
            rb_01c = SE(
                parent=self.subwindow_mineral_matrix_quantification, row_id=var_row_start + 4,
                column_id=var_column_start, n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=3,
                color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text=str_lbl_04,
                sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
            rb_01d = SE(
                parent=self.subwindow_mineral_matrix_quantification, row_id=var_row_start + 5,
                column_id=var_column_start, n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=4,
                color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text=str_lbl_05,
                sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
            rb_01e = SE(
                parent=self.subwindow_mineral_matrix_quantification, row_id=var_row_start + 3,
                column_id=var_column_start, n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=5,
                color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text=str_lbl_06,
                sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
            # BUTTONS
            btn_02a = SE(
                parent=self.subwindow_mineral_matrix_quantification, row_id=var_row_start + 1,
                column_id=var_header_n + 1, n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.ma_matrix_concentration_setup)
        elif str_method == "100 wt.% Oxides":
            self.subwindow_mineral_matrix_quantification.destroy()
            self.checkup_oxides()

    def oxides_setup_composition(self, focus="MAT"):
        # Window Settings
        window_width = 1220
        window_height = 525
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        if self.pysills_mode == "MA":
            str_title_window = "Sample Quantification"
            str_title_window = self.language_dict["Sample Settings"][self.var_language]
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            str_title_window = "Matrix Quantification"
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            if focus == "MAT":
                str_title_window = "Matrix Quantification"
            else:
                str_title_window = "Inclusion Quantification"
            var_setting_key = "mi_setting"

        self.subwindow_oxides_composition = tk.Toplevel(self.parent)
        self.subwindow_oxides_composition.title(str_title_window)
        self.subwindow_oxides_composition.geometry(var_geometry)
        self.subwindow_oxides_composition.resizable(False, False)
        self.subwindow_oxides_composition["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_oxides_composition, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_oxides_composition, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_oxides_composition.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_oxides_composition.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 1
        var_row_n = 1
        var_header_n = 8

        str_focus = focus

        # FRAMES
        frm_01 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=var_column_start, n_rows=19,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_02 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=var_header_n + 2, n_rows=19,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_03 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=2*var_header_n + 3, n_rows=19,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_04 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=3*var_header_n + 4, n_rows=19,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)
        frm_04 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=4*var_header_n + 5, n_rows=19,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_frame(
            relief=tk.FLAT)

        # LABELS
        lbl_01 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start, column_id=var_column_start,
            n_rows=var_row_n, n_columns=4*var_header_n + 3, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Select all present elements and their oxides", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=var_column_start,
            n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Dark"]).create_simple_label(
            text="Rock-forming Elements", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=var_header_n + 2,
            n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Dark"]).create_simple_label(
            text="Industrial Metals", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=2*var_header_n + 3,
            n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Dark"]).create_simple_label(
            text="Precious Metals", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=3*var_header_n + 4,
            n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Dark"]).create_simple_label(
            text="Rare-Earth Elements", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_07 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=4*var_header_n + 5,
            n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Dark"]).create_simple_label(
            text="Other Elements", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_06 = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 1, column_id=5*var_header_n + 6,
            n_rows=var_row_n, n_columns=2*var_header_n - 2, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Dark"]).create_simple_label(
            text="Define the oxide ratios", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_06a = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 2, column_id=5*var_header_n + 6,
            n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="FeO/(FeO + Fe2O3)", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_06b = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 3, column_id=5*var_header_n + 6,
            n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text="MnO/(MnO + Mn2O3)", relief=tk.FLAT, fontsize="sans 10 bold")

        # BUTTONS
        btn_01a = SE(
            parent=self.subwindow_oxides_composition, row_id=var_row_start + 18, column_id=5*var_header_n + 6, n_rows=2,
            n_columns=2*var_header_n - 2, fg=self.bg_colors["Dark Font"],
            bg=self.accent_color).create_simple_button(
            text="Guess the composition", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.guess_composition)

        # CHECKBOXES
        self.container_checkboxes = {}
        ## Major Oxides
        list_major_oxides = [
            "SiO2", "Al2O3", "FeO", "Fe2O3", "CaO", "Na2O", "MgO", "K2O", "TiO2", "P2O5", "MnO", "Mn2O3", "SO3"]
        list_major_oxides = sorted(list_major_oxides)
        for index, oxide in enumerate(list_major_oxides):
            if focus == "MAT":
                var_cb_002a = self.container_var["Oxides Quantification"]["Major"][oxide]
            else:
                var_cb_002a = self.container_var["Oxides Quantification INCL"]["Major"][oxide]

            cb_002a = SE(
                parent=self.subwindow_oxides_composition, row_id=var_row_start + 2 + index,
                column_id=var_column_start, fg=self.bg_colors["Dark Font"], n_rows=var_row_n,
                n_columns=var_header_n, bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_002a, text=oxide, set_sticky="nesw", own_color=True,
                command=lambda var_oxide=oxide, var_key="Major", focus=str_focus:
                self.select_oxide(var_oxide, var_key, focus))
            self.container_checkboxes[oxide] = cb_002a

            if oxide in self.container_lists["Selected Oxides"]["All"]:
                cb_002a.select()

        ## Industrial Metals
        list_industrial_metals = ["Cr2O3", "NiO", "ZnO", "CuO", "PbO", "PbO2", "SnO2", "WO3", "MoO3", "V2O5", "ZrO2",
            "Nb2O5", "HfO2", "Ta2O5"]
        list_industrial_metals = sorted(list_industrial_metals)
        for index, oxide in enumerate(list_industrial_metals):
            if focus == "MAT":
                var_cb_003a = self.container_var["Oxides Quantification"]["Minor"][oxide]
            else:
                var_cb_003a = self.container_var["Oxides Quantification INCL"]["Minor"][oxide]

            cb_003a = SE(
                parent=self.subwindow_oxides_composition, row_id=var_row_start + 2 + index,
                column_id=var_header_n + 2, fg=self.bg_colors["Dark Font"], n_rows=var_row_n,
                n_columns=var_header_n, bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_003a, text=oxide, set_sticky="nesw", own_color=True,
                command=lambda var_oxide=oxide, var_key="Minor", focus=str_focus:
                self.select_oxide(var_oxide, var_key, focus))
            self.container_checkboxes[oxide] = cb_003a

            if oxide in self.container_lists["Selected Oxides"]["All"]:
                cb_003a.select()

        ## Precious Metals
        list_precious_metals = ["AgO", "PdO", "PtO", "Au2O", "OsO", "RuO", "IrO", "RhO"]
        list_precious_metals = sorted(list_precious_metals)
        for index, oxide in enumerate(list_precious_metals):
            if focus == "MAT":
                var_cb_004a = self.container_var["Oxides Quantification"]["Minor"][oxide]
            else:
                var_cb_004a = self.container_var["Oxides Quantification INCL"]["Minor"][oxide]

            cb_004a = SE(
                parent=self.subwindow_oxides_composition, row_id=var_row_start + 2 + index,
                column_id=2*var_header_n + 3, fg=self.bg_colors["Dark Font"], n_rows=var_row_n,
                n_columns=var_header_n, bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_004a, text=oxide, set_sticky="nesw", own_color=True,
                command=lambda var_oxide=oxide, var_key="Minor", focus=str_focus:
                self.select_oxide(var_oxide, var_key, focus))
            self.container_checkboxes[oxide] = cb_004a

            if oxide in self.container_lists["Selected Oxides"]["All"]:
                cb_004a.select()

        ## Rare Earth Metals
        list_rareearth_metals = ["Ce2O3", "Nd2O3", "La2O3", "Y2O3", "Sc2O3", "Pr2O3", "Pr6O11", "Sm2O3", "Gd2O3",
                                 "Dy2O3", "Er2O3", "Yb2O3", "Eu2O3", "Ho2O3", "Tb2O3", "Tb4O7", "Lu2O3", "Tm2O3"]
        list_rareearth_metals = sorted(list_rareearth_metals)
        for index, oxide in enumerate(list_rareearth_metals):
            if focus == "MAT":
                var_cb_005a = self.container_var["Oxides Quantification"]["Minor"][oxide]
            else:
                var_cb_005a = self.container_var["Oxides Quantification INCL"]["Minor"][oxide]

            cb_005a = SE(
                parent=self.subwindow_oxides_composition, row_id=var_row_start + 2 + index,
                column_id=3*var_header_n + 4, fg=self.bg_colors["Dark Font"], n_rows=var_row_n,
                n_columns=var_header_n, bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_005a, text=oxide, set_sticky="nesw", own_color=True,
                command=lambda var_oxide=oxide, var_key="Minor", focus=str_focus:
                self.select_oxide(var_oxide, var_key, focus))
            self.container_checkboxes[oxide] = cb_005a

            if oxide in self.container_lists["Selected Oxides"]["All"]:
                cb_005a.select()

        ## Other Elements
        list_other_elements = [
            "Li2O", "Ga2O3", "B2O3", "BeO", "GeO2", "As2O3", "Sb2O3", "BaO", "SrO", "Cl2O", "Br2O", "I2O", "Rb2O",
            "Cs2O", "Fr2O", ]
        list_other_elements = sorted(list_other_elements)
        for index, oxide in enumerate(list_other_elements):
            if focus == "MAT":
                var_cb_006a = self.container_var["Oxides Quantification"]["Minor"][oxide]
            else:
                var_cb_006a = self.container_var["Oxides Quantification INCL"]["Minor"][oxide]

            cb_006a = SE(
                parent=self.subwindow_oxides_composition, row_id=var_row_start + 2 + index,
                column_id=4*var_header_n + 5, fg=self.bg_colors["Dark Font"], n_rows=var_row_n,
                n_columns=var_header_n, bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_006a, text=oxide, set_sticky="nesw", own_color=True,
                command=lambda var_oxide=oxide, var_key="Minor", focus=str_focus:
                self.select_oxide(var_oxide, var_key, focus))
            self.container_checkboxes[oxide] = cb_006a

            if oxide in self.container_lists["Selected Oxides"]["All"]:
                cb_006a.select()

        # ENTRIES
        list_oxideratios = ["Fe-Ratio", "Mn-Ratio"]
        for index, ratio in enumerate(list_oxideratios):
            if ratio in ["Mn-Ratio"]:
                if focus == "MAT":
                    self.container_var["Oxides Quantification"]["Ratios"][ratio].set("1.0")
                else:
                    self.container_var["Oxides Quantification INCL"]["Ratios"][ratio].set("1.0")

            if focus == "MAT":
                entr_002 = SE(
                    parent=self.subwindow_oxides_composition, row_id=var_row_start + 2 + index,
                    column_id=6*var_header_n + 6, n_rows=var_row_n, n_columns=var_header_n - 2,
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                    var=self.container_var["Oxides Quantification"]["Ratios"][ratio],
                    text_default=self.container_var["Oxides Quantification"]["Ratios"][ratio].get())
            else:
                entr_002 = SE(
                    parent=self.subwindow_oxides_composition, row_id=var_row_start + 2 + index,
                    column_id=6*var_header_n + 6, n_rows=var_row_n, n_columns=var_header_n - 2,
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                    var=self.container_var["Oxides Quantification INCL"]["Ratios"][ratio],
                    text_default=self.container_var["Oxides Quantification INCL"]["Ratios"][ratio].get())

    def guess_composition(self):
        list_major_oxides = [
            "SiO2", "Al2O3", "FeO", "Fe2O3", "CaO", "Na2O", "MgO", "K2O", "TiO2", "P2O5", "MnO", "Mn2O3", "SO3"]
        list_industrial_metals = ["Cr2O3", "NiO", "ZnO", "CuO", "PbO", "PbO2", "SnO2", "WO3", "MoO3", "V2O5", "ZrO2",
            "Nb2O5", "HfO2", "Ta2O5"]
        list_precious_metals = ["AgO", "PdO", "PtO", "Au2O", "OsO", "RuO", "IrO", "RhO"]
        list_rareearth_metals = [
            "Ce2O3", "Nd2O3", "La2O3", "Y2O3", "Sc2O3", "Pr2O3", "Pr6O11", "Sm2O3", "Gd2O3", "Dy2O3", "Er2O3", "Yb2O3",
            "Eu2O3", "Ho2O3", "Tb2O3", "Tb4O7", "Lu2O3", "Tm2O3"]
        list_other_elements = [
            "Li2O", "Ga2O3", "B2O3", "BeO", "GeO2", "As2O3", "Sb2O3", "BaO", "SrO", "Cl2O", "Br2O", "I2O", "Rb2O",
            "Cs2O", "Fr2O", ]
        all_lists = [
            list_major_oxides, list_industrial_metals, list_precious_metals, list_rareearth_metals, list_other_elements]

        for list_oxides in all_lists:
            for oxide in list_oxides:
                key = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide)
                element_oxide = key.group(1)
                if element_oxide in self.container_lists["Measured Elements"]["All"]:
                    if oxide not in ["PbO2", "Pr6O11", "Tb4O7"]:
                        self.container_checkboxes[oxide].select()

                        if oxide not in self.container_lists["Selected Oxides"]["All"]:
                            self.container_lists["Selected Oxides"]["All"].append(oxide)

    def select_oxide(self, var_oxide, var_key, focus="MAT"):
        if focus == "MAT":
            state_cb = self.container_var["Oxides Quantification"][var_key][var_oxide].get()
        else:
            state_cb = self.container_var["Oxides Quantification INCL"][var_key][var_oxide].get()

        if state_cb == 1:
            if var_oxide not in self.container_lists["Selected Oxides"]["All"]:
                self.container_lists["Selected Oxides"]["All"].append(var_oxide)

        if state_cb == 0:
            if var_oxide in self.container_lists["Selected Oxides"]["All"]:
                self.container_lists["Selected Oxides"]["All"].remove(var_oxide)

    def oxides_setup_files(self, focus="MAT"):
        """ Definition of the file-specific settings that are necessary for a 100 wt.-% calculation.
        Parameters:  -
        """
        # Window Settings
        window_width = 760
        window_height = 425
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        if self.pysills_mode == "MA":
            str_title_window = "Sample Quantification"
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            str_title_window = "Matrix Quantification"
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            if focus == "MAT":
                str_title_window = "Matrix Quantification"
            else:
                str_title_window = "Inclusion Quantification"
            var_setting_key = "mi_setting"

        self.subwindow_oxides_files = tk.Toplevel(self.parent)
        self.subwindow_oxides_files.title(str_title_window)
        self.subwindow_oxides_files.geometry(var_geometry)
        self.subwindow_oxides_files.resizable(False, False)
        self.subwindow_oxides_files["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_oxides_files, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_oxides_files, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_oxides_files.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_oxides_files.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_row_n = 1
        var_header_n = 8

        str_focus = focus

        str_btn_01 = self.language_dict["Import data"][self.var_language]

        # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --

        # LABELS
        lbl_01 = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start, column_id=var_column_start,
            n_rows=var_row_n, n_columns=2*var_header_n + 1, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="File-specific Settings", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Default total amount of oxides", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 2, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Import data from file", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 7, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Select Reference Element", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 5, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Default amount of reference oxide", relief=tk.FLAT, fontsize="sans 10 bold")

        # ENTRIES
        var_entr_default = tk.StringVar()
        var_entr_default.set("100.0")
        entr_02a = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 1, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_default, text_default=var_entr_default.get())
        entr_02a.bind(
            "<Return>", lambda event, var_entr=var_entr_default, focus=str_focus:
            self.change_total_oxides_amount(var_entr, focus, event))

        var_entr_03_default = tk.StringVar()
        var_entr_03_default.set("100.0")
        entr_03a = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 6, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_03_default, text_default=var_entr_03_default.get())
        entr_03a.bind(
            "<Return>", lambda event, var_entr=var_entr_03_default: self.change_reference_oxide_amount(var_entr, event))

        # BUTTONS
        btn_03a = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 3, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])

        # OPTION MENUS
        list_opt04a = sorted(self.container_lists["Selected Oxides"]["All"])
        if focus == "MAT":
            var_opt_04 = self.container_var[var_setting_key]["Oxide"]
        elif focus == "INCL":
            var_opt_04 = self.container_var[var_setting_key]["Oxide Inclusion"]

        opt_04a = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 8, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=var_opt_04, option_list=list_opt04a, text_set=var_opt_04.get(),
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=var_opt_04, var_file=None, state_default=True:
            self.ma_change_matrix_compound(var_opt, var_file, state_default))
        opt_04a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_04a.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        self.opt_02b = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 9, column_id=3*var_header_n + 1,
            n_rows=var_row_n, n_columns=var_header_n + 4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["IS"]["Default SMPL"],
            option_list=self.container_lists["Measured Isotopes"]["All"],
            text_set=self.container_var["IS"]["Default SMPL"].get(), fg_active=self.bg_colors["Dark Font"],
            bg_active=self.accent_color, command=lambda var_opt=self.container_var["IS"]["Default SMPL"]:
            self.select_reference_element(var_opt))
        self.opt_02b["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        self.opt_02b.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        ## TREEVIEWS
        frm_tv = SE(
            parent=self.subwindow_oxides_files, row_id=var_row_start + 1, column_id=var_column_start, n_rows=15,
            n_columns=3*var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_tv = ttk.Scrollbar(master=frm_tv, orient="vertical")
        text_tv = tk.Text(
            master=frm_tv, width=30, height=25, yscrollcommand=vsb_tv.set, bg=self.bg_colors["Very Light"])
        vsb_tv.config(command=text_tv.yview)
        vsb_tv.pack(side="right", fill="y")
        text_tv.pack(side="left", fill="both", expand=True)

        lbl_i = tk.Label(
            frm_tv, text="Filename", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_tv.window_create("end", window=lbl_i)
        text_tv.insert("end", "\t")
        lbl_i = tk.Label(
            frm_tv, text="Reference Oxide", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_tv.window_create("end", window=lbl_i)
        text_tv.insert("end", "\t")
        lbl_i = tk.Label(
            frm_tv, text="Reference Isotope", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_tv.window_create("end", window=lbl_i)
        text_tv.insert("end", "\t")
        lbl_i = tk.Label(
            frm_tv, text="Total amount of oxides (wt.%)", bg=self.bg_colors["Very Light"],
            fg=self.bg_colors["Dark Font"])
        text_tv.window_create("end", window=lbl_i)
        text_tv.insert("end", "\t")
        lbl_i = tk.Label(
            frm_tv, text="Reference oxide amount (wt.%)", bg=self.bg_colors["Very Light"],
            fg=self.bg_colors["Dark Font"])
        text_tv.window_create("end", window=lbl_i)
        text_tv.insert("end", "\n")

        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            if focus == "INCL":
                if "Inclusion Setup" not in self.container_var["SMPL"][filename_long]:
                    self.container_var["SMPL"][filename_long]["Inclusion Setup"] = {
                        "IS": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                        "Oxide": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                        "Element": {"Name": tk.StringVar(), "Concentration": tk.StringVar()}}

            if focus == "MAT":
                key_setup = "Matrix Setup"
            elif focus == "INCL":
                key_setup = "Inclusion Setup"

            if len(self.container_var["SMPL"][filename_long][key_setup]["Oxide"]["Concentration"].get()) == 0:
                self.container_var["SMPL"][filename_long][key_setup]["Oxide"]["Concentration"].set("100.0")
            lbl_i = tk.Label(
                frm_tv, text=filename_short, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_tv.window_create("end", window=lbl_i)
            text_tv.insert("end", "\t")

            list_opt_oxide_i = sorted(self.container_lists["Selected Oxides"]["All"])
            opt_oxide_i = tk.OptionMenu(
                frm_tv, self.container_var["SMPL"][filename_long][key_setup]["Oxide"]["Name"],
                *list_opt_oxide_i,
                command=lambda var_opt=self.container_var["SMPL"][filename_long][key_setup]["Oxide"]["Name"],
                               var_file=filename_long, state_default=False:
                self.ma_change_matrix_compound(var_opt, var_file, state_default))
            opt_oxide_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_oxide_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)
            text_tv.window_create("end", window=opt_oxide_i)
            text_tv.insert("end", " \t")

            if self.pysills_mode == "MA":
                var_opt_is_i = self.container_var["SMPL"][filename_long]["IS Data"]["IS"]
            else:
                var_opt_is_i = self.container_var["SMPL"][filename_long][key_setup]["IS"]["Name"]

            opt_ref_i = tk.OptionMenu(
                frm_tv, var_opt_is_i, *self.container_lists["Measured Isotopes"]["All"],
                command=lambda var_opt=var_opt_is_i, var_file=filename_long, state_default=False:
                self.ma_change_matrix_compound(var_opt, var_file, state_default))
            opt_ref_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_ref_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)
            text_tv.window_create("end", window=opt_ref_i)
            text_tv.insert("end", " \t")

            if focus == "MAT":
                if filename_short not in self.container_var["Oxides Quantification"]["Total Amounts"]:
                    self.container_var["Oxides Quantification"]["Total Amounts"][filename_short] = tk.StringVar()
                    self.container_var["Oxides Quantification"]["Total Amounts"][filename_short].set("100.0")

                entr_i = tk.Entry(
                    frm_tv, textvariable=self.container_var["Oxides Quantification"]["Total Amounts"][filename_short],
                    fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=self.bg_colors["Very Light"])
            else:
                if filename_short not in self.container_var["Oxides Quantification INCL"]["Total Amounts"]:
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][filename_short] = tk.StringVar()
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][filename_short].set("100.0")

                entr_i = tk.Entry(
                    frm_tv, textvariable=self.container_var["Oxides Quantification INCL"]["Total Amounts"][
                        filename_short], fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"])

            text_tv.window_create("insert", window=entr_i)
            text_tv.insert("end", "\t")

            entr_i = tk.Entry(
                frm_tv, textvariable=self.container_var["SMPL"][filename_long][key_setup]["Oxide"]["Concentration"],
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0,
                highlightbackground=self.bg_colors["Very Light"])
            text_tv.window_create("insert", window=entr_i)
            text_tv.insert("end", "\n")

    def change_reference_oxide_amount(self, var_entr, event):
        for filename_long in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][filename_long]["Matrix Setup"]["Oxide"]["Concentration"].set(var_entr.get())

    def change_total_oxides_amount(self, var_entr, focus, event):
        for filename_short in self.container_lists["SMPL"]["Short"]:
            if focus == "MAT":
                self.container_var["Oxides Quantification"]["Total Amounts"][filename_short].set(var_entr.get())
            else:
                self.container_var["Oxides Quantification INCL"]["Total Amounts"][filename_short].set(var_entr.get())

    def select_reference_element(self, var_opt):
        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set(var_opt)

    def place_quantification_method(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Quantification Method'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        if self.pysills_mode == "MA":
            pass
        else:
            if self.pysills_mode == "FI":
                key_setting = "fi_setting"
                int_row_start_quantification = 2
            elif self.pysills_mode == "MI":
                key_setting = "mi_setting"
                int_row_start_quantification = 2

            str_lbl_01 = self.language_dict["Inclusion Settings"][self.var_language]
            str_lbl_02 = self.language_dict["Quantification Method"][self.var_language]

            # Labels
            lbl_04 = SE(
                parent=var_parent, row_id=var_row_start + int_row_start_quantification, column_id=var_column_start,
                n_rows=var_row_n, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
            lbl_05 = SE(
                parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
                n_columns=var_header_n, fg=self.bg_colors["Light Font"],
                bg=self.bg_colors["Super Dark"]).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")

            # Option Menu
            str_default_inclusion_setup = self.container_var[key_setting]["Inclusion Setup Option"].get()
            if self.pysills_mode == "FI":
                list_opt_incl_is_quantification = ["Mass Balance", "Charge Balance", "PyPitzer (Liu et al. 2024)",
                                                   "Custom Data", "External Calculation"]
            elif self.pysills_mode == "MI":
                list_opt_incl_is_quantification = ["100 wt.% Oxides", "Custom Data", "External Calculation"]

            opt_02a = SE(
                parent=var_parent, row_id=var_row_start + 3, column_id=var_column_start, n_rows=var_row_n,
                n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_srm(
                var_srm=self.container_var[key_setting]["Inclusion Setup Option"], text_set=str_default_inclusion_setup,
                fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color, sort_list=False,
                option_list=list_opt_incl_is_quantification,
                command=lambda var_opt=self.container_var[key_setting]["Inclusion Setup Option"],
                               dict_geometry_info=var_geometry_info:
                self.select_opt_inclusion_is_quantification(var_opt, dict_geometry_info))
            opt_02a["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            opt_02a.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

            str_default_quantification_setup = self.container_var[key_setting]["Quantification Method Option"].get()
            list_opt_incl_quantification = [
                "Matrix-only Tracer (SILLS)", "Second Internal Standard (SILLS)",
                "Geometric Approach (Halter et al. 2002)", "Geometric Approach (Borisova et al. 2021)"]

            opt_03a = SE(
                parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
                n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_srm(
                var_srm=self.container_var[key_setting]["Quantification Method Option"],
                text_set=str_default_quantification_setup, fg_active=self.bg_colors["Dark Font"],
                bg_active=self.accent_color, option_list=list_opt_incl_quantification, sort_list=False,
                command=lambda var_opt=self.container_var[key_setting]["Quantification Method Option"],
                               dict_geometry_info=var_geometry_info:
                self.select_opt_inclusion_quantification(var_opt, dict_geometry_info))
            opt_03a["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            opt_03a.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

    def select_opt_inclusion_is_quantification(self, var_opt, dict_geometry_info):
        var_row_start = dict_geometry_info["Row start"]
        var_row_n = dict_geometry_info["N rows"]
        var_column_n = dict_geometry_info["N columns"]
        var_category_n = var_column_n - 6

        if self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings

        str_btn_01 = self.language_dict["Setup"][self.var_language]

        self.bool_incl_is_massbalance = False
        self.bool_incl_is_chargebalance = False
        self.bool_incl_is_pypitzer = False
        self.bool_incl_is_custom = False
        self.bool_incl_is_external = False
        self.bool_incl_is_100pct = False

        if var_opt == "Mass Balance":
            if self.bool_incl_is_massbalance == False:
                self.btn_setup_massbalance = SE(
                    parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.fi_mass_balance_new)
                self.bool_incl_is_massbalance = True
            else:
                self.btn_setup_massbalance.grid()
                if self.bool_incl_is_chargebalance:
                    self.btn_setup_chargebalance.grid_remove()
                if self.bool_incl_is_pypitzer:
                    self.btn_setup_pypitzer.grid_remove()
                if self.bool_incl_is_custom:
                    self.btn_setup_customdata.grid_remove()
                if self.bool_incl_is_external:
                    self.btn_setup_external.grid_remove()
                if self.bool_incl_is_100pct:
                    self.btn_setup_100pct.grid_remove()
        elif var_opt == "Charge Balance":
            if self.bool_incl_is_chargebalance == False:
                self.btn_setup_chargebalance = SE(
                    parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=lambda mode="charge balance": self.fi_mass_balance_new(mode))
                self.bool_incl_is_chargebalance = True
            else:
                self.btn_setup_chargebalance.grid()
                if self.bool_incl_is_massbalance:
                    self.btn_setup_massbalance.grid_remove()
                if self.bool_incl_is_pypitzer:
                    self.btn_setup_pypitzer.grid_remove()
                if self.bool_incl_is_custom:
                    self.btn_setup_customdata.grid_remove()
                if self.bool_incl_is_external:
                    self.btn_setup_external.grid_remove()
                if self.bool_incl_is_100pct:
                    self.btn_setup_100pct.grid_remove()
        elif var_opt == "PyPitzer (Liu et al. 2024)":
            if self.bool_incl_is_pypitzer == False:
                self.btn_setup_pypitzer = SE(
                    parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.fi_pypitzer)
                self.bool_incl_is_pypitzer = True
            else:
                self.btn_setup_pypitzer.grid()
                if self.bool_incl_is_massbalance:
                    self.btn_setup_massbalance.grid_remove()
                if self.bool_incl_is_chargebalance:
                    self.btn_setup_chargebalance.grid_remove()
                if self.bool_incl_is_custom:
                    self.btn_setup_customdata.grid_remove()
                if self.bool_incl_is_external:
                    self.btn_setup_external.grid_remove()
                if self.bool_incl_is_100pct:
                    self.btn_setup_100pct.grid_remove()
        elif var_opt == "Custom Data":
            if self.bool_incl_is_custom == False:
                self.btn_setup_customdata = SE(
                    parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.fi_inclusion_setup_plugin)
                self.bool_incl_is_custom = True
                self.str_incl_is_custom_external = "Custom"
            else:
                self.btn_setup_customdata.grid()
                if self.bool_incl_is_massbalance:
                    self.btn_setup_massbalance.grid_remove()
                if self.bool_incl_is_chargebalance:
                    self.btn_setup_chargebalance.grid_remove()
                if self.bool_incl_is_pypitzer:
                    self.btn_setup_pypitzer.grid_remove()
                if self.bool_incl_is_external:
                    self.btn_setup_external.grid_remove()
                if self.bool_incl_is_100pct:
                    self.btn_setup_100pct.grid_remove()
        elif var_opt == "External Calculation":
            if self.bool_incl_is_external == False:
                self.btn_setup_external = SE(
                    parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.fi_inclusion_setup_plugin)
                self.bool_incl_is_external = True
                self.str_incl_is_custom_external = "External"
            else:
                self.btn_setup_external.grid()
                if self.bool_incl_is_massbalance:
                    self.btn_setup_massbalance.grid_remove()
                if self.bool_incl_is_chargebalance:
                    self.btn_setup_chargebalance.grid_remove()
                if self.bool_incl_is_pypitzer:
                    self.btn_setup_pypitzer.grid_remove()
                if self.bool_incl_is_custom:
                    self.btn_setup_customdata.grid_remove()
                if self.bool_incl_is_100pct:
                    self.btn_setup_100pct.grid_remove()
        elif var_opt == "100 wt.% Oxides":
            if self.bool_incl_is_100pct == False:
                self.btn_setup_100pct = SE(
                    parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.checkup_oxides)

                self.bool_incl_is_100pct = True
                self.str_incl_is_custom_external = "100 wt.% Oxides"
            else:
                self.btn_setup_100pct.grid()
                if self.bool_incl_is_massbalance:
                    self.btn_setup_massbalance.grid_remove()
                if self.bool_incl_is_chargebalance:
                    self.btn_setup_chargebalance.grid_remove()
                if self.bool_incl_is_pypitzer:
                    self.btn_setup_pypitzer.grid_remove()
                if self.bool_incl_is_custom:
                    self.btn_setup_customdata.grid_remove()
                if self.bool_incl_is_external:
                    self.btn_setup_external.grid_remove()

    def select_opt_inclusion_quantification(self, var_opt, dict_geometry_info):
        var_row_start = dict_geometry_info["Row start"]
        var_row_n = dict_geometry_info["N rows"]
        var_column_n = dict_geometry_info["N columns"]
        var_category_n = var_column_n - 6

        if self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings

        str_btn_01 = self.language_dict["Setup"][self.var_language]

        if var_opt == "Matrix-only Tracer (SILLS)":
            if self.bool_matrixonlytracer == False:
                self.btn_setup_matrixonlytracer = SE(
                    parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.fi_setup_matrix_only_tracer)
                self.bool_matrixonlytracer = True
            else:
                try:
                    self.btn_setup_matrixonlytracer.grid()
                except:
                    self.btn_setup_matrixonlytracer = SE(
                        parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
                        n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                        bg=self.bg_colors["Light"]).create_simple_button(
                        text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                        command=self.fi_setup_matrix_only_tracer)
                    self.bool_matrixonlytracer = True
                if self.bool_secondinternalstandard:
                    self.btn_setup_secondis.grid_remove()
                if self.bool_halter2002:
                    self.btn_setup_halter2002.grid_remove()
                if self.bool_borisova2021:
                    self.btn_setup_borisova2021.grid_remove()
        elif var_opt == "Second Internal Standard (SILLS)":
            if self.bool_secondinternalstandard == False:
                self.btn_setup_secondis = SE(
                    parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.fi_setup_second_internal_standard)
                self.bool_secondinternalstandard = True
            else:
                self.btn_setup_secondis.grid()
                if self.bool_matrixonlytracer:
                    self.btn_setup_matrixonlytracer.grid_remove()
                if self.bool_halter2002:
                    self.btn_setup_halter2002.grid_remove()
                if self.bool_borisova2021:
                    self.btn_setup_borisova2021.grid_remove()
        elif var_opt == "Geometric Approach (Halter et al. 2002)":
            if self.bool_halter2002 == False:
                self.btn_setup_halter2002 = SE(
                    parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.define_setup_halter2002)
                self.bool_halter2002 = True
            else:
                self.btn_setup_halter2002.grid()
                if self.bool_matrixonlytracer:
                    self.btn_setup_matrixonlytracer.grid_remove()
                if self.bool_secondinternalstandard:
                    self.btn_setup_secondis.grid_remove()
                if self.bool_borisova2021:
                    self.btn_setup_borisova2021.grid_remove()
        elif var_opt == "Geometric Approach (Borisova et al. 2021)":
            if self.bool_borisova2021 == False:
                self.btn_setup_borisova2021 = SE(
                    parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
                    n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                    command=self.define_setup_borisova2021)
                self.bool_borisova2021 = True
            else:
                self.btn_setup_borisova2021.grid()
                if self.bool_matrixonlytracer:
                    self.btn_setup_matrixonlytracer.grid_remove()
                if self.bool_secondinternalstandard:
                    self.btn_setup_secondis.grid_remove()
                if self.bool_halter2002:
                    self.btn_setup_halter2002.grid_remove()

    def place_assemblage_setup(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Assemblage Setup'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        str_lbl_01 = self.language_dict["Assemblage Settings"][self.var_language]
        str_lbl_02 = self.language_dict["Sample Files"][self.var_language]

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        # Labels
        lbl_05 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")

        # Option Menus
        if self.container_var["ID"]["Default SMPL"].get() != "Select ID":
            var_text = self.container_var["ID"]["Default SMPL"].get()
        else:
            var_text = "Select ID"
        opt_05a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["ID"]["Default SMPL"], option_list=self.list_alphabet, text_set=var_text,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["ID"]["Default SMPL"]: self.fi_select_id_default(var_opt))
        opt_05a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_05a.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

    def place_dwell_time_setup(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Dwell Time Setup'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        str_lbl_01 = self.language_dict["Dwell Time Settings"][self.var_language]
        str_lbl_02 = self.language_dict["Isotope Dwell Times"][self.var_language]
        str_btn_01 = self.language_dict["Setup"][self.var_language]

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        # Labels
        lbl_06 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_06a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")

        # Buttons
        btn_06a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.create_dwell_time_window)

    def place_calculation_window_bg(self, var_geometry_info, var_relief=tk.FLAT):
        """Creates and places the necessary tkinter widgets for the section: 'Calculation Window (Background) Setup'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        str_lbl_01 = self.language_dict["Default Time Window (Background)"][self.var_language]
        str_lbl_02 = self.language_dict["Start"][self.var_language]
        str_lbl_03 = self.language_dict["End"][self.var_language]
        str_lbl_04 = self.language_dict["Auto-Detection"][self.var_language]
        str_btn_01 = self.language_dict["Run"][self.var_language]
        str_btn_02 = self.language_dict["Remove all"][self.var_language]

        # Labels
        lbl_07 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_07a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize="sans 10 bold")
        lbl_07b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_03, relief=var_relief, fontsize="sans 10 bold")
        lbl_07c = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_04, relief=var_relief, fontsize="sans 10 bold")

        # Buttons
        btn_07c = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n - 6, n_rows=1,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="BG": self.detect_signal_interval(mode))
        btn_07cd = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=1,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="BG": self.clear_all_calculation_intervals(mode))

        # Entries
        var_entr_07a_default = self.container_var[var_setting_key]["Time BG Start"].get()
        var_entr_07b_default = self.container_var[var_setting_key]["Time BG End"].get()

        entr_07a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[var_setting_key]["Time BG Start"], text_default=var_entr_07a_default,
            command=lambda event, var_entr=self.container_var["ma_setting"]["Time BG Start"], var_key="Start",
                           mode="default", var_interval="BG":
            self.ma_set_bg_interval(var_entr, var_key, mode, var_interval, event))
        entr_07b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_category_n, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[var_setting_key]["Time BG End"], text_default=var_entr_07b_default,
            command=lambda event, var_entr=self.container_var["ma_setting"]["Time BG End"], var_key="End",
                           mode="default", var_interval="BG":
            self.ma_set_bg_interval(var_entr, var_key, mode, var_interval, event))

    def place_calculation_window_smpl(self, var_geometry_info, var_relief=tk.FLAT):
        """Creates and places the necessary tkinter widgets for the section: 'Calculation Window (Sample) Setup'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
            str_lbl_01 = self.language_dict["Default Time Window (Sample)"][self.var_language]
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
            str_lbl_01 = self.language_dict["Default Time Window (Matrix)"][self.var_language]
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"
            str_lbl_01 = self.language_dict["Default Time Window (Matrix)"][self.var_language]

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        str_lbl_02 = self.language_dict["Start"][self.var_language]
        str_lbl_03 = self.language_dict["End"][self.var_language]
        str_lbl_04 = self.language_dict["Auto-Detection"][self.var_language]
        str_btn_01 = self.language_dict["Run"][self.var_language]
        str_btn_02 = self.language_dict["Remove all"][self.var_language]

        # Labels
        lbl_08 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_08a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize="sans 10 bold")
        lbl_08b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_03, relief=var_relief, fontsize="sans 10 bold")
        lbl_08c = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_04, relief=var_relief, fontsize="sans 10 bold")

        # Buttons
        btn_08c = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n - 6, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="MAT": self.detect_signal_interval(mode))
        btn_08cd = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_category_n, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="MAT": self.clear_all_calculation_intervals(mode))

        # Entries
        var_entr_08a_default = self.container_var[var_setting_key]["Time MAT Start"].get()
        var_entr_08b_default = self.container_var[var_setting_key]["Time MAT End"].get()

        entr_08a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_category_n, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[var_setting_key]["Time MAT Start"], text_default=var_entr_08a_default,
            command=lambda event, var_entr=self.container_var[var_setting_key]["Time MAT Start"], var_key="Start",
                           mode="default", var_interval="MAT":
            self.ma_set_bg_interval(var_entr, var_key, mode, var_interval, event))
        entr_08b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_category_n, n_rows=var_row_n,
            n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[var_setting_key]["Time MAT End"], text_default=var_entr_08b_default,
            command=lambda event, var_entr=self.container_var[var_setting_key]["Time MAT End"], var_key="End",
                           mode="default", var_interval="MAT":
            self.ma_set_bg_interval(var_entr, var_key, mode, var_interval, event))

    def place_spike_elimination_setup(self, var_geometry_info, var_relief=tk.FLAT):
        """Creates and places the necessary tkinter widgets for the section: 'Spike Elimination Setup'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n

        str_lbl_01 = self.language_dict["Spike Elimination"][self.var_language]
        str_lbl_02 = self.language_dict["Calculation Method"][self.var_language]
        str_lbl_03 = self.language_dict["Exclude inclusion"][self.var_language]

        # Labels
        lbl_09 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_09b = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n - 9, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)

        # Option Menus
        if self.container_var["Spike Elimination Method"].get() != "Select Method":
            var_text = self.container_var["Spike Elimination Method"].get()
        else:
            var_text = "Select Method"
        opt_09b = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_header_n - 9, n_rows=var_row_n,
            n_columns=var_header_n - 9, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Spike Elimination Method"], option_list=self.list_se_methods, text_set=var_text,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["Spike Elimination Method"], start_row=var_row_start:
            self.select_spike_elimination(var_opt, start_row))
        opt_09b["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_09b.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        if self.pysills_mode != "MA":
            # Checkboxes
            cb_09b = SE(
                parent=var_parent, row_id=var_row_start + 2, column_id=0, fg=self.bg_colors["Dark Font"], n_rows=1,
                n_columns=var_header_n, bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=self.container_var[var_setting_key]["Check Inclusion Exclusion"], text=str_lbl_03,
                set_sticky="nesw", own_color=True, command=lambda setting_key=var_setting_key:
                self.change_inclusion_consideration(setting_key))
            self.change_inclusion_consideration(setting_key=var_setting_key)

    def change_inclusion_consideration(self, setting_key):
        if self.container_var[setting_key]["Check Inclusion Exclusion"].get() == True:
            self.container_var[setting_key]["Spike Elimination Inclusion"].set(2)
        else:
            self.container_var[setting_key]["Spike Elimination Inclusion"].set(1)

    def place_checkup_feature(self, var_geometry_info, var_relief=tk.FLAT):
        """Creates and places the necessary tkinter widgets for the section: 'Check-Up'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        str_lbl_01 = self.language_dict["Check-Up"][self.var_language]
        str_lbl_02 = self.language_dict["Standard Reference Material (SRM)"][self.var_language]
        str_lbl_03 = self.language_dict["Internal Standard"][self.var_language]
        str_lbl_04 = self.language_dict["100 wt.% oxides"][self.var_language]
        str_lbl_05 = self.language_dict["Calculation Intervals"][self.var_language]
        str_lbl_06 = self.language_dict["Acquisition Times"][self.var_language]
        str_lbl_07 = self.language_dict["Imported Files"][self.var_language]
        str_btn_01 = self.language_dict["Check"][self.var_language]

        # Labels
        lbl_10 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_10a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
        lbl_10b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_03, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
        lbl_10b = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_04, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
        lbl_10c = SE(
            parent=var_parent, row_id=var_row_start + 4, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_05, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
        lbl_10d = SE(
            parent=var_parent, row_id=var_row_start + 5, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_06, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
        lbl_10e = SE(
            parent=var_parent, row_id=var_row_start + 6, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text=str_lbl_07, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)

        # Buttons
        btn_10a = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start + var_category_n,
            n_rows=var_row_n, n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.check_srm_settings)  # Check-Up - SRM Settings
        btn_10b = SE(
            parent=var_parent, row_id=var_row_start + 2, column_id=var_column_start + var_category_n,
            n_rows=var_row_n, n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.checkup_internal_standard)  # Check-Up - Internal Standard Settings
        btn_10b = SE(
            parent=var_parent, row_id=var_row_start + 3, column_id=var_column_start + var_category_n,
            n_rows=var_row_n, n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.checkup_oxides)  # Check-Up - 100 wt.% oxides
        btn_10c = SE(
            parent=var_parent, row_id=var_row_start + 4, column_id=var_column_start + var_category_n,
            n_rows=var_row_n, n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.check_interval_settings)  # Check-Up - Calculation Interval Settings
        btn_10d = SE(
            parent=var_parent, row_id=var_row_start + 5, column_id=var_column_start + var_category_n,
            n_rows=var_row_n, n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.check_acquisition_times)  # Check-Up - Acquisition Times
        btn_10e = SE(
            parent=var_parent, row_id=var_row_start + 6, column_id=var_column_start + var_category_n,
            n_rows=var_row_n, n_columns=var_category_n - 6, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.check_imported_files)

    def place_measured_isotopes_overview(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Measured Isotopes'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 11

        str_lbl_01 = self.language_dict["Measured isotopes"][self.var_language]

        # Labels
        lbl_iso = SE(
            parent=var_parent, row_id=var_row_start - 1, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        frm_iso = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_iso = ttk.Scrollbar(frm_iso, orient="vertical")
        text_iso = tk.Text(
            master=frm_iso, width=30, height=25, yscrollcommand=vsb_iso.set, bg=self.bg_colors["Very Light"])
        vsb_iso.config(command=text_iso.yview)
        vsb_iso.pack(side="right", fill="y")
        text_iso.pack(side="left", fill="both", expand=True)
        for index, isotope in enumerate(self.container_lists["Measured Isotopes"]["All"]):
            if isotope.isdigit():
                pass
            else:
                if self.container_var["LASER"].get() != "Select Gas":
                    var_text = self.container_var["LASER"].get()
                else:
                    var_text = "Select Gas"

                if isotope not in self.container_var["SRM"]:
                    self.container_var["SRM"][isotope] = tk.StringVar()
                    self.container_var["SRM"][isotope].set("Select SRM")
                    #
                    self.container_var["dwell_times"]["Entry"][isotope] = tk.StringVar()
                    self.container_var["dwell_times"]["Entry"][isotope].set("0.002")
                    #
                    for file_std_short in self.container_lists["STD"]["Short"]:
                        self.build_checkbutton_isotope_visibility(
                            var_mode=var_setting_key, var_filetype="STD", var_filename_short=file_std_short,
                            var_isotope=isotope)

                        if file_std_short not in self.container_var[var_setting_key]["Time-Signal Lines"]["STD"]:
                            self.container_var[var_setting_key]["Time-Signal Lines"]["STD"][file_std_short] = {}
                            self.container_var[var_setting_key]["Time-Ratio Lines"]["STD"][file_std_short] = {}
                            self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["STD"][file_std_short] = {}
                            self.container_var[var_setting_key]["Calculation Interval"]["STD"][file_std_short] = tk.IntVar()
                            self.container_var[var_setting_key]["Calculation Interval"]["STD"][file_std_short].set(3)
                            self.container_var[var_setting_key]["Calculation Interval Visibility"]["STD"][
                                file_std_short] = {}

                        self.container_var[var_setting_key]["Time-Signal Lines"]["STD"][file_std_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Time-Ratio Lines"]["STD"][file_std_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["STD"][file_std_short][
                            isotope] = {
                            "RAW": None, "SMOOTHED": None}
                    #
                    for file_smpl_short in self.container_lists["SMPL"]["Short"]:
                        self.build_checkbutton_isotope_visibility(
                            var_mode=var_setting_key, var_filetype="SMPL", var_filename_short=file_smpl_short,
                            var_isotope=isotope)

                        if file_smpl_short not in self.container_var[var_setting_key]["Time-Signal Lines"]["SMPL"]:
                            self.container_var[var_setting_key]["Time-Signal Lines"]["SMPL"][file_smpl_short] = {}
                            self.container_var[var_setting_key]["Time-Ratio Lines"]["SMPL"][file_smpl_short] = {}
                            self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["SMPL"][file_smpl_short] = {}
                            self.container_var[var_setting_key]["Calculation Interval"]["SMPL"][
                                file_smpl_short] = tk.IntVar()
                            self.container_var[var_setting_key]["Calculation Interval"]["SMPL"][file_smpl_short].set(3)
                            self.container_var[var_setting_key]["Calculation Interval Visibility"]["SMPL"][
                                file_smpl_short] = {}

                        self.container_var[var_setting_key]["Time-Signal Lines"]["SMPL"][file_smpl_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Time-Ratio Lines"]["SMPL"][file_smpl_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["SMPL"][file_smpl_short][
                            isotope] = {
                            "RAW": None, "SMOOTHED": None}
                #
                if self.file_loaded:
                    for file_std_short in self.container_lists["STD"]["Short"]:
                        self.build_checkbutton_isotope_visibility(
                            var_mode=var_setting_key, var_filetype="STD", var_filename_short=file_std_short,
                            var_isotope=isotope)

                        if file_std_short not in self.container_var[var_setting_key]["Time-Signal Lines"]["STD"]:
                            self.container_var[var_setting_key]["Time-Signal Lines"]["STD"][file_std_short] = {}
                            self.container_var[var_setting_key]["Time-Ratio Lines"]["STD"][file_std_short] = {}
                            self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["STD"][file_std_short] = {}
                            self.container_var[var_setting_key]["Calculation Interval"]["STD"][file_std_short] = tk.IntVar()
                            self.container_var[var_setting_key]["Calculation Interval"]["STD"][file_std_short].set(3)
                            self.container_var[var_setting_key]["Calculation Interval Visibility"]["STD"][
                                file_std_short] = {}

                        self.container_var[var_setting_key]["Time-Signal Lines"]["STD"][file_std_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Time-Ratio Lines"]["STD"][file_std_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["STD"][file_std_short][
                            isotope] = {
                            "RAW": None, "SMOOTHED": None}
                    #
                    for file_smpl_short in self.container_lists["SMPL"]["Short"]:
                        self.build_checkbutton_isotope_visibility(
                            var_mode=var_setting_key, var_filetype="SMPL", var_filename_short=file_smpl_short,
                            var_isotope=isotope)

                        if file_smpl_short not in self.container_var[var_setting_key]["Time-Signal Lines"]["SMPL"]:
                            self.container_var[var_setting_key]["Time-Signal Lines"]["SMPL"][file_smpl_short] = {}
                            self.container_var[var_setting_key]["Time-Ratio Lines"]["SMPL"][file_smpl_short] = {}
                            self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["SMPL"][file_smpl_short] = {}
                            self.container_var[var_setting_key]["Calculation Interval"]["SMPL"][
                                file_smpl_short] = tk.IntVar()
                            self.container_var[var_setting_key]["Calculation Interval"]["SMPL"][file_smpl_short].set(3)
                            self.container_var[var_setting_key]["Calculation Interval Visibility"]["SMPL"][
                                file_smpl_short] = {}

                        self.container_var[var_setting_key]["Time-Signal Lines"]["SMPL"][file_smpl_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Time-Ratio Lines"]["SMPL"][file_smpl_short][isotope] = {
                            "RAW": None, "SMOOTHED": None}
                        self.container_var[var_setting_key]["Checkboxes Isotope Diagram"]["SMPL"][file_smpl_short][
                            isotope] = {
                            "RAW": None, "SMOOTHED": None}

                frm_i = tk.Frame(frm_iso, bg=self.isotope_colors[isotope], relief=tk.SOLID, height=15, width=15,
                                 highlightbackground="black", bd=1)
                text_iso.window_create("end", window=frm_i)
                text_iso.insert("end", "")
                lbl_i = tk.Label(frm_iso, text=isotope, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Very Dark"])
                text_iso.window_create("end", window=lbl_i)
                text_iso.insert("end", "\t")

                opt_srm_i = tk.OptionMenu(
                    frm_iso, self.container_var["SRM"][isotope], *np.sort(self.container_lists["SRM Library"]),
                    command=lambda var_opt=self.container_var["SRM"][isotope], var_indiv=isotope, mode="ISOTOPES":
                    self.ma_change_srm_individual(var_opt, var_indiv, mode))
                opt_srm_i["menu"].config(
                    fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"],
                    activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
                opt_srm_i.config(
                    bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"], activebackground=self.accent_color,
                    activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
                text_iso.window_create("end", window=opt_srm_i)
                text_iso.insert("end", "\t")
                #
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)

                self.container_var["charge"][isotope] = {"textvar": tk.StringVar()}

                for oxide in self.chemistry_oxides_sorted[element]:
                    if oxide not in self.container_lists["Oxides"]:
                        self.container_lists["Oxides"].append(oxide)

                if float(self.container_var["Gas Energy"].get()) >= float(self.ionization_energies["First"][element]) \
                        and float(self.container_var["Gas Energy"].get()) >= float(self.ionization_energies["Second"][
                                                                                       element]):
                    self.container_var["charge"][isotope]["textvar"].set("2+ charged")
                    charge_fg = self.accent_color
                else:
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    charge_fg = self.bg_colors["Very Dark"]
                #
                lbl_i = tk.Label(
                    frm_iso, text=self.container_var["charge"][isotope]["textvar"].get(),
                    textvariable=self.container_var["charge"][isotope]["textvar"], bg=self.bg_colors["Very Light"],
                    fg=charge_fg)
                self.container_var["charge"][isotope]["labelvar"] = lbl_i
                text_iso.window_create("end", window=lbl_i)
                text_iso.insert("end", "\n")

        # Option Menus
        list_opt_gas = ["Helium", "Neon", "Argon", "Krypton", "Xenon", "Radon"]
        opt_laser = SE(
            parent=var_parent, row_id=var_row_start + var_row_n, column_id=var_column_start + 11, n_rows=1,
            n_columns=var_category_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["LASER"], option_list=list_opt_gas, text_set="Argon",
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["LASER"]: self.change_carrier_gas(var_opt))
        opt_laser["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_laser.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

    def place_acquisition_times_check(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Acquisition Times'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n
        var_category_n = var_column_n - 6

        str_lbl_01 = self.language_dict["Acquisition Times"][self.var_language]
        str_lbl_02 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_03 = self.language_dict["Sample Files"][self.var_language]

        # Labels
        lbl_01 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")

        # Treeviews
        frm_02 = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start,
            n_rows=7, n_columns=var_header_n, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()
        vsb_02 = ttk.Scrollbar(frm_02, orient="vertical")
        text_02 = tk.Text(
            master=frm_02, width=25, height=25, yscrollcommand=vsb_02.set, bg=self.bg_colors["Very Light"])
        vsb_02.config(command=text_02.yview)
        vsb_02.pack(side="right", fill="y")
        text_02.pack(side="left", fill="both", expand=True)

        if len(self.container_var["acquisition times"]["STD"]) == 0:
            self.get_acquisition_times(var_filetype="STD")
        if len(self.container_var["acquisition times"]["SMPL"]) == 0:
            self.get_acquisition_times(var_filetype="SMPL")

        lbl_i = tk.Label(
            frm_02, text=str_lbl_02, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_02.window_create("end", window=lbl_i)
        text_02.insert("end", "\n")
        for var_file_short in self.container_lists["STD"]["Short"]:
            lbl_i = tk.Label(
                frm_02, text=var_file_short, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_02.window_create("end", window=lbl_i)
            text_02.insert("end", "\t")

            entr_i = tk.Entry(
                frm_02, textvariable=self.container_var["acquisition times"]["STD"][var_file_short],
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0, width=12)
            text_02.window_create("insert", window=entr_i)
            text_02.insert("end", "\n")

        lbl_i = tk.Label(
            frm_02, text=str_lbl_03, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_02.window_create("end", window=lbl_i)
        text_02.insert("end", "\n")
        for var_file_short in self.container_lists["SMPL"]["Short"]:
            lbl_i = tk.Label(
                frm_02, text=var_file_short, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_02.window_create("end", window=lbl_i)
            text_02.insert("end", "\t")

            entr_i = tk.Entry(
                frm_02, textvariable=self.container_var["acquisition times"]["SMPL"][var_file_short],
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0, width=12)
            text_02.window_create("insert", window=entr_i)
            text_02.insert("end", "\n")

    def get_acquisition_times(self, var_filetype):
        for var_file_long in self.container_lists[var_filetype]["Long"]:
            parts = var_file_long.split("/")
            var_file_short = parts[-1]
            if self.container_icpms["timestamp"] != "undefined":
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                var_timestamp = self.container_icpms["timestamp"]
                var_icpms = self.container_icpms["name"]
                dates, times = Data(filename=var_file_long).import_as_list(
                    skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp, icpms=var_icpms)
                if var_file_short not in self.container_var["acquisition times"][var_filetype]:
                    self.container_var["acquisition times"][var_filetype][var_file_short] = tk.StringVar()
                    self.container_var["acquisition times"][var_filetype][var_file_short].set(
                        times[0][0] + ":" + times[0][1] + ":" + times[0][2])
            else:
                times = [["00", "00", "00"]]
                if var_file_short not in self.container_var["acquisition times"][var_filetype]:
                    self.container_var["acquisition times"][var_filetype][var_file_short] = tk.StringVar()
                    self.container_var["acquisition times"][var_filetype][var_file_short].set(
                        times[0][0] + ":" + times[0][1] + ":" + times[0][2])

    def place_time_signal_plot_checker(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Time-Signal Diagram Checker'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_mode_setting = "ma_setting"
            row_correction = 0
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_mode_setting = "fi_setting"
            row_correction = 1
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_mode_setting = "mi_setting"
            row_correction = 1

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n

        str_lbl_01 = self.language_dict["Time-Signal Diagram"][self.var_language]
        str_lbl_02 = self.language_dict["Standard file"][self.var_language]
        str_lbl_03 = self.language_dict["Sample file"][self.var_language]
        str_btn_01 = self.language_dict["Before"][self.var_language]
        str_btn_02 = self.language_dict["Next"][self.var_language]

        # Labels
        lbl_01 = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")

        # Frames
        frm_02 = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start,
            n_rows=11, n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)

        # Radiobuttons
        rb_01 = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=5, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[var_mode_setting]["Time-Signal Checker"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text=str_lbl_02, sticky="nesw",
            relief=tk.FLAT, font="sans 10 bold", command=lambda var_setting_key=var_mode_setting:
            self.change_filetype_time_signal_diagram_checker(var_setting_key))
        rb_02 = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start + 5,
            n_rows=var_row_n, n_columns=5, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[var_mode_setting]["Time-Signal Checker"], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text=str_lbl_03, sticky="nesw",
            relief=tk.FLAT, font="sans 10 bold", command=lambda var_setting_key=var_mode_setting:
            self.change_filetype_time_signal_diagram_checker(var_setting_key))

        if len(self.container_lists["STD"]["Short"]) == 0:
            rb_01.configure(state="disabled")

        if len(self.container_lists["SMPL"]["Short"]) == 0:
            rb_02.configure(state="disabled")

        # Buttons
        btn_01 = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start + 10,
            n_rows=var_row_n, n_columns=4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_mode="Before", var_setting_key=var_mode_setting:
            self.change_file_time_signal_diagram_checker(var_mode, var_setting_key))
        btn_02 = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start + 14,
            n_rows=var_row_n, n_columns=4, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_mode="Next", var_setting_key=var_mode_setting:
            self.change_file_time_signal_diagram_checker(var_mode, var_setting_key))

        ## Initialization
        self.current_file_id_checker = 0

        self.fig_time_signal_checker = Figure(
            figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.canvas_time_signal_checker = FigureCanvasTkAgg(
            self.fig_time_signal_checker, master=var_parent)
        self.canvas_time_signal_checker.get_tk_widget().grid(
            row=var_row_start + 2, column=var_column_start, rowspan=10 + row_correction, columnspan=var_header_n,
            sticky="nesw")

        self.temp_axes_checkup2 = {"STD": {}, "SMPL": {}}
        self.temp_lines_checkup2 = {"STD": {}, "SMPL": {}}

        for filetype in ["STD", "SMPL"]:
            for file_short in self.container_lists[filetype]["Short"]:
                if filetype == "STD":
                    self.temp_axes_checkup2[filetype][file_short] = self.fig_time_signal_checker.add_subplot(
                        label=file_short)
                else:
                    self.temp_axes_checkup2[filetype][file_short] = self.fig_time_signal_checker.add_subplot(
                        label=file_short)
                self.temp_lines_checkup2[filetype][file_short] = 0

        self.show_time_signal_diagram_checker(var_setting_key=var_mode_setting)

    def show_time_signal_diagram_checker(self, var_setting_key):
        if self.container_var[var_setting_key]["Time-Signal Checker"].get() == 1:
            var_filetype = "STD"
        else:
            var_filetype = "SMPL"

        for filetype in ["STD", "SMPL"]:
            for key, axis_item in self.temp_axes_checkup2[filetype].items():
                axis_item.axis("off")
                axis_item.set_visible(False)

            self.canvas_time_signal_checker.draw()

        var_file_long = self.container_lists[var_filetype]["Long"][self.current_file_id_checker]
        var_file_short = self.container_lists[var_filetype]["Short"][self.current_file_id_checker]

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5

        if self.temp_lines_checkup2[var_filetype][var_file_short] == 0:
            if self.file_loaded == False:
                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_data = DE(filename_long=var_file_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_data = DE(filename_long=var_file_long).get_measurements(
                        delimiter=",", skip_header=3, skip_footer=1)
            else:
                df_data = self.container_measurements["Dataframe"][var_file_short]

            dataset_time = list(DE().get_times(dataframe=df_data))
            x_max = max(dataset_time)
            icp_measurements = np.array(
                [[df_data[isotope] for isotope in self.container_lists["Measured Isotopes"]["All"]
                  if isotope in df_data]])
            y_max = np.amax(icp_measurements)

            if var_filetype == "STD":
                ax = self.fig_time_signal_checker.add_subplot(label=np.random.uniform())
            else:
                ax = self.fig_time_signal_checker.add_subplot(label=np.random.uniform())

            self.temp_axes_checkup2[var_filetype][var_file_short] = ax

            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                if isotope in df_data:
                    ln_raw = ax.plot(
                        dataset_time, df_data[isotope], label=isotope, color=self.isotope_colors[isotope],
                        linewidth=var_lw, visible=True)

            # Background window
            if var_file_short in self.container_helper[var_filetype]:
                var_check_bg = self.container_helper[var_filetype][var_file_short]["BG"]["Content"]

                if len(var_check_bg) > 0:
                    if self.pysills_mode in ["MA", "FI", "MI"]:
                        for var_id, var_content in self.container_helper[var_filetype][var_file_short]["BG"][
                            "Content"].items():
                            times_bg = var_content["Times"]
                            box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.35, color=self.colors_intervals["BG"])

            # Sample/Matrix window
            if var_file_short in self.container_helper[var_filetype]:
                var_check_sig = self.container_helper[var_filetype][var_file_short]["MAT"]["Content"]

                if len(var_check_sig) > 0:
                    if self.pysills_mode in ["FI"]:
                        for var_id, var_content in self.container_helper[var_filetype][var_file_short]["MAT"][
                            "Content"].items():
                            times_sig = var_content["Times"]
                            var_color = self.colors_intervals["MAT"]
                            box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                    elif self.pysills_mode in ["MI"]:
                        for var_id, var_content in self.container_helper[var_filetype][var_file_short]["MAT"][
                            "Content"].items():
                            times_sig = var_content["Times"]
                            var_color = self.colors_intervals["MAT"]
                            box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                    else:
                        for var_id, var_content in self.container_helper[var_filetype][var_file_short]["MAT"][
                            "Content"].items():
                            times_sig = var_content["Times"]
                            var_color = self.colors_intervals["MAT"]
                            box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)

            # Inclusion window
            if self.pysills_mode != "MA":
                if var_filetype == "SMPL":
                    inclusion_key = "INCL"
                    var_check_incl = self.container_helper[var_filetype][var_file_short][inclusion_key]["Content"]
                    if len(var_check_incl) > 0:
                        if self.pysills_mode == "FI":
                            for var_id, var_content in \
                            self.container_helper[var_filetype][var_file_short][inclusion_key][
                                "Content"].items():
                                times_incl = var_content["Times"]
                                box_incl = ax.axvspan(
                                    times_incl[0], times_incl[1], alpha=0.35, color=self.colors_intervals["INCL"])
                        elif self.pysills_mode == "MI":
                            for var_id, var_content in \
                            self.container_helper[var_filetype][var_file_short][inclusion_key][
                                "Content"].items():
                                times_incl = var_content["Times"]
                                box_incl = ax.axvspan(
                                    times_incl[0], times_incl[1], alpha=0.35, color=self.colors_intervals["INCL"])

            ax.set_title("Current file: " + str(var_file_short), fontsize=9)
            ax.set_xlabel("Time (s)", labelpad=0.5, fontsize=8)
            ax.set_ylabel("Intensity (cps)", labelpad=0.5, fontsize=8)

            ax.set_yscale("log")
            ax.set_xlim(left=0, right=x_max)
            ax.set_xticks(np.arange(0, x_max, 20))
            ax.set_ylim(bottom=100, top=1.5*y_max)
            ax.grid(which="major", linestyle="-", linewidth=1)
            ax.minorticks_on()
            ax.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
            ax.set_axisbelow(True)
            ax.xaxis.set_tick_params(labelsize=8)
            ax.yaxis.set_tick_params(labelsize=8)

            self.canvas_time_signal_checker.draw()
            self.temp_lines_checkup2[var_filetype][var_file_short] = 1
        else:
            self.temp_axes_checkup2[var_filetype][var_file_short].axis("on")
            self.temp_axes_checkup2[var_filetype][var_file_short].set_visible(True)

            self.canvas_time_signal_checker.draw()

    def place_standard_files_table(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Standard Files'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n

        str_lbl_01 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_02 = self.language_dict["Setup"][self.var_language]
        str_btn_01 = self.language_dict["Confirm all"][self.var_language]

        # Labels
        lbl_header = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=1, n_columns=var_header_n,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")

        # Buttons
        btn_confirm = SE(
            parent=var_parent, row_id=var_row_start + var_row_n + 1, column_id=var_column_start + var_header_n - 6,
            n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_filetype="STD": self.confirm_all_files_2(var_filetype))
        # Frames
        frm_files = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_files = ttk.Scrollbar(master=frm_files, orient="vertical")
        text_files = tk.Text(
            master=frm_files, width=30, height=25, yscrollcommand=vsb_files.set, bg=self.bg_colors["Very Light"])
        vsb_files.config(command=text_files.yview)
        vsb_files.pack(side="right", fill="y")
        text_files.pack(side="left", fill="both", expand=True)

        for index, file_std in enumerate(self.container_lists["STD"]["Long"]):
            parts = file_std.split("/")
            file_std_short = parts[-1]

            if self.initialization_run_std:
                # Assigns isotopic signal intensity and time data for every standard/srm file
                df_isotopes, times_std_i = self.assign_time_and_isotopic_data(filetype="STD", filename_long=file_std)

                for isotope in df_isotopes:
                    if isotope.isdigit():
                        print(isotope, "in file", file_std_short,"is missing its element. Let's hope it will get it back.")
                    else:
                        if isotope not in self.container_lists["Measured Isotopes"]["All"]:
                            self.container_lists["Measured Isotopes"]["All"].append(isotope)

                if file_std_short not in self.container_measurements["EDITED"]:
                    self.container_measurements["EDITED"][file_std_short] = {}
                    self.container_measurements["EDITED"]["Time"] = times_std_i.tolist()
                # Creates all necessary variables that are related to the standard files
                self.build_all_needed_variables(filetype="STD", filename_long=file_std, filename_short=file_std_short)

                if file_std not in self.container_var["SRM"]:
                    self.container_var["SRM"][file_std] = tk.StringVar()
                    self.container_var["SRM"][file_std].set("Select SRM")

            if index == len(self.container_lists["STD"]["Long"]) - 1:
                self.initialization_run_std = False

            if self.container_flags["STD"]["Initialization"] == False:
                self.container_flags["STD"][file_std_short] = {
                    "BG set": False, "MAT set": False, "SMOOTHED data": False}

            if len(self.container_lists["STD"]["Long"]) < len(self.list_std) and self.file_loaded == False:
                self.build_container_helper(mode="STD")

                if "BG" not in self.container_helper["STD"][file_std_short]:
                    self.container_helper["STD"][file_std_short]["BG"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["STD"][file_std_short]["MAT"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["STD"][file_std_short]["INCL"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}

                self.spikes_isotopes["STD"][file_std_short] = {}
            elif len(self.container_lists["STD"]["Long"]) == len(self.list_std) and self.file_loaded == False:
                self.build_container_helper(mode="STD")

                if "BG" not in self.container_helper["STD"][file_std_short]:
                    self.container_helper["STD"][file_std_short]["BG"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["STD"][file_std_short]["MAT"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["STD"][file_std_short]["INCL"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}

                self.spikes_isotopes["STD"][file_std_short] = {}
            elif len(self.container_lists["STD"]["Long"]) == len(self.list_std) and self.file_loaded == True:
                for item_01 in ["BG", "MAT"]:
                    if file_std_short not in self.container_helper["STD"]:
                        self.build_container_helper(mode="STD")
                    if item_01 not in self.container_helper["STD"][file_std_short]:
                        self.container_helper["STD"][file_std_short][item_01] = {}
                    for item_02 in ["Listbox", "Content", "ID", "Indices"]:
                        if item_02 not in self.container_helper["STD"][file_std_short][item_01]:
                            if item_02 == "Listbox":
                                self.container_helper["STD"][file_std_short][item_01][item_02] = None
                            elif item_02 == "Content":
                                self.container_helper["STD"][file_std_short][item_01][item_02] = {}
                            elif item_02 == "ID":
                                self.container_helper["STD"][file_std_short][item_01][item_02] = 0
                            elif item_02 == "Indices":
                                self.container_helper["STD"][file_std_short][item_01][item_02] = []

            self.create_container_results(var_filetype="STD", var_file_short=file_std_short, mode=self.pysills_mode)

            categories = ["FIG", "AX", "CANVAS", "TOOLBARFRAME", "FIG_RATIO", "AX_RATIO", "CANVAS_RATIO",
                          "TOOLBARFRAME_RATIO"]
            self.container_diagrams["STD"][file_std_short] = {}
            self.container_listboxes["STD"][file_std_short] = {}
            self.diagrams_setup["STD"][file_std_short] = {}
            for category in categories:
                self.container_diagrams["STD"][file_std_short][category] = None
                self.diagrams_setup["STD"][file_std_short][category] = None
            categories = ["Time Signal Raw", "Time Signal Smoothed", "Histogram", "Scatter", "Time Ratio"]
            for category in categories:
                self.diagrams_setup["STD"][file_std_short][category] = {}
            categories = ["BG", "MAT", "INCL", "SPK", "ISORAT"]
            for category in categories:
                self.container_listboxes["STD"][file_std_short][category] = None

            try:
                cb_i = tk.Checkbutton(
                    master=frm_files, text=file_std_short, fg=self.bg_colors["Very Dark"],
                    bg=self.bg_colors["Very Light"], variable=self.container_var["STD"][file_std]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=self.bg_colors["Very Light"], activeforeground=self.bg_colors["Very Dark"],
                    anchor=tk.CENTER, highlightthickness=0, bd=0)
            except:
                self.check_variable_on_existence(
                    var_name_check=self.container_var["STD"], filetype="STD", filename_long=file_std,
                    filename_short=file_std_short)

                cb_i = tk.Checkbutton(
                    master=frm_files, text=file_std_short, fg=self.bg_colors["Very Dark"],
                    bg=self.bg_colors["Very Light"], variable=self.container_var["STD"][file_std]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=self.bg_colors["Very Light"], activeforeground=self.bg_colors["Very Dark"],
                    anchor=tk.CENTER, highlightthickness=0, bd=0)

            text_files.window_create("end", window=cb_i)
            text_files.insert("end", "\t")

            if self.container_var["STD"][file_std]["SRM"].get() != "Select SRM":
                var_text = self.container_var["STD"][file_std]["SRM"].get()
                self.container_files["STD"][file_std_short]["SRM"].set(var_text)
            else:
                if self.container_var["General Settings"]["Default SRM"].get() != "Select SRM":
                    var_text = self.container_var["General Settings"]["Default SRM"].get()
                    self.container_var["SRM"][file_std].set(var_text)
                    self.container_files["STD"][file_std_short]["SRM"].set(var_text)

            opt_srm_i = tk.OptionMenu(
                frm_files, self.container_var["STD"][file_std]["SRM"],
                *np.sort(self.container_lists["SRM Library"]),
                command=lambda var_opt=self.container_var["STD"][file_std]["SRM"], var_indiv=file_std, mode="STD":
                self.fi_change_srm_individual(var_opt, var_indiv, mode))
            opt_srm_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_srm_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
            text_files.window_create("end", window=opt_srm_i)
            text_files.insert("end", "\t")

            if self.pysills_mode == "MA":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                    activebackground=self.accent_color, activeforeground=self.bg_colors["Dark Font"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
                    command=lambda var_filename_long=file_std, var_filetype="STD":
                    self.ma_check_specific_file(var_filename_long, var_filetype))
            elif self.pysills_mode == "FI":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                    activebackground=self.accent_color, activeforeground=self.bg_colors["Dark Font"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
                    command=lambda var_file=file_std, var_type="STD": self.fi_check_specific_file(var_file, var_type))
            elif self.pysills_mode == "MI":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                    activebackground=self.accent_color, activeforeground=self.bg_colors["Dark Font"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
                    command=lambda var_file=file_std, var_type="STD": self.fi_check_specific_file(var_file, var_type))
            text_files.window_create("end", window=btn_i)
            text_files.insert("end", "\t")

            try:
                color_sign = self.container_var["STD"][file_std]["Sign Color"].get()
            except:
                self.container_var["STD"][file_std]["Sign Color"] = tk.StringVar()
                self.container_var["STD"][file_std]["Sign Color"].set(self.sign_red)
                color_sign = self.container_var["STD"][file_std]["Sign Color"].get()

            frm_i = tk.Frame(
                frm_files, bg=color_sign, relief=tk.SOLID, height=15, width=15, highlightbackground="black", bd=1)
            text_files.window_create("end", window=frm_i)
            text_files.insert("end", "\n")

            self.container_var["STD"][file_std]["Frame"] = frm_i

    def check_variable_on_existence(self, var_name_check, filetype, filename_long, filename_short):
        if filename_long not in var_name_check:
            self.build_all_needed_variables(
                filetype=filetype, filename_long=filename_long, filename_short=filename_short)

        if "Checkbox" not in var_name_check[filename_long]:
            self.build_all_needed_variables(
                filetype=filetype, filename_long=filename_long, filename_short=filename_short)

    def assign_time_and_isotopic_data(self, filetype, filename_long):
        parts = filename_long.split("/")
        filename_short = parts[-1]

        if self.file_loaded == False:
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_i = DE(filename_long=filename_long).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_i = DE(filename_long=filename_long).get_measurements(delimiter=",", skip_header=3, skip_footer=1)
        else:
            if self.old_file:
                if self.container_icpms["name"] != None:
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    df_i = DE(filename_long=filename_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                else:
                    df_i = DE(filename_long=filename_long).get_measurements(delimiter=",", skip_header=3, skip_footer=1)

                if "Dataframe" not in self.container_measurements:
                    self.container_measurements["Dataframe"] = {}

                if filename_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][filename_short] = df_i
            else:
                if "_copy" in filename_short:
                    key = re.search(r"(_copy\d*)", filename_short)
                    key_copy = key.group(1)
                    filename_short_original = filename_short.replace(key_copy, "")
                    df_i = self.container_measurements["Dataframe"][filename_short_original]
                else:
                    df_i = self.container_measurements["Dataframe"][filename_short]

        df_isotopes_i = DE().get_isotopes(dataframe=df_i)
        self.container_lists["Measured Isotopes"][filename_short] = df_isotopes_i
        df_times_i = DE().get_times(dataframe=df_i)

        return df_isotopes_i, df_times_i

    def build_all_needed_variables(self, filetype, filename_long, filename_short):
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"

        str_var_01 = self.language_dict["Select IS"][self.var_language]
        str_var_02 = self.language_dict["Select oxide"][self.var_language]
        str_var_03 = self.language_dict["Select element"][self.var_language]
        str_var_04 = self.language_dict["Select isotope"][self.var_language]

        # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --

        if filename_long not in self.container_lists[filetype]["Long"]:
            self.container_lists[filetype]["Long"].append(filename_long)
        if filename_short not in self.container_lists[filetype]["Short"]:
            self.container_lists[filetype]["Short"].append(filename_short)

        if filename_short not in self.container_var[var_setting_key]["Data Type Plot"][filetype]:
            self.container_var[var_setting_key]["Data Type Plot"][filetype][filename_short] = tk.IntVar()
            self.container_var[var_setting_key]["Data Type Plot"][filetype][filename_short].set(0)
        if filename_short not in self.container_var[var_setting_key]["Analyse Mode Plot"][filetype]:
            self.container_var[var_setting_key]["Analyse Mode Plot"][filetype][filename_short] = tk.IntVar()
            self.container_var[var_setting_key]["Analyse Mode Plot"][filetype][filename_short].set(0)
        if filename_short not in self.container_var[var_setting_key]["Display RAW"][filetype]:
            self.container_var[var_setting_key]["Display RAW"][filetype][filename_short] = {}
        if filename_short not in self.container_var[var_setting_key]["Display SMOOTHED"][filetype]:
            self.container_var[var_setting_key]["Display SMOOTHED"][filetype][filename_short] = {}

        if filename_long not in self.container_var[filetype]:
            self.container_var[filetype][filename_long] = {}

        if self.file_loaded == False or "IS Data" not in self.container_var[filetype][filename_long]:
            self.container_var[filetype][filename_long]["IS Data"] = {
                "IS": tk.StringVar(), "Concentration": tk.StringVar(),
                "RAW": {"IS": tk.StringVar(), "Concentration": tk.StringVar()},
                "SMOOTHED": {"IS": tk.StringVar(), "Concentration": tk.StringVar()}}
            self.container_var[filetype][filename_long]["IS Data"]["IS"].set(str_var_01)
            self.container_var[filetype][filename_long]["IS Data"]["Concentration"].set("0.0")
            self.container_var[filetype][filename_long]["IS Data"]["RAW"]["IS"].set(str_var_01)
            self.container_var[filetype][filename_long]["IS Data"]["RAW"]["Concentration"].set("0.0")
            self.container_var[filetype][filename_long]["IS Data"]["SMOOTHED"]["IS"].set(str_var_01)
            self.container_var[filetype][filename_long]["IS Data"]["SMOOTHED"]["Concentration"].set("0.0")
            self.container_var[filetype][filename_long]["Checkbox"] = tk.IntVar()
            self.container_var[filetype][filename_long]["Checkbox"].set(1)
            self.container_var[filetype][filename_long]["SRM"] = tk.StringVar()
            self.container_var[filetype][filename_long]["SRM"].set("Select SRM")
            self.container_var[filetype][filename_long]["Sign Color"] = tk.StringVar()
            self.container_var[filetype][filename_long]["Sign Color"].set(self.sign_red)
            self.container_var[filetype][filename_long]["ID"] = tk.StringVar()
            self.container_var[filetype][filename_long]["ID"].set("A")

        if filetype == "STD":
            if filename_long not in self.container_var["SRM"]:
                self.container_var["SRM"][filename_long] = tk.StringVar()
                self.container_var["SRM"][filename_long].set("Select SRM")

            if filename_short not in self.container_files[filetype]:
                self.container_files["STD"][filename_short] = {}
                self.container_files["STD"][filename_short]["SRM"] = tk.StringVar()
                self.container_files["STD"][filename_short]["IS"] = tk.StringVar()

        if filetype == "SMPL":
            if self.file_loaded == False or "Matrix Setup" not in self.container_var[filetype][filename_long]:
                self.container_var[filetype][filename_long]["ID"] = tk.StringVar()
                self.container_var[filetype][filename_long]["ID"].set("A")
                self.container_var[filetype][filename_long]["Matrix Setup"] = {
                    "IS": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                    "Oxide": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                    "Element": {"Name": tk.StringVar(), "Concentration": tk.StringVar()}}
                self.container_var[filetype][filename_long]["Matrix Setup"]["IS"]["Name"].set(str_var_01)
                self.container_var[filetype][filename_long]["Matrix Setup"]["IS"]["Concentration"].set("1000000")
                self.container_var[filetype][filename_long]["Matrix Setup"]["Oxide"]["Name"].set(str_var_02)
                self.container_var[filetype][filename_long]["Matrix Setup"]["Oxide"]["Concentration"].set("100.0")
                self.container_var[filetype][filename_long]["Matrix Setup"]["Element"]["Name"].set(str_var_03)
                self.container_var[filetype][filename_long]["Matrix Setup"]["Element"]["Concentration"].set("100.0")

            if filename_short not in self.container_var["Oxides Quantification"]["Total Amounts"]:
                if self.file_loaded == False or filename_short not in self.container_var["Oxides Quantification"][
                    "Total Amounts"]:
                    self.container_var["Oxides Quantification"]["Total Amounts"][filename_short] = tk.StringVar()
                    self.container_var["Oxides Quantification"]["Total Amounts"][filename_short].set("100.0")

            if filename_short not in self.container_var["Oxides Quantification INCL"]["Total Amounts"]:
                if self.file_loaded == False or filename_short not in self.container_var["Oxides Quantification INCL"][
                    "Total Amounts"]:
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][filename_short] = tk.StringVar()
                    self.container_var["Oxides Quantification INCL"]["Total Amounts"][filename_short].set("100.0")

            if self.pysills_mode != "MA":
                # Matrix-only Tracer
                if "Host Only Tracer" not in self.container_var["SMPL"][filename_long]:
                    self.container_var["SMPL"][filename_long]["Host Only Tracer"] = {
                        "Name": tk.StringVar(), "Value": tk.StringVar(), "Matrix": tk.StringVar(),
                        "Amount": tk.StringVar()}
                    self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Name"].set(str_var_04)
                    self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Value"].set("0")
                    self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Matrix"].set(str_var_02)
                    self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Amount"].set("100")
                # Second Internal Standard
                if "Second Internal Standard" not in self.container_var["SMPL"][filename_long]:
                    self.container_var["SMPL"][filename_long]["Second Internal Standard"] = {
                        "Name": tk.StringVar(), "Value": tk.StringVar()}
                    self.container_var["SMPL"][filename_long]["Second Internal Standard"]["Name"].set(
                        "Select Isotope")
                    self.container_var["SMPL"][filename_long]["Second Internal Standard"]["Value"].set("0")
                # Geometric Approach (Halter et al. 2002)
                if "Halter2002" not in self.container_var["SMPL"][filename_long]:
                    self.container_var["SMPL"][filename_long]["Halter2002"] = {
                        "a": tk.StringVar(), "b": tk.StringVar(), "rho(incl)": tk.StringVar(),
                        "rho(host)": tk.StringVar(), "R": tk.StringVar(), "Name": tk.StringVar()}
                    self.container_var["SMPL"][filename_long]["Halter2002"]["a"].set("50.0")
                    self.container_var["SMPL"][filename_long]["Halter2002"]["b"].set("50.0")
                    self.container_var["SMPL"][filename_long]["Halter2002"]["rho(incl)"].set("1200.0")
                    self.container_var["SMPL"][filename_long]["Halter2002"]["rho(host)"].set("2700.0")
                    self.container_var["SMPL"][filename_long]["Halter2002"]["R"].set("75.0")
                    self.container_var["SMPL"][filename_long]["Halter2002"]["Name"].set(str_var_04)
                # Geometric Approach (Borisova et al. 2021)
                if "Borisova2021" not in self.container_var["SMPL"][filename_long]:
                    self.container_var["SMPL"][filename_long]["Borisova2021"] = {
                        "R(incl)": tk.StringVar(), "R(host)": tk.StringVar(), "rho(incl)": tk.StringVar(),
                        "rho(host)": tk.StringVar(), "Name": tk.StringVar()}
                    self.container_var["SMPL"][filename_long]["Borisova2021"]["R(incl)"].set("50.0")
                    self.container_var["SMPL"][filename_long]["Borisova2021"]["R(host)"].set("75.0")
                    self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(incl)"].set("1200.0")
                    self.container_var["SMPL"][filename_long]["Borisova2021"]["rho(host)"].set("2700.0")
                    self.container_var["SMPL"][filename_long]["Borisova2021"]["Name"].set(str_var_04)
                # Melting temperatures
                if "Melting temperature" not in self.container_var["SMPL"][filename_long]:
                    self.container_var["SMPL"][filename_long]["Melting temperature"] = tk.StringVar()
                    self.container_var["SMPL"][filename_long]["Melting temperature"].set("25.0")
                # Last compound
                if "Last compound" not in self.container_var["SMPL"][filename_long]:
                    self.container_var["SMPL"][filename_long]["Last compound"] = tk.StringVar()
                    self.container_var["SMPL"][filename_long]["Last compound"].set("Select last solid")
                # Salinity
                if filename_short not in self.container_var[var_setting_key]["Salt Correction"][
                    "Salinity SMPL"]:
                    self.container_var[var_setting_key]["Salt Correction"]["Salinity SMPL"][
                        filename_short] = tk.StringVar()
                    self.container_var[var_setting_key]["Salt Correction"]["Salinity SMPL"][
                        filename_short].set("Set salinity")

        if filename_short not in self.spikes_isotopes[filetype]:
            self.spikes_isotopes[filetype][filename_short] = {}

        if filename_short not in self.container_var[var_setting_key]["Time-Signal Lines"][filetype]:
            self.container_var[var_setting_key]["Time-Signal Lines"][filetype][filename_short] = {}
        if filename_short not in self.container_var[var_setting_key]["Time-Ratio Lines"][filetype]:
            self.container_var[var_setting_key]["Time-Ratio Lines"][filetype][filename_short] = {}
        if filename_short not in self.container_var[var_setting_key]["Checkboxes Isotope Diagram"][filetype]:
            self.container_var[var_setting_key]["Checkboxes Isotope Diagram"][filetype][filename_short] = {}
        if filename_short not in self.container_var[var_setting_key]["Calculation Interval"][filetype]:
            self.container_var[var_setting_key]["Calculation Interval"][filetype][filename_short] = tk.IntVar()
            self.container_var[var_setting_key]["Calculation Interval"][filetype][filename_short].set(3)
        if filename_short not in self.container_var[var_setting_key]["Calculation Interval Visibility"][filetype]:
            self.container_var[var_setting_key]["Calculation Interval Visibility"][filetype][filename_short] = {}

        if filename_short not in self.container_helper[filetype]:
            self.container_helper[filetype][filename_short] = {}

        for category in ["FIGURE", "CANVAS", "TOOLBARFRAME", "RESULTS FRAME", "FIGURE RATIO", "CANVAS RATIO",
                         "TOOLBARFRAME RATIO"]:
            if category not in self.container_helper[filetype][filename_short]:
                self.container_helper[filetype][filename_short][category] = None
        for category in ["AXES", "AXES RATIO"]:
            if category not in self.container_helper[filetype][filename_short]:
                self.container_helper[filetype][filename_short][category] = {}

        if filename_short not in self.container_measurements["EDITED"]:
            self.container_measurements["EDITED"][filename_short] = {}

        # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --

        file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
        for isotope in file_isotopes:
            if isotope not in self.container_measurements["EDITED"][filename_short]:
                self.container_measurements["EDITED"][filename_short][isotope] = {"BG": [], "MAT": [], "INCL": []}
            if isotope not in self.container_var[var_setting_key]["Display RAW"][filetype][filename_short]:
                self.container_var[var_setting_key]["Display RAW"][filetype][filename_short][isotope] = tk.IntVar()
                self.container_var[var_setting_key]["Display RAW"][filetype][filename_short][isotope].set(1)
            if isotope not in self.container_var[var_setting_key]["Display SMOOTHED"][filetype][filename_short]:
                self.container_var[var_setting_key]["Display SMOOTHED"][filetype][filename_short][isotope] = tk.IntVar()
                self.container_var[var_setting_key]["Display SMOOTHED"][filetype][filename_short][isotope].set(0)
            if isotope not in self.container_var[var_setting_key]["Time-Signal Lines"][filetype][filename_short]:
                self.container_var[var_setting_key]["Time-Signal Lines"][filetype][filename_short][isotope] = {
                    "RAW": None, "SMOOTHED": None}
            if isotope not in self.container_var[var_setting_key]["Time-Signal Lines"][filetype][filename_short]:
                self.container_var[var_setting_key]["Time-Ratio Lines"][filetype][filename_short][isotope] = {
                    "RAW": None, "SMOOTHED": None}
            if isotope not in self.container_var[var_setting_key]["Time-Signal Lines"][filetype][filename_short]:
                self.container_var[var_setting_key]["Checkboxes Isotope Diagram"][filetype][filename_short][isotope] = {
                    "RAW": None, "SMOOTHED": None}

    def place_sample_files_table(self, var_geometry_info):
        """Creates and places the necessary tkinter widgets for the section: 'Standard Files'
        Parameters:  var_geometry_info  -   contains information for the widget setup
        """
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"

        var_row_start = var_geometry_info["Row start"]
        var_column_start = var_geometry_info["Column start"]
        var_row_n = var_geometry_info["N rows"]
        var_column_n = var_geometry_info["N columns"]
        var_header_n = var_column_n

        str_lbl_01 = self.language_dict["Sample Files"][self.var_language]
        str_lbl_02 = self.language_dict["Setup"][self.var_language]
        str_btn_01 = self.language_dict["Confirm all"][self.var_language]

        # Labels
        lbl_header = SE(
            parent=var_parent, row_id=var_row_start, column_id=var_column_start, n_rows=1, n_columns=var_header_n,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")

        # Buttons
        btn_confirm = SE(
            parent=var_parent, row_id=var_row_start + var_row_n + 1, column_id=var_column_start + var_header_n - 6,
            n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_filetype="SMPL": self.confirm_all_files_2(var_filetype))

        # Frames
        frm_files = SE(
            parent=var_parent, row_id=var_row_start + 1, column_id=var_column_start, n_rows=var_row_n,
            n_columns=var_header_n, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_files = ttk.Scrollbar(master=frm_files, orient="vertical")
        text_files = tk.Text(
            master=frm_files, width=30, height=25, yscrollcommand=vsb_files.set, bg=self.bg_colors["Very Light"])
        vsb_files.config(command=text_files.yview)
        vsb_files.pack(side="right", fill="y")
        text_files.pack(side="left", fill="both", expand=True)
        #
        for index, file_smpl in enumerate(self.container_lists["SMPL"]["Long"]):
            parts = file_smpl.split("/")
            file_smpl_short = parts[-1]

            if self.initialization_run_smpl:
                # Assigns isotopic signal intensity and time data for every sample file
                df_isotopes, times_smpl_i = self.assign_time_and_isotopic_data(filetype="SMPL", filename_long=file_smpl)

                for isotope in df_isotopes:
                    if isotope.isdigit():
                        print(isotope, "in file", file_smpl_short,
                              "is missing its element. Let's hope it will get it back.")
                    else:
                        if isotope not in self.container_lists["Measured Isotopes"]["All"]:
                            self.container_lists["Measured Isotopes"]["All"].append(isotope)

                if file_smpl_short not in self.container_measurements["EDITED"]:
                    self.container_measurements["EDITED"][file_smpl_short] = {}
                    self.container_measurements["EDITED"]["Time"] = times_smpl_i.tolist()
                # Creates all necessary variables that are related to the sample files
                self.build_all_needed_variables(filetype="SMPL", filename_long=file_smpl,
                                                filename_short=file_smpl_short)

            if index == len(self.container_lists["SMPL"]["Long"]) - 1:
                self.initialization_run_smpl = False

            if self.container_flags["SMPL"]["Initialization"] == False:
                self.container_flags["SMPL"][file_smpl_short] = {
                    "BG set": False, "MAT set": False, "SMOOTHED data": False}

            if len(self.container_lists["SMPL"]["Long"]) < len(self.list_smpl) and self.file_loaded == False:
                self.build_container_helper(mode="SMPL")

                if "BG" not in self.container_helper["SMPL"][file_smpl_short]:
                    self.container_helper["SMPL"][file_smpl_short]["BG"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["SMPL"][file_smpl_short]["MAT"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["SMPL"][file_smpl_short]["INCL"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}

                self.spikes_isotopes["SMPL"][file_smpl_short] = {}
            elif len(self.container_lists["SMPL"]["Long"]) == len(self.list_smpl) and self.file_loaded == False:
                self.build_container_helper(mode="SMPL")

                if "BG" not in self.container_helper["SMPL"][file_smpl_short]:
                    self.container_helper["SMPL"][file_smpl_short]["BG"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["SMPL"][file_smpl_short]["MAT"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}
                    self.container_helper["SMPL"][file_smpl_short]["INCL"] = {
                        "Listbox": None, "Content": {}, "ID": 0, "Indices": []}

                self.spikes_isotopes["SMPL"][file_smpl_short] = {}
            elif len(self.container_lists["SMPL"]["Long"]) == len(self.list_smpl) and self.file_loaded == True:
                if self.pysills_mode in ["FI", "MI"]:
                    list_focus = ["BG", "MAT", "INCL"]
                else:
                    list_focus = ["BG", "MAT"]
                for item_01 in list_focus:
                    if file_smpl_short not in self.container_helper["SMPL"]:
                        self.build_container_helper(mode="SMPL")
                    if item_01 not in self.container_helper["SMPL"][file_smpl_short]:
                        self.container_helper["SMPL"][file_smpl_short][item_01] = {}
                    for item_02 in ["Listbox", "Content", "ID", "Indices"]:
                        if item_02 not in self.container_helper["SMPL"][file_smpl_short][item_01]:
                            if item_02 == "Listbox":
                                self.container_helper["SMPL"][file_smpl_short][item_01][item_02] = None
                            elif item_02 == "Content":
                                self.container_helper["SMPL"][file_smpl_short][item_01][item_02] = {}
                            elif item_02 == "ID":
                                self.container_helper["SMPL"][file_smpl_short][item_01][item_02] = 0
                            elif item_02 == "Indices":
                                self.container_helper["SMPL"][file_smpl_short][item_01][item_02] = []

            self.create_container_results(var_filetype="SMPL", var_file_short=file_smpl_short, mode=self.pysills_mode)

            categories = ["FIG", "AX", "CANVAS", "TOOLBARFRAME", "FIG_RATIO", "AX_RATIO", "CANVAS_RATIO",
                          "TOOLBARFRAME_RATIO"]
            self.container_diagrams["SMPL"][file_smpl_short] = {}
            self.container_listboxes["SMPL"][file_smpl_short] = {}
            self.diagrams_setup["SMPL"][file_smpl_short] = {}
            for category in categories:
                self.container_diagrams["SMPL"][file_smpl_short][category] = None
                self.diagrams_setup["SMPL"][file_smpl_short][category] = None
            categories = ["Time Signal Raw", "Time Signal Smoothed", "Histogram", "Scatter", "Time Ratio"]
            for category in categories:
                self.diagrams_setup["SMPL"][file_smpl_short][category] = {}
            categories = ["BG", "MAT", "INCL", "SPK", "ISORAT"]
            for category in categories:
                self.container_listboxes["SMPL"][file_smpl_short][category] = None

            if file_smpl not in self.container_var["SMPL"]:
                self.build_all_needed_variables(
                    filetype="SMPL", filename_long=file_smpl, filename_short=file_smpl_short)

            file_isotopes = self.container_lists["Measured Isotopes"][file_smpl_short]

            try:
                cb_i = tk.Checkbutton(
                    master=frm_files, text=file_smpl_short, fg=self.bg_colors["Very Dark"],
                    bg=self.bg_colors["Very Light"], variable=self.container_var["SMPL"][file_smpl]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=self.bg_colors["Very Light"], activeforeground=self.bg_colors["Very Dark"],
                    anchor=tk.CENTER, highlightthickness=0, bd=0)
            except:
                self.check_variable_on_existence(
                    var_name_check=self.container_var["SMPL"], filetype="SMPL", filename_long=file_smpl,
                    filename_short=file_smpl_short)

                cb_i = tk.Checkbutton(
                    master=frm_files, text=file_smpl_short, fg=self.bg_colors["Very Dark"],
                    bg=self.bg_colors["Very Light"], variable=self.container_var["SMPL"][file_smpl]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=self.bg_colors["Very Light"], activeforeground=self.bg_colors["Very Dark"],
                    anchor=tk.CENTER, highlightthickness=0, bd=0)

            text_files.window_create("end", window=cb_i)
            text_files.insert("end", "\t")

            opt_is_i = tk.OptionMenu(
                frm_files, self.container_var["SMPL"][file_smpl]["IS Data"]["IS"], *file_isotopes)
            opt_is_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_is_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
            text_files.window_create("end", window=opt_is_i)
            text_files.insert("end", "\t")
            #
            if self.container_var["SMPL"][file_smpl]["ID"].get() != "A":
                var_text = self.container_var["SMPL"][file_smpl]["ID"].get()
            else:
                var_text = "A"
            opt_id_i = tk.OptionMenu(
                frm_files, self.container_var["SMPL"][file_smpl]["ID"], *np.sort(self.list_alphabet))
            opt_id_i["menu"].config(
                fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_id_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
            text_files.window_create("end", window=opt_id_i)
            text_files.insert("end", "\t")

            if self.pysills_mode == "MA":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"],
                    activebackground=self.accent_color, activeforeground=self.bg_colors["Dark Font"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
                    command=lambda var_filename_long=file_smpl, var_filetype="SMPL":
                    self.ma_check_specific_file(var_filename_long, var_filetype))
            elif self.pysills_mode == "FI":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"],
                    activebackground=self.accent_color, activeforeground=self.bg_colors["Dark Font"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
                    command=lambda var_file=file_smpl, var_type="SMPL": self.fi_check_specific_file(var_file, var_type))
            elif self.pysills_mode == "MI":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"],
                    activebackground=self.accent_color, activeforeground=self.bg_colors["Dark Font"],
                    highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
                    command=lambda var_file=file_smpl, var_type="SMPL": self.fi_check_specific_file(var_file, var_type))
            text_files.window_create("end", window=btn_i)
            text_files.insert("end", "\t")

            try:
                color_sign = self.container_var["SMPL"][file_smpl]["Sign Color"].get()
            except:
                self.container_var["SMPL"][file_smpl]["Sign Color"] = tk.StringVar()
                self.container_var["SMPL"][file_smpl]["Sign Color"].set(self.sign_red)
                color_sign = self.container_var["SMPL"][file_smpl]["Sign Color"].get()

            frm_i = tk.Frame(
                frm_files, bg=color_sign, relief=tk.SOLID, height=15, width=15, highlightbackground="black", bd=1)
            text_files.window_create("end", window=frm_i)
            text_files.insert("end", "\n")
            #
            self.container_var["SMPL"][file_smpl]["Frame"] = frm_i

    def change_filetype_time_signal_diagram_checker(self, var_setting_key):
        self.current_file_id_checker = 0

        if self.container_var[var_setting_key]["Time-Signal Checker"].get() == 1:
            var_filetype = "STD"
            var_filetype_previous = "SMPL"
        else:
            var_filetype = "SMPL"
            var_filetype_previous = "STD"

        self.show_time_signal_diagram_checker(var_setting_key=var_setting_key)

    def change_file_time_signal_diagram_checker(self, var_mode, var_setting_key):
        if self.container_var[var_setting_key]["Time-Signal Checker"].get() == 1:
            var_filetype = "STD"
        else:
            var_filetype = "SMPL"

        if var_mode == "Next":
            if self.current_file_id_checker < len(self.container_lists[var_filetype]["Short"]) - 1:
                self.current_file_id_checker += 1
            else:
                self.current_file_id_checker = 0
        else:
            if self.current_file_id_checker > 0:
                self.current_file_id_checker -= 1
            else:
                self.current_file_id_checker = len(self.container_lists[var_filetype]["Short"]) - 1

        self.show_time_signal_diagram_checker(var_setting_key=var_setting_key)

    def build_checkbutton_isotope_visibility(self, var_mode, var_filetype, var_filename_short, var_isotope):
        self.container_var[var_mode]["Display RAW"][var_filetype][var_filename_short][var_isotope] = tk.IntVar()
        self.container_var[var_mode]["Display SMOOTHED"][var_filetype][var_filename_short][var_isotope] = tk.IntVar()
        self.container_var[var_mode]["Display RAW"][var_filetype][var_filename_short][var_isotope].set(1)
        self.container_var[var_mode]["Display SMOOTHED"][var_filetype][var_filename_short][var_isotope].set(0)

    def define_temporary_colors(self, filename_short):
        var_n = len(self.container_lists["Measured Isotopes"][filename_short])
        var_cm = self.container_var["General Settings"]["Colormap"].get()
        cmap = plt.get_cmap(var_cm, var_n)
        colors_mpl = []

        for i in range(cmap.N):
            rgba = cmap(i)
            colors_mpl.append(mpl.colors.rgb2hex(rgba))

        self.isotope_colors_temporary = {}
        for index, isotope in enumerate(self.container_lists["Measured Isotopes"][filename_short]):
            self.isotope_colors_temporary[isotope] = colors_mpl[index]

    def define_isotope_colors(self):
        var_n = len(self.container_lists["Measured Isotopes"]["All"])
        var_cm = self.container_var["General Settings"]["Colormap"].get()
        cmap = plt.get_cmap(var_cm, var_n)
        colors_mpl = []

        for i in range(cmap.N):
            rgba = cmap(i)
            colors_mpl.append(mpl.colors.rgb2hex(rgba))

        self.isotope_colors = {}
        for index, isotope in enumerate(self.container_lists["Measured Isotopes"]["All"]):
            self.container_files["SRM"][isotope] = tk.StringVar()
            self.isotope_colors[isotope] = colors_mpl[index]

    def build_container_helper(self, mode):
        """Creates and defines some important helper variables.
        Args:
            mode (str): It defines the file type ("STD" vs. "SMPL").
        Returns:
        """

        for var_file_short in self.container_lists[mode]["Short"]:
            if var_file_short not in self.container_helper[mode]:
                self.container_helper[mode][var_file_short] = {}

                self.container_helper[mode][var_file_short]["FIGURE"] = None
                self.container_helper[mode][var_file_short]["CANVAS"] = None
                self.container_helper[mode][var_file_short]["TOOLBARFRAME"] = None
                self.container_helper[mode][var_file_short]["AXES"] = {}
                self.container_helper[mode][var_file_short]["RESULTS FRAME"] = None
                self.container_helper[mode][var_file_short]["FIGURE RATIO"] = None
                self.container_helper[mode][var_file_short]["CANVAS RATIO"] = None
                self.container_helper[mode][var_file_short]["TOOLBARFRAME RATIO"] = None
                self.container_helper[mode][var_file_short]["AXES RATIO"] = {}

    def build_matrix_setup_variables(self):
        for var_file in self.container_lists["SMPL"]["Long"]:
            if var_file not in self.container_var["SMPL"]:
                self.container_var["SMPL"][var_file] = {}

            if "Matrix Setup" not in self.container_var["SMPL"][var_file]:
                self.container_var["SMPL"][var_file]["Matrix Setup"] = {
                    "IS": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                    "Oxide": {"Name": tk.StringVar(), "Concentration": tk.StringVar()},
                    "Element": {"Name": tk.StringVar(), "Concentration": tk.StringVar()}}

                self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Name"].set("Select IS")
                self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Concentration"].set("0.0")
                self.container_var["SMPL"][var_file]["Matrix Setup"]["Oxide"]["Name"].set("Select Oxide")
                self.container_var["SMPL"][var_file]["Matrix Setup"]["Oxide"]["Concentration"].set("100.0")
                self.container_var["SMPL"][var_file]["Matrix Setup"]["Element"]["Name"].set("Select Element")
                self.container_var["SMPL"][var_file]["Matrix Setup"]["Element"]["Concentration"].set("100.0")

    def confirm_all_files_2(self, var_filetype):
        for var_file_long in self.container_lists[var_filetype]["Long"]:
            self.container_var[var_filetype][var_file_long]["Sign Color"].set(self.sign_green)
            self.container_var[var_filetype][var_file_long]["Frame"].config(background=self.sign_green, bd=1)

    ## MATRIX SETTINGS #################################################################################################
    def ma_matrix_concentration_setup(self):
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
            var_window_header = "MINERAL ANALYSIS - Sample Concentration Setup"
            var_window_header = self.language_dict["Sample Settings"][self.var_language]
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
            var_window_header = "FLUID INCLUSION ANALYSIS - Matrix Concentration Setup"
            var_window_header = self.language_dict["Matrix Settings"][self.var_language]
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"
            var_window_header = "MELT INCLUSION ANALYSIS - Matrix Concentration Setup"
            var_window_header = self.language_dict["Matrix Settings"][self.var_language]

        ## Window Settings
        window_width = 800
        window_height = 450
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_ma_matrix_concentration = tk.Toplevel(self.parent)
        subwindow_ma_matrix_concentration.title(var_window_header)
        subwindow_ma_matrix_concentration.geometry(var_geometry)
        subwindow_ma_matrix_concentration.resizable(False, False)
        subwindow_ma_matrix_concentration["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_ma_matrix_concentration, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_ma_matrix_concentration, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_ma_matrix_concentration.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_ma_matrix_concentration.grid_columnconfigure(i, minsize=column_min)

        start_row = 0
        start_column = 0

        ## INITIAL VALUES
        list_oxides = sorted(self.container_lists["Oxides"])

        str_lbl_01 = self.language_dict["Sample Files"][self.var_language]
        str_lbl_02 = self.language_dict["Default settings"][self.var_language]
        str_var_01 = self.language_dict["Select oxide"][self.var_language]
        str_var_02 = self.language_dict["Select element"][self.var_language]
        str_var_03 = self.language_dict["Select IS"][self.var_language]
        str_btn_01 = self.language_dict["Import data"][self.var_language]

        ## LABELS
        if self.container_var[var_setting_key]["Host Setup Selection"].get() == 1:
            var_text_02 = "Oxide Settings (default)"
            var_key = "oxides"
        elif self.container_var[var_setting_key]["Host Setup Selection"].get() == 2:
            var_text_02 = "Element Settings (default) (wt.%)"
            var_key = "elements"
        elif self.container_var[var_setting_key]["Host Setup Selection"].get() == 3:
            var_text_02 = "Experimental data"
            var_key = "experiments"
        elif self.container_var[var_setting_key]["Host Setup Selection"].get() == 4:
            var_text_02 = "Custom data"
            var_key = "custom"
        elif self.container_var[var_setting_key]["Host Setup Selection"].get() == 5:
            var_text_02 = "Mineral selection"
            var_key = "mineral"

        lbl_01 = SE(
            parent=subwindow_ma_matrix_concentration, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=19,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_ma_matrix_concentration, row_id=start_row, column_id=start_column + 30, n_rows=1,
            n_columns=9, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")

        list_possible_elements = []
        for isotope in self.container_var["SRM"]:
            if isotope in self.container_lists["Measured Isotopes"]["All"]:
                var_srm_i = self.container_var["SRM"][isotope].get()
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if element in self.srm_actual[var_srm_i]:
                    var_isotope_concentration = self.srm_actual[var_srm_i][element]
                    if var_isotope_concentration > 0:
                        list_possible_elements.append(isotope)

        ## OPTION MENUS
        if var_key == "oxides":
            list_elements = []
            list_compound = []
            list_elements = self.container_lists["Measured Elements"]["All"]
            list_compound = list_oxides
            var_opt_is_list = list_possible_elements
            # for isotope in list_possible_elements:
            #     key = re.search(r"(\D+)(\d*)", isotope)
            #     element_isotope = key.group(1)
            #     if element_isotope not in list_elements:
            #         list_elements.append(element_isotope)
            # for oxide in list_oxides:
            #     key = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide)
            #     element_oxide = key.group(1)
            #     if element_oxide in list_elements:
            #         if oxide not in list_compound:
            #             list_compound.append(oxide)
            var_list_is = list_oxides
            var_opt_default = self.container_var[var_setting_key]["Oxide"]
            var_entr_default = self.container_var[var_setting_key]["Oxide Concentration"]

            if self.container_var[var_setting_key]["Oxide"].get() != str_var_01 \
                    and self.container_var[var_setting_key]["Oxide"].get() not in self.container_lists["Elements"]:
                var_opt_default_text = self.container_var[var_setting_key]["Oxide"].get()
            else:
                var_opt_default_text = str_var_01

            if self.container_var[var_setting_key]["Oxide Concentration"].get() != "100.0":
                var_entr_default_text = self.container_var[var_setting_key]["Oxide Concentration"].get()
            else:
                var_entr_default_text = "100.0"
        elif var_key == "elements":
            list_elements = []
            list_compound = []
            for isotope in list_possible_elements:
                key = re.search(r"(\D+)(\d*)", isotope)
                element_isotope = key.group(1)
                if element_isotope not in list_elements:
                    list_elements.append(element_isotope)
            for element in self.container_lists["Elements"]:
                if element in list_elements:
                    if element not in list_compound:
                        list_compound.append(element)
            var_list_is = self.container_lists["Elements"]
            var_opt_default = self.container_var[var_setting_key]["Element"]
            var_entr_default = self.container_var[var_setting_key]["Element Concentration"]

            if self.container_var[var_setting_key]["Element"].get() != str_var_02 \
                    and self.container_var[var_setting_key]["Element"].get() not in list_oxides:
                var_opt_default_text = self.container_var[var_setting_key]["Element"].get()
            else:
                var_opt_default_text = str_var_02

            if self.container_var[var_setting_key]["Element Concentration"].get() != "1000000":
                var_entr_default_text = self.container_var[var_setting_key]["Element Concentration"].get()
            else:
                var_entr_default_text = "1000000"
        elif var_key == "experiments":
            btn_smpl = SE(
                parent=subwindow_ma_matrix_concentration, row_id=start_row + 1, column_id=start_column + 30, n_rows=1,
                n_columns=9, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda parent=subwindow_ma_matrix_concentration, mode="MA": self.import_is_data(parent, mode))
        elif var_key == "custom":
            var_opt_is_default = self.container_var["IS"]["Default SMPL"]
            var_opt_is_list = list_possible_elements

            if var_opt_is_default.get() != str_var_03:
                var_opt_is_default_text = var_opt_is_default.get()
            else:
                var_opt_is_default_text = str_var_03

            self.opt_02b = SE(
                parent=subwindow_ma_matrix_concentration, row_id=start_row + 1, column_id=start_column + 30, n_rows=1,
                n_columns=9, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
                var_iso=var_opt_is_default, option_list=var_opt_is_list, text_set=var_opt_is_default_text,
                fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
                command=lambda var_opt=var_opt_is_default, var_file=None, state_default=True:
                self.ma_change_is_smpl(var_opt, var_file, state_default))
            self.opt_02b["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            self.opt_02b.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, highlightthickness=0)

            var_entr_is_default = self.container_var["IS"]["Default SMPL Concentration"]
            var_entr_is_default_text = self.container_var["IS"]["Default SMPL Concentration"].get()

            entr_02b = SE(
                parent=subwindow_ma_matrix_concentration, row_id=start_row + 2, column_id=start_column + 30, n_rows=1,
                n_columns=9, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=var_entr_is_default, text_default=var_entr_is_default_text,
                command=lambda event, var_entr=var_entr_is_default, var_file=None, state_default=True:
                self.ma_change_is_concentration(var_entr, var_file, state_default, event))
        elif var_key == "mineral":
            var_opt_default = self.container_var[var_setting_key]["Mineral"]
            var_opt_is_default = self.container_var["IS"]["Default SMPL"]
            list_compound = self.container_lists["Minerals"]
            var_opt_default_text = self.container_var[var_setting_key]["Mineral"].get()

        if var_key not in ["experiments", "custom"]:
            var_opt_is_default = self.container_var["IS"]["Default SMPL"]
            var_opt_is_list = self.container_lists["Measured Isotopes"]["All"]
            var_entr_is_default = self.container_var["IS"]["Default SMPL Concentration"]

            if var_opt_is_default.get() != str_var_03:
                var_opt_is_default_text = var_opt_is_default.get()
            else:
                var_opt_is_default_text = str_var_03

            var_entr_is_default_text = self.container_var["IS"]["Default SMPL Concentration"].get()

            if var_key != "mineral":
                opt_02a = SE(
                    parent=subwindow_ma_matrix_concentration, row_id=start_row + 1, column_id=start_column + 30,
                    n_rows=1, n_columns=9, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_option_isotope(
                    var_iso=var_opt_default, option_list=list_compound, text_set=var_opt_default_text,
                    fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
                    command=lambda var_opt=var_opt_default, var_file=None, state_default=True:
                    self.ma_change_matrix_compound(var_opt, var_file, state_default))
            else:
                opt_02a = SE(
                    parent=subwindow_ma_matrix_concentration, row_id=start_row + 1, column_id=start_column + 30,
                    n_rows=1, n_columns=9, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_option_isotope(
                    var_iso=var_opt_default, option_list=list_compound, text_set=var_opt_default_text,
                    fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color)

            opt_02a["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            opt_02a.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, highlightthickness=0)

            if var_key != "mineral":
                self.opt_02b = SE(
                    parent=subwindow_ma_matrix_concentration, row_id=start_row + 4, column_id=start_column + 30,
                    n_rows=1, n_columns=9, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_option_isotope(
                    var_iso=var_opt_is_default, option_list=var_opt_is_list, text_set=var_opt_is_default_text,
                    fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
                    command=lambda var_opt=var_opt_is_default, var_file=None, state_default=True:
                    self.ma_change_is_smpl(var_opt, var_file, state_default))
            else:
                self.opt_02b = SE(
                    parent=subwindow_ma_matrix_concentration, row_id=start_row + 3, column_id=start_column + 30,
                    n_rows=1, n_columns=9, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Light"]).create_option_isotope(
                    var_iso=var_opt_is_default, option_list=var_opt_is_list, text_set=var_opt_is_default_text,
                    fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
                    command=lambda var_opt=var_opt_is_default, var_file=None, state_default=True:
                    self.ma_change_is_smpl(var_opt, var_file, state_default))

            self.opt_02b["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            self.opt_02b.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, highlightthickness=0)

            if var_key != "mineral":
                ## ENTRIES
                entr_02a = SE(
                    parent=subwindow_ma_matrix_concentration, row_id=start_row + 2, column_id=start_column + 30,
                    n_rows=1, n_columns=9, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["White"]).create_simple_entry(
                    var=var_entr_default, text_default=var_entr_default_text,
                    command=lambda event, var_entr=var_entr_default, var_file=None, state_default=True:
                    self.ma_change_matrix_concentration(var_entr, var_file, state_default, event))
                entr_02b = SE(
                    parent=subwindow_ma_matrix_concentration, row_id=start_row + 5, column_id=start_column + 30,
                    n_rows=1, n_columns=9, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["White"]).create_simple_entry(
                    var=var_entr_is_default, text_default=var_entr_is_default_text,
                    command=lambda event, var_entr=var_entr_is_default, var_file=None, state_default=True:
                    self.ma_change_is_concentration(var_entr, var_file, state_default, event))

        ## SAMPLE FILES
        frm_smpl = SE(
            parent=subwindow_ma_matrix_concentration, row_id=start_row + 1, column_id=start_column, n_rows=16,
            n_columns=29, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_smpl = ttk.Scrollbar(master=frm_smpl, orient="vertical")
        text_smpl = tk.Text(
            master=frm_smpl, width=30, height=25, yscrollcommand=vsb_smpl.set, bg=self.bg_colors["Very Light"])
        vsb_smpl.config(command=text_smpl.yview)
        vsb_smpl.pack(side="right", fill="y")
        text_smpl.pack(side="left", fill="both", expand=True)

        for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
            if file_smpl_short not in self.helper_option_menus:
                self.helper_option_menus[file_smpl_short] = {}

            if "Matrix Setup IS" not in self.helper_option_menus[file_smpl_short]:
                self.helper_option_menus[file_smpl_short]["Matrix Setup IS"] = None

            file_smpl = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_smpl, text=file_smpl_short, bg=self.bg_colors["Very Light"],
                             fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("end", window=lbl_i)
            text_smpl.insert("end", "\t")

            if var_key == "oxides":  # Oxide Selection
                var_list_is = list_possible_elements
                var_list_comp = list_oxides
                var_opt_comp_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Oxide"]["Name"]
                var_entr_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Oxide"]["Concentration"]

                if self.pysills_mode == "MA":
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"]
                else:
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"]

                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Oxide"]["Name"].get() != "Select Oxide":
                    var_opt_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Oxide"]["Name"].get()
                else:
                    if var_opt_default.get() != str_var_01 \
                            and var_opt_default.get() not in self.container_lists["Elements"]:
                        var_opt_i_default = var_opt_default.get()
                    else:
                        var_opt_i_default = str_var_01

                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Oxide"]["Concentration"].get() != "100.0":
                    var_entr_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Oxide"][
                        "Concentration"].get()
                else:
                    var_entr_i_default = "100.0"

                if self.pysills_mode == "MA":
                    if self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].get() != "1000000":
                        var_entr_is_default = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].get()
                    else:
                        var_entr_is_default = "1000000"
                else:
                    if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"][
                        "Concentration"].get() != "1000000":
                        var_entr_is_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"][
                            "Concentration"].get()
                    else:
                        var_entr_is_default = "1000000"

            elif var_key == "elements":  # Element Selection
                var_list_is = list_possible_elements  # self.container_lists["ISOTOPES"]
                var_list_comp = self.container_lists["Elements"]
                var_opt_comp_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"]["Name"]
                var_entr_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"]["Concentration"]
                if self.pysills_mode == "MA":
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"]
                else:
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"]

                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"]["Name"].get() != "Select Element":
                    var_opt_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"][
                        "Name"].get()
                else:
                    if var_opt_default.get() != str_var_02 and var_opt_default.get() not in list_oxides:
                        var_opt_i_default = var_opt_default.get()
                    else:
                        var_opt_i_default = str_var_02

                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"]["Concentration"].get() != "100.0":
                    var_entr_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"][
                        "Concentration"].get()
                else:
                    var_entr_i_default = "100.0"

                if self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].get() != "1000000":
                    var_entr_is_default = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].get()
                else:
                    var_entr_is_default = "1000000"
            elif var_key in ["experiments", "custom", "mineral"]:  # Experimental Data Selection
                var_list_is = list_possible_elements
                var_entr_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"]["Concentration"]
                if self.pysills_mode == "MA":
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"]
                else:
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"]

                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"]["Concentration"].get() != "100.0":
                    var_entr_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"][
                        "Concentration"].get()
                else:
                    var_entr_i_default = "100.0"

                if self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].get() != "1000000":
                    if self.pysills_mode == "MA":
                        var_entr_is_default = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].get()
                    else:
                        var_entr_is_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"][
                            "Concentration"].get()
                else:
                    var_entr_is_default = "1000000"

            var_entr_is_i.set(var_entr_is_default)
            if var_key not in ["experiments", "custom", "mineral"]:
                var_entr_i.set(var_entr_i_default)
                if len(var_opt_i_default) > 0:
                    var_opt_comp_i.set(var_opt_i_default)
                else:
                    var_opt_comp_i.set(var_opt_default_text)

                opt_comp_i = tk.OptionMenu(
                    frm_smpl, var_opt_comp_i, *var_list_comp,
                    command=lambda event, filename_short=file_smpl_short, mode=var_key:
                    self.update_list_of_possible_is(filename_short, mode, event))
                opt_comp_i["menu"].config(fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                                          activeforeground=self.bg_colors["Dark Font"],
                                          activebackground=self.accent_color)
                opt_comp_i.config(bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                                  activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                                  highlightthickness=0)
                text_smpl.window_create("end", window=opt_comp_i)
                text_smpl.insert("end", " \t")

                if len(var_entr_i.get()) > 0:
                    var_entr_i.set(var_entr_i.get())
                else:
                    var_entr_i.set(var_entr_default_text)

                entr_i = tk.Entry(
                    frm_smpl, textvariable=var_entr_i, width=15, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["White"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"])
                entr_i.bind(
                    "<Return>", lambda event, filename_short=file_smpl_short, mode=var_key:
                    self.update_concentration_value(filename_short, mode, event))
                text_smpl.window_create("insert", window=entr_i)
                text_smpl.insert("end", "\t")

            opt_is_i = tk.OptionMenu(
                frm_smpl, var_opt_is_i, *var_list_is,
                command=lambda variable=var_opt_is_i, filename_short=file_smpl_short, mode=var_key:
                self.run_update_concentration_value(variable, filename_short, mode))
            opt_is_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_is_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)
            self.helper_option_menus[file_smpl_short]["Matrix Setup IS"] = opt_is_i
            text_smpl.window_create("end", window=opt_is_i)
            text_smpl.insert("end", " \t")

            entr_is_i = tk.Entry(
                frm_smpl, textvariable=var_entr_is_i, width=15, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["White"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"])
            entr_is_i.bind(
                "<Return>", lambda event, var_entr=var_entr_is_i, var_file=file_smpl, state_default=False:
                self.ma_change_is_concentration(var_entr, var_file, state_default, event))
            text_smpl.window_create("insert", window=entr_is_i)
            text_smpl.insert("end", "\n")

        # Finishing
        for var_file_smpl in self.container_var["SMPL"].keys():
            if var_file_smpl in self.container_lists["SMPL"]["Short"]:
                if "IS Data" in self.container_var["SMPL"][var_file_smpl]:
                    var_is = self.container_var["SMPL"][var_file_smpl]["IS Data"]["IS"].get()
                    if var_is not in self.container_lists["Possible IS"]:
                        self.container_lists["Possible IS"].append(var_is)

    def run_update_concentration_value(self, variable, filename_short, mode):
        index_file = self.container_lists["SMPL"]["Short"].index(filename_short)
        filename_long = self.container_lists["SMPL"]["Long"][index_file]

        if mode == "oxides":
            oxide_i = self.container_var["SMPL"][filename_long]["Matrix Setup"]["Oxide"]["Name"].get()
            amount_oxide_i = float(self.container_var["SMPL"][filename_long]["Matrix Setup"]["Oxide"][
                                       "Concentration"].get())/100
            if amount_oxide_i > 1:
                amount_oxide_i = 1.0
                self.container_var["SMPL"][filename_long]["Matrix Setup"]["Oxide"]["Concentration"].set("100.0")
            elif amount_oxide_i < 0:
                amount_oxide_i = 0.0
                self.container_var["SMPL"][filename_long]["Matrix Setup"]["Oxide"]["Concentration"].set("0.0")

            key_oxide = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide_i)
            name_cation = key_oxide.group(1)
            name_anion = key_oxide.group(3)

            if len(key_oxide.group(2)) == 0:
                amount_cation = 1
            else:
                amount_cation = int(key_oxide.group(2))

            if len(key_oxide.group(4)) == 0:
                amount_anion = 1
            else:
                amount_anion = int(key_oxide.group(4))

            molar_mass_cation = self.chemistry_data[name_cation]
            molar_mass_anion = self.chemistry_data[name_anion]
            molar_mass_oxide = amount_cation*molar_mass_cation + amount_anion*molar_mass_anion
            mass_amount_cation = round(amount_oxide_i*(amount_cation*molar_mass_cation/molar_mass_oxide)*10**6, 4)

            if self.pysills_mode == "MA":
                self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].set(mass_amount_cation)
                if variable != None and variable != "Select IS":
                    self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set(variable)
            else:
                self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Concentration"].set(mass_amount_cation)
                if variable != None and variable != "Select IS":
                    self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Name"].set(variable)

    def update_concentration_value(self, filename_short, mode, event):
        """ Calculates the cation concentration for a given oxide and oxide amount.
        -------
        Parameters
        var_opt : str
            Contains the variable.
        filename_short : str
            The filename as short version.
        mode : str
            Specifies the calculation (oxides, elements, minerals).
        -------
        Returns
        -------
        """

        self.run_update_concentration_value(variable=None, filename_short=filename_short, mode=mode)

    def import_is_data(self, parent, mode="MA"):
        self.pypitzer_performed = False
        filename = filedialog.askopenfilenames(
            parent=parent,
            filetypes=(("LA-ICP-MS files", "*.csv *.xl *.txt"), ("csv files", "*.csv"), ("xl files", "*.xl"),
                       ("txt files", "*.txt"), ("all files", "*.*")), initialdir=os.getcwd())
        df_expdata = pd.read_csv(filename[0])

        if mode == "MA":
            for index, file in enumerate(df_expdata["file"]):
                file_id = self.container_lists["SMPL"]["Short"].index(file)
                file_long = self.container_lists["SMPL"]["Long"][file_id]
                self.container_var["SMPL"][file_long]["IS Data"]["IS"].set(df_expdata["isotope"][index])
                self.container_var["SMPL"][file_long]["IS Data"]["Concentration"].set(df_expdata["value"][index])
                if self.container_var["IS"]["Default STD"].get() == "Select IS":
                    self.container_var["IS"]["Default STD"].set(df_expdata["isotope"][index])
                    for file_std in self.container_lists["STD"]["Long"]:
                        if self.container_var["STD"][file_std]["IS Data"]["IS"].get() == "Select IS":
                            self.container_var["STD"][file_std]["IS Data"]["IS"].set(df_expdata["isotope"][index])
        elif mode in ["FI", "MI"]:
            for index, file in enumerate(df_expdata["file"]):
                file_id = self.container_lists["SMPL"]["Short"].index(file)
                file_long = self.container_lists["SMPL"]["Long"][file_id]
                self.container_var["SMPL"][file_long]["IS Data"]["IS"].set(df_expdata["isotope"][index])
                self.container_var["SMPL"][file_long]["IS Data"]["Concentration"].set(df_expdata["value"][index])
                if self.container_var["IS"]["Default STD"].get() == "Select IS":
                    self.container_var["IS"]["Default STD"].set(df_expdata["isotope"][index])
                    for file_std in self.container_lists["STD"]["Long"]:
                        if self.container_var["STD"][file_std]["IS Data"]["IS"].get() == "Select IS":
                            self.container_var["STD"][file_std]["IS Data"]["IS"].set(df_expdata["isotope"][index])

    def ma_change_matrix_compound(self, var_opt, var_file=None, state_default=False):
        """ Defines which oxide was selected by the user and calculates the concentration of the internal standard.
        -------
        Parameters
        var_opt : str
            Contains the option menu variable.
        var_file : str
            The filename as long version (the whole path).
        state_default : boolean
            Specifies if the selection is valid for all files or only for one.
        -------
        Returns
        -------
        """
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"

        str_method = self.container_var["Quantification Mineral"]["Method"].get()
        total_ppm = 10**6
        if var_file in self.container_lists["SMPL"]["Long"]:
            index_file = self.container_lists["SMPL"]["Long"].index(var_file)
            filename_short = self.container_lists["SMPL"]["Short"][index_file]
            self.update_concentration_value(filename_short=filename_short, mode="Oxides")

        if self.container_var[var_setting_key]["Host Setup Selection"].get() == 1 or str_method != "Internal Standard":
            var_key = "Oxide"
            value_default = 100
        else:
            var_key = "Element"
            value_default = float(self.container_var[var_setting_key]["Element Concentration"].get())

        if value_default > 100:
            value_default = 100
        elif value_default < 0:
            value_default = 0

        if state_default:
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file_smpl]["Matrix Setup"][var_key]["Name"].set(var_opt)

            value_default_is = total_ppm*value_default/100
            self.container_var["IS"]["Default SMPL Concentration"].set(value_default_is)

            if var_key == "Oxide":
                key = re.search(r"(\D+)(\d*)(\D+)(\d*)", var_opt)
                var_opt_element = key.group(1)
            else:
                var_opt_element = var_opt


            possible_is = self.container_lists["Measured Elements"][var_opt_element]

            self.container_var["IS"]["Default SMPL"].set("Select IS")
            for index, isotope in enumerate(possible_is):
                if index == 0:
                    self.opt_02b["menu"].delete(0, "end")

                self.opt_02b["menu"].add_command(
                    label=isotope, command=lambda var_opt=isotope, var_file=None, state_default=True:
                    self.ma_change_is_smpl(var_opt, var_file, state_default))
        else:
            self.container_var["SMPL"][var_file]["Matrix Setup"][var_key]["Name"].set(var_opt)

    def update_list_of_possible_is(self, filename_short, mode, event):
        index_file = self.container_lists["SMPL"]["Short"].index(filename_short)
        filename_long = self.container_lists["SMPL"]["Long"][index_file]
        str_filename_short = filename_short
        str_mode = mode

        if mode == "oxides":
            oxide_i = self.container_var["SMPL"][filename_long]["Matrix Setup"]["Oxide"]["Name"].get()
            key_oxide = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide_i)
            name_cation = key_oxide.group(1)
            name_anion = key_oxide.group(3)
            possible_is = self.container_lists["Measured Elements"][filename_short][name_cation]

            if name_anion in self.container_lists["Measured Elements"][filename_short]:
                possible_is.extend(self.container_lists["Measured Elements"][filename_short])
                possible_is.sort()

            for index, isotope in enumerate(possible_is):
                menu_i = self.helper_option_menus[filename_short]["Matrix Setup IS"]["menu"]
                if index == 0:
                    menu_i.delete(0, "end")

                menu_i.add_command(
                    label=isotope, command=lambda variable=isotope, filename_short=str_filename_short, mode=str_mode:
                    self.run_update_concentration_value(variable, filename_short, mode))

        if self.pysills_mode == "MA":
            self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set("Select IS")
            self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].set("0.0")
        else:
            self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Name"].set("Select IS")
            self.container_var["SMPL"][filename_long]["Matrix Setup"]["IS"]["Concentration"].set("0.0")

    def ma_change_matrix_concentration(self, var_entr, var_file, state_default, event):
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"

        if self.container_var[var_setting_key]["Host Setup Selection"].get() == 1:
            var_key = "Oxide"
        else:
            var_key = "Element"

        value = float(var_entr.get())
        total_ppm = 10**6

        if value > 100:
            value = 100
        elif value < 0:
            value = 0

        concentration_default_smpl = float(self.container_var["IS"]["Default SMPL Concentration"].get())

        if "Matrix Maximum Concentration" in self.container_var["IS"]:
            concentration_default_smpl = float(self.container_var["IS"]["Matrix Maximum Concentration"].get())
            value_is_default = round(concentration_default_smpl*value/100, 4)
        else:
            value_is_default = round(total_ppm*value/100, 2)

        self.container_var["IS"]["Default SMPL Concentration"].set(value_is_default)

        if state_default:
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file_smpl]["Matrix Setup"][var_key]["Concentration"].set(value)
                self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"].set(value_is_default)
                self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].set(value_is_default)
        else:
            self.container_var["SMPL"][var_file]["Matrix Setup"][var_key]["Concentration"].set(value)
            self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Concentration"].set(value_is_default)
            self.container_var["SMPL"][var_file]["IS Data"]["Concentration"].set(value_is_default)

    def ma_change_is_smpl(self, var_opt, var_file=None, state_default=False):
        """ Defines which internal standard was selected and calculates its concentration based on further information.
        -------
        Parameters
        var_opt : str
            Contains the option menu variable.
        var_file : str
            The filename as long version (the whole path).
        state_default : boolean
            Specifies if the selection is valid for all files or only for one.
        -------
        Returns
        -------
        """
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"

        if self.container_var[var_setting_key]["Host Setup Selection"].get() == 1:
            var_key = "Oxide"
        elif self.container_var[var_setting_key]["Host Setup Selection"].get() == 2:
            var_key = "Element"
        elif self.container_var[var_setting_key]["Host Setup Selection"].get() == 4:
            var_key = "custom"

        self.container_var["IS"]["Default SMPL"].set(var_opt)

        if state_default:
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                if self.pysills_mode == "MA":
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"]
                else:
                    var_opt_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"]
                    var_entr_is_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"]

                var_opt_is_i.set(var_opt)
                if var_key == "Oxide":
                    var_oxide = self.container_var["SMPL"][file_smpl]["Matrix Setup"][var_key]["Name"].get()

                    if var_oxide != "Select Oxide":
                        key = re.search(r"(\D+)(\d*)(\D+)(\d*)", var_oxide)
                        list_elements = []
                        list_amounts = []
                        list_fraction = {}

                        for index, item in enumerate(key.groups()):
                            if index in [0, 2]:
                                list_elements.append(item)
                            else:
                                if item == "":
                                    list_amounts.append(1)
                                else:
                                    list_amounts.append(int(item))

                        mass_total = 0
                        for index, element in enumerate(list_elements):
                            if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                                mass_total += list_amounts[index]*self.chemistry_data[element]
                            else:
                                mass_total += list_amounts[index]*self.chemistry_data_sills[element]

                        for index, element in enumerate(list_elements):
                            if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                                list_fraction[element] = (list_amounts[index]*self.chemistry_data[element])/mass_total
                            else:
                                list_fraction[element] = (list_amounts[index]*self.chemistry_data_sills[
                                    element])/mass_total

                            if index == 0:
                                oxide_weight = (float(self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Oxide"][
                                                          "Concentration"].get()))/100
                                is_concentration = round(list_fraction[element]*10**6, 4)
                                self.container_var["IS"]["Default SMPL Concentration"].set(
                                    round(oxide_weight*is_concentration, 4))

                                if "Matrix Maximum Concentration" not in self.container_var["IS"]:
                                    self.container_var["IS"]["Matrix Maximum Concentration"] = tk.StringVar()
                                    self.container_var["IS"]["Matrix Maximum Concentration"].set(
                                        round(oxide_weight*is_concentration, 4))

                                var_entr_is_i.set(round(oxide_weight*is_concentration, 4))

                        if self.container_var["IS"]["Default STD"].get() == "Select IS":
                            self.container_var["IS"]["Default STD"].set(var_opt)
                            for file_std in self.container_lists["STD"]["Long"]:
                                if self.container_var["STD"][file_std]["IS Data"]["IS"].get() == "Select IS":
                                    self.container_var["STD"][file_std]["IS Data"]["IS"].set(var_opt)
                    else:
                        if self.container_var["IS"]["Default SMPL"].get() == "Select IS":
                            self.container_var["IS"]["Default SMPL"].set(var_opt)
                        if self.container_var["IS"]["Default STD"].get() == "Select IS":
                            self.container_var["IS"]["Default STD"].set(var_opt)
                            for file_std in self.container_lists["STD"]["Long"]:
                                if self.container_var["STD"][file_std]["IS Data"]["IS"].get() == "Select IS":
                                    self.container_var["STD"][file_std]["IS Data"]["IS"].set(var_opt)

                else:
                    oxide_weight = (float(self.container_var["SMPL"][file_smpl]["Matrix Setup"]["Element"][
                                              "Concentration"].get()))/100
                    is_concentration = round(1*10**6, 4)
                    self.container_var["IS"]["Default SMPL Concentration"].set(round(oxide_weight*is_concentration, 4))
                    var_entr_is_i.set(round(oxide_weight*is_concentration, 4))

                    if self.container_var["IS"]["Default STD"].get() == "Select IS":
                        self.container_var["IS"]["Default STD"].set(var_opt)
                        for file_std in self.container_lists["STD"]["Long"]:
                            if self.container_var["STD"][file_std]["IS Data"]["IS"].get() == "Select IS":
                                self.container_var["STD"][file_std]["IS Data"]["IS"].set(var_opt)
        else:
            if self.pysills_mode == "MA":
                var_opt_is_i = self.container_var["SMPL"][var_file]["IS Data"]["IS"]
            else:
                var_opt_is_i = self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Name"]

            var_opt_is_i.set(var_opt)
            self.container_var["SMPL"][var_file]["IS"].set(var_opt)

        if self.pysills_mode == "MA":
            self.container_lists["Possible IS"].clear()
            for var_file, var_content in self.container_var["SMPL"].items():
                if var_file in self.container_lists["SMPL"]["Long"]:
                    var_is = var_content["IS Data"]["IS"].get()
                    if var_is not in self.container_lists["Possible IS"]:
                        self.container_lists["Possible IS"].append(var_is)

    def ma_change_is_concentration(self, var_entr, var_file, state_default, event):
        if state_default:
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                if self.pysills_mode == "MA":
                    self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].set(var_entr.get())
                else:
                    self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"].set(var_entr.get())
        else:
            if self.pysills_mode == "MA":
                self.container_var["SMPL"][var_file]["IS Data"]["Concentration"].set(var_entr.get())
            else:
                self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Concentration"].set(var_entr.get())

    def ma_select_srm_default(self, var_opt, mode="STD"):
        if mode == "STD":
            for file_std in self.list_std:
                parts = file_std.split("/")
                if self.container_var["STD"][file_std]["SRM"].get() == "Select SRM":
                    self.container_var["STD"][file_std]["SRM"].set(var_opt)
                    self.container_files["STD"][parts[-1]]["SRM"].set(var_opt)
        elif mode == "ISOTOPES":
            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                if isotope.isdigit():
                    pass
                else:
                    if self.container_var["SRM"][isotope].get() == "Select SRM":
                        self.container_var["SRM"][isotope].set(var_opt)

        if var_opt not in self.srm_actual and var_opt != "Select SRM":
            self.srm_actual[var_opt] = {}
            ESRM().place_srm_values(srm_name=var_opt, srm_dict=self.srm_actual)
            self.fill_srm_values(var_srm=var_opt)

    def ma_select_id_default(self, var_opt):
        var_id = var_opt
        for file_smpl in self.list_smpl:
            self.container_var["SMPL"][file_smpl]["ID"].set(var_id)

    def ma_change_srm_individual(self, var_opt, var_indiv, mode="STD"):
        if mode == "STD":
            parts = var_indiv.split("/")
            self.container_var["STD"][var_indiv]["SRM"].set(var_opt)
            self.container_files["STD"][parts[-1]]["SRM"].set(var_opt)
        elif mode == "ISOTOPES":
            self.container_var["SRM"][var_indiv].set(var_opt)
            self.container_files["SRM"][var_indiv].set(var_opt)

        if var_opt not in self.srm_actual:
            self.srm_actual[var_opt] = {}
            ESRM().place_srm_values(srm_name=var_opt, srm_dict=self.srm_actual)

        self.fill_srm_values(var_srm=var_opt)

    #
    ## FILE-SPECIFIC ANALYSIS ##########################################################################################
    #
    def ma_check_specific_file(self, var_filename_long, var_filetype="STD", checkup_mode=False):
        str_filename_long = var_filename_long
        str_filetype = var_filetype
        bool_checkup_mode = checkup_mode

        if str_filetype == "STD":
            self.index_file_std = self.container_lists[str_filetype]["Long"].index(str_filename_long)
        elif str_filetype == "SMPL":
            self.index_file_smpl = self.container_lists[str_filetype]["Long"].index(str_filename_long)

        if bool_checkup_mode:
            if str_filetype == "STD":
                str_filename_long = self.ma_current_file_std
            elif str_filetype == "SMPL":
                str_filename_long = self.ma_current_file_smpl

        ## INPUT
        parts = str_filename_long.split("/")
        var_filename_short = parts[-1]
        filename_short = var_filename_short
        self.helper_intervals = {"BG": [], "MAT": []}
        self.container_var["ma_setting"]["Analyse Mode Plot"][str_filetype][var_filename_short].set(0)

        ## Window Settings
        window_width = 1100
        window_height = 800
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_ma_checkfile = tk.Toplevel(self.parent)
        self.subwindow_ma_checkfile.title("MINERAL ANALYSIS - File Analysis of " + str(var_filename_short))
        self.subwindow_ma_checkfile.geometry(var_geometry)
        self.subwindow_ma_checkfile.resizable(False, False)
        self.subwindow_ma_checkfile["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_ma_checkfile, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_ma_checkfile, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_ma_checkfile.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_ma_checkfile.grid_columnconfigure(i, minsize=column_min)
        #
        start_row = 0
        start_column = 0

        ## FRAMES
        frm_00 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row, column_id=start_column + 14, n_rows=n_rows - 10,
            n_columns=n_columns - 14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame(
            relief=tk.SOLID)

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row, column_id=start_column, n_rows=1, n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Measured Isotopes", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 15, column_id=start_column, n_rows=1,
            n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Display Options", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 18, column_id=start_column, n_rows=1,
            n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Anaylsis Mode", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 22, column_id=start_column, n_rows=1,
            n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Interval Setup", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04a = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 23, column_id=start_column, n_rows=1,
            n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Start", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04b = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 24, column_id=start_column, n_rows=1,
            n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="End", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 22, column_id=start_column + 40, n_rows=1,
            n_columns=n_columns - (start_column + 40) - 6, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Parallelism", relief=tk.FLAT, fontsize="sans 10 bold")

        ## BUTTONS
        btn_02a = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 16, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Show All", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda var_type=str_filetype, var_file_short=var_filename_short: self.ma_show_all_lines(
                var_type, var_file_short, ))
        btn_02b = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 17, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Hide All", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda var_type=str_filetype, var_file_short=var_filename_short: self.ma_hide_all_lines(
                var_type, var_file_short))
        btn_04a = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 25, column_id=0, n_rows=2, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Remove Interval", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda var_type=str_filetype, var_file_short=var_filename_short:
            self.ma_remove_interval(var_type, var_file_short))
        btn_05a = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 28, column_id=0, n_rows=2, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Previous file", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda filetype=str_filetype, mode="back": self.switch_to_another_file(filetype, mode))
        btn_05b = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 28, column_id=7, n_rows=2, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Next file", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda filetype=str_filetype, mode="next": self.switch_to_another_file(filetype, mode))
        btn_08 = SE(
            parent=self.subwindow_ma_checkfile, row_id=n_rows - 2, column_id=0, n_rows=2, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Confirm and Close", bg_active=self.bg_colors["Dark"],
            fg_active=self.bg_colors["Light Font"],
            command=lambda var_parent=self.subwindow_ma_checkfile, var_type=str_filetype,
                           var_file_long=str_filename_long:
            self.confirm_specific_file_setup(var_parent, var_type, var_file_long))
        btn_09 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 22, column_id=n_columns - 6, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Update", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda var_filetype=str_filetype, var_filename_short=filename_short,
                           var_filename_long=str_filename_long:
            self.update_parallelism_values(var_filetype, var_filename_short, var_filename_long))

        if str_filetype == "STD":
            btn_09.configure(state="disabled")

        ## RADIOBUTTONS
        rb_02a = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 16, column_id=0, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Data Type Plot"][str_filetype][var_filename_short], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="RAW", sticky="nesw",
            relief=tk.FLAT)
        rb_02b = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 17, column_id=0, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Data Type Plot"][str_filetype][var_filename_short], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SMOOTHED", sticky="nesw",
            relief=tk.FLAT)
        #
        rb_03a = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 19, column_id=0, n_rows=1, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Analyse Mode Plot"][str_filetype][var_filename_short], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Time-Signal Plot", sticky="nesw",
            relief=tk.FLAT, command=lambda var_file=str_filename_long, var_filetype=str_filetype, var_lb_state=False:
            self.ma_show_time_signal_diagram(var_file, var_filetype, var_lb_state))
        rb_03b = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 20, column_id=0, n_rows=1, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Analyse Mode Plot"][str_filetype][var_filename_short], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Time-Ratio Plot", sticky="nesw",
            relief=tk.FLAT, command=lambda var_file=str_filename_long, var_type=str_filetype:
            self.ma_show_time_ratio_diagram(var_file, var_type))
        rb_03c = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 21, column_id=0, n_rows=1, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Analyse Mode Plot"][str_filetype][var_filename_short], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Quick Results", sticky="nesw",
            relief=tk.FLAT, command=lambda var_file=str_filename_long, var_type=str_filetype:
            self.ma_show_quick_results(var_file, var_type))
        rb_05 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 23, column_id=start_column + 14, n_rows=1,
            n_columns=13, fg=self.bg_colors["Light Font"], bg=self.colors_intervals["BG"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Calculation Interval"][str_filetype][var_filename_short],
            value_rb=0,
            color_bg=self.colors_intervals["BG"], fg=self.bg_colors["Light Font"], text="Background Interval",
            sticky="nesw", relief=tk.FLAT)
        rb_06 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 23, column_id=start_column + 27, n_rows=1,
            n_columns=13, fg=self.bg_colors["Light Font"], bg=self.colors_intervals["MAT"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Calculation Interval"][str_filetype][var_filename_short],
            value_rb=1,
            color_bg=self.colors_intervals["MAT"], fg=self.bg_colors["Light Font"], text="Sample Interval",
            sticky="nesw",
            relief=tk.FLAT)
        rb_08 = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 22, column_id=start_column + 14, n_rows=1,
            n_columns=26, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_setting"]["Calculation Interval"][str_filetype][var_filename_short],
            value_rb=3,
            color_bg=self.bg_colors["Super Dark"], fg=self.bg_colors["Light Font"], text="No Selection",
            sticky="nesw", relief=tk.FLAT)

        ## CHECKBOXES
        if "BG" not in self.container_var["ma_setting"]["Calculation Interval Visibility"][str_filetype][
            var_filename_short]:
            self.container_var["ma_setting"]["Calculation Interval Visibility"][str_filetype][var_filename_short] = {
                "BG": tk.IntVar(), "MAT": tk.IntVar(), "INCL": tk.IntVar()}
            self.container_var["ma_setting"]["Calculation Interval Visibility"][str_filetype][var_filename_short][
                "BG"].set(
                1)
            self.container_var["ma_setting"]["Calculation Interval Visibility"][str_filetype][var_filename_short][
                "MAT"].set(1)
        #
        cb_bg = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 23, column_id=start_column + 25,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=2,
            bg=self.colors_intervals["BG"]).create_simple_checkbox(
            var_cb=
            self.container_var["ma_setting"]["Calculation Interval Visibility"][str_filetype][var_filename_short][
                "BG"],
            text="", set_sticky="", own_color=True,
            command=lambda var_key="BG", var_type=str_filetype, var_file_short=var_filename_short:
            self.ma_change_interval_visibility(var_key, var_type, var_file_short))
        cb_mat = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 23, column_id=start_column + 38,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=2,
            bg=self.colors_intervals["MAT"]).create_simple_checkbox(
            var_cb=
            self.container_var["ma_setting"]["Calculation Interval Visibility"][str_filetype][var_filename_short][
                "MAT"],
            text="", set_sticky="", own_color=True,
            command=lambda var_key="MAT", var_type=str_filetype, var_file_short=var_filename_short:
            self.ma_change_interval_visibility(var_key, var_type, var_file_short))

        ## ENTRIES
        var_entr_start = tk.StringVar()
        var_entr_start.set("Set start value")
        var_entr_end = tk.StringVar()
        var_entr_end.set("Set end value")
        self.helper_time_entries = {"Start": var_entr_start, "End": var_entr_end}

        entr_04a = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 23, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_start, text_default=var_entr_start.get(),
            command=lambda event, var_entr=var_entr_start, var_key="Start", mode=str_filename_long, var_interval=None:
            self.ma_set_bg_interval(var_entr, var_key, mode, var_interval, event))
        entr_04b = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 24, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_end, text_default=var_entr_end.get(),
            command=lambda event, var_entr=var_entr_end, var_key="End", mode=str_filename_long, var_interval=None:
            self.ma_set_bg_interval(var_entr, var_key, mode, var_interval, event))

        ## MEASURED ISOTOPES
        frm_iso = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 1, column_id=start_column, n_rows=14,
            n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_iso = ttk.Scrollbar(frm_iso, orient="vertical")
        text_iso = tk.Text(
            master=frm_iso, width=30, height=25, yscrollcommand=vsb_iso.set, bg=self.bg_colors["Very Light"])
        vsb_iso.config(command=text_iso.yview)
        vsb_iso.pack(side="right", fill="y")
        text_iso.pack(side="left", fill="both", expand=True)

        df_isotopes = self.container_lists["Measured Isotopes"][var_filename_short]
        for index, isotope in enumerate(df_isotopes):
            if isotope in self.isotope_colors:
                frm_i = tk.Frame(
                    frm_iso, bg=self.isotope_colors[isotope], relief=tk.SOLID, height=15, width=15,
                    highlightbackground="black", bd=1)
                text_iso.window_create("end", window=frm_i)
                text_iso.insert("end", "")

                lbl_i = tk.Label(frm_iso, text=isotope, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
                text_iso.window_create("end", window=lbl_i)
                text_iso.insert("end", "\t")

                cb_raw_i = tk.Checkbutton(
                    frm_iso,
                    variable=self.container_var["ma_setting"]["Display RAW"][str_filetype][var_filename_short][isotope],
                    text="RAW", onvalue=1, offvalue=0, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"],
                    command=lambda var_type=str_filetype, var_file_short=var_filename_short, var_datatype="RAW",
                                   var_isotope=isotope: self.ma_change_line_visibility(var_type, var_file_short,
                                                                                       var_datatype, var_isotope))
                text_iso.window_create("end", window=cb_raw_i)
                text_iso.insert("end", "\t")

                cb_smoothed_i = tk.Checkbutton(
                    frm_iso,
                    variable=self.container_var["ma_setting"]["Display SMOOTHED"][str_filetype][var_filename_short][
                        isotope], text="SMOOTHED", onvalue=1, offvalue=0, bg=self.bg_colors["Very Light"],
                    fg=self.bg_colors["Dark Font"],
                    command=lambda var_type=str_filetype, var_file_short=var_filename_short, var_datatype="SMOOTHED",
                                   var_isotope=isotope: self.ma_change_line_visibility(var_type, var_file_short,
                                                                                       var_datatype, var_isotope))

                if self.container_var["Spike Elimination"][str_filetype]["State"] == False:
                    cb_smoothed_i.configure(state="disabled")
                else:
                    cb_smoothed_i.configure(state="normal")
                text_iso.window_create("end", window=cb_smoothed_i)
                text_iso.insert("end", "\n")

        ## BACKGROUND INTERVAL
        lb_bg, scrollbar_bg_y = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 24, column_id=start_column + 14, n_rows=8,
            n_columns=13, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["BG LB"]).create_simple_listbox_grid(
            include_scrb_x=False)
        self.container_helper[str_filetype][var_filename_short]["BG"]["Listbox"] = lb_bg

        ## MATRIX INTERVAL
        lb_mat, scrollbar_mat_y = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 24, column_id=start_column + 27, n_rows=8,
            n_columns=13, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["MAT LB"]).create_simple_listbox_grid(include_scrb_x=False)
        self.container_helper[str_filetype][var_filename_short]["MAT"]["Listbox"] = lb_mat

        ## TREEVIEWS
        self.tv_parallelism = SE(
            parent=self.subwindow_ma_checkfile, row_id=start_row + 23, column_id=start_column + 40, n_rows=9,
            n_columns=n_columns - 40, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=2, text_n=["Isotope", "Sample"], width_n=["90", "100"], individual=True)

        ## INITIALIZATION

        self.ma_show_time_signal_diagram(var_file=str_filename_long, var_filetype=str_filetype)

        for isotope in df_isotopes:
            entry_parallelism = [isotope, "---", "---"]
            self.tv_parallelism.insert("", tk.END, values=entry_parallelism)

    def update_parallelism_values(self, var_filetype, var_filename_short, var_filename_long):
        if var_filetype == "SMPL":
            self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_filename_short)
            self.get_intensity(
                var_filetype=var_filetype, var_datatype="RAW", var_file_short=var_filename_short, mode="Specific")

            if len(self.tv_parallelism.get_children()) > 0:
                for item in self.tv_parallelism.get_children():
                    self.tv_parallelism.delete(item)

            if self.pysills_mode == "MA":
                var_mat_is = self.container_var[var_filetype][var_filename_long]["IS Data"]["IS"].get()
            else:
                var_mat_is = self.container_var[var_filetype][var_filename_long]["Matrix Setup"]["IS"]["Name"].get()
                var_incl_is = self.container_var[var_filetype][var_filename_long]["IS Data"]["IS"].get()

            file_isotopes = self.container_lists["Measured Isotopes"][var_filename_short]
            value_mat1_is = self.container_intensity[var_filetype]["RAW"][var_filename_short]["Parallelism MAT"][
                var_mat_is][0]
            value_mat2_is = self.container_intensity[var_filetype]["RAW"][var_filename_short]["Parallelism MAT"][
                var_mat_is][1]
            if self.pysills_mode in ["FI", "MI"]:
                value_incl1_is = self.container_intensity[var_filetype]["RAW"][var_filename_short]["Parallelism INCL"][
                    var_incl_is][0]
                value_incl2_is = self.container_intensity[var_filetype]["RAW"][var_filename_short]["Parallelism INCL"][
                    var_incl_is][1]
            for isotope in file_isotopes:
                value_mat1_i = self.container_intensity[var_filetype]["RAW"][var_filename_short]["Parallelism MAT"][
                    isotope][0]
                value_mat2_i = self.container_intensity[var_filetype]["RAW"][var_filename_short]["Parallelism MAT"][
                    isotope][1]
                if self.pysills_mode in ["FI", "MI"]:
                    value_incl1_i = self.container_intensity[var_filetype]["RAW"][var_filename_short][
                        "Parallelism INCL"][isotope][0]
                    value_incl2_i = self.container_intensity[var_filetype]["RAW"][var_filename_short][
                        "Parallelism INCL"][isotope][1]

                if value_mat2_is > 0 and value_mat1_is > 0 and value_mat1_i > 0:
                    result_mat_i = round((value_mat2_i/value_mat2_is)/(value_mat1_i/value_mat1_is), 2)
                else:
                    result_mat_i = np.nan

                if self.pysills_mode in ["FI", "MI"]:
                    if value_incl2_is > 0 and value_incl1_is > 0 and value_incl1_i > 0:
                        result_incl_i = round((value_incl2_i/value_incl2_is)/(value_incl1_i/value_incl1_is), 2)
                    else:
                        result_mat_i = np.nan

                    entry_results = [isotope, result_mat_i, result_incl_i]
                else:
                    entry_results = [isotope, result_mat_i]

                self.tv_parallelism.insert("", tk.END, values=entry_results)

    def switch_to_another_file(self, filetype, mode):
        if filetype == "STD":
            if mode == "next":
                self.index_file_std += 1
                if self.index_file_std >= len(self.container_lists[filetype]["Long"]):
                    self.index_file_std = 0
            elif mode == "back":
                self.index_file_std -= 1
                if self.index_file_std < 0:
                    self.index_file_std = len(self.container_lists[filetype]["Long"]) - 1
            filename_long = self.container_lists[filetype]["Long"][self.index_file_std]
        elif filetype == "SMPL":
            if mode == "next":
                self.index_file_smpl += 1
                if self.index_file_smpl >= len(self.container_lists[filetype]["Long"]):
                    self.index_file_smpl = 0
            elif mode == "back":
                self.index_file_smpl -= 1
                if self.index_file_smpl < 0:
                    self.index_file_smpl = len(self.container_lists[filetype]["Long"]) - 1
            filename_long = self.container_lists[filetype]["Long"][self.index_file_smpl]

        if self.pysills_mode == "MA":
            self.subwindow_ma_checkfile.destroy()
            self.ma_check_specific_file(var_filename_long=filename_long, var_filetype=filetype, checkup_mode=False)
        elif self.pysills_mode == "FI":
            self.subwindow_fi_checkfile.destroy()
            self.fi_check_specific_file(var_file=filename_long, var_type=filetype, checkup_mode=False)
        elif self.pysills_mode == "MI":
            self.subwindow_fi_checkfile.destroy()
            self.fi_check_specific_file(var_file=filename_long, var_type=filetype, checkup_mode=False)

    def confirm_specific_file_setup(self, var_parent, var_type, var_file_long):
        self.container_var[var_type][var_file_long]["Frame"].config(background=self.sign_green, bd=1)
        self.container_var[var_type][var_file_long]["Sign Color"].set(self.sign_green)
        var_parent.destroy()

    def ma_show_time_signal_diagram(self, var_file, var_filetype, var_lb_state=True):
        str_filename_long = var_file
        str_filetype = var_filetype
        bool_lb_state = var_lb_state

        parts = str_filename_long.split("/")
        str_filename_short = parts[-1]

        ## Cleaning
        try:
            canvas_ratio = self.container_helper[str_filetype][str_filename_short]["CANVAS RATIO"]
            toolbarframe_ratio = self.container_helper[str_filetype][str_filename_short]["TOOLBARFRAME RATIO"]

            if canvas_ratio == None:
                canvas_ratio.get_tk_widget().grid_remove()
                toolbarframe_ratio.grid_remove()
        except AttributeError:
            pass

        try:
            resultsframe = self.container_helper[str_filetype][str_filename_short]["RESULTS FRAME"]

            if resultsframe != None:
                resultsframe.destroy()
        except AttributeError:
            pass

        self.fig_specific = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.canvas_specific = FigureCanvasTkAgg(self.fig_specific, master=self.subwindow_ma_checkfile)
        self.canvas_specific.get_tk_widget().grid(row=0, column=14, rowspan=20, columnspan=39, sticky="nesw")
        self.toolbarFrame_specific = tk.Frame(master=self.subwindow_ma_checkfile)
        self.toolbarFrame_specific.grid(row=20, column=14, rowspan=2, columnspan=39, sticky="ew")
        self.toolbar_specific = NavigationToolbar2Tk(self.canvas_specific, self.toolbarFrame_specific)
        self.toolbar_specific.config(
            bg=self.bg_colors["Very Light"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
            highlightcolor=self.bg_colors["Dark Font"], bd=0)
        self.toolbar_specific._message_label.config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_specific.winfo_children()[-2].config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])

        self.container_helper[str_filetype][str_filename_short]["FIGURE"] = self.fig_specific
        self.container_helper[str_filetype][str_filename_short]["CANVAS"] = self.canvas_specific
        self.container_helper[str_filetype][str_filename_short]["TOOLBARFRAME"] = self.toolbarFrame_specific

        if self.file_loaded == False:
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
        else:
            if str_filename_short not in self.container_measurements["Dataframe"] and "_copy" in str_filename_short:
                str_filename_short_original = str_filename_short.replace("_copy", "")
                df_data = self.container_measurements["Dataframe"][str_filename_short_original]
            else:
                df_data = self.container_measurements["Dataframe"][str_filename_short]
        self.dataset_time = list(DE().get_times(dataframe=df_data))
        x_max = max(self.dataset_time)
        df_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]
        icp_measurements = np.array([[df_data[isotope] for isotope in df_isotopes]])
        y_max = np.amax(icp_measurements)

        ## DIAGRAMS
        ax = self.fig_specific.add_subplot(label=np.random.uniform())
        self.container_helper[str_filetype][str_filename_short]["AXES"] = {"Time-Signal": ax}

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5

        for isotope in df_isotopes:
            if isotope in self.isotope_colors:
                ln_raw = ax.plot(self.dataset_time, df_data[isotope], label=isotope, color=self.isotope_colors[isotope],
                                 linewidth=var_lw, visible=True)
                self.container_var["ma_setting"]["Time-Signal Lines"][str_filetype][str_filename_short][isotope][
                    "RAW"] = ln_raw

                if (self.container_var["Spike Elimination"][str_filetype]["State"] == True and
                        isotope in self.container_spikes[str_filename_short]):
                    ln_smoothed = ax.plot(
                        self.dataset_time, self.container_spikes[str_filename_short][isotope]["Data IMPROVED"],
                        label=isotope, color=self.isotope_colors[isotope], linewidth=var_lw, visible=True)
                    self.container_var["ma_setting"]["Time-Signal Lines"][str_filetype][str_filename_short][
                        isotope]["SMOOTHED"] = ln_smoothed
                    self.container_var["ma_setting"]["Display SMOOTHED"][str_filetype][str_filename_short][
                        isotope].set(1)

        if self.pysills_mode in ["FI", "MI"]:
            var_check_bg = self.container_helper[str_filetype][str_filename_short]["BG"]["Content"]
        else:
            var_check_bg = self.container_helper[str_filetype][str_filename_short]["BG"]["Content"]

        if len(var_check_bg) > 0:
            if self.pysills_mode in ["MA", "FI", "MI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short]["BG"][
                    "Content"].items():
                    times_bg = var_content["Times"]
                    if times_bg[0] != None and times_bg[1] != None:
                        box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.35, color=self.colors_intervals["BG"])
                        var_content["Object"] = box_bg

                        if bool_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["BG"]["Listbox"].insert(
                                tk.END, "BG" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["BG"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["BG"]["Content"][var_id]

            else:
                times_bg = self.container_helper[str_filetype][str_filename_short]["BG"][1]["Times"]

                box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.35, color=self.colors_intervals["BG"])
                self.container_helper[str_filetype][str_filename_short]["BG"][1]["Object"] = box_bg

        if self.pysills_mode == "MA":
            signal_key = "MAT"
            var_check_sig = self.container_helper[str_filetype][str_filename_short][signal_key]["Content"]
        else:
            signal_key = "MAT"
            var_check_sig = self.container_helper[str_filetype][str_filename_short][signal_key]["Content"]
        #
        if len(var_check_sig) > 0:
            if self.pysills_mode in ["FI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][signal_key][
                    "Content"].items():
                    times_sig = var_content["Times"]
                    var_color = self.colors_intervals["MAT"]
                    if times_sig[0] != None and times_sig[1] != None:
                        box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                        var_content["Object"] = box_mat
                        #
                        if bool_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["MAT"]["Listbox"].insert(
                                tk.END, "MAT" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["MAT"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["MAT"]["Content"][var_id]
            elif self.pysills_mode in ["MI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][signal_key][
                    "Content"].items():
                    times_sig = self.container_helper[str_filetype][str_filename_short][signal_key]["Content"][1][
                        "Times"]
                    var_color = self.colors_intervals["MAT"]
                    if times_sig[0] != None and times_sig[1] != None:
                        box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                        var_content["Object"] = box_mat
                        #
                        if bool_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["MAT"]["Listbox"].insert(
                                tk.END, "MAT" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["MAT"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["MAT"]["Content"][var_id]
            else:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][signal_key][
                    "Content"].items():
                    times_sig = var_content["Times"]
                    var_color = self.colors_intervals["MAT"]
                    if times_sig[0] != None and times_sig[1] != None:
                        box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                        var_content["Object"] = box_mat
                        #
                        if bool_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["MAT"]["Listbox"].insert(
                                tk.END, "MAT" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["MAT"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["MAT"]["Content"][var_id]
        #
        if self.pysills_mode == "MA":
            inclusion_key = "INCL"
            var_check_incl = []
        else:
            inclusion_key = "INCL"
            var_check_incl = self.container_helper[str_filetype][str_filename_short][inclusion_key]["Content"]
        #
        if len(var_check_incl) > 0:
            if self.pysills_mode in ["FI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][inclusion_key][
                    "Content"].items():
                    times_incl = var_content["Times"]
                    if times_incl[0] != None and times_incl[1] != None:
                        box_incl = ax.axvspan(
                            times_incl[0], times_incl[1], alpha=0.35, color=self.colors_intervals["INCL"])
                        var_content["Object"] = box_incl
                        #
                        if bool_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["INCL"]["Listbox"].insert(
                                tk.END, "INCL" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["INCL"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["INCL"]["Content"][var_id]
            elif self.pysills_mode in ["MI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][inclusion_key][
                    "Content"].items():
                    times_incl = self.container_helper[str_filetype][str_filename_short][inclusion_key]["Content"][1][
                        "Times"]
                    if times_incl[0] != None and times_incl[1] != None:
                        box_incl = ax.axvspan(times_incl[0], times_incl[1], alpha=0.35,
                                              color=self.colors_intervals["INCL"])
                        var_content["Object"] = box_incl
                        #
                        if bool_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["INCL"]["Listbox"].insert(
                                tk.END, "INCL" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["INCL"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["INCL"]["Content"][var_id]

        ax.grid(True)
        ax.set_yscale("log")
        ax.set_xlim(left=0, right=x_max)
        ax.set_xticks(np.arange(0, x_max, 20))
        ax.set_ylim(bottom=100, top=1.5*y_max)
        ax.grid(which="major", linestyle="-", linewidth=1)
        ax.minorticks_on()
        ax.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        ax.set_axisbelow(True)
        ax.set_title(str_filename_short, fontsize=9)
        ax.set_xlabel("Experiment Time $t$ (s)", labelpad=0.5, fontsize=8)
        ax.set_ylabel("Signal Intensity $I$ (cps)", labelpad=0.5, fontsize=8)
        ax.xaxis.set_tick_params(labelsize=8)
        ax.yaxis.set_tick_params(labelsize=8)
        #
        self.canvas_specific.draw()
        #
        self.canvas_specific.mpl_connect(
            "button_press_event", lambda event, var_type=str_filetype, var_file_short=str_filename_short:
            self.ma_add_interval_to_diagram(var_type, var_file_short, event))

    def ma_show_time_ratio_diagram(self, var_file, var_type):
        parts = var_file.split("/")
        var_file_short = parts[-1]

        ## Cleaning
        try:
            canvas = self.container_helper[var_type][var_file_short]["CANVAS"]
            toolbarframe = self.container_helper[var_type][var_file_short]["TOOLBARFRAME"]

            if canvas == None:
                canvas.get_tk_widget().grid_remove()
                toolbarframe.grid_remove()
        except AttributeError:
            pass

        try:
            resultsframe = self.container_helper[var_type][var_file_short]["RESULTS FRAME"]

            if resultsframe != None:
                resultsframe.destroy()
        except AttributeError:
            pass

        if var_type == "STD":
            var_srm_file = self.container_var["STD"][var_file]["SRM"].get()
            for element, value in sorted(self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                if element in self.container_lists["Measured Elements"][var_file_short]:
                    var_is = self.container_lists["Measured Elements"][var_file_short][element][0]
                break
        else:
            var_is = self.container_var[var_type][var_file]["IS Data"]["IS"].get()
        var_id = self.container_lists[var_type]["Long"].index(var_file)
        var_file_short = self.container_lists[var_type]["Short"][var_id]

        self.fig_specific_ratio = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        ax_ratio = self.fig_specific_ratio.add_subplot(label=np.random.uniform())
        self.container_helper[var_type][var_file_short]["AXES"] = {"Time-Ratio": ax_ratio}

        self.canvas_specific_ratio = FigureCanvasTkAgg(self.fig_specific_ratio, master=self.subwindow_ma_checkfile)
        self.canvas_specific_ratio.get_tk_widget().grid(row=0, column=14, rowspan=20, columnspan=39, sticky="nesw")
        self.toolbarFrame_specific_ratio = tk.Frame(master=self.subwindow_ma_checkfile)
        self.toolbarFrame_specific_ratio.grid(row=20, column=14, rowspan=2, columnspan=39, sticky="w")
        self.toolbar_specific_ratio = NavigationToolbar2Tk(self.canvas_specific_ratio, self.toolbarFrame_specific_ratio)
        self.toolbar_specific_ratio.config(background=self.bg_colors["Very Light"])
        self.toolbar_specific_ratio._message_label.config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_specific_ratio.winfo_children()[-2].config(background=self.bg_colors["Very Light"])

        self.container_helper[var_type][var_file_short]["FIGURE RATIO"] = self.fig_specific_ratio
        self.container_helper[var_type][var_file_short]["CANVAS RATIO"] = self.canvas_specific_ratio
        self.container_helper[var_type][var_file_short]["TOOLBARFRAME RATIO"] = self.toolbarFrame_specific_ratio

        if self.file_loaded == False:
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
        else:
            if var_file_short not in self.container_measurements["Dataframe"] and "_copy" in var_file_short:
                file_short_original = var_file_short.replace("_copy", "")
                df_data = self.container_measurements["Dataframe"][file_short_original]
            else:
                df_data = self.container_measurements["Dataframe"][var_file_short]

        self.dataset_time = list(DE().get_times(dataframe=df_data))
        x_max = max(self.dataset_time)
        if var_is != "Select IS":
            icp_measurements = np.array(
                [[df_data[isotope]/df_data[var_is] for isotope in self.container_lists["ISOTOPES"]]])
            y_max = np.amax(icp_measurements)

            var_lw = float(self.container_var["General Settings"]["Line width"].get())
            if var_lw < 0.25:
                var_lw = 0.25
            elif var_lw > 2.5:
                var_lw = 2.5

            for isotope in self.container_lists["ISOTOPES"]:
                ln_raw = ax_ratio.plot(self.dataset_time, df_data[isotope]/df_data[var_is], label=isotope,
                                       color=self.isotope_colors[isotope], linewidth=var_lw, visible=True)

            ax_ratio.grid(True)
            ax_ratio.set_yscale("log")
            ax_ratio.set_xlim(left=0, right=x_max)
            ax_ratio.set_xticks(np.arange(0, x_max, 20))
            ax_ratio.set_ylim(bottom=10**(-5), top=1.5*y_max)
            ax_ratio.grid(which="major", linestyle="-", linewidth=1)
            ax_ratio.minorticks_on()
            ax_ratio.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
            ax_ratio.set_axisbelow(True)
            ax_ratio.set_title(var_file_short, fontsize=9)
            ax_ratio.set_xlabel("Experiment Time $t$ (s)", labelpad=0.5, fontsize=8)
            ax_ratio.set_ylabel("Signal Intensity Ratio $I$ (cps/cps)", labelpad=0.5, fontsize=8)
            ax_ratio.xaxis.set_tick_params(labelsize=8)
            ax_ratio.yaxis.set_tick_params(labelsize=8)

            self.canvas_specific_ratio.draw()

    def check_results_oxide_normalization(self, var_filename):
        sum_oxides_mat = 0
        sum_oxides_incl = 0

        file_isotopes = self.container_lists["Measured Isotopes"][var_filename]
        for isotope in file_isotopes:
            key = re.search(r"(\D+)(\d*)", isotope)
            element = key.group(1)
            if self.pysills_mode in ["MA", "FI"]:
                concentration_mat_i = self.container_concentration["SMPL"]["RAW"][var_filename]["MAT"][isotope]
                for oxide in self.container_lists["Possible Oxides"][element]:
                    if element == "Fe":
                        factor = float(self.container_var["Oxides Quantification"]["Ratios"]["Fe-Ratio"].get())
                        concentration_oxide_mat_i = (factor*self.conversion_factors[oxide]*concentration_mat_i*
                                                     10**(-4))
                    elif element == "Mn":
                        factor = float(self.container_var["Oxides Quantification"]["Ratios"]["Mn-Ratio"].get())
                        concentration_oxide_mat_i = (factor*self.conversion_factors[oxide]*concentration_mat_i*
                                                     10**(-4))
                    else:
                        concentration_oxide_mat_i = self.conversion_factors[oxide]*concentration_mat_i*10**(-4)

                    if np.isnan(concentration_oxide_mat_i) == False:
                        sum_oxides_mat += concentration_oxide_mat_i
            else:
                concentration_mat_i = self.container_concentration["SMPL"]["RAW"][var_filename]["MAT"][isotope]
                concentration_incl_i = self.container_concentration["SMPL"]["RAW"][var_filename]["INCL"][isotope]
                for oxide in self.container_lists["Possible Oxides"][element]:
                    if element == "Fe":
                        factor = float(self.container_var["Oxides Quantification INCL"]["Ratios"]["Fe-Ratio"].get())
                        concentration_oxide_mat_i = (factor*self.conversion_factors[oxide]*concentration_mat_i*
                                                     10**(-4))
                        if concentration_incl_i != None:
                            concentration_oxide_incl_i = (factor*self.conversion_factors[oxide]*concentration_incl_i*
                                                          10**(-4))
                        else:
                            concentration_oxide_incl_i = np.nan
                    elif element == "Mn":
                        factor = float(self.container_var["Oxides Quantification INCL"]["Ratios"]["Mn-Ratio"].get())
                        concentration_oxide_mat_i = (factor*self.conversion_factors[oxide]*concentration_mat_i*
                                                     10**(-4))
                        if concentration_incl_i != None:
                            concentration_oxide_incl_i = (factor*self.conversion_factors[oxide]*concentration_incl_i*
                                                          10**(-4))
                        else:
                            concentration_oxide_incl_i = np.nan
                    else:
                        if concentration_mat_i != None:
                            concentration_oxide_mat_i = self.conversion_factors[oxide]*concentration_mat_i*10**(-4)
                        else:
                            concentration_oxide_mat_i = np.nan

                        if concentration_incl_i != None:
                            concentration_oxide_incl_i = self.conversion_factors[oxide]*concentration_incl_i*10**(-4)
                        else:
                            concentration_oxide_incl_i = np.nan

                    if np.isnan(concentration_oxide_mat_i) == False:
                        sum_oxides_mat += concentration_oxide_mat_i

                    if np.isnan(concentration_oxide_incl_i) == False:
                        sum_oxides_incl += concentration_oxide_incl_i

        print("")
        print("Results - plausibility check (100 wt.% oxides calculation)")
        print("File:", var_filename)
        print("Sum(oxides, matrix/sample):", round(sum_oxides_mat, 4), round(sum_oxides_mat - 100, 4), "%")
        if self.pysills_mode == "MI":
            print("Sum(oxides, inclusion):", round(sum_oxides_incl, 4), round(sum_oxides_incl - 100, 4), "%")
        self.counter_calculation_runs += 1
        print("Number of calculation runs:", self.counter_calculation_runs)

    def ma_show_quick_results(self, var_file, var_type):
        #
        parts = var_file.split("/")
        var_file_short = parts[-1]
        #
        ## Cleaning
        try:
            canvas = self.container_helper[var_type][var_file_short]["CANVAS"]
            toolbarframe = self.container_helper[var_type][var_file_short]["TOOLBARFRAME"]
            #
            if canvas == None:
                canvas.get_tk_widget().grid_remove()
                toolbarframe.grid_remove()
        except AttributeError:
            pass
        #
        try:
            canvas_ratio = self.container_helper[var_type][var_file_short]["CANVAS RATIO"]
            toolbarframe_ratio = self.container_helper[var_type][var_file_short]["TOOLBARFRAME RATIO"]
            #
            if canvas_ratio == None:
                canvas_ratio.get_tk_widget().grid_remove()
                toolbarframe_ratio.grid_remove()
        except AttributeError:
            pass

        var_id = self.container_lists[var_type]["Long"].index(var_file)
        var_file_short = self.container_lists[var_type]["Short"][var_id]

        ## FRAMES
        frm_quick = SE(
            parent=self.subwindow_ma_checkfile, row_id=0, column_id=14, n_rows=32, n_columns=39,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)

        self.container_helper[var_type][var_file_short]["RESULTS FRAME"] = frm_quick

        ## TREEVIEWS
        list_categories = ["Category"]
        if var_type == "STD":
            var_srm_file = self.container_var["STD"][var_file]["SRM"].get()
            for element, value in sorted(self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                if element in self.container_lists["Measured Elements"][var_file_short]:
                    var_is = self.container_lists["Measured Elements"][var_file_short][element][0]
                break
            list_considered_isotopes = []
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                var_srm_i = self.container_var["SRM"][isotope].get()
                if var_srm_i == var_srm_file:
                    list_considered_isotopes.append(isotope)
            list_categories.extend(list_considered_isotopes)

            key_element_is = re.search(r"(\D+)(\d+)", var_is)
            element_is = key_element_is.group(1)
            stop_calculation = False
            if element_is in self.srm_actual[var_srm_file]:
                stop_calculation = False
            else:
                stop_calculation = True
        else:
            var_is = self.container_var[var_type][var_file]["IS Data"]["IS"].get()
            list_considered_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            list_categories.extend(list_considered_isotopes)
            stop_calculation = False
        list_width = list(85*np.ones(len(list_categories)))
        list_width = [int(item) for item in list_width]
        list_width[0] = 175

        n_intervals_bg = len(self.container_helper[var_type][var_file_short]["BG"]["Content"])
        n_intervals_mat = len(self.container_helper[var_type][var_file_short]["MAT"]["Content"])
        n_intervals_incl = 1

        if self.pysills_mode != "MA":
            n_intervals_incl = len(self.container_helper[var_type][var_file_short]["INCL"]["Content"])

        if len(list_categories) > 1 and stop_calculation == False:
            self.tv_results_quick = SE(
                parent=self.subwindow_ma_checkfile, row_id=0, column_id=14, n_rows=18, n_columns=38,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
                n_categories=len(list_categories), text_n=list_categories,
                width_n=list_width, individual=True)

            scb_v = ttk.Scrollbar(self.subwindow_ma_checkfile, orient="vertical")
            scb_h = ttk.Scrollbar(self.subwindow_ma_checkfile, orient="horizontal")
            self.tv_results_quick.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
            scb_v.config(command=self.tv_results_quick.yview)
            scb_h.config(command=self.tv_results_quick.xview)
            scb_v.grid(row=0, column=52, rowspan=18, columnspan=1, sticky="ns")
            scb_h.grid(row=18, column=14, rowspan=1, columnspan=38, sticky="ew")

            if var_is != "Select IS" and n_intervals_bg > 0 and n_intervals_mat > 0 and n_intervals_incl > 0:
                ## INITIALIZATION
                # Intensity-related parameters
                if var_type == "STD":
                    self.get_condensed_intervals_of_file(filetype=var_type, filename_short=var_file_short)
                    self.get_intensity(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, mode="Specific")
                    self.ma_get_concentration(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file)
                else:
                    var_srm_file = None
                    for index, file_std_short in enumerate(self.container_lists["STD"]["Short"]):
                        self.get_condensed_intervals_of_file(filetype="STD", filename_short=file_std_short)
                        self.get_intensity(
                            var_filetype="STD", var_datatype="RAW", var_file_short=file_std_short, mode="Specific")

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        str_averagetype = "arithmetic mean"
                    else:
                        str_averagetype = "median"
                    IQ(dataframe=None, project_type=self.pysills_mode,
                       results_container=self.container_intensity_corrected["STD"]["RAW"]).get_averaged_intensities(
                        data_container=self.container_intensity_corrected["STD"]["RAW"], average_type=str_averagetype)

                    self.get_intensity(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, mode="Specific")

                    self.ma_get_intensity_ratio(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="MAT")
                    # Sensitivity-related parameters
                    self.get_analytical_sensitivity_std(var_datatype="RAW", mode="all")
                    #self.get_analytical_sensitivity_std_alternative(var_datatype="RAW", mode="all")

                self.get_analytical_sensitivity(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file)
                results_is = self.determine_possible_is(filetype="ALL")
                # Intensity Ratio
                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_ratio[var_type]["RAW"]).get_intensity_ratio(
                    data_container=self.container_intensity_corrected[var_type]["RAW"], dict_is=results_is,
                    filename_short=var_file_short)
                # Concentration-related parameters
                time_now = datetime.datetime.now()
                time_previous = time_now
                self.ma_get_concentration(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file)
                time_now = datetime.datetime.now()
                time_delta_new = (time_now - time_previous)*1000
                time_previous = time_now
                print(f"Process time (Concentration calculation:", time_delta_new.total_seconds(), "ms")
                # Normalized Sensitivity
                SQ(dataframe_01=self.container_intensity_corrected[var_type]["RAW"][var_file_short],
                   dataframe_02=self.container_concentration[var_type]["RAW"][var_file_short],
                   results_container=self.container_normalized_sensitivity[var_type]["RAW"]).get_normalized_sensitivity(
                    filename_short=var_file_short, filetype=var_type,
                    data_sensitivity=self.container_analytical_sensitivity[var_type]["RAW"][var_file_short],
                    dict_is=results_is)

                if var_type == "SMPL":
                    self.ma_get_rsf(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file)

                if var_type == "SMPL":
                    self.ma_get_concentration_ratio(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file)

                self.ma_get_lod(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file)

                entries_intensity_bg_i = ["Intensity BG"]
                entries_intensity_mat_i = ["Intensity SMPL"]
                entries_intensity_mat_sigma_i = ["Intensity 1 SIGMA SMPL"]
                entries_intensity_ratio_i = ["Intensity SMPL Ratio"]
                entries_analytical_sensitivity_i = ["Analytical Sensitivity"]
                entries_normalized_sensitivity_i = ["Normalized Sensitivity"]
                entries_rsf_i = ["Relative Sensitivity Factor"]
                entries_concentration_i = ["Concentration"]
                entries_concentration_sigma_i = ["Concentration 1 SIGMA SMPL"]
                entries_concentration_ratio_i = ["Concentration Ratio"]
                entries_lod_i = ["Limit of Detection"]
                entries_empty = [""]

                for isotope in list_considered_isotopes:
                    entries_empty.append("")
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    # Intensity Results
                    intensity_bg_i = self.container_intensity[var_type]["RAW"][var_file_short]["BG"][isotope]
                    intensity_mat_i = self.container_intensity_corrected[var_type]["RAW"][var_file_short]["MAT"][
                        isotope]
                    intensity_mat_sigma_i = self.container_intensity[var_type]["RAW"][var_file_short][
                        "1 SIGMA MAT"][isotope]

                    if isinstance(intensity_bg_i, np.floating) == False:
                        print(var_file_short, isotope, "BG:", intensity_bg_i)

                    if isinstance(intensity_mat_i, np.floating) == False:
                        print(var_file_short, isotope, "MAT:", intensity_mat_i)

                    if isinstance(intensity_mat_sigma_i, np.floating) == False:
                        print(var_file_short, isotope, "MAT:", intensity_mat_sigma_i)

                    # Sensitivity Results
                    analytical_sensitivity_i = self.container_analytical_sensitivity[var_type]["RAW"][var_file_short][
                        "MAT"][isotope]
                    normalized_sensitivity_i = self.container_normalized_sensitivity[var_type]["RAW"][var_file_short][
                        "MAT"][isotope]
                    # Concentration Results
                    concentration_i = self.container_concentration[var_type]["RAW"][var_file_short]["MAT"][isotope]
                    concentration_sigma_i = self.container_concentration[var_type]["RAW"][var_file_short][
                        "1 SIGMA MAT"][isotope]
                    lod_i = self.container_lod[var_type]["RAW"][var_file_short]["MAT"][isotope]

                    if var_type == "SMPL":
                        intensity_ratio_i = self.container_intensity_ratio[var_type]["RAW"][var_file_short]["MAT"][
                            isotope]
                        rsf_i = self.container_rsf[var_type]["RAW"][var_file_short]["MAT"][isotope]
                        concentration_ratio_i = self.container_concentration_ratio[var_type]["RAW"][var_file_short][
                            "MAT"][isotope]
                    else:
                        intensity_ratio_i = self.container_intensity_ratio[var_type]["RAW"][var_file_short]["MAT"][
                            isotope]

                    if var_srm_file == None or var_srm_file == var_srm_i:
                        entries_intensity_bg_i.append(f"{intensity_bg_i:.{4}f}")
                        entries_intensity_mat_i.append(f"{intensity_mat_i:.{4}f}")
                        entries_intensity_mat_sigma_i.append(f"{intensity_mat_sigma_i:.{4}f}")
                        entries_intensity_ratio_i.append(f"{intensity_ratio_i:.{4}E}")
                        entries_analytical_sensitivity_i.append(f"{analytical_sensitivity_i:.{4}f}")
                        entries_normalized_sensitivity_i.append(f"{normalized_sensitivity_i:.{4}f}")
                        if var_type == "SMPL":
                            entries_concentration_i.append(f"{concentration_i:.{4}f}")
                            entries_concentration_sigma_i.append(f"{concentration_sigma_i:.{4}f}")
                        else:
                            entries_concentration_i.append(f"{concentration_i:.{1}f}")
                            entries_concentration_sigma_i.append(f"{concentration_sigma_i:.{1}f}")
                        entries_lod_i.append(f"{lod_i:.{4}f}")
                    else:
                        entries_intensity_bg_i.append("---")
                        entries_intensity_mat_i.append("---")
                        entries_intensity_mat_sigma_i.append("---")
                        entries_analytical_sensitivity_i.append("---")
                        entries_normalized_sensitivity_i.append("---")
                        entries_concentration_i.append("---")
                        entries_concentration_sigma_i.append("---")
                        entries_lod_i.append("---")

                    if var_type == "SMPL":
                        entries_concentration_ratio_i.append(f"{concentration_ratio_i:.{4}E}")
                        entries_rsf_i.append(f"{rsf_i:.{4}f}")

                self.tv_results_quick.insert("", tk.END, values=entries_intensity_bg_i)
                self.tv_results_quick.insert("", tk.END, values=entries_intensity_mat_i)
                self.tv_results_quick.insert("", tk.END, values=entries_intensity_mat_sigma_i)
                self.tv_results_quick.insert("", tk.END, values=entries_intensity_ratio_i)
                self.tv_results_quick.insert("", tk.END, values=entries_empty)
                self.tv_results_quick.insert("", tk.END, values=entries_analytical_sensitivity_i)
                self.tv_results_quick.insert("", tk.END, values=entries_normalized_sensitivity_i)

                if var_type == "SMPL":
                    self.tv_results_quick.insert("", tk.END, values=entries_rsf_i)

                self.tv_results_quick.insert("", tk.END, values=entries_empty)
                self.tv_results_quick.insert("", tk.END, values=entries_concentration_i)
                self.tv_results_quick.insert("", tk.END, values=entries_concentration_sigma_i)

                if var_type == "SMPL":
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_ratio_i)

                self.tv_results_quick.insert("", tk.END, values=entries_lod_i)

    def ma_show_all_lines(self, var_type, var_file_short):
        if self.container_var["ma_setting"]["Data Type Plot"][var_type][var_file_short].get() == 0:
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if isotope in self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short]:
                    self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "RAW"][0].set_visible(True)
                    self.container_var["ma_setting"]["Display RAW"][var_type][var_file_short][isotope].set(1)
        elif self.container_var["ma_setting"]["Data Type Plot"][var_type][var_file_short].get() == 1:
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if isotope in self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short]:
                    self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "SMOOTHED"][0].set_visible(True)
                    self.container_var["ma_setting"]["Display SMOOTHED"][var_type][var_file_short][isotope].set(1)

        self.canvas_specific.draw()

    def ma_hide_all_lines(self, var_type, var_file_short):
        if self.container_var["ma_setting"]["Data Type Plot"][var_type][var_file_short].get() == 0:
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if isotope in self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short]:
                    self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "RAW"][0].set_visible(False)
                    self.container_var["ma_setting"]["Display RAW"][var_type][var_file_short][isotope].set(0)
        elif self.container_var["ma_setting"]["Data Type Plot"][var_type][var_file_short].get() == 1:
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if isotope in self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short]:
                    self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "SMOOTHED"][0].set_visible(False)
                    self.container_var["ma_setting"]["Display SMOOTHED"][var_type][var_file_short][isotope].set(0)

        self.canvas_specific.draw()

    def ma_change_line_visibility(self, var_type, var_file_short, var_datatype, var_isotope):
        var_key = "Display " + str(var_datatype)
        if self.container_var["ma_setting"][var_key][var_type][var_file_short][var_isotope].get() == 1:
            self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short][var_isotope][
                var_datatype][
                0].set_visible(True)
        elif self.container_var["ma_setting"][var_key][var_type][var_file_short][var_isotope].get() == 0:
            self.container_var["ma_setting"]["Time-Signal Lines"][var_type][var_file_short][var_isotope][
                var_datatype][
                0].set_visible(False)
        #
        self.canvas_specific.draw()

    def ma_add_interval_to_diagram(self, var_type, var_file_short, event):
        filename_index = self.container_lists[var_type]["Short"].index(var_file_short)
        filename_long = self.container_lists[var_type]["Long"][filename_index]

        if self.container_var["ma_setting"]["Calculation Interval"][var_type][var_file_short].get() == 0:  # BG
            var_key = "BG"
            var_color = self.colors_intervals[var_key]
        elif self.container_var["ma_setting"]["Calculation Interval"][var_type][var_file_short].get() == 1:  # MAT
            var_key = "MAT"
            var_color = self.colors_intervals[var_key]

        if self.container_var["ma_setting"]["Calculation Interval"][var_type][var_file_short].get() in [0, 1, 2]:
            x_nearest = min(self.dataset_time, key=lambda x: abs(x - event.xdata))

            if len(self.helper_intervals[var_key]) < 1:
                x_id = self.dataset_time.index(x_nearest)
                self.helper_intervals[var_key].append([x_nearest, x_id])
            else:
                x_id = self.dataset_time.index(x_nearest)
                self.helper_intervals[var_key].append([x_nearest, x_id])
                key_id = self.container_helper[var_type][var_file_short][var_key]["ID"] + 1
                time_0_pre = self.helper_intervals[var_key][0][0]
                time_1_pre = self.helper_intervals[var_key][1][0]
                index_0_pre = self.helper_intervals[var_key][0][1]
                index_1_pre = self.helper_intervals[var_key][1][1]

                if time_1_pre < time_0_pre:
                    time_0 = time_1_pre
                    time_1 = time_0_pre
                    index_0 = index_1_pre
                    index_1 = index_0_pre
                else:
                    time_0 = time_0_pre
                    time_1 = time_1_pre
                    index_0 = index_0_pre
                    index_1 = index_1_pre

                box_key = self.container_helper[var_type][var_file_short]["AXES"]["Time-Signal"].axvspan(
                    time_0, time_1, alpha=0.35, color=var_color)
                self.canvas_specific.draw()

                self.container_helper[var_type][var_file_short][var_key]["Content"][key_id] = {
                    "Times": [time_0, time_1], "Indices": [index_0, index_1], "Object": box_key}

                self.container_helper[var_type][var_file_short][var_key]["Listbox"].insert(
                    tk.END, var_key + str(key_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                self.helper_intervals[var_key].clear()
                self.container_helper[var_type][var_file_short][var_key]["ID"] = key_id
                self.container_helper[var_type][var_file_short][var_key]["Indices"].append(key_id)

                self.canvas_specific.draw()

        if var_type == "STD":
            if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) + \
                    len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) < 2:
                self.container_var[var_type][filename_long]["Frame"].config(background=self.sign_yellow, bd=1)
                self.container_var[var_type][filename_long]["Sign Color"].set(self.sign_yellow)
            else:
                if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) > 0 and \
                        len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) > 0:
                    self.container_var[var_type][filename_long]["Frame"].config(background=self.sign_green, bd=1)
                    self.container_var[var_type][filename_long]["Sign Color"].set(self.sign_green)
                else:
                    self.container_var[var_type][filename_long]["Frame"].config(background=self.sign_yellow, bd=1)
                    self.container_var[var_type][filename_long]["Sign Color"].set(self.sign_yellow)

        else:
            if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) + \
                    len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) < 2:
                self.container_var[var_type][filename_long]["Frame"].config(background=self.sign_yellow, bd=1)
                self.container_var[var_type][filename_long]["Sign Color"].set(self.sign_yellow)
            else:
                if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) > 0 and \
                        len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) > 0:
                    self.container_var[var_type][filename_long]["Frame"].config(background=self.sign_green, bd=1)
                    self.container_var[var_type][filename_long]["Sign Color"].set(self.sign_green)
                else:
                    self.container_var[var_type][filename_long]["Frame"].config(background=self.sign_yellow, bd=1)
                    self.container_var[var_type][filename_long]["Sign Color"].set(self.sign_yellow)

    def ma_change_interval_visibility(self, var_key, var_type, var_file_short):
        if self.container_var["ma_setting"]["Calculation Interval Visibility"][var_type][var_file_short][
            var_key].get() == 0:
            var_state = False
        else:
            var_state = True

        for var_id, var_content in self.container_helper[var_type][var_file_short][var_key]["Content"].items():
            if var_content["Object"] != None:
                var_content["Object"].set_visible(var_state)

        self.canvas_specific.draw()

    def ma_remove_interval(self, var_type, var_file_short):
        if self.container_var["ma_setting"]["Calculation Interval"][var_type][var_file_short].get() == 0:
            var_key = "BG"
        elif self.container_var["ma_setting"]["Calculation Interval"][var_type][var_file_short].get() == 1:
            var_key = "MAT"

        var_lb = self.container_helper[var_type][var_file_short][var_key]["Listbox"]

        item = self.container_helper[var_type][var_file_short][var_key]["Listbox"].curselection()[0]
        value = var_lb.get(item)
        value_parts = value.split(" ")
        key_id = re.search(r"(\D+)(\d+)", value_parts[0])
        var_id = int(key_id.group(2))

        self.container_helper[var_type][var_file_short][var_key]["Indices"].remove(var_id)
        var_lb.delete(tk.ANCHOR)
        self.container_helper[var_type][var_file_short][var_key]["Content"][var_id]["Object"].set_visible(False)
        del self.container_helper[var_type][var_file_short][var_key]["Content"][var_id]

        self.canvas_specific.draw()

    def set_start_interval(self, filetype, filename_long, filename_short):
        val_entr = self.helper_time_entries["Start"].get()

        if self.container_icpms["name"] != None:
            var_skipheader = self.container_icpms["skipheader"]
            var_skipfooter = self.container_icpms["skipfooter"]
            df_data = DE(filename_long=filename_long).get_measurements(
                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
        else:
            df_data = DE(filename_long=filename_long).get_measurements(
                delimiter=",", skip_header=3, skip_footer=1)
        dataset_time = list(DE().get_times(dataframe=df_data))

        time = val_entr
        time = time.replace(",", ".")
        x_nearest = round(min(dataset_time, key=lambda x: abs(x - float(time))), 8)

        if self.container_var["ma_setting"]["Calculation Interval"][filetype][filename_short].get() == 0:
            var_category = "BG"
        elif self.container_var["ma_setting"]["Calculation Interval"][filetype][filename_short].get() == 1:
            var_category = "MAT"

    def ma_set_bg_interval(self, var_entr, var_key, mode, var_interval, event):
        if mode == "default":
            time = var_entr.get()
            time = time.replace(",", ".")
            if self.pysills_mode in ["FI", "MI"]:
                if var_interval == "MAT":
                    list_filetypes = ["STD"]
                else:
                    list_filetypes = ["STD", "SMPL"]
            else:
                list_filetypes = ["STD", "SMPL"]
            for var_type in list_filetypes:
                for var_file in self.container_lists[var_type]["Long"]:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_data = DE(filename_long=var_file).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_data = DE(filename_long=var_file).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                    dataset_time = list(DE().get_times(dataframe=df_data))
                    var_file_short = var_file.split("/")[-1]

                    if 1 not in self.container_helper[var_type][var_file_short][var_interval]["Content"]:
                        self.container_helper[var_type][var_file_short][var_interval]["Content"][1] = {
                            "Times": [None, None], "Indices": [None, None], "Object": None}
                        self.container_helper[var_type][var_file_short][var_interval]["ID"] += 1
                        self.container_helper[var_type][var_file_short][var_interval]["Indices"].append(1)

                    x_nearest = round(min(dataset_time, key=lambda x: abs(x - float(time))), 8)
                    if var_key == "Start":
                        var_entr.set("Start value set!")
                        var_time = x_nearest
                        var_index = dataset_time.index(var_time)
                        #
                        self.container_helper[var_type][var_file_short][var_interval]["Content"][1]["Times"][
                            0] = var_time
                        self.container_helper[var_type][var_file_short][var_interval]["Content"][1]["Indices"][
                            0] = var_index
                    elif var_key == "End":
                        var_entr.set("End value set!")
                        var_time = x_nearest
                        var_index = dataset_time.index(var_time)

                        self.container_helper[var_type][var_file_short][var_interval]["Content"][1]["Times"][
                            1] = var_time
                        self.container_helper[var_type][var_file_short][var_interval]["Content"][1]["Indices"][
                            1] = var_index
                        if self.pysills_mode == "MA":
                            self.temp_lines_checkup2[var_type][var_file_short] = 0
                            self.show_time_signal_diagram_checker(var_setting_key="ma_setting")
                        elif self.pysills_mode == "FI":
                            self.temp_lines_checkup2[var_type][var_file_short] = 0
                            self.show_time_signal_diagram_checker(var_setting_key="fi_setting")
                        elif self.pysills_mode == "MI":
                            self.temp_lines_checkup2[var_type][var_file_short] = 0
                            self.show_time_signal_diagram_checker(var_setting_key="mi_setting")
        elif mode in self.container_lists["STD"]["Long"]:
            var_file = mode
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
            dataset_time = list(DE().get_times(dataframe=df_data))
            var_file_short = var_file.split("/")[-1]

            if self.container_var["ma_setting"]["Calculation Interval"]["STD"][var_file_short].get() == 0:
                var_category = "BG"
            elif self.container_var["ma_setting"]["Calculation Interval"]["STD"][var_file_short].get() == 1:
                var_category = "MAT"

            time = var_entr.get()
            time = time.replace(",", ".")
            x_nearest = round(min(dataset_time, key=lambda x: abs(x - float(time))), 8)

            current_id = self.container_helper["STD"][var_file_short][var_category]["ID"]
            if var_key == "Start":
                var_id = current_id + 1
            elif var_key == "End":
                var_id = current_id
                if var_id == 0:
                    var_id = 1
                elif var_id == 1:
                    if var_id in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                        if self.container_helper["STD"][var_file_short][var_category]["Content"][1]["Times"][1] == None:
                            var_id = var_id
                        else:
                            var_id = current_id + 1
                        if var_id not in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                            self.container_helper["STD"][var_file_short][var_category]["Content"][var_id] = {
                                "Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper["STD"][var_file_short][var_category]["ID"] = var_id
                            self.container_helper["STD"][var_file_short][var_category]["Indices"].append(var_id)

            var_entr.set(x_nearest)
            var_time = x_nearest
            var_index = dataset_time.index(var_time)

            if var_id > 1:
                condition = False
                var_id_previous = var_id - 1
                while condition == False:
                    if var_id_previous in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                        condition = True
                    elif len(self.container_helper["STD"][var_file_short][var_category]["Content"]) == 0:
                        var_id_previous = 1
                        if var_id_previous not in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                            self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous] = {
                                "Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper["STD"][var_file_short][var_category]["ID"] = var_id_previous
                            self.container_helper["STD"][var_file_short][var_category]["Indices"].append(
                                var_id_previous)
                        condition = True
                    else:
                        var_id_previous -= 1

                if var_key == "Start":
                    if self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous]["Times"][
                        1] == None:
                        var_id = var_id_previous
                    else:
                        if self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous][
                            "Times"][0] == None:
                            var_id = var_id_previous
                elif var_key == "End":
                    if self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous]["Times"][
                        0] == None:
                        var_id = var_id_previous
                    elif self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][
                        0] != None and self.container_helper["STD"][var_file_short][var_category]["Content"][var_id][
                        "Times"][1] != None:
                            var_id = var_id + 1

            if var_id not in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id] = {
                    "Times": [None, None], "Indices": [None, None], "Object": None}
                self.container_helper["STD"][var_file_short][var_category]["ID"] = var_id
                self.container_helper["STD"][var_file_short][var_category]["Indices"].append(var_id)

            if var_key == "Start":
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][0] = var_time
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Indices"][
                    0] = var_index

                time_0 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper["STD"][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Object"] = box_key

                    self.container_helper["STD"][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.canvas_specific.draw()

                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")
            elif var_key == "End":
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][1] = var_time
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Indices"][
                    1] = var_index

                time_0 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper["STD"][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Object"] = box_key

                    self.container_helper["STD"][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.canvas_specific.draw()

                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")

        elif mode in self.container_lists["SMPL"]["Long"]:
            var_file = mode
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
            dataset_time = list(DE().get_times(dataframe=df_data))
            var_file_short = var_file.split("/")[-1]

            if self.container_var["ma_setting"]["Calculation Interval"]["SMPL"][var_file_short].get() == 0:
                var_category = "BG"
            elif self.container_var["ma_setting"]["Calculation Interval"]["SMPL"][var_file_short].get() == 1:
                var_category = "MAT"

            time = var_entr.get()
            time = time.replace(",", ".")
            x_nearest = round(min(dataset_time, key=lambda x: abs(x - float(time))), 8)

            current_id = self.container_helper["SMPL"][var_file_short][var_category]["ID"]
            if var_key == "Start":
                var_id = current_id + 1
            elif var_key == "End":
                var_id = current_id
                if var_id == 0:
                    var_id = 1
                elif var_id == 1:
                    if var_id in self.container_helper["SMPL"][var_file_short][var_category]["Content"]:
                        if self.container_helper["SMPL"][var_file_short][var_category]["Content"][1]["Times"][1] == None:
                            var_id = var_id
                        else:
                            var_id = current_id + 1
                        if var_id not in self.container_helper["SMPL"][var_file_short][var_category]["Content"]:
                            self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id] = {
                                "Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper["SMPL"][var_file_short][var_category]["ID"] = var_id
                            self.container_helper["SMPL"][var_file_short][var_category]["Indices"].append(var_id)

            var_entr.set(x_nearest)
            var_time = x_nearest
            var_index = dataset_time.index(var_time)

            if var_id > 1:
                condition = False
                var_id_previous = var_id - 1
                while condition == False:
                    if var_id_previous in self.container_helper["SMPL"][var_file_short][var_category]["Content"]:
                        condition = True
                    elif len(self.container_helper["SMPL"][var_file_short][var_category]["Content"]) == 0:
                        var_id_previous = 1
                        if var_id_previous not in self.container_helper["SMPL"][var_file_short][var_category]["Content"]:
                            self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id_previous] = {
                                "Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper["SMPL"][var_file_short][var_category]["ID"] = var_id_previous
                            self.container_helper["SMPL"][var_file_short][var_category]["Indices"].append(
                                var_id_previous)
                        condition = True
                    else:
                        var_id_previous -= 1

                if var_key == "Start":
                    if self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id_previous]["Times"][
                        1] == None:
                        var_id = var_id_previous
                    else:
                        if self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id_previous][
                            "Times"][0] == None:
                            var_id = var_id_previous
                elif var_key == "End":
                    if self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id_previous]["Times"][
                        0] == None:
                        var_id = var_id_previous
                    elif self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"][
                        0] != None and self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id][
                        "Times"][1] != None:
                            var_id = var_id + 1

            if var_id not in self.container_helper["SMPL"][var_file_short][var_category]["Content"]:
                self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id] = {
                    "Times": [None, None], "Indices": [None, None], "Object": None}
                self.container_helper["SMPL"][var_file_short][var_category]["ID"] = var_id
                self.container_helper["SMPL"][var_file_short][var_category]["Indices"].append(var_id)

            if var_key == "Start":
                self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"][
                    0] = var_time
                self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Indices"][
                    0] = var_index

                time_0 = self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper["SMPL"][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Object"] = box_key

                    self.container_helper["SMPL"][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.canvas_specific.draw()

                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")
            elif var_key == "End":
                self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"][
                    1] = var_time
                self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Indices"][
                    1] = var_index

                time_0 = self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper["SMPL"][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper["SMPL"][var_file_short][var_category]["Content"][var_id]["Object"] = box_key

                    self.container_helper["SMPL"][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.canvas_specific.draw()

                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")

    def ma_datareduction_tables(self, init=False):  # MA - data reduction tables #######################
        ## Initialization
        if init:
            helper_times_init = {}
            time_start = datetime.datetime.now()
            time_previous = time_start

            for var_filetype in ["STD", "SMPL"]:
                for var_file_short in self.container_lists[var_filetype]["Short"]:
                    self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)

            time_new = datetime.datetime.now()
            time_delta_new = (time_new - time_previous)*1000
            time_previous = time_new
            title = "A"
            helper_times_init[title] = time_delta_new.total_seconds()
            print(f"Process time (Final calculation - part '" + title + "'):",
                  time_delta_new.total_seconds(), "ms")

            var_filetype = "None"
            var_file_short = "None"
            var_file_long = "None"
            var_focus = "None"
            self.var_init_ma_datareduction = True

            list_is = {"STD": [], "SMPL": []}
            for str_filename_long in self.container_lists["SMPL"]["Long"]:
                str_is = self.container_var["SMPL"][str_filename_long]["IS Data"]["IS"].get()
                if str_is not in list_is["SMPL"]:
                    list_is["SMPL"].append(str_is)

            time_new = datetime.datetime.now()
            time_delta_new = (time_new - time_previous)*1000
            time_previous = time_new
            title = "B"
            helper_times_init[title] = time_delta_new.total_seconds()
            print(f"Process time (Final calculation - part '" + title + "'):",
                  time_delta_new.total_seconds(), "ms")

            for var_datatype in ["RAW", "SMOOTHED"]:
                # Intensity Analysis
                self.get_intensity(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_focus=var_focus, mode="All")

                if self.container_var["General Settings"]["Desired Average"].get() == 1:
                    str_averagetype = "arithmetic mean"
                else:
                    str_averagetype = "median"

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "C " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_corrected["STD"][var_datatype]).get_averaged_intensities(
                    data_container=self.container_intensity_corrected["STD"][var_datatype],
                    average_type=str_averagetype)

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "D " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                self.ma_get_intensity_ratio(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=var_focus, mode="All")

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "E " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                # Sensitivity Analysis
                self.get_analytical_sensitivity(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, mode="All")
                results_is = self.determine_possible_is(filetype="ALL")

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "F " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_ratio).get_intensity_ratio(
                    data_container=self.container_intensity_corrected, dict_is=results_is, datatype=var_datatype)

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "G " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                # Compositional Analysis
                self.ma_get_concentration(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, mode="All")

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "H " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                self.ma_get_rsf(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, mode="All")

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "I " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                SQ(dataframe_01=self.container_intensity_corrected, dataframe_02=self.container_concentration,
                   results_container=self.container_normalized_sensitivity).get_normalized_sensitivity(
                    datatype=var_datatype, data_sensitivity=self.container_analytical_sensitivity, dict_is=results_is)

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "J " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                self.ma_get_concentration_ratio(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, mode="All")

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "K " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

                self.get_lod(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=None, mode="All")

                time_new = datetime.datetime.now()
                time_delta_new = (time_new - time_previous)*1000
                time_previous = time_new
                title = "L " + var_datatype
                helper_times_init[title] = time_delta_new.total_seconds()
                print(f"Process time (Final calculation - part '" + title + "'):",
                      time_delta_new.total_seconds(), "ms")

            time_new = datetime.datetime.now()
            time_delta_new = (time_new - time_start)*1000
            time_previous = time_new
            title = "Total"
            helper_times_init[title] = time_delta_new.total_seconds()
            print(f"Process time (Final calculation -" + title + "'):",
                  time_delta_new.total_seconds(), "ms")

        if self.container_var["ma_datareduction_files"]["File Type"].get() == 0:
            var_filetype = "STD"
            self.rb_conc_ratio.configure(state="disabled")
            self.rb_int_ratio.configure(state="disabled")
            self.rb_rsf.configure(state="disabled")
            self.rb_lod.configure(state="disabled")
            if self.container_var["ma_datareduction_files"]["Result Category"].get() not in [0, 3, 5, 6]:
                self.container_var["ma_datareduction_files"]["Result Category"].set(0)
        elif self.container_var["ma_datareduction_files"]["File Type"].get() == 1:
            var_filetype = "SMPL"
            self.rb_conc_ratio.configure(state="normal")
            self.rb_int_ratio.configure(state="normal")
            self.rb_rsf.configure(state="normal")
            self.rb_lod.configure(state="normal")

        if self.container_var["ma_datareduction_files"]["Data Type"].get() == 0:
            var_datatype = "RAW"
        elif self.container_var["ma_datareduction_files"]["Data Type"].get() == 1:
            var_datatype = "SMOOTHED"

        if self.container_var["ma_datareduction_files"]["Focus"].get() == 0:
            var_focus = "MAT"

        var_id = self.container_var["ID"]["Results Files"].get()

        if len(self.tv_results_files.get_children()) > 0:
            for item in self.tv_results_files.get_children():
                self.tv_results_files.delete(item)

        helper_values = {}
        helper_separator = ["-"]
        for isotope in self.container_lists["ISOTOPES"]:
            if isotope not in helper_values:
                helper_values[isotope] = []
                helper_separator.append("-")
        #
        if self.container_var["ma_datareduction_files"]["Result Category"].get() == 0:  # Concentrations
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                try:
                                    value = self.container_concentration[var_filetype][var_datatype][file_short][
                                        var_focus][isotope]
                                    value_lod_i = self.container_lod[var_filetype][var_datatype][file_short][var_focus][
                                        isotope]

                                    if value >= value_lod_i:
                                        if var_filetype == "SMPL":
                                            n_digits = self.ma_determine_ndigits(var_value=value)
                                        else:
                                            n_digits = 1
                                        entries_category.append(f"{value:.{n_digits}f}")
                                        helper_values[isotope].append(value)
                                    else:
                                        entries_category.append("< LoD")
                                except:
                                    entries_category.append(None)
                            else:
                                entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")
            #
            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)
            #
        elif self.container_var["ma_datareduction_files"]["Result Category"].get() == 1:  # Concentration Ratios
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                value = self.container_concentration_ratio[var_filetype][var_datatype][file_short][
                                    var_focus][isotope]
                                entries_category.append(f"{value:.{4}E}")
                                helper_values[isotope].append(value)
                            else:
                                entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")
            #
            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values, ratio=True)
            #
        elif self.container_var["ma_datareduction_files"]["Result Category"].get() == 2:  # LoDs
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                value = self.container_lod[var_filetype][var_datatype][file_short][var_focus][isotope]
                                n_digits = self.ma_determine_ndigits(var_value=value)
                                entries_category.append(f"{value:.{n_digits}f}")
                                helper_values[isotope].append(value)
                            else:
                                entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")
            #
            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)
            #
        elif self.container_var["ma_datareduction_files"]["Result Category"].get() == 3:  # Intensities (corrected)
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        #
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                value = self.container_intensity_corrected[var_filetype][var_datatype][file_short][
                                    var_focus][isotope]
                                n_digits = self.ma_determine_ndigits(var_value=value)
                                entries_category.append(f"{value:.{n_digits}f}")
                                helper_values[isotope].append(value)
                            else:
                                entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")
            #
            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)
            #
        elif self.container_var["ma_datareduction_files"]["Result Category"].get() == 4:  # Intensity Ratios
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        #
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                value = self.container_intensity_ratio[var_filetype][var_datatype][file_short][
                                    var_focus][isotope]
                                entries_category.append(f"{value:.{4}E}")
                                helper_values[isotope].append(value)
                            else:
                                entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")
            #
            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values, ratio=True)
            #
        elif self.container_var["ma_datareduction_files"]["Result Category"].get() == 5:  # Analytical Sensitivities
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                        var_is_file = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var[var_filetype][var_file_long]["SRM"].get()
                        var_is_file = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                value = self.container_analytical_sensitivity[var_filetype][var_datatype][file_short][
                                    var_focus][isotope]

                                if var_is_file != None:
                                    value_is = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                        file_short][var_focus][var_is_file]
                                    value = value/value_is

                                n_digits = self.ma_determine_ndigits(var_value=value)
                                entries_category.append(f"{value:.{n_digits}f}")
                                helper_values[isotope].append(value)
                            else:
                                value_is = self.container_analytical_sensitivity["STD"][var_datatype][file_short][
                                    "MAT"][isotope]
                                if value_is == 1:
                                    value = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                        file_short][var_focus][isotope]
                                    n_digits = self.ma_determine_ndigits(var_value=value)
                                    entries_category.append(f"{value:.{n_digits}f}")
                                    helper_values[isotope].append(value)
                                else:
                                    entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["ma_datareduction_files"]["Result Category"].get() == 6:  # Normalized Sensitivities
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                value = self.container_normalized_sensitivity[var_filetype][var_datatype][file_short][
                                    var_focus][isotope]
                                n_digits = self.ma_determine_ndigits(var_value=value)
                                entries_category.append(f"{value:.{n_digits}f}")
                                helper_values[isotope].append(value)
                            else:
                                entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")
            #
            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)
            #
        elif self.container_var["ma_datareduction_files"]["Result Category"].get() == 7:  # RSFs
            for index, file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_category = [file_short]
                        for isotope in self.container_lists["ISOTOPES"]:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if var_srm_file == None or var_srm_file == var_srm_i:
                                value = self.container_rsf[var_filetype][var_datatype][file_short][var_focus][isotope]
                                entries_category.append(f"{value:.{4}E}")
                                helper_values[isotope].append(value)
                            else:
                                entries_category.append("---")

                        self.tv_results_files.insert("", tk.END, values=entries_category)
                    else:
                        for isotope in self.container_lists["ISOTOPES"]:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")
            #
            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values, ratio=True)

    def determine_possible_is(self, filetype="SMPL"):
        """ Collect the file-specific information about the internal standard (IS).
        -------
        Parameters
        filetype : str
            The file category, e.g. STD
        -------
        Returns
        helper_is : dict
            A dictionary that contains the file-specific information about the internal standard.
        -------
        """
        helper_is = {"STD": {}, "SMPL": {}}

        if filetype == "STD":
            for index, filename_long in enumerate(self.container_lists[filetype]["Long"]):
                filename_short = self.container_lists[filetype]["Short"][index]
                isotope_is = self.container_var[filetype][filename_long]["IS Data"]["IS"].get()
                helper_is[filetype][filename_short] = isotope_is
        elif filetype == "SMPL":
            for index, filename_long in enumerate(self.container_lists[filetype]["Long"]):
                filename_short = self.container_lists[filetype]["Short"][index]
                isotope_is = self.container_var[filetype][filename_long]["IS Data"]["IS"].get()
                helper_is[filetype][filename_short] = isotope_is
        elif filetype == "ALL":
            for filetype_key in ["STD", "SMPL"]:
                for index, filename_long in enumerate(self.container_lists[filetype_key]["Long"]):
                    filename_short = self.container_lists[filetype_key]["Short"][index]
                    isotope_is = self.container_var[filetype_key][filename_long]["IS Data"]["IS"].get()
                    helper_is[filetype_key][filename_short] = isotope_is

        return helper_is

    def ma_determine_ndigits(self, var_value):
        trunc_value = math.trunc(var_value)

        if len(str(trunc_value)) >= 9:
            n_digits = 0
        elif len(str(trunc_value)) >= 8:
            n_digits = 1
        elif len(str(trunc_value)) >= 7:
            n_digits = 2
        elif len(str(trunc_value)) >= 6:
            n_digits = 3
        else:
            n_digits = 4

        return n_digits

    def ma_calculate_statistics_table(self, var_data, ratio=False):
        entries_mean = ["Arithmetic Mean"]
        entries_std = ["Standard Deviation"]
        entries_chrg = ["Charge"]
        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            if self.container_var["General Settings"]["Desired Average"].get() == 1:
                if len(var_data[isotope]) > 0:
                    value = np.nanmean(var_data[isotope])
                else:
                    value = "undefined"
            else:
                if len(var_data[isotope]) > 0:
                    value = np.nanmedian(var_data[isotope])
                else:
                    value = "undefined"

            var_charge_complete = self.container_var["charge"][isotope]["textvar"].get()
            var_charge = var_charge_complete[:2]
            if len(var_data[isotope]) > 1:
                value_std = np.nanstd(var_data[isotope], ddof=1)
            else:
                value_std = 0.0
            if len(var_data[isotope]) > 0:
                n_digits = 4
                n_digits_std = 4
                #
                if ratio == False:
                    entries_mean.append(f"{value:.{n_digits}f}")
                    entries_std.append(f"{value_std:.{n_digits_std}f}")
                else:
                    entries_mean.append(f"{value:.{4}E}")
                    entries_std.append(f"{value_std:.{4}E}")
                entries_chrg.append(var_charge)
            else:
                entries_mean.append("---")
                entries_std.append("---")
                entries_chrg.append("---")
            #
        self.tv_results_files.insert("", tk.END, values=entries_mean)
        self.tv_results_files.insert("", tk.END, values=entries_std)
        self.tv_results_files.insert("", tk.END, values=entries_chrg)

    ####################
    ## Data Reduction ##
    ####################

    def accept_no_spike_elimination(self):
        self.do_spike_elimination_all_grubbs(filetype="STD", spike_elimination_performed=False)
        self.do_spike_elimination_all_grubbs(filetype="SMPL", spike_elimination_performed=False)

    def background_datareduction(self, var_filetype, var_datatype, var_file_short=None, mode="specific"):
        if mode == "specific":
            pass
        else:
            for filename_short in self.container_lists[var_filetype]["Short"]:
                pass

    def mineral_datareduction(self, var_filetype, var_datatype, var_file_short):
        pass

    def inclusion_datareduction(self, var_filetype, var_datatype, var_file_short):
        pass

    def get_intensity(self, var_filetype, var_datatype, var_file_short, var_focus=None, mode="Specific", check=False):
        """ Collect the signal intensities from all defined calculation intervals.
        -------
        Parameters
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_focus : str
            The signal section of interest, e.g. the background or inclusion signal
        mode : str
            It specifies if the data reduction has to be done for all files or only one specific file
        check : boolean
            It defines if a check-up has to be run after the data reduction
        -------
        Returns
        -------
        """
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if mode == "Specific" and var_focus == None:
            self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)
            condensed_intervals_bg = self.container_var[var_filetype][var_file_short]["Intervals"]["BG"]
            condensed_intervals_mat = self.container_var[var_filetype][var_file_short]["Intervals"]["MAT"]
            str_datakey = "Data " + str(var_datatype)

            if self.pysills_mode in ["FI", "MI"]:
                condensed_intervals_incl = self.container_var[var_filetype][var_file_short]["Intervals"]["INCL"]
            else:
                condensed_intervals_incl = None

            if self.container_var["General Settings"]["Desired Average"].get() == 1:
                str_averagetype = "arithmetic mean"
            else:
                str_averagetype = "median"

            if self.container_var["General Settings"]["Interval Processing"].get() == 1:
                bool_intervalstack = False
            else:
                bool_intervalstack = True

            if var_file_short not in self.container_spikes:
                self.accept_no_spike_elimination()

            IQ(dataframe=self.container_spikes[var_file_short], project_type=self.pysills_mode,
               results_container=self.container_intensity[var_filetype][var_datatype][
                   var_file_short]).get_intensity(
                interval_bg=condensed_intervals_bg, interval_min=condensed_intervals_mat,
                interval_incl=condensed_intervals_incl, data_key=str_datakey, average_type=str_averagetype,
                stack_intervals=bool_intervalstack)

            if self.pysills_mode == "FI":
                mode_id = self.container_var[key_setting]["Inclusion Intensity Calculation"].get()
                if var_filetype == "SMPL":
                    var_index = self.container_lists[var_filetype]["Short"].index(var_file_short)
                    var_file_long = self.container_lists[var_filetype]["Long"][var_index]

                    if self.container_var[key_setting][
                        "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                        var_t = self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].get()
                        if var_t == "Select Isotope":
                            var_t = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                            self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].set(var_t)
                    elif self.container_var[key_setting][
                        "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                        var_t = self.container_var["SMPL"][var_file_long]["Second Internal Standard"]["Name"].get()
                    elif self.container_var[key_setting][
                        "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                        var_t = self.container_var["Halter2002"]["Name"].get()
                    elif self.container_var[key_setting][
                        "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                        var_t = self.container_var["Borisova2021"]["Name"].get()

                    if var_t != "Select Isotope":
                        IQ(dataframe=None, project_type=self.pysills_mode,
                           results_container=self.container_intensity_corrected[var_filetype][var_datatype][
                               var_file_short]).get_intensity_corrected(
                            data_container=self.container_intensity[var_filetype][var_datatype][var_file_short],
                            mode=mode_id, isotope_t=var_t)
                    else:
                        self.create_popup_window_before_error(
                            var_text="It seems that a variable was still not defined. Please check if the "
                                     "reference isotope for the matrix-only tracer method, the 2nd internal "
                                     "standard method or for the methods from Halter or Borisova was already "
                                     "defined.")

            elif self.pysills_mode == "MI":
                mode_id = self.container_var["mi_setting"]["Inclusion Intensity Calculation"].get()

                if var_filetype == "SMPL":
                    var_index = self.container_lists[var_filetype]["Short"].index(var_file_short)
                    var_file_long = self.container_lists[var_filetype]["Long"][var_index]

                    if self.container_var[key_setting][
                        "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                        var_t = self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].get()
                        if var_t == "Select Isotope":
                            var_t = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                            self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].set(var_t)
                    elif self.container_var["mi_setting"][
                        "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                        var_t = self.container_var["SMPL"][var_file_long]["Second Internal Standard"]["Name"].get()
                    elif self.container_var["mi_setting"][
                        "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                        var_t = self.container_var["Halter2002"]["Name"].get()
                    elif self.container_var["mi_setting"][
                        "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                        var_t = self.container_var["Borisova2021"]["Name"].get()

                    if var_t != "Select Isotope":
                        IQ(dataframe=None, project_type=self.pysills_mode,
                           results_container=self.container_intensity_corrected[var_filetype][var_datatype][
                               var_file_short]).get_intensity_corrected(
                            data_container=self.container_intensity[var_filetype][var_datatype][var_file_short],
                            mode=mode_id, isotope_t=var_t)
                    else:
                        self.create_popup_window_before_error(
                            var_text="It seems that a variable was still not defined. Please check if the "
                                     "reference isotope for the matrix-only tracer method, the 2nd internal "
                                     "standard method or for the methods from Halter or Borisova was already "
                                     "defined.")
            else:
                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_corrected[var_filetype][var_datatype][
                       var_file_short]).get_intensity_corrected(
                    data_container=self.container_intensity[var_filetype][var_datatype][var_file_short])
        else:
            if var_focus == "STD":
                list_filetypes = ["STD"]
            elif var_focus == "SMPL":
                list_filetypes = ["SMPL"]
            else:
                list_filetypes = ["STD", "SMPL"]

            run_calculation = True
            for var_filetype in list_filetypes:
                for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                    if run_calculation == True:
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]

                            self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)
                            condensed_intervals_bg = self.container_var[var_filetype][var_file_short]["Intervals"]["BG"]
                            condensed_intervals_mat = self.container_var[var_filetype][var_file_short]["Intervals"]["MAT"]

                            if var_filetype == "SMPL":
                                var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                var_id_selected = self.container_var["ID"]["Results Files"].get()
                                if var_id == var_id_selected or self.var_init_ma_datareduction:
                                    condensed_intervals_bg = self.container_var[var_filetype][var_file_short]["Intervals"][
                                        "BG"]
                                    condensed_intervals_mat = self.container_var[var_filetype][var_file_short]["Intervals"][
                                        "MAT"]
                                    str_datakey = "Data " + str(var_datatype)

                                    if self.pysills_mode in ["FI", "MI"]:
                                        condensed_intervals_incl = self.container_var[var_filetype][var_file_short][
                                            "Intervals"]["INCL"]
                                    else:
                                        condensed_intervals_incl = None

                                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                                        str_averagetype = "arithmetic mean"
                                    else:
                                        str_averagetype = "median"

                                    if self.container_var["General Settings"]["Interval Processing"].get() == 1:
                                        bool_intervalstack = False
                                    else:
                                        bool_intervalstack = True

                                    if var_file_short in self.container_spikes:
                                        IQ(dataframe=self.container_spikes[var_file_short], project_type=self.pysills_mode,
                                           results_container=self.container_intensity[var_filetype][var_datatype][
                                               var_file_short]).get_intensity(
                                            interval_bg=condensed_intervals_bg, interval_min=condensed_intervals_mat,
                                            interval_incl=condensed_intervals_incl, data_key=str_datakey,
                                            average_type=str_averagetype,
                                            stack_intervals=bool_intervalstack)
                                    else:
                                        print("The file", var_file_short,
                                              "is missing. Please refresh the spike elimination for the", var_filetype,
                                              "files. Thank you!")
                                        run_calculation = False
                                        self.parent.bell()
                            else:
                                condensed_intervals_bg = self.container_var[var_filetype][var_file_short]["Intervals"][
                                    "BG"]
                                condensed_intervals_mat = self.container_var[var_filetype][var_file_short]["Intervals"][
                                    "MAT"]
                                str_datakey = "Data " + str(var_datatype)

                                if self.pysills_mode in ["FI", "MI"]:
                                    condensed_intervals_incl = self.container_var[var_filetype][var_file_short][
                                        "Intervals"]["INCL"]
                                else:
                                    condensed_intervals_incl = None

                                if self.container_var["General Settings"]["Desired Average"].get() == 1:
                                    str_averagetype = "arithmetic mean"
                                else:
                                    str_averagetype = "median"

                                if self.container_var["General Settings"]["Interval Processing"].get() == 1:
                                    bool_intervalstack = False
                                else:
                                    bool_intervalstack = True

                                IQ(dataframe=self.container_spikes[var_file_short], project_type=self.pysills_mode,
                                   results_container=self.container_intensity[var_filetype][var_datatype][
                                       var_file_short]).get_intensity(
                                    interval_bg=condensed_intervals_bg, interval_min=condensed_intervals_mat,
                                    interval_incl=condensed_intervals_incl, data_key=str_datakey,
                                    average_type=str_averagetype,
                                    stack_intervals=bool_intervalstack)

                            if self.pysills_mode == "FI" and run_calculation == True:
                                mode_id = self.container_var[key_setting]["Inclusion Intensity Calculation"].get()
                                if var_filetype == "SMPL":
                                    var_index = self.container_lists[var_filetype]["Short"].index(var_file_short)
                                    var_file_long = self.container_lists[var_filetype]["Long"][var_index]

                                    if self.container_var[key_setting][
                                        "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                                        var_t = self.container_var["SMPL"][var_file_long]["Host Only Tracer"][
                                            "Name"].get()
                                        if var_t == "Select Isotope":
                                            var_t = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"][
                                                "Name"].get()
                                            self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].set(
                                                var_t)
                                    elif self.container_var[key_setting][
                                        "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                                        var_t = self.container_var["SMPL"][var_file_long]["Second Internal Standard"][
                                            "Name"].get()
                                    elif self.container_var[key_setting][
                                        "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                                        var_t = self.container_var["Halter2002"]["Name"].get()
                                    elif self.container_var[key_setting][
                                        "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                                        var_t = self.container_var["Borisova2021"]["Name"].get()

                                    if var_t != "Select Isotope":
                                        IQ(dataframe=None, project_type=self.pysills_mode,
                                           results_container=self.container_intensity_corrected[var_filetype][var_datatype][
                                               var_file_short]).get_intensity_corrected(
                                            data_container=self.container_intensity[var_filetype][var_datatype][
                                                var_file_short], mode=mode_id, isotope_t=var_t)
                                    else:
                                        self.create_popup_window_before_error(
                                            var_text="It seems that a variable was still not defined. Please check if the "
                                                     "reference isotope for the matrix-only tracer method, the 2nd internal "
                                                     "standard method or for the methods from Halter or Borisova was already "
                                                     "defined.")
                            elif self.pysills_mode == "MI" and run_calculation == True:
                                mode_id = self.container_var["mi_setting"]["Inclusion Intensity Calculation"].get()

                                if var_filetype == "SMPL":
                                    var_index = self.container_lists[var_filetype]["Short"].index(var_file_short)
                                    var_file_long = self.container_lists[var_filetype]["Long"][var_index]

                                    if self.container_var[key_setting][
                                        "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                                        var_t = self.container_var["SMPL"][var_file_long]["Host Only Tracer"][
                                            "Name"].get()
                                        if var_t == "Select Isotope":
                                            var_t = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"][
                                                "Name"].get()
                                            self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].set(
                                                var_t)
                                    elif self.container_var["mi_setting"][
                                        "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                                        var_t = self.container_var["SMPL"][var_file_long]["Second Internal Standard"][
                                            "Name"].get()
                                    elif self.container_var["mi_setting"][
                                        "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                                        var_t = self.container_var["Halter2002"]["Name"].get()
                                    elif self.container_var["mi_setting"][
                                        "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                                        var_t = self.container_var["Borisova2021"]["Name"].get()

                                    if var_t != "Select Isotope":
                                        IQ(dataframe=None, project_type=self.pysills_mode,
                                           results_container=self.container_intensity_corrected[var_filetype][var_datatype][
                                               var_file_short]).get_intensity_corrected(
                                            data_container=self.container_intensity[var_filetype][var_datatype][var_file_short],
                                            mode=mode_id, isotope_t=var_t)
                                    else:
                                        self.create_popup_window_before_error(
                                            var_text="It seems that a variable was still not defined. Please check if the "
                                                     "reference isotope for the matrix-only tracer method, the 2nd internal "
                                                     "standard method or for the methods from Halter or Borisova was already "
                                                     "defined.")
                            else:
                                if run_calculation == True:
                                    IQ(dataframe=None, project_type=self.pysills_mode,
                                       results_container=self.container_intensity_corrected[var_filetype][var_datatype][
                                           var_file_short]).get_intensity_corrected(
                                        data_container=self.container_intensity[var_filetype][var_datatype][var_file_short])
                                else:
                                    print(
                                        "To avoid the appearance of additional calculation problems, please check if the previous "
                                        "problem can be solved due to the given instructions if present.")
                                    break
                    else:
                        print("To avoid the appearance of additional calculation problems, please check if the previous "
                              "problem can be solved due to the given instructions if present.")
                        break

        ## CHECK
        if check:
            for key_01, item_01 in self.container_intensity.items():
                print("Filetype:", key_01)
                for key_02, item_02 in item_01.items():
                    print("Datatype:", key_02)
                    print(item_02)

    def get_condensed_intervals_of_file(self, filetype, filename_short):
        """ Collect the valid and condensed intervals for BG, MAT and INCL of a file.
        -------
        Parameters
        filetype : str
            The file category, e.g. STD
        filename_short : str
            The file as a short version (without the complete filepath)
        -------
        Returns
        -------
        """
        if self.pysills_mode == "MA":
            list_focus = ["BG", "MAT"]
        else:
            list_focus = ["BG", "MAT", "INCL"]

        for focus in list_focus:
            condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                interval_set=self.container_helper[filetype][filename_short][focus]["Content"])

            if filename_short not in self.container_var[filetype]:
                self.container_var[filetype][filename_short] = {}

            if "Intervals" not in self.container_var[filetype][filename_short]:
                self.container_var[filetype][filename_short]["Intervals"] = {}

            if focus not in self.container_var[filetype][filename_short]["Intervals"]:
                self.container_var[filetype][filename_short]["Intervals"][focus] = None

            self.container_var[filetype][filename_short]["Intervals"][focus] = condensed_intervals

    def ma_get_intensity_corrected(self, var_filetype, var_datatype, var_file_short, var_file_long, mode="Specific"):
        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

            for isotope in file_isotopes:
                var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][isotope]
                var_intensity_mat_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["MAT"][
                    isotope]
                var_result = var_intensity_mat_i - var_intensity_bg_i

                if var_result < 0:
                    var_result = 0.0
                self.container_intensity_corrected[var_filetype][var_datatype][var_file_short]["MAT"][
                    isotope] = var_result

        elif mode == "only STD":
            for var_filetype in ["STD"]:
                for var_focus in ["MAT"]:
                    if var_focus not in self.container_intensity_corrected[var_filetype][var_datatype]:
                        self.container_intensity_corrected[var_filetype][var_datatype][var_focus] = {}

                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        var_srm_i = self.container_var["SRM"][isotope].get()

                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()

                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

                                if isotope in file_isotopes and var_srm_i == var_srm_file:
                                    self.ma_get_intensity_corrected(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long)
                                    var_result_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                        var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)

                        self.container_intensity_corrected[var_filetype][var_datatype][isotope] = var_result_i
                        self.container_intensity_corrected[var_filetype][var_datatype][var_focus][
                            isotope] = var_result_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                for var_focus in ["MAT"]:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

                                if isotope in file_isotopes:
                                    if var_filetype == "SMPL":
                                        var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                        var_id_selected = self.container_var["ID"]["Results Files"].get()

                                        if var_id == var_id_selected or self.var_init_ma_datareduction == True:
                                            self.ma_get_intensity_corrected(
                                                var_filetype=var_filetype, var_datatype=var_datatype,
                                                var_file_short=var_file_short, var_file_long=var_file_long)
                                            var_result_i = self.container_intensity_corrected[var_filetype][
                                                var_datatype][var_file_short][var_focus][isotope]
                                            helper_results.append(var_result_i)

                                    else:
                                        self.ma_get_intensity_corrected(
                                            var_filetype=var_filetype, var_datatype=var_datatype,
                                            var_file_short=var_file_short,
                                            var_file_long=var_file_long)
                                        var_result_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                            var_file_short][var_focus][isotope]
                                        helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_intensity_corrected[var_filetype][var_datatype][isotope] = var_result_i

    def ma_get_intensity_ratio(self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus,
                               mode="Specific"):
        if mode == "Specific":
            if var_filetype == "STD":
                var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
            elif var_filetype == "SMPL":
                var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()

            if var_focus == "MAT":
                var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                    var_focus][var_is]
            else:
                var_intensity_is = self.container_intensity[var_filetype][var_datatype][var_file_short][
                    var_focus][var_is]

            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if var_focus == "MAT":
                    var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        var_focus][isotope]
                else:
                    var_intensity_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                        var_focus][isotope]

                var_result = var_intensity_i/var_intensity_is
                self.container_intensity_ratio[var_filetype][var_datatype][var_file_short][var_focus][
                    isotope] = var_result

        else:
            for var_filetype in ["SMPL"]:
                for var_focus in ["BG", "MAT"]:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []

                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    if var_filetype == "SMPL":
                                        var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                        var_id_selected = self.container_var["ID"]["Results Files"].get()

                                        if var_id == var_id_selected or self.var_init_ma_datareduction == True:
                                            self.ma_get_intensity_ratio(
                                                var_filetype=var_filetype, var_datatype=var_datatype,
                                                var_file_short=var_file_short, var_file_long=var_file_long,
                                                var_focus=var_focus)
                                            var_result_i = self.container_intensity_ratio[var_filetype][var_datatype][
                                                var_file_short][var_focus][isotope]
                                            helper_results.append(var_result_i)
                                    else:
                                        self.ma_get_intensity_ratio(
                                            var_filetype=var_filetype, var_datatype=var_datatype,
                                            var_file_short=var_file_short, var_file_long=var_file_long,
                                            var_focus=var_focus)
                                        var_result_i = self.container_intensity_ratio[var_filetype][var_datatype][
                                            var_file_short][var_focus][isotope]
                                        helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)

                        self.container_intensity_ratio[var_filetype][var_datatype][isotope] = var_result_i

    def ma_get_normalized_sensitivity(self, var_filetype, var_datatype, var_file_short, var_file_long,
                                      mode="Specific"):
        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if var_filetype == "STD":
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)
                    if element in self.srm_actual[var_srm_i]:
                        var_concentration_i = self.srm_actual[var_srm_i][element]
                        var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                            var_file_short]["MAT"][isotope]
                        var_result_i = var_intensity_i/var_concentration_i
                    else:
                        var_result_i = 0.0
                    self.container_normalized_sensitivity[var_filetype][var_datatype][var_file_short]["MAT"][
                        isotope] = var_result_i
                else:
                    sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                        "MAT"][isotope]
                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        "MAT"][var_is]
                    concentration_is = float(self.container_var[var_filetype][var_file_long]["IS Data"][
                                                 "Concentration"].get())
                    var_result_i = sensitivity_i*(intensity_is/concentration_is)
                    self.container_normalized_sensitivity[var_filetype][var_datatype][var_file_short]["MAT"][
                        isotope] = var_result_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                for var_focus in ["MAT"]:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []

                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    if var_filetype == "SMPL":
                                        var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                        var_id_selected = self.container_var["ID"]["Results Files"].get()

                                        if var_id == var_id_selected or self.var_init_ma_datareduction == True:
                                            self.ma_get_normalized_sensitivity(
                                                var_filetype=var_filetype, var_datatype=var_datatype,
                                                var_file_short=var_file_short, var_file_long=var_file_long)
                                            var_result_i = self.container_normalized_sensitivity[var_filetype][
                                                var_datatype][var_file_short][var_focus][isotope]
                                            helper_results.append(var_result_i)
                                    else:
                                        self.ma_get_normalized_sensitivity(
                                            var_filetype=var_filetype, var_datatype=var_datatype,
                                            var_file_short=var_file_short, var_file_long=var_file_long)
                                        var_result_i = self.container_normalized_sensitivity[var_filetype][
                                            var_datatype][var_file_short][var_focus][isotope]
                                        helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_normalized_sensitivity[var_filetype][var_datatype][isotope] = var_result_i

    def get_analytical_sensitivity_std(
            self, var_datatype=None, var_file_short=None, mode="specific", var_is_host=None, var_is_smpl=None):
        """ Calculates the analytical sensitivity of isotope i with respect to the internal standard IS.
        -------
        Parameters
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        mode : str
            It specifies if the data reduction has to be done for all files or only one specific file
        var_is_host : str
            It defines the internal standard of the host in a sample file
        var_is_smpl : str
            It defines the internal standard of a sample file
        -------
        Returns
        -------
        """
        if mode == "specific":
            filename_short = var_file_short
            index_filename = self.container_lists["STD"]["Short"].index(filename_short)
            filename_long = self.container_lists["STD"]["Long"][index_filename]
            isotopes_file = self.container_lists["Measured Isotopes"][filename_short]
            elements_file = self.container_lists["Measured Elements"][filename_short]

            srm_file = self.container_var["STD"][filename_long]["SRM"].get()
            if srm_file not in self.container_analytical_sensitivity:
                self.container_analytical_sensitivity[srm_file] = {}
            if filename_short not in self.container_analytical_sensitivity[srm_file]:
                self.container_analytical_sensitivity[srm_file][filename_short] = {}

            var_is = None
            element_is_smpl = None
            if var_is_smpl == None:
                for element, value in sorted(
                        self.srm_actual[srm_file].items(), key=lambda item: item[1], reverse=True):
                    if element in elements_file:
                        var_is = elements_file[element][0]

                    if var_is != None:
                        break
            else:
                key_element_is_smpl = re.search(r"(\D+)(\d+)", var_is_smpl)
                element_is_smpl = key_element_is_smpl.group(1)
                var_intensity_is_smpl = self.container_intensity_corrected["STD"][var_datatype][filename_short]["MAT"][
                    var_is_smpl]

                if var_is_host != None:
                    var_is = var_is_host
                else:
                    var_is = var_is_smpl

            if var_is != None:
                key_element_is = re.search(r"(\D+)(\d+)", var_is)
                element_is = key_element_is.group(1)

                if element_is in self.srm_actual[srm_file]:
                    pass
                else:
                    var_is = var_is_smpl

                key_element_is = re.search(r"(\D+)(\d+)", var_is)
                element_is = key_element_is.group(1)

                var_intensity_is = self.container_intensity_corrected["STD"][var_datatype][filename_short]["MAT"][
                    var_is]
                self.container_var["STD"][filename_long]["IS Data"]["IS"].set(var_is)

            for isotope in isotopes_file:
                if isotope.isdigit():
                    self.container_lists["Measured Isotopes"][filename_short].remove(isotope)
                    isotopes_file = self.container_lists["Measured Isotopes"][filename_short]
                else:
                    srm_isotope = self.container_var["SRM"][isotope].get()

                    if srm_isotope == srm_file:
                        if element_is in self.srm_actual[srm_isotope]:
                            var_concentration_is = self.srm_actual[srm_isotope][element_is]
                        else:
                            var_concentration_is = 0.0

                        if element_is_smpl != None:
                            if element_is_smpl in self.srm_actual[srm_isotope]:
                                var_concentration_is_smpl = self.srm_actual[srm_isotope][element_is_smpl]
                            else:
                                var_concentration_is_smpl = 0.0

                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)

                        if element in self.srm_actual[srm_isotope]:
                            if var_is_host == isotope:
                                var_concentration_i = self.srm_actual[srm_file][element]
                            else:
                                var_concentration_i = self.srm_actual[srm_isotope][element]

                            var_intensity_i = self.container_intensity_corrected["STD"][var_datatype][
                                filename_short]["MAT"][isotope]
                            var_result_i = (var_intensity_i/var_intensity_is)*(
                                    var_concentration_is/var_concentration_i)
                        else:
                            var_result_i = 0.0

                        if var_is_smpl != None:
                            if var_intensity_is > 0 and var_concentration_is_smpl > 0:
                                var_result_is_smpl = (var_intensity_is_smpl/var_intensity_is)*(
                                        var_concentration_is/var_concentration_is_smpl)
                            else:
                                var_result_is_smpl = np.nan
                        else:
                            var_result_is_smpl = 0.0

                        self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                            isotope] = var_result_i
                        self.container_analytical_sensitivity[srm_file][filename_short][isotope] = var_result_i
                        self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                            var_is_smpl] = var_result_is_smpl
                        self.container_analytical_sensitivity[srm_file][filename_short][
                            var_is_smpl] = var_result_is_smpl
                    elif srm_isotope != srm_file and var_is_host == isotope:
                        if element_is in self.srm_actual[srm_file]:
                            var_concentration_is = self.srm_actual[srm_file][element_is]
                        else:
                            var_concentration_is = 0.0

                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element in self.srm_actual[srm_file]:
                            if var_is_host == isotope:
                                var_concentration_i = self.srm_actual[srm_file][element]
                            else:
                                var_concentration_i = self.srm_actual[srm_isotope][element]

                            var_intensity_i = self.container_intensity_corrected["STD"][var_datatype][
                                filename_short]["MAT"][isotope]
                            var_result_i = (var_intensity_i/var_intensity_is)*(
                                    var_concentration_is/var_concentration_i)
                        else:
                            var_result_i = 0.0

                        self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                            isotope] = var_result_i
                        self.container_analytical_sensitivity[srm_file][filename_short][isotope] = var_result_i

                        if var_is_smpl != None:
                            var_result_is = 1.0
                            self.container_analytical_sensitivity["STD"][var_datatype][filename_short][
                                "MAT"][var_is] = var_result_is
                    else:
                        if element_is in self.srm_actual[srm_file]:
                            var_concentration_is = self.srm_actual[srm_file][element_is]
                        else:
                            print("The element", element_is, "is not part of the SRM", srm_file + "!")
                            var_concentration_is = 0.0

                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)

                        if element in self.srm_actual[srm_file]:
                            var_concentration_i = self.srm_actual[srm_file][element]
                            var_intensity_i = self.container_intensity_corrected["STD"][var_datatype][filename_short][
                                "MAT"][isotope]
                            var_result_i = (var_intensity_i/var_intensity_is)*(
                                    var_concentration_is/var_concentration_i)
                        else:
                            var_result_i = 0.0

                        if var_is_smpl != None:
                            if element_is_smpl in self.srm_actual[srm_file]:
                                var_concentration_is_smpl = self.srm_actual[srm_file][element_is_smpl]
                                var_intensity_is_smpl = self.container_intensity_corrected["STD"][var_datatype][
                                    filename_short]["MAT"][var_is_smpl]
                                var_result_is_smpl = (var_intensity_is_smpl/var_intensity_is)*(
                                        var_concentration_is/var_concentration_is_smpl)
                            else:
                                var_result_is_smpl = 0.0
                        else:
                            var_result_is_smpl = 0.0

                        self.container_analytical_sensitivity[srm_file][filename_short][isotope] = var_result_i
                        self.container_analytical_sensitivity[srm_file][filename_short][
                            var_is_smpl] = var_result_is_smpl
                        self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                                isotope] = var_result_i
        else:
            str_datatype = var_datatype
            for index, filename_short in enumerate(self.container_lists["STD"]["Short"]):
                if var_is_host != None and var_is_smpl != None:
                    self.get_analytical_sensitivity_std(
                        var_datatype=str_datatype, var_file_short=filename_short, var_is_host=var_is_host,
                        var_is_smpl=var_is_smpl)
                else:
                    self.get_analytical_sensitivity_std(var_datatype=str_datatype, var_file_short=filename_short)

    def get_analytical_sensitivity_std_alternative(
            self, var_datatype=None, var_file_short=None, mode="specific", var_is_host=None, var_is_smpl=None):
        """ Calculates the analytical sensitivity of isotope i with respect to the internal standard IS.
        -------
        Parameters
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        mode : str
            It specifies if the data reduction has to be done for all files or only one specific file
        var_is_host : str
            It defines the internal standard of the host in a sample file
        var_is_smpl : str
            It defines the internal standard of a sample file
        -------
        Returns
        -------
        """
        if mode == "specific":
            filename_short = var_file_short
            index_filename = self.container_lists["STD"]["Short"].index(filename_short)
            filename_long = self.container_lists["STD"]["Long"][index_filename]
            isotopes_file = self.container_lists["Measured Isotopes"][filename_short]
            elements_file = self.container_lists["Measured Elements"][filename_short]

            srm_file = self.container_var["STD"][filename_long]["SRM"].get()
            if srm_file not in self.container_analytical_sensitivity:
                self.container_analytical_sensitivity[srm_file] = {}

            if filename_short not in self.container_analytical_sensitivity[srm_file]:
                self.container_analytical_sensitivity[srm_file][filename_short] = {}

            var_is = None
            element_is_smpl = None

            if var_is_smpl == None:
                for element, value in sorted(
                        self.srm_actual[srm_file].items(), key=lambda item: item[1], reverse=True):
                    if element in elements_file:
                        var_is = elements_file[element][0]

                    if var_is != None:
                        break
            else:
                key_element_is_smpl = re.search(r"(\D+)(\d+)", var_is_smpl)
                element_is_smpl = key_element_is_smpl.group(1)
                var_intensity_is_smpl = self.container_intensity_corrected["STD"][var_datatype][filename_short]["MAT"][
                    var_is_smpl]

                if var_is_host != None:
                    var_is = var_is_host
                else:
                    var_is = var_is_smpl

            if var_is != None:
                key_element_is = re.search(r"(\D+)(\d+)", var_is)
                element_is = key_element_is.group(1)
                if element_is in self.srm_actual[srm_file]:
                    pass
                else:
                    var_is = var_is_smpl

                key_element_is = re.search(r"(\D+)(\d+)", var_is)
                element_is = key_element_is.group(1)

                var_intensity_is = self.container_intensity_corrected["STD"][var_datatype][filename_short]["MAT"][
                    var_is]
                self.container_var["STD"][filename_long]["IS Data"]["IS"].set(var_is)

            for isotope in isotopes_file:
                if isotope.isdigit():
                    self.container_lists["Measured Isotopes"][filename_short].remove(isotope)
                    isotopes_file = self.container_lists["Measured Isotopes"][filename_short]
                else:
                    srm_isotope = self.container_var["SRM"][isotope].get()
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)

                    if element_is in self.srm_actual[srm_file]:
                        var_concentration_is = self.srm_actual[srm_file][element_is]
                    else:
                        var_concentration_is = 0.0

                    if element_is_smpl != None:
                        if element_is_smpl in self.srm_actual[srm_file]:
                            var_concentration_is_smpl = self.srm_actual[srm_file][element_is_smpl]
                        else:
                            var_concentration_is_smpl = 0.0
                    else:
                        var_concentration_is_smpl = 0.0

                    if element in self.srm_actual[srm_file]:
                        if var_is_host == isotope:
                            var_concentration_i = self.srm_actual[srm_file][element]
                        else:
                            var_concentration_i = self.srm_actual[srm_isotope][element]

                        var_intensity_i = self.container_intensity_corrected["STD"][var_datatype][filename_short][
                            "MAT"][isotope]

                        var_result_i = (var_intensity_i/var_intensity_is)*(
                                var_concentration_is/var_concentration_i)
                    else:
                        var_result_i = 0.0

                    if var_is_smpl != None:
                        var_result_is_smpl = (var_intensity_is_smpl/var_intensity_is)*(
                                var_concentration_is/var_concentration_is_smpl)
                    else:
                        var_result_is_smpl = 0.0

                    self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                        isotope] = var_result_i
                    self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                        var_is_smpl] = var_result_is_smpl

                    if element in self.srm_actual[srm_file]:
                        self.container_analytical_sensitivity[srm_file][filename_short][isotope] = var_result_i
                        self.container_analytical_sensitivity[srm_file][filename_short][
                            var_is_smpl] = var_result_is_smpl

                    if srm_file != srm_isotope:
                        if element_is in self.srm_actual[srm_file]:
                            var_concentration_is = self.srm_actual[srm_file][element_is]
                        else:
                            var_concentration_is = 0.0

                        if element_is_smpl != None:
                            if element_is_smpl in self.srm_actual[srm_file]:
                                var_concentration_is_smpl = self.srm_actual[srm_file][element_is_smpl]
                            else:
                                var_concentration_is_smpl = 0.0

                        if element in self.srm_actual[srm_file]:
                            var_concentration_i = self.srm_actual[srm_file][element]
                            var_intensity_i = self.container_intensity_corrected["STD"][var_datatype][filename_short][
                                "MAT"][isotope]

                            var_result_i = (var_intensity_i/var_intensity_is)*(
                                    var_concentration_is/var_concentration_i)
                        else:
                            var_result_i = 0.0

                        if var_is_smpl != None:
                            var_result_is_smpl = (var_intensity_is_smpl/var_intensity_is)*(
                                    var_concentration_is/var_concentration_is_smpl)
                        else:
                            var_result_is_smpl = 0.0

                        self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                            isotope] = var_result_i
                        self.container_analytical_sensitivity["STD"][var_datatype][filename_short]["MAT"][
                            var_is_smpl] = var_result_is_smpl
        else:
            str_datatype = var_datatype
            for index, filename_short in enumerate(self.container_lists["STD"]["Short"]):
                if var_is_host != None and var_is_smpl != None:
                    self.get_analytical_sensitivity_std_alternative(
                        var_datatype=str_datatype, var_file_short=filename_short, var_is_host=var_is_host,
                        var_is_smpl=var_is_smpl)
                else:
                    self.get_analytical_sensitivity_std_alternative(
                        var_datatype=str_datatype, var_file_short=filename_short)

    def get_analytical_sensitivity(
            self, var_filetype, var_datatype, var_file_short, var_file_long, mode="Specific", var_is_smpl=None,
            var_focus=None, var_is_host=None):
        """ Calculates the analytical sensitivity of isotope i with respect to the internal standard IS.
        -------
        Parameters
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as a long version (including the complete filepath)
        var_focus : str
            The signal section of interest, e.g. the background or inclusion signal
        mode : str
            It specifies if the data reduction has to be done for all files or only one specific file
        var_is_smpl : str
            It defines the internal standard of a sample file
        -------
        Returns
        -------
        """
        if mode == "Specific":
            if var_filetype == "STD":
                var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                if var_srm_file not in self.container_analytical_sensitivity:
                    self.container_analytical_sensitivity[var_srm_file] = {}
                if var_file_short not in self.container_analytical_sensitivity[var_srm_file]:
                    self.container_analytical_sensitivity[var_srm_file][var_file_short] = {}

                if var_is_smpl == None:
                    for element, value in sorted(
                            self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                        if element in self.container_lists["Measured Elements"][var_file_short]:
                            var_is = self.container_lists["Measured Elements"][var_file_short][element][0]
                        break
                else:
                    var_is = var_is_smpl

                key_element_is = re.search(r"(\D+)(\d+)", var_is)
                element_is = key_element_is.group(1)
                var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                    "MAT"][var_is]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].set(var_is)

                for isotope in file_isotopes:
                    if isotope.isdigit():
                        self.container_lists["Measured Isotopes"][var_file_short].remove(isotope)
                    else:
                        var_srm_i = self.container_var["SRM"][isotope].get()

                        if var_srm_i == var_srm_file:
                            if element_is in self.srm_actual[var_srm_i]:
                                var_concentration_is = self.srm_actual[var_srm_i][element_is]
                            else:
                                var_concentration_is = 0.0

                            key_element = re.search(r"(\D+)(\d+)", isotope)
                            element = key_element.group(1)
                            if element in self.srm_actual[var_srm_i]:
                                if var_is_host == isotope:
                                    var_concentration_i = self.srm_actual[var_srm_file][element]
                                else:
                                    var_concentration_i = self.srm_actual[var_srm_i][element]
                                var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                    var_file_short]["MAT"][isotope]
                                var_result_i = (var_intensity_i/var_intensity_is)*(
                                        var_concentration_is/var_concentration_i)
                            else:
                                var_result_i = 0.0

                            self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short]["MAT"][
                                isotope] = var_result_i
                            self.container_analytical_sensitivity[var_srm_file][var_file_short][isotope] = var_result_i

                            if var_is_smpl != None:
                                var_result_is = 1.0
                                self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                                    "MAT"][var_is] = var_result_is
                        elif var_srm_i != var_srm_file and var_is_host == isotope:
                            if element_is in self.srm_actual[var_srm_file]:
                                var_concentration_is = self.srm_actual[var_srm_file][element_is]
                            else:
                                var_concentration_is = 0.0

                            key_element = re.search(r"(\D+)(\d+)", isotope)
                            element = key_element.group(1)
                            if element in self.srm_actual[var_srm_file]:
                                if var_is_host == isotope:
                                    var_concentration_i = self.srm_actual[var_srm_file][element]
                                else:
                                    var_concentration_i = self.srm_actual[var_srm_i][element]
                                var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                    var_file_short]["MAT"][isotope]
                                var_result_i = (var_intensity_i/var_intensity_is)*(
                                        var_concentration_is/var_concentration_i)
                            else:
                                var_result_i = 0.0

                            self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short]["MAT"][
                                isotope] = var_result_i
                            self.container_analytical_sensitivity[var_srm_file][var_file_short][isotope] = var_result_i

                            if var_is_smpl != None:
                                var_result_is = 1.0
                                self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                                    "MAT"][var_is] = var_result_is
                        else:
                            if element_is in self.srm_actual[var_srm_file]:
                                var_concentration_is = self.srm_actual[var_srm_file][element_is]
                            else:
                                var_concentration_is = 0.0

                            key_element = re.search(r"(\D+)(\d+)", isotope)
                            element = key_element.group(1)
                            if element in self.srm_actual[var_srm_file]:
                                var_concentration_i = self.srm_actual[var_srm_file][element]
                                var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                    var_file_short]["MAT"][isotope]
                                var_result_i = (var_intensity_i/var_intensity_is)*(
                                        var_concentration_is/var_concentration_i)
                            else:
                                var_result_i = 0.0

                            self.container_analytical_sensitivity[var_srm_file][var_file_short][isotope] = var_result_i

            else:
                self.calculate_acquisition_time_deltas()
                xi_opt = {}
                xi_std_helper = {}
                list_valid_std = []
                list_valid_isotopes = []

                var_is_smpl = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                if self.pysills_mode == "MA":
                    var_is_host = var_is_smpl
                else:
                    var_is_host = self.container_var[var_filetype][var_file_long]["Matrix Setup"]["IS"]["Name"].get()

                var_srm_host = self.container_var["SRM"][var_is_host].get()

                file_isotopes_smpl = self.container_lists["Measured Isotopes"][var_file_short]
                list_delta_std_i = []
                list_xi_std_i = {}

                for index, file_std in enumerate(self.container_lists["STD"]["Long"]):
                    file_std_short = self.container_lists["STD"]["Short"][index]
                    file_isotopes = self.container_lists["Measured Isotopes"][file_std_short]
                    var_srm_file = self.container_var["STD"][file_std]["SRM"].get()
                    if self.container_var["STD"][file_std]["Checkbox"].get() == 1:
                        xi_std_helper[file_std_short] = {}
                        delta_std_i = self.container_lists["Acquisition Times Delta"][file_std_short]
                        list_delta_std_i.append(delta_std_i)

                        for isotope in file_isotopes:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            if isotope not in list_xi_std_i:
                                list_xi_std_i[isotope] = []
                            if var_srm_i == var_srm_file:
                                if isotope not in list_valid_isotopes:
                                    list_valid_isotopes.append(isotope)

                                if file_std_short not in list_valid_std:
                                    list_valid_std.append(file_std_short)

                                if isotope not in xi_opt:
                                    xi_opt[isotope] = []

                                sensitivity_i = self.container_analytical_sensitivity["STD"][var_datatype][
                                    file_std_short]["MAT"][isotope]
                                if var_srm_host == var_srm_i:
                                    sensitivity_is = self.container_analytical_sensitivity["STD"][var_datatype][
                                        file_std_short]["MAT"][var_is_host]
                                else:
                                    sensitivity_is = self.container_analytical_sensitivity["STD"][var_datatype][
                                        file_std_short]["MAT"][var_is_host]
                                    if sensitivity_is != 1.0:
                                        pass
                                    else:
                                        sensitivity_is = 1.0

                                if sensitivity_is != None:
                                    if sensitivity_is > 0:
                                        sensitivity_i = sensitivity_i/sensitivity_is
                                    else:
                                        sensitivity_i = 0.0

                                list_xi_std_i[isotope].append(sensitivity_i)

                                xi_std_helper[file_std_short][isotope] = [delta_std_i, sensitivity_i]
                            else:
                                list_xi_std_i[isotope].append(None)

                for isotope in file_isotopes_smpl:
                    a_i, b_i = self.calculate_linear_regression(
                        x_values=list_delta_std_i, y_values=list_xi_std_i[isotope])
                    a_i = round(a_i, 12)
                    b_i = round(b_i, 12)
                    xi_regr = [b_i, a_i]

                    xi_opt[isotope].extend(xi_regr)

                delta_i = self.container_lists["Acquisition Times Delta"][var_file_short]

                if var_focus == "MAT":
                    if self.pysills_mode == "MA":
                        var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    else:
                        var_is = self.container_var[var_filetype][var_file_long]["Matrix Setup"]["IS"]["Name"].get()

                    var_result_is = xi_opt[var_is][0]*delta_i + xi_opt[var_is][1]
                elif var_focus == "INCL":
                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    var_result_is = xi_opt[var_is][0]*delta_i + xi_opt[var_is][1]
                elif var_focus == None:
                    var_focus = "MAT"
                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    var_result_is = xi_opt[var_is][0]*delta_i + xi_opt[var_is][1]

                    if self.pysills_mode != "MA":
                        var_focus2 = "INCL"

                if var_result_is == 0.0:
                    if self.pysills_mode == "MA":
                        var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    else:
                        var_is = self.container_var[var_filetype][var_file_long]["Matrix Setup"]["IS"]["Name"].get()

                    var_result_is = xi_opt[var_is][0]*delta_i + xi_opt[var_is][1]

                for isotope in file_isotopes_smpl:
                    var_result_i_pre = xi_opt[isotope][0]*delta_i + xi_opt[isotope][1]
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    caution = False

                    if var_focus == "MAT":  # MAT
                        xi_opt_host_is = []
                        for index, file_std in enumerate(self.container_lists["STD"]["Long"]):
                            file_std_short = self.container_lists["STD"]["Short"][index]
                            var_srm_file = self.container_var["STD"][file_std]["SRM"].get()
                            if var_srm_i != var_srm_file:
                                xi_opt_host_is.append(None)
                            else:
                                if self.pysills_mode == "MA":
                                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                                else:
                                    var_is = self.container_var[var_filetype][var_file_long]["Matrix Setup"]["IS"][
                                        "Name"].get()

                                value_is = self.container_analytical_sensitivity[var_srm_file][file_std_short][var_is]
                                xi_opt_host_is.append(value_is)
                                caution = True
                                var_focus2 = "INCL"

                        a_i, b_i = self.calculate_linear_regression(x_values=list_delta_std_i, y_values=xi_opt_host_is)
                        a_i = round(a_i, 12)
                        b_i = round(b_i, 12)
                        var_result_is_new = b_i*delta_i + a_i

                        if var_result_is > 0:
                            if var_result_is != 1.0:
                                var_result_is = b_i*delta_i + a_i
                            else:
                                var_result_is = 1.0
                            var_result_i = var_result_i_pre/var_result_is
                        else:
                            var_result_i = 0.0

                        if caution == True and var_focus2 == "INCL":
                            xi_opt_host_is = []
                            for index, file_std in enumerate(self.container_lists["STD"]["Long"]):
                                file_std_short = self.container_lists["STD"]["Short"][index]
                                var_srm_file = self.container_var["STD"][file_std]["SRM"].get()
                                if var_srm_i != var_srm_file:
                                    xi_opt_host_is.append(None)
                                else:

                                    var_incl_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                                    value_i = self.container_analytical_sensitivity[var_srm_file][file_std_short][
                                        isotope]
                                    value_is = self.container_analytical_sensitivity[var_srm_file][file_std_short][
                                        var_incl_is]

                                    if value_is > 0:
                                        value_i = value_i/value_is
                                    else:
                                        value_i = np.nan

                                    xi_opt_host_is.append(value_i)

                            a_i, b_i = self.calculate_linear_regression(x_values=list_delta_std_i,
                                                                        y_values=xi_opt_host_is)
                            a_i = round(a_i, 12)
                            b_i = round(b_i, 12)
                            var_result_incl_is_new = b_i*delta_i + a_i

                            if var_result_incl_is_new > 0:
                                var_result_incl_i = var_result_incl_is_new
                            else:
                                var_result_incl_i = 0.0

                            var_result_is_new = var_result_incl_i
                    else:   # INCL
                        xi_opt_host_is = []
                        for index, file_std in enumerate(self.container_lists["STD"]["Long"]):
                            file_std_short = self.container_lists["STD"]["Short"][index]
                            var_srm_file = self.container_var["STD"][file_std]["SRM"].get()

                            if var_srm_i != var_srm_file:
                                xi_opt_host_is.append(None)
                            else:
                                var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                                value_i = self.container_analytical_sensitivity[var_srm_file][file_std_short][isotope]
                                value_is = self.container_analytical_sensitivity[var_srm_file][file_std_short][var_is]

                                if value_is > 0:
                                    value_i = value_i/value_is
                                else:
                                    value_i = np.nan

                                xi_opt_host_is.append(value_i)
                                caution = True
                                var_focus2 = "INCL"

                        a_i, b_i = self.calculate_linear_regression(x_values=list_delta_std_i, y_values=xi_opt_host_is)
                        a_i = round(a_i, 12)
                        b_i = round(b_i, 12)
                        var_result_is_new = b_i*delta_i + a_i

                        if var_result_is > 0:
                            if var_result_is != 1.0:
                                var_result_is = b_i*delta_i + a_i
                            else:
                                var_result_is = 1.0

                            var_result_i = var_result_i_pre/var_result_is
                        else:
                            var_result_i = 0.0

                    self.container_lists["Analytical Sensitivity Regression"][isotope] = {
                        "a": xi_opt[isotope][0], "b": xi_opt[isotope][1]}

                    if var_datatype == "RAW":
                        self.container_lists["Analytical Sensitivity Regression RAW"][isotope] = {
                            "a": xi_opt[isotope][0], "b": xi_opt[isotope][1]}
                    elif var_datatype == "SMOOTHED":
                        self.container_lists["Analytical Sensitivity Regression SMOOTHED"][isotope] = {
                            "a": xi_opt[isotope][0], "b": xi_opt[isotope][1]}

                    if var_focus == "MAT":
                        self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = var_result_i
                    elif var_focus == "INCL":
                        if caution == False:
                            self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                                var_focus][isotope] = var_result_i
                        else:
                            self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                                var_focus][isotope] = var_result_is_new

                    try:
                        self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                            var_focus2][isotope] = var_result_i
                    except:
                        pass

                    if caution == True:
                        try:
                            self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                                var_focus2][isotope] = var_result_is_new
                        except:
                            pass
        else:
            str_datatype = var_datatype
            self.get_analytical_sensitivity_std(var_datatype=str_datatype, mode="all")
            for var_filetype in ["SMPL"]:
                if self.pysills_mode == "MA":
                    list_focus = ["MAT"]
                else:
                    list_focus = ["MAT", "INCL"]
                for var_focus in list_focus:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                var_id_selected = self.container_var["ID"]["Results Files"].get()
                                if (self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1
                                        and var_id == var_id_selected):
                                    self.get_analytical_sensitivity(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long,
                                        var_focus=var_focus)
                                    var_result_i = self.container_analytical_sensitivity[var_filetype][
                                        var_datatype][var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)

                        self.container_analytical_sensitivity[var_filetype][var_datatype][isotope] = var_result_i

    def ma_get_rsf(self, var_filetype, var_datatype, var_file_short, var_file_long, mode="Specific"):
        """ Calculates the Relative Sensitivity Factor, RSF, based on the following two equations:
        1) Standard Files:  RSF_i = sensitivity_i*(concentration_std_i/intensity_std_i)*
                                    (intensity_std_is/concentration_std_is) = 1
        2) Sample Files:    RSF_i = sensitivity_i*(concentration_std_i/intensity_std_i)*
                                    (intensity_smpl_is/concentration_smpl_is)

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)

        Returns
        -------
        """
        if mode == "Specific":
            if var_filetype == "STD":
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                for isotope in file_isotopes:
                    var_result_i = 1
                    self.container_rsf[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i
            elif var_filetype == "SMPL":
                var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                var_concentration_is = float(self.container_var[var_filetype][var_file_long]["IS Data"][
                                                 "Concentration"].get())
                var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                    "MAT"][var_is]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                for isotope in file_isotopes:
                    var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                        var_file_short]["MAT"][isotope]
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)
                    if element in self.srm_actual[var_srm_i]:
                        var_concentration_i = self.srm_actual[var_srm_i][element]
                    else:
                        var_concentration_i = 0.0

                    var_intensity_i = self.container_intensity_corrected["STD"][var_datatype][isotope]

                    if var_intensity_i > 0 and var_concentration_is > 0:
                        var_result_i = (var_sensitivity_i*(var_concentration_i/var_intensity_i)*
                                        (var_intensity_is/var_concentration_is))
                    else:
                        var_result_i = np.nan

                    self.container_rsf[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                if var_filetype == "SMPL":
                                    var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                    var_id_selected = self.container_var["ID"]["Results Files"].get()
                                    #
                                    if var_id == var_id_selected or self.var_init_ma_datareduction == True:
                                        self.ma_get_rsf(
                                            var_filetype=var_filetype, var_datatype=var_datatype,
                                            var_file_short=var_file_short, var_file_long=var_file_long)
                                        var_result_i = self.container_rsf[var_filetype][var_datatype][var_file_short][
                                            "MAT"][isotope]
                                        helper_results.append(var_result_i)
                                else:
                                    self.ma_get_rsf(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long)
                                    var_result_i = self.container_rsf[var_filetype][var_datatype][var_file_short][
                                        "MAT"][isotope]
                                    helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)

                    self.container_rsf[var_filetype][var_datatype][isotope] = var_result_i

    def ma_get_concentration(self, var_filetype, var_datatype, var_file_short, var_file_long, mode="Specific"):
        """ Calculates the concentration, C, based on the following two equations:
        1) Standard Files:  C_i = SRM_dataset(element)
        2) Sample Files:    C_i = (intensity_smpl_i/intensity_smpl_is)*(concentration_smpl_is/sensitivity_i)

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)

        Returns
        -------
        """
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"

        if mode == "Specific":
            if var_filetype == "STD":
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                for isotope in file_isotopes:
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)

                    if element in self.srm_actual[var_srm_i]:
                        var_result_i = self.srm_actual[var_srm_i][element]
                    else:
                        var_result_i = 0.0

                    self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                        isotope] = var_result_i
                    self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
                        isotope] = 0.0
            elif var_filetype == "SMPL":
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                if (self.container_var["Quantification Mineral"]["Method"].get() == "Internal Standard" and
                        self.oxide_calculation_mat.get() == 0):
                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    key_element = re.search(r"(\D+)(\d+)", var_is)
                    is_element = key_element.group(1)
                    max_amount_is = self.maximum_amounts[is_element]
                    var_concentration_is = float(self.container_var[var_filetype][var_file_long]["IS Data"][
                                                     "Concentration"].get())

                    for isotope in file_isotopes:
                        if var_concentration_is <= max_amount_is:
                            correction_factor_i = 1
                            var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]
                            var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][var_is]
                            var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]

                            var_std_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "BG SIGMA"][isotope]
                            var_std_mat_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "MAT SIGMA"][isotope]
                            var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "N BG"][isotope]
                            var_n_mat = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "N MAT"][isotope]
                            var_sigma_bg_i = var_std_bg_i/(var_n_bg**0.5)
                            var_sigma_mat_i = var_std_mat_i/(var_n_mat**0.5)
                            var_sigma = var_sigma_bg_i + var_sigma_mat_i

                            if var_sensitivity_i > 0 and var_intensity_is > 0 and var_intensity_i > 0:
                                var_result_i = ((var_intensity_i/var_intensity_is)*
                                                (var_concentration_is/var_sensitivity_i))
                                var_result_sigma_i = (var_sigma*var_result_i)/var_intensity_i
                            else:
                                var_result_i = 0.0
                                var_result_sigma_i = 0.0

                            self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                                isotope] = var_result_i
                            self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
                                isotope] = var_result_sigma_i

                            key_element = re.search(r"(\D+)(\d+)", isotope)
                            element = key_element.group(1)
                            max_amount_i = self.maximum_amounts[element]

                            if var_result_i > max_amount_i:
                                correction_factor_i = max_amount_i/var_result_i
                                break
                        else:
                            var_concentration_is = max_amount_is
                            correction_factor_i = 1
                            var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]
                            var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][var_is]
                            var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]

                            var_std_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "BG SIGMA"][isotope]
                            var_std_mat_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "MAT SIGMA"][isotope]
                            var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "N BG"][isotope]
                            var_n_mat = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "N MAT"][isotope]
                            var_sigma_bg_i = var_std_bg_i/(var_n_bg**0.5)
                            var_sigma_mat_i = var_std_mat_i/(var_n_mat**0.5)
                            var_sigma = var_sigma_bg_i + var_sigma_mat_i

                            if var_sensitivity_i > 0 and var_intensity_is > 0 and var_intensity_i > 0:
                                var_result_i = ((var_intensity_i/var_intensity_is)*
                                                (var_concentration_is/var_sensitivity_i))
                                var_result_sigma_i = (var_sigma*var_result_i)/var_intensity_i
                            else:
                                var_result_i = 0.0
                                var_result_sigma_i = 0.0

                            self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                                isotope] = var_result_i
                            self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
                                isotope] = var_result_sigma_i

                            key_element = re.search(r"(\D+)(\d+)", isotope)
                            element = key_element.group(1)
                            max_amount_i = self.maximum_amounts[element]

                            if var_result_i > max_amount_i:
                                correction_factor_i = max_amount_i/var_result_i
                                break

                    if correction_factor_i != 1:
                        for isotope in file_isotopes:
                            var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]
                            var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][var_is]
                            var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]

                            var_std_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "BG SIGMA"][isotope]
                            var_std_mat_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "MAT SIGMA"][isotope]
                            var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "N BG"][isotope]
                            var_n_mat = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "N MAT"][isotope]
                            var_sigma_bg_i = var_std_bg_i/(var_n_bg**0.5)
                            var_sigma_mat_i = var_std_mat_i/(var_n_mat**0.5)
                            var_sigma = var_sigma_bg_i + var_sigma_mat_i

                            if var_sensitivity_i > 0 and var_intensity_is > 0 and var_intensity_i > 0:
                                var_result_i = (correction_factor_i*(var_intensity_i/var_intensity_is)*
                                                (var_concentration_is/var_sensitivity_i))
                                var_result_sigma_i = (var_sigma*var_result_i)/var_intensity_i
                            else:
                                var_result_i = 0.0
                                var_result_sigma_i = 0.0

                            self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                                isotope] = var_result_i
                            self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
                                isotope] = var_result_sigma_i
                else:
                    self.run_total_oxides_calculation(
                        filetype=var_filetype, datatype=var_datatype, filename_short=var_file_short,
                        list_isotopes=file_isotopes)
        else:
            # for var_filetype in ["STD", "SMPL"]:
            #     for isotope in self.container_lists["Measured Isotopes"]["All"]:
            #         helper_results = []
            #         for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
            #             if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
            #                 var_file_short = self.container_lists[var_filetype]["Short"][index]
            #                 file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            #                 if isotope in file_isotopes:
            #                     if var_filetype == "SMPL":
            #                         var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
            #                         var_id_selected = self.container_var["ID"]["Results Files"].get()
            #                         if var_id == var_id_selected or self.var_init_ma_datareduction == True:
            #                             self.ma_get_concentration(
            #                                 var_filetype=var_filetype, var_datatype=var_datatype,
            #                                 var_file_short=var_file_short, var_file_long=var_file_long)
            #                             var_result_i = self.container_concentration[var_filetype][var_datatype][
            #                                 var_file_short]["MAT"][isotope]
            #                             helper_results.append(var_result_i)
            #                     else:
            #                         self.ma_get_concentration(
            #                             var_filetype=var_filetype, var_datatype=var_datatype,
            #                             var_file_short=var_file_short, var_file_long=var_file_long)
            #                         var_result_i = self.container_concentration[var_filetype][var_datatype][
            #                             var_file_short]["MAT"][isotope]
            #                         helper_results.append(var_result_i)
            #
            #         if self.container_var["General Settings"]["Desired Average"].get() == 1:
            #             var_result_i = np.mean(helper_results)
            #         else:
            #             var_result_i = np.median(helper_results)
            #
            #         self.container_concentration[var_filetype][var_datatype][isotope] = var_result_i

            for var_filetype in ["STD", "SMPL"]:
                for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                    if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                        var_file_short = self.container_lists[var_filetype]["Short"][index]
                        if var_filetype == "SMPL":
                            var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                            var_id_selected = self.container_var["ID"]["Results Files"].get()
                            if var_id == var_id_selected or self.var_init_ma_datareduction == True:
                                self.ma_get_concentration(
                                    var_filetype=var_filetype, var_datatype=var_datatype,
                                    var_file_short=var_file_short, var_file_long=var_file_long)
                        else:
                            self.ma_get_concentration(
                                var_filetype=var_filetype, var_datatype=var_datatype,
                                var_file_short=var_file_short, var_file_long=var_file_long)

                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                var_result_i = self.container_concentration[var_filetype][var_datatype][var_file_short][
                                    "MAT"][isotope]
                                helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)

                    self.container_concentration[var_filetype][var_datatype][isotope] = var_result_i

    def get_oxide_ratio(self, var_focus, var_element, var_oxide, sills_mode=False):
        if var_element == "Fe":
            if var_focus == "MAT":
                r = float(self.container_var["Oxides Quantification"]["Ratios"]["Fe-Ratio"].get())
            else:
                r = float(self.container_var["Oxides Quantification INCL"]["Ratios"]["Fe-Ratio"].get())

            if sills_mode == False:
                if var_oxide == "FeO":
                    factor = r
                elif var_oxide == "Fe2O3":
                    factor = 1 - r
            else:
                if r > 0:
                    gamma = (1 + (2*self.chemistry_data_oxides["FeO"])/(
                        self.chemistry_data_oxides["Fe2O3"])*(1 - r)/(r))**(-1)
                else:
                    gamma = 0

                if var_oxide == "FeO":
                    factor = gamma
                elif var_oxide == "Fe2O3":
                    factor = 1 - gamma
        elif var_element == "Mn":
            if var_focus == "MAT":
                r = float(self.container_var["Oxides Quantification"]["Ratios"]["Mn-Ratio"].get())
            else:
                r = float(self.container_var["Oxides Quantification INCL"]["Ratios"]["Mn-Ratio"].get())

            if sills_mode == False:
                if var_oxide == "MnO":
                    factor = r
                elif var_oxide == "Mn2O3":
                    factor = 1 - r
            else:
                if r > 0:
                    gamma = (1 + (2*self.chemistry_data_oxides["MnO"])/(
                        self.chemistry_data_oxides["Mn2O3"])*(1 - r)/(r))**(-1)
                else:
                    gamma = 0

                if var_oxide == "MnO":
                    factor = gamma
                elif var_oxide == "Mn2O3":
                    factor = 1 - gamma
        else:
            factor = 1

        return factor

    def run_total_oxides_calculation_alternative(self, var_filetype, var_datatype, var_filename_short, var_focus="MAT"):
        """ Calculates the element concentrations based on a normalized total oxide approach.
        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_filename_short : str
            The file as a short version (without the complete filepath)
        var_focus : str
            It specifies if the quantification has to be done for the matrix or the inclusion signal.
        Returns
        -------
        """
        file_isotopes = self.container_lists["Measured Isotopes"][var_filename_short]
        index_filename = self.container_lists["SMPL"]["Short"].index(var_filename_short)
        var_filename_long = self.container_lists["SMPL"]["Long"][index_filename]

        if self.pysills_mode == "MA":
            var_is = self.container_var["SMPL"][var_filename_long]["IS Data"]["IS"].get()
        else:
            if var_focus == "MAT":
                var_is = self.container_var["SMPL"][var_filename_long]["Matrix Setup"]["IS"]["Name"].get()
            else:
                var_is = self.container_var["SMPL"][var_filename_long]["IS Data"]["IS"].get()

        if var_focus == "MAT":
            total_amount_oxides = float(
                self.container_var["Oxides Quantification"]["Total Amounts"][var_filename_short].get())
        else:
            total_amount_oxides = float(
                self.container_var["Oxides Quantification INCL"]["Total Amounts"][var_filename_short].get())

        helper_a = 0
        for isotope in file_isotopes:
            key_element = re.search(r"(\D+)(\d+)", isotope)
            element = key_element.group(1)
            if isotope == var_is:
                element_is = element

            for oxide in self.container_lists["Possible Oxides"][element]:
                focus = var_focus
                gamma = self.get_oxide_ratio(var_focus=focus, var_element=element, var_oxide=oxide)
                conversion_factor_i = gamma*self.conversion_factors[oxide]
                if element in ["F", "Cl", "Br", "I", "At", "Ts"]:
                    conversion_factor_i = 1.0

                intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                    var_filename_short][var_focus][isotope]
                intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][
                    var_filename_short][var_focus][var_is]
                sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                    var_filename_short][var_focus][isotope]

                if (intensity_is*sensitivity_i) > 0:
                    helper_a += (conversion_factor_i*intensity_i)/(intensity_is*sensitivity_i)

        concentration_is = (total_amount_oxides*10**4)/helper_a
        max_amount_element = self.maximum_amounts[element_is]

        if concentration_is > max_amount_element:
            correction_factor = max_amount_element/concentration_is
            concentration_is = correction_factor*concentration_is

        for isotope in file_isotopes:
            intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][var_filename_short][
                var_focus][isotope]
            intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_filename_short][
                var_focus][var_is]
            sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][var_filename_short][
                var_focus][isotope]

            if (intensity_is*sensitivity_i) > 0:
                concentration_i = (intensity_i*concentration_is)/(intensity_is*sensitivity_i)
            else:
                concentration_i = np.nan

    def run_total_oxides_calculation_alternative2(self, var_filetype, var_datatype, var_filename_short, var_focus="MAT",
                                                  sills_mode=False):
        """ Calculates the element concentrations based on a normalized total oxide approach.
        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_filename_short : str
            The file as a short version (without the complete filepath)
        var_focus : str
            It specifies if the quantification has to be done for the matrix or the inclusion signal.
        Returns
        -------
        """
        file_isotopes = self.container_lists["Measured Isotopes"][var_filename_short]
        index_filename = self.container_lists["SMPL"]["Short"].index(var_filename_short)
        var_filename_long = self.container_lists["SMPL"]["Long"][index_filename]

        if self.pysills_mode == "MA":
            var_is = self.container_var["SMPL"][var_filename_long]["IS Data"]["IS"].get()
        else:
            if var_focus == "MAT":
                var_is = self.container_var["SMPL"][var_filename_long]["Matrix Setup"]["IS"]["Name"].get()
            else:
                var_is = self.container_var["SMPL"][var_filename_long]["IS Data"]["IS"].get()

        if var_focus == "MAT":
            total_amount_oxides = float(
                self.container_var["Oxides Quantification"]["Total Amounts"][var_filename_short].get())
        else:
            total_amount_oxides = float(
                self.container_var["Oxides Quantification INCL"]["Total Amounts"][var_filename_short].get())

        sensitivity_is = self.container_analytical_sensitivity[var_filetype][var_datatype][var_filename_short][
            var_focus][var_is]

        sum_c = 0
        helper_b = {}
        helper = {}
        if sills_mode == True:
            list_oxides = ["SiO2", "TiO2", "Al2O3", "Fe2O3", "FeO", "MnO", "MgO", "CaO", "Na2O", "K2O", "P2O5"]
        else:
            list_oxides = self.container_lists["Selected Oxides"]["All"]

        for oxide in list_oxides:
            key_element = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide)
            element = key_element.group(1)
            if element in self.container_lists["Measured Elements"]:
                list_isotopes = self.container_lists["Measured Elements"][element]

                for index, isotope in enumerate(list_isotopes):
                    if index == 0:
                        intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                            var_filename_short][var_focus][isotope]
                        sensitivity_i_pre = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_filename_short][var_focus][isotope]
                        sensitivity_i = sensitivity_i_pre/sensitivity_is
                        # Determine a_i
                        a_i = intensity_i
                        # Determine b_i_pre
                        if sensitivity_i > 0:
                            b_i_pre = a_i/sensitivity_i
                        else:
                            b_i_pre = np.nan
                        # Determine b_i
                        focus= var_focus
                        factor = self.get_oxide_ratio(
                            var_focus=focus, var_element=element, var_oxide=oxide, sills_mode=True)
                        if np.isnan(b_i_pre) == False:
                            b_i = factor*b_i_pre
                            helper_b[isotope] = b_i
                            # Determine c_i
                            conversion_factor = self.conversion_factors[oxide]
                            c_i = conversion_factor*b_i
                            sum_c += c_i
                            helper[isotope] = {
                                "Element": element, "a": a_i, "b*": b_i_pre, "b": b_i, "c": c_i,
                                "Sensitivity": sensitivity_i}

        # Determine c
        c_total = sum_c
        # Determine d
        if c_total > 0:
            factor_d = total_amount_oxides/c_total
        else:
            print("Attention! It is probably necessary to define first the set of oxides before the calculation can be "
                  "run successfully.")
            factor_d= np.nan

        # Determine e_i
        concentration_is = None
        for isotope, b_i in helper_b.items():
            e_i = factor_d*b_i
            concentration_i = e_i*10**4
            self.container_concentration[var_filetype][var_datatype][var_filename_short][var_focus][
                isotope] = concentration_i

            if isotope == var_is:
                concentration_is = concentration_i
                if var_focus == "INCL":
                    if isotope == var_is:
                        self.container_var["SMPL"][var_filename_long]["IS Data"]["Concentration"].set(concentration_is)
                elif var_focus == "MAT":
                    if self.pysills_mode == "MA":
                        if isotope == var_is:
                            self.container_var["SMPL"][var_filename_long]["IS Data"]["Concentration"].set(
                                concentration_is)
                    else:
                        var_is = self.container_var["SMPL"][var_filename_long]["Matrix Setup"]["IS"]["Name"].get()
                        if isotope == var_is:
                            self.container_var["SMPL"][var_filename_long]["Matrix Setup"]["IS"]["Concentration"].set(
                                concentration_is)

        if concentration_is != None:
            for isotope in file_isotopes:
                concentration_is = concentration_is
                sensitivity_is = self.container_analytical_sensitivity[var_filetype][var_datatype][var_filename_short][
                    var_focus][var_is]
                intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][
                    var_filename_short][var_focus][var_is]
                intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                    var_filename_short][var_focus][isotope]
                sensitivity_i_pre = self.container_analytical_sensitivity[var_filetype][var_datatype][
                    var_filename_short][var_focus][isotope]
                sensitivity_i = sensitivity_i_pre/sensitivity_is

                if (intensity_is*sensitivity_i) > 0:
                    concentration_i = (intensity_i*concentration_is)/(intensity_is*sensitivity_i)
                else:
                    concentration_i = np.nan

                self.container_concentration[var_filetype][var_datatype][var_filename_short][var_focus][
                    isotope] = concentration_i

                var_std_bg_i = self.container_intensity[var_filetype][var_datatype][var_filename_short]["BG SIGMA"][
                    isotope]
                key_std = var_focus + " SIGMA"
                var_std_mat_i = self.container_intensity[var_filetype][var_datatype][var_filename_short][key_std][
                    isotope]
                var_n_bg = self.container_intensity[var_filetype][var_datatype][var_filename_short]["N BG"][isotope]
                key_n = "N " + var_focus
                var_n_mat = self.container_intensity[var_filetype][var_datatype][var_filename_short][key_n][isotope]
                var_sigma_bg_i = var_std_bg_i/(var_n_bg**0.5)
                var_sigma_mat_i = var_std_mat_i/(var_n_mat**0.5)
                var_sigma = var_sigma_bg_i + var_sigma_mat_i

                if intensity_i > 0:
                    var_result_sigma_i = round((var_sigma*concentration_i)/intensity_i, 4)
                else:
                    var_result_sigma_i = 0.0

                key_sigma = "1 SIGMA " + var_focus
                self.container_concentration[var_filetype][var_datatype][var_filename_short][key_sigma][
                    isotope] = var_result_sigma_i

    def run_total_oxides_calculation(self, filetype, datatype, filename_short, list_isotopes, focus="MAT"):
        """ Calculates the element concentrations based on a normalized total oxide approach.
        Parameters
        ----------
        filetype : str
            The file category, e.g. STD
        datatype : str
            The data category, e.g. RAW
        filename_short : str
            The file as a short version (without the complete filepath)
        list_isotopes : list
            The list contains all measured isotopes that belong to the file.
        Returns
        -------
        """
        self.run_total_oxides_calculation_alternative2(
            var_filetype=filetype, var_datatype=datatype, var_filename_short=filename_short, var_focus=focus)
        helper_oxides = {}
        helper_oxides2 = {}
        for oxide in self.container_lists["Selected Oxides"]["All"]:
            if oxide not in helper_oxides:
                helper_oxides[oxide] = {
                    "Element": None, "Isotopes": [], "Intensities": {}, "Sensitivities": {}, "a": {},
                    "b": {}, "c": {}, "d": {}, "e": {}, "Concentrations": {}}
            key_element = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide)
            ref_element = key_element.group(1)
            if helper_oxides[oxide]["Element"] == None:
                helper_oxides[oxide]["Element"] = ref_element
            if ref_element not in helper_oxides2:
                helper_oxides2[ref_element] = []
            helper_oxides2[ref_element].append(oxide)

        for isotope in list_isotopes:
            key_element = re.search(r"(\D+)(\d+)", isotope)
            element = key_element.group(1)
            if element in helper_oxides2:
                for oxide in helper_oxides2[element]:
                    helper_oxides[oxide]["Isotopes"].append(isotope)
            else:
                print("ATTENTION - The element", element, "is not included in the list of elements for the 100 wt.% "
                                                          "oxides calculation.")

        self.container_oxides = helper_oxides

    def ma_get_concentration_ratio(self, var_filetype, var_datatype, var_file_short, var_file_long,
                                   mode="Specific"):
        """ Calculates the concentration ratio, C_i/C_is, based on the following two equations:
                1) Standard Files:  C_i = C_std_i/C_std_is
                2) Sample Files:    C_i = C_smpl_i/C_smpl_is

                Parameters
                ----------
                var_filetype : str
                    The file category, e.g. STD
                var_datatype : str
                    The data category, e.g. RAW
                var_file_short : str
                    The file as a short version (without the complete filepath)
                var_file_long : str
                    The file as the long version (with the complete filepath)

                Returns
                -------
                """
        if mode == "Specific":
            var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
            var_concentration_is = self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                var_is]
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                var_concentration_i = self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                    isotope]
                if var_concentration_is > 0:
                    var_result_i = var_concentration_i/var_concentration_is
                else:
                    var_result_i = np.nan

                self.container_concentration_ratio[var_filetype][var_datatype][var_file_short]["MAT"][
                    isotope] = var_result_i
        else:
            for var_filetype in ["SMPL"]:
                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                if var_filetype == "SMPL":
                                    var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                    var_id_selected = self.container_var["ID"]["Results Files"].get()
                                    #
                                    if var_id == var_id_selected or self.var_init_ma_datareduction == True:
                                        self.ma_get_concentration_ratio(
                                            var_filetype=var_filetype, var_datatype=var_datatype,
                                            var_file_short=var_file_short, var_file_long=var_file_long)
                                        var_result_i = self.container_concentration_ratio[var_filetype][var_datatype][
                                            var_file_short]["MAT"][isotope]
                                        helper_results.append(var_result_i)
                                else:
                                    self.ma_get_concentration_ratio(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long)
                                    var_result_i = self.container_concentration_ratio[var_filetype][var_datatype][
                                        var_file_short]["MAT"][isotope]
                                    helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)

                    self.container_concentration_ratio[var_filetype][var_datatype][isotope] = var_result_i

    def ma_get_lod(self, var_filetype, var_datatype, var_file_short, var_file_long, mode="Specific"):
        """ Calculates the Limit of Detection, LoD, based on the following two equations:
        1) Standard Files:  C_i = C_std_i/C_std_is
        2) Sample Files:    C_i = C_smpl_i/C_smpl_is

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)

        Returns
        -------
        """
        if mode == "Specific":
            if var_filetype == "STD":
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                for index, isotope in enumerate(file_isotopes):
                    var_n_bg = 0
                    var_n_mat = 0
                    helper_sigma_i = []

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short]["BG"]["Content"])
                    for key, items in condensed_intervals.items():
                        var_indices = items
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_bg += len(var_data)
                        helper_sigma_i.append(np.std(var_data, ddof=1))

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short]["MAT"]["Content"])
                    for key, items in condensed_intervals.items():
                        var_indices = items
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_mat += len(var_data)

                    var_concentration_i = self.container_concentration[var_filetype][var_datatype][var_file_short][
                        "MAT"][isotope]
                    var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        "MAT"][isotope]

                    if self.container_var["General Settings"]["LOD Selection"].get() == 0:
                        var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                            isotope]
                        var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                        parameter_list = [var_n_bg, var_n_mat, var_tau_i, var_intensity_i]
                        if any(v == 0 for v in parameter_list) == False:
                            var_result_i = (3.29*(
                                    var_intensity_bg_i*var_tau_i*var_n_mat*(1 + var_n_mat/var_n_bg))**(0.5) + 2.71)/(
                                                   var_n_mat*var_tau_i)*(var_concentration_i/var_intensity_i)
                        else:
                            var_result_i = 0.0
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i

                    elif self.container_var["General Settings"]["LOD Selection"].get() == 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_sigma_bg_i = np.mean(helper_sigma_i)
                        else:
                            var_sigma_bg_i = np.median(helper_sigma_i)

                        var_result_i = (3*var_sigma_bg_i*var_concentration_i)/(var_intensity_i)*(
                                1/var_n_bg + 1/var_n_mat)**(0.5)
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i

            elif var_filetype == "SMPL":
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                for index, isotope in enumerate(file_isotopes):
                    var_n_bg = 0
                    var_n_mat = 0
                    helper_sigma_i = []

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short]["BG"]["Content"])
                    for key, items in condensed_intervals.items():
                        var_indices = items
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_bg += len(var_data)
                        helper_sigma_i.append(np.std(var_data, ddof=1))

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short]["MAT"]["Content"])
                    for key, items in condensed_intervals.items():
                        var_indices = items
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_mat += len(var_data)

                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    var_concentration_is = self.container_concentration[var_filetype][var_datatype][var_file_short][
                        "MAT"][var_is]
                    var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        "MAT"][var_is]

                    if self.container_var["General Settings"]["LOD Selection"].get() == 0:
                        var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                            isotope]
                        var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                        var_sensitivity_i = \
                            self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                                "MAT"][isotope]
                        if var_sensitivity_i > 0:
                            var_result_i = (3.29*(
                                    var_intensity_bg_i*var_tau_i*var_n_mat*(1 + var_n_mat/var_n_bg))**(0.5) + 2.71)/(
                                                   var_n_mat*var_tau_i*var_sensitivity_i)*(
                                                       var_concentration_is/var_intensity_is)
                        else:
                            var_result_i = 0.0
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i

                    elif self.container_var["General Settings"]["LOD Selection"].get() == 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_sigma_bg_i = np.mean(helper_sigma_i)
                        else:
                            var_sigma_bg_i = np.median(helper_sigma_i)

                        var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_file_short]["MAT"][isotope]

                        var_result_i = (3*var_sigma_bg_i*var_concentration_is)/(var_sensitivity_i*var_intensity_is)*(
                                1/var_n_bg + 1/var_n_mat)**(0.5)
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                if var_filetype == "SMPL":
                                    var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                    var_id_selected = self.container_var["ID"]["Results Files"].get()
                                    if var_id == var_id_selected or self.var_init_ma_datareduction == True:
                                        self.ma_get_lod(
                                            var_filetype=var_filetype, var_datatype=var_datatype,
                                            var_file_short=var_file_short, var_file_long=var_file_long)
                                        var_result_i = self.container_lod[var_filetype][var_datatype][var_file_short][
                                            "MAT"][isotope]
                                        helper_results.append(var_result_i)
                                else:
                                    self.ma_get_lod(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long)
                                    var_result_i = self.container_lod[var_filetype][var_datatype][var_file_short][
                                        "MAT"][isotope]
                                    helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)

                    self.container_lod[var_filetype][var_datatype][isotope] = var_result_i

    def get_lod(self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus, mode="Specific"):
        """ Calculates the Limit of Detection, LoD, based on the following two equations:
        1) Standard Files:  C_i = C_std_i/C_std_is
        2) Sample Files:    C_i = C_smpl_i/C_smpl_is

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)

        Returns
        -------
        """
        if mode == "Specific":
            if var_filetype == "STD":
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                for index, isotope in enumerate(file_isotopes):
                    var_n_bg = 0
                    var_n_mat = 0
                    helper_sigma_i = []

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short]["BG"]["Content"])
                    for key, items in condensed_intervals.items():
                        var_indices = items
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_bg += len(var_data)
                        helper_sigma_i.append(np.std(var_data, ddof=1))

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short]["MAT"]["Content"])
                    for key, items in condensed_intervals.items():
                        var_indices = items
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_mat += len(var_data)

                    var_concentration_i = self.container_concentration[var_filetype][var_datatype][var_file_short][
                        "MAT"][isotope]
                    var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        "MAT"][isotope]

                    if self.container_var["General Settings"]["LOD Selection"].get() == 0:
                        var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                            isotope]
                        var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                        parameter_list = [var_n_bg, var_n_mat, var_tau_i, var_intensity_i]
                        if any(v == 0 for v in parameter_list) == False:
                            var_result_i = (3.29*(
                                    var_intensity_bg_i*var_tau_i*var_n_mat*(1 + var_n_mat/var_n_bg))**(0.5) + 2.71)/(
                                                   var_n_mat*var_tau_i)*(var_concentration_i/var_intensity_i)
                        else:
                            var_result_i = 0.0
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i

                    elif self.container_var["General Settings"]["LOD Selection"].get() == 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_sigma_bg_i = np.mean(helper_sigma_i)
                        else:
                            var_sigma_bg_i = np.median(helper_sigma_i)

                        var_result_i = (3*var_sigma_bg_i*var_concentration_i)/(var_intensity_i)*(
                                1/var_n_bg + 1/var_n_mat)**(0.5)
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][isotope] = var_result_i

            elif var_filetype == "SMPL":
                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                for index, isotope in enumerate(file_isotopes):
                    if index == 0:
                        var_n_bg = 0
                        var_n_mat = 0
                        helper_sigma_i = []

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short]["BG"]["Content"])
                        for key, items in condensed_intervals.items():
                            var_indices = items
                            var_key = "Data " + str(var_datatype)
                            var_data = self.container_spikes[var_file_short][isotope][var_key][
                                       var_indices[0]:var_indices[1] + 1]
                            var_n_bg += len(var_data)
                            helper_sigma_i.append(np.std(var_data, ddof=1))

                    if index == 0:
                        condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                            interval_set=self.container_helper[var_filetype][var_file_short][var_focus]["Content"])
                        for key, items in condensed_intervals.items():
                            var_indices = items
                            var_key = "Data " + str(var_datatype)
                            var_data = self.container_spikes[var_file_short][isotope][var_key][
                                       var_indices[0]:var_indices[1] + 1]
                            var_n_mat += len(var_data)

                    if self.pysills_mode == "MA":
                        var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    else:
                        if var_focus == "MAT":
                            var_is = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                        else:
                            var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()

                    var_concentration_is = self.container_concentration[var_filetype][var_datatype][var_file_short][
                        var_focus][var_is]
                    var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        var_focus][var_is]
                    var_sensitivity_is = self.container_analytical_sensitivity[var_filetype][var_datatype][
                        var_file_short]["MAT"][var_is]

                    if self.container_var["General Settings"]["LOD Selection"].get() == 0:
                        var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                            isotope]
                        var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())

                        if var_sensitivity_is > 0:
                            var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]/var_sensitivity_is
                        else:
                            var_sensitivity_i = 0.0

                        if None not in [var_concentration_is, var_sensitivity_i, var_intensity_is]:
                            if var_sensitivity_i > 0 and var_intensity_is > 0 and var_n_bg > 0:
                                var_result_i = ((3.29*
                                                (var_intensity_bg_i*var_tau_i*var_n_mat*(1 + var_n_mat/var_n_bg))**(0.5)
                                                + 2.71)/(var_n_mat*var_tau_i*var_sensitivity_i)*
                                                (var_concentration_is/var_intensity_is))
                            else:
                                var_result_i = np.nan
                        else:
                            var_result_i = np.nan

                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = var_result_i

                    elif self.container_var["General Settings"]["LOD Selection"].get() == 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_sigma_bg_i = np.mean(helper_sigma_i)
                        else:
                            var_sigma_bg_i = np.median(helper_sigma_i)

                        var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_file_short]["MAT"][isotope]

                        var_result_i = (3*var_sigma_bg_i*var_concentration_is)/(var_sensitivity_i*var_intensity_is)*(
                                1/var_n_bg + 1/var_n_mat)**(0.5)
                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = var_result_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                if self.pysills_mode == "MA":
                    list_focus = ["MAT"]
                    var_init_datareduction = self.var_init_ma_datareduction
                else:
                    if var_filetype == "STD":
                        list_focus = ["MAT"]
                    else:
                        list_focus = ["MAT", "INCL"]
                    if self.pysills_mode == "FI":
                        var_init_datareduction = self.var_init_fi_datareduction
                    else:
                        var_init_datareduction = self.var_init_mi_datareduction
                for focus in list_focus:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                var_srm_i = self.container_var["SRM"][isotope].get()
                                var_srm_file = None
                                if var_filetype == "STD":
                                    var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                                if var_srm_i == var_srm_file or var_filetype == "SMPL":
                                    if isotope in file_isotopes:
                                        if var_filetype == "SMPL":
                                            var_id = self.container_var[var_filetype][var_file_long]["ID"].get()
                                            var_id_selected = self.container_var["ID"]["Results Files"].get()
                                            if var_id == var_id_selected or var_init_datareduction == True:
                                                self.get_lod(
                                                    var_filetype=var_filetype, var_datatype=var_datatype,
                                                    var_file_short=var_file_short, var_file_long=var_file_long,
                                                    var_focus=focus)
                                                var_result_i = self.container_lod[var_filetype][var_datatype][
                                                    var_file_short][focus][isotope]
                                                helper_results.append(var_result_i)
                                        else:
                                            self.get_lod(
                                                var_filetype=var_filetype, var_datatype=var_datatype,
                                                var_file_short=var_file_short, var_file_long=var_file_long,
                                                var_focus=focus)
                                            var_result_i = self.container_lod[var_filetype][var_datatype][
                                                var_file_short][focus][isotope]
                                            helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)

                        self.container_lod[var_filetype][var_datatype][isotope] = var_result_i

    def ma_datareduction_files(self):  # MA - DATAREDUCTION FILES ######################################################
        ## Window Settings
        window_width = 1260
        window_height = 625
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        self.subwindow_ma_datareduction_files = tk.Toplevel(self.parent)
        self.subwindow_ma_datareduction_files.title("MINERAL ANALYSIS - Data Reduction")
        self.subwindow_ma_datareduction_files.geometry(var_geometry)
        self.subwindow_ma_datareduction_files.resizable(False, False)
        self.subwindow_ma_datareduction_files["bg"] = self.bg_colors["Super Dark"]
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_ma_datareduction_files, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_ma_datareduction_files, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            self.subwindow_ma_datareduction_files.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_ma_datareduction_files.grid_columnconfigure(i, minsize=column_min)
        #
        ################################################################################################################
        #
        start_row = 0
        start_column = 0
        #
        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="File Type Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Data Type Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 6, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Assemblage Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 8, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Focus Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 10, column_id=start_column,
            n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Result Selection", relief=tk.FLAT, fontsize="sans 10 bold")

        ## RADIOBUTTONS
        rb_01a = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["File Type"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Standard Files", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        rb_01b = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["File Type"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Sample Files", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        #
        rb_02a = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 4, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Data Type"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="RAW Data", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        rb_02b = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Data Type"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="SMOOTHED Data", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        #
        rb_04a = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 9, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Focus"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Mineral/Glass", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        #
        rb_05a = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 11, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Concentration", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        self.rb_conc_ratio = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 12, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Concentration Ratio", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        self.rb_lod = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 13, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=2,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Limit of Detection", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        rb_05d = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 14, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=3,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Intensity", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        self.rb_int_ratio = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 15, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=4,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Intensity Ratio", sticky="nesw",
            relief=tk.FLAT, command=self.ma_datareduction_tables)
        rb_05f = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 16, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=5,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Analytical Sensitivity",
            sticky="nesw", relief=tk.FLAT, command=self.ma_datareduction_tables)
        rb_05g = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 17, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=6,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Normalized Sensitivity",
            sticky="nesw", relief=tk.FLAT, command=self.ma_datareduction_tables)
        self.rb_rsf = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 18, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=7,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Relative Sensitivity Factor",
            sticky="nesw", relief=tk.FLAT, command=self.ma_datareduction_tables)

        ## OPTION MENUS
        if self.container_var["ID"]["Default SMPL"].get() != "Select ID":
            var_text = self.container_var["ID"]["Default SMPL"].get()
        else:
            var_text = "Select ID"

        list_id_found = []
        for var_file_long in self.container_lists["SMPL"]["Long"]:
            var_id_i = self.container_var["SMPL"][var_file_long]["ID"].get()
            if var_id_i not in list_id_found:
                list_id_found.append(var_id_i)

        if len(list_id_found) > 0:
            opt_03a = SE(
                parent=self.subwindow_ma_datareduction_files, row_id=start_row + 7, column_id=start_column, n_rows=1,
                n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
                var_iso=self.container_var["ID"]["Results Files"], option_list=list_id_found,
                text_set=var_text, fg_active=self.bg_colors["Dark Font"], bg_active=self.red_dark,
                command=lambda var_opt=self.container_var["ID"]["Results Files"]: self.change_id_results(var_opt))
            opt_03a["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            opt_03a.config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, highlightthickness=0)

        ## BUTTONS
        btn_06a = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 20, column_id=start_column, n_rows=2,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Export Results", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.calculation_report_setup)

        self.var_rb_01 = tk.IntVar()
        self.var_rb_01.set(1)
        self.var_rb_02 = tk.IntVar()
        self.var_rb_02.set(0)
        self.var_rb_03 = tk.IntVar()
        self.var_rb_03.set(0)

        btn_07c = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 23, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Sensitivity Drift", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.show_diagrams_sensitivity)
        btn_07d = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row + 22, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Detailed Data Analysis", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.detailed_data_analysis)

        ## FRAMES
        frm_a = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row, column_id=start_column + 11,
            n_rows=n_rows, n_columns=n_columns - 11, fg=self.bg_colors["Very Light"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)

        ## TREEVIEWS
        list_categories = ["Files"]
        list_categories.extend(self.container_lists["Measured Isotopes"]["All"])
        list_width = list(75*np.ones(len(list_categories)))
        list_width = [int(item) for item in list_width]
        list_width[0] = 125

        if len(list_categories) > 1:
            self.tv_results_files = SE(
                parent=self.subwindow_ma_datareduction_files, row_id=0, column_id=11, n_rows=24, n_columns=51,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
                n_categories=len(list_categories), text_n=list_categories,
                width_n=list_width, individual=True)

            scb_v = ttk.Scrollbar(self.subwindow_ma_datareduction_files, orient="vertical")
            scb_h = ttk.Scrollbar(self.subwindow_ma_datareduction_files, orient="horizontal")
            self.tv_results_files.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
            scb_v.config(command=self.tv_results_files.yview)
            scb_h.config(command=self.tv_results_files.xview)
            scb_v.grid(row=0, column=62, rowspan=24, columnspan=1, sticky="ns")
            scb_h.grid(row=24, column=11, rowspan=1, columnspan=51, sticky="ew")

            ## INITIALIZATION
            self.ma_datareduction_tables(init=True)
        else:
            rb_01a.configure(state="disabled")
            rb_01b.configure(state="disabled")
            rb_02a.configure(state="disabled")
            rb_02b.configure(state="disabled")
            rb_04a.configure(state="disabled")
            rb_05a.configure(state="disabled")
            self.rb_conc_ratio.configure(state="disabled")
            self.rb_lod.configure(state="disabled")
            rb_05d.configure(state="disabled")
            self.rb_int_ratio.configure(state="disabled")
            rb_05f.configure(state="disabled")
            rb_05g.configure(state="disabled")
            self.rb_rsf.configure(state="disabled")

            btn_06a.configure(state="disabled")
            btn_07c.configure(state="disabled")
            btn_07d.configure(state="disabled")

    def detailed_data_analysis(self):
        if self.pysills_mode == "MA":
            str_title_window = "MINERAL ANALYSIS - Detailed Data Analysis"
        elif self.pysills_mode == "FI":
            str_title_window = "FLUID INCLUSION ANALYSIS - Detailed Data Analysis"
        elif self.pysills_mode == "MI":
            str_title_window = "MELT INCLUSION ANALYSIS - Detailed Data Analysis"

        ## Window Settings
        window_width = 900
        window_height = 600
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_detailed_data_analysis = tk.Toplevel(self.parent)
        self.subwindow_detailed_data_analysis.title(str_title_window)
        self.subwindow_detailed_data_analysis.geometry(var_geometry)
        self.subwindow_detailed_data_analysis.resizable(False, False)
        self.subwindow_detailed_data_analysis["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_detailed_data_analysis, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_detailed_data_analysis, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_detailed_data_analysis.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_detailed_data_analysis.grid_columnconfigure(i, minsize=column_min)

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

        start_row = 0
        start_column = 0

        # LABELS
        lbl_01 = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Filename", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Experimental Data", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 6, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Experimental Focus", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 11, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Intensity Results", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 13, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Sensitivity Results", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_06 = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 15, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Composition Results", relief=tk.FLAT, fontsize="sans 10 bold")

        # RADIOBUTTONS
        rb_02a = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 4, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Datatype"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Original Data", sticky="nesw",
            relief=tk.FLAT, command=lambda var_rb=self.container_var["Detailed Data Analysis"]["Datatype"]:
            self.detailed_analysis_change_datatype(var_rb))
        rb_02b = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Datatype"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Smoothed Data", sticky="nesw",
            relief=tk.FLAT, command=lambda var_rb=self.container_var["Detailed Data Analysis"]["Datatype"]:
            self.detailed_analysis_change_datatype(var_rb))

        rb_03a = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 7, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Background", sticky="nesw",
            relief=tk.FLAT, command=lambda var_rb=self.container_var["Detailed Data Analysis"]["Focus"]:
            self.detailed_analysis_change_focus(var_rb))
        rb_03b = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 8, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Mineral / Matrix", sticky="nesw",
            relief=tk.FLAT, command=lambda var_rb=self.container_var["Detailed Data Analysis"]["Focus"]:
            self.detailed_analysis_change_focus(var_rb))
        rb_03c = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 9, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=2,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Inclusion", sticky="nesw",
            relief=tk.FLAT, command=lambda var_rb=self.container_var["Detailed Data Analysis"]["Focus"]:
            self.detailed_analysis_change_focus(var_rb))
        rb_03d = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 10, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=3,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Mixed Signal", sticky="nesw",
            relief=tk.FLAT, command=lambda var_rb=self.container_var["Detailed Data Analysis"]["Focus"]:
            self.detailed_analysis_change_focus(var_rb))

        # OPTION MENUS
        list_files_std = self.container_lists["STD"]["Short"]
        str_default_std = "Select Standard File"

        opt_01a = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Detailed Data Analysis"]["Filename STD"], option_list=list_files_std,
            text_set=str_default_std, fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["Detailed Data Analysis"]["Filename STD"]:
            self.detailed_analysis_select_file(var_opt))
        opt_01a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_01a.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        list_files_smpl = self.container_lists["SMPL"]["Short"]
        str_default_smpl = "Select Sample File"
        opt_01b = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Detailed Data Analysis"]["Filename SMPL"], option_list=list_files_smpl,
            text_set=str_default_smpl, fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["Detailed Data Analysis"]["Filename SMPL"]:
            self.detailed_analysis_select_file(var_opt))
        opt_01b["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_01b.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        list_intensity_parameter = ["Measured Intensity", "Intensity", "Intensity Ratio", "Intensity Noise",
                                    "\u03C3 Intensity"]
        str_default_intensity = "Select Parameter"
        opt_04a = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 12, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Detailed Data Analysis"]["Intensity Results"],
            option_list=list_intensity_parameter, text_set=str_default_intensity, fg_active=self.bg_colors["Dark Font"],
            bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["Detailed Data Analysis"]["Intensity Results"]:
            self.detailed_analysis_select_focus(var_opt))
        opt_04a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_04a.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        list_sensitivity_parameter = ["Analytical Sensitivity", "Normalized Sensitivity", "Relative Sensitivity Factor"]
        str_default_sensitivity = "Select Parameter"
        opt_05a = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 14, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Detailed Data Analysis"]["Sensitivity Results"],
            option_list=list_sensitivity_parameter, text_set=str_default_sensitivity,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["Detailed Data Analysis"]["Sensitivity Results"]:
            self.detailed_analysis_select_focus(var_opt))
        opt_05a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_05a.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        list_concentration_parameter = ["Concentration", "Concentration Ratio", "Concentration Noise",
                                        "Limit of Detection", "\u03C3 Concentration"]
        str_default_concentration = "Select Parameter"
        opt_05a = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row + 16, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Detailed Data Analysis"]["Concentration Results"],
            option_list=list_concentration_parameter, text_set=str_default_concentration,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["Detailed Data Analysis"]["Concentration Results"]:
            self.detailed_analysis_select_focus(var_opt))
        opt_05a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_05a.config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        # FRAMES
        frm_a = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row, column_id=start_column + 11,
            n_rows=n_rows, n_columns=n_columns - 11, fg=self.bg_colors["Very Light"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)

        # TREEVIEW
        list_categories = ["Isotope", "Value"]
        list_width = list(130*np.ones(len(list_categories)))
        list_width = [int(item) for item in list_width]
        list_width[0] = 90

        if len(list_categories) > 1:
            self.tv_results_detailed = SE(
                parent=self.subwindow_detailed_data_analysis, row_id=start_row, column_id=start_column + 11,
                n_rows=n_rows - 1, n_columns=11, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["White"]).create_treeview(
                n_categories=len(list_categories), text_n=list_categories,
                width_n=list_width, individual=True)

            scb_v = ttk.Scrollbar(self.subwindow_detailed_data_analysis, orient="vertical")
            scb_h = ttk.Scrollbar(self.subwindow_detailed_data_analysis, orient="horizontal")
            self.tv_results_detailed.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
            scb_v.config(command=self.tv_results_detailed.yview)
            scb_h.config(command=self.tv_results_detailed.xview)
            scb_v.grid(row=0, column=22, rowspan=n_rows - 1, columnspan=1, sticky="ns")
            scb_h.grid(row=n_rows - 1, column=11, rowspan=1, columnspan=11, sticky="ew")

        # INITIALIZATION
        self.last_category_parameter = "No"
        if self.pysills_mode == "MA":
            rb_03c.configure(state="disabled")
            rb_03d.configure(state="disabled")

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            entries_i = [isotope, 0.000]
            self.tv_results_detailed.insert("", tk.END, values=entries_i)

    def detailed_analysis_select_file(self, var_opt):
        self.container_var["Detailed Data Analysis"]["Datatype"].set(0)
        self.container_var["Detailed Data Analysis"]["Focus"].set(1)

        if var_opt in self.container_lists["STD"]["Short"]:
            self.container_var["Detailed Data Analysis"]["Filename SMPL"].set("Select Sample File")
        elif var_opt in self.container_lists["SMPL"]["Short"]:
            self.container_var["Detailed Data Analysis"]["Filename STD"].set("Select Standard File")

        str_last_category = self.last_category_parameter + " Results"
        if str_last_category in ["Intensity Results", "Sensitivity Results", "Concentration Results"]:
            self.detailed_analysis_select_focus(var_opt=self.container_var["Detailed Data Analysis"][str_last_category])
        else:
            self.container_var["Detailed Data Analysis"]["Intensity Results"].set("Select Parameter")
            self.container_var["Detailed Data Analysis"]["Sensitivity Results"].set("Select Parameter")
            self.container_var["Detailed Data Analysis"]["Concentration Results"].set("Select Parameter")

    def detailed_analysis_change_datatype(self, var_rb):
        if var_rb.get() == 0:
            str_datatype = "RAW"
        else:
            str_datatype = "SMOOTHED"

        str_last_category = self.last_category_parameter + " Results"
        self.detailed_analysis_select_focus(
            var_opt=self.container_var["Detailed Data Analysis"][str_last_category], var_datatype=str_datatype)

    def detailed_analysis_change_focus(self, var_rb):
        if var_rb.get() == 0:
            str_focus = "BG"
        elif var_rb.get() == 1:
            str_focus = "MAT"
        elif var_rb.get() == 2:
            str_focus = "INCL"
        else:
            str_focus = "MIX"

        str_last_category = self.last_category_parameter + " Results"
        self.detailed_analysis_select_focus(
            var_opt=self.container_var["Detailed Data Analysis"][str_last_category], var_focus=str_focus)

    def detailed_analysis_select_focus(self, var_opt, var_datatype=None, var_focus=None):
        # Cleaning
        if len(self.tv_results_detailed.get_children()) > 0:
            for item in self.tv_results_detailed.get_children():
                self.tv_results_detailed.delete(item)

        # Initialization
        str_filename_std_short = self.container_var["Detailed Data Analysis"]["Filename STD"].get()
        str_filename_smpl_short = self.container_var["Detailed Data Analysis"]["Filename SMPL"].get()

        if str_filename_std_short != "Select Standard File":
            str_filename_short = str_filename_std_short
            str_filetype = "STD"
        else:
            str_filename_short = str_filename_smpl_short
            str_filetype = "SMPL"

        file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]

        if var_datatype == None:
            if self.container_var["Detailed Data Analysis"]["Datatype"].get() == 0:
                str_datatype = "RAW"
            else:
                str_datatype = "SMOOTHED"
        else:
            str_datatype = var_datatype

        if var_focus == None:
            if self.container_var["Detailed Data Analysis"]["Focus"].get() == 0:
                str_focus = "BG"
            elif self.container_var["Detailed Data Analysis"]["Focus"].get() == 1:
                str_focus = "MAT"
            elif self.container_var["Detailed Data Analysis"]["Focus"].get() == 2:
                str_focus = "INCL"
            else:
                str_focus = "MIX"
        else:
            str_focus = var_focus

        if type(var_opt) != str:
            var_opt = var_opt.get()

        # Algorithm
        if var_opt in ["Measured Intensity", "Intensity", "Intensity Ratio", "Intensity Noise", "\u03C3 Intensity"]:
            self.container_var["Detailed Data Analysis"]["Sensitivity Results"].set("Select Parameter")
            self.container_var["Detailed Data Analysis"]["Concentration Results"].set("Select Parameter")
            self.last_category_parameter = "Intensity"

            if var_opt == "Measured Intensity":
                for isotope in file_isotopes:
                    value_i = self.container_intensity[str_filetype][str_datatype][str_filename_short][str_focus][
                        isotope]
                    entries_i = [isotope, round(value_i, 4)]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "Intensity":
                for isotope in file_isotopes:
                    value_i = self.container_intensity_corrected[str_filetype][str_datatype][str_filename_short][
                        str_focus][isotope]
                    entries_i = [isotope, round(value_i, 4)]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "Intensity Ratio":
                for isotope in file_isotopes:
                    value_i = self.container_intensity_ratio[str_filetype][str_datatype][str_filename_short][
                        str_focus][isotope]
                    entries_i = [isotope, f"{value_i:.{4}E}"]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "Intensity Noise":
                pass
            elif var_opt == "\u03C3 Intensity":
                pass
        elif var_opt in ["Analytical Sensitivity", "Normalized Sensitivity", "Relative Sensitivity Factor"]:
            self.container_var["Detailed Data Analysis"]["Intensity Results"].set("Select Parameter")
            self.container_var["Detailed Data Analysis"]["Concentration Results"].set("Select Parameter")
            self.last_category_parameter = "Sensitivity"
            if var_opt == "Analytical Sensitivity":
                for isotope in file_isotopes:
                    if str_focus in self.container_analytical_sensitivity[str_filetype][str_datatype][
                        str_filename_short]:
                        value_i = self.container_analytical_sensitivity[str_filetype][str_datatype][str_filename_short][
                            str_focus][isotope]
                    else:
                        value_i = None

                    if value_i != None:
                        entries_i = [isotope, round(value_i, 4)]
                    else:
                        entries_i = [isotope, "undefined"]

                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "Normalized Sensitivity":
                for isotope in file_isotopes:
                    value_i = self.container_normalized_sensitivity[str_filetype][str_datatype][str_filename_short][
                        str_focus][isotope]
                    entries_i = [isotope, round(value_i, 4)]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "Relative Sensitivity Factor":
                for isotope in file_isotopes:
                    value_i = self.container_rsf[str_filetype][str_datatype][str_filename_short][str_focus][isotope]
                    entries_i = [isotope, f"{value_i:.{4}E}"]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
        elif var_opt in ["Concentration", "Concentration Ratio", "Concentration Noise", "Limit of Detection",
                         "\u03C3 Concentration"]:
            self.container_var["Detailed Data Analysis"]["Intensity Results"].set("Select Parameter")
            self.container_var["Detailed Data Analysis"]["Sensitivity Results"].set("Select Parameter")
            self.last_category_parameter = "Concentration"

            if var_opt == "Concentration":
                for isotope in file_isotopes:
                    value_i = self.container_concentration[str_filetype][str_datatype][str_filename_short][
                        str_focus][isotope]
                    lod_i = self.container_lod[str_filetype][str_datatype][str_filename_short][str_focus][isotope]
                    if value_i >= lod_i:
                        entries_i = [isotope, round(value_i, 4)]
                    else:
                        entries_i = [isotope, str(round(value_i, 4)) + " < LoD"]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "Concentration Ratio":
                for isotope in file_isotopes:
                    value_i = self.container_concentration_ratio[str_filetype][str_datatype][str_filename_short][
                        str_focus][isotope]
                    entries_i = [isotope, f"{value_i:.{4}E}"]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "Concentration Noise":
                pass
            elif var_opt == "Limit of Detection":
                for isotope in file_isotopes:
                    value_i = self.container_lod[str_filetype][str_datatype][str_filename_short][str_focus][isotope]
                    entries_i = [isotope, round(value_i, 4)]
                    self.tv_results_detailed.insert("", tk.END, values=entries_i)
            elif var_opt == "\u03C3 Concentration":
                pass

    def about_pysills(self):
        ## Window Settings
        window_width = 620
        window_height = 550
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_about_pysills = tk.Toplevel(self.parent)
        self.subwindow_about_pysills.title("PySILLS - About")
        self.subwindow_about_pysills.geometry(var_geometry)
        self.subwindow_about_pysills.resizable(False, False)
        self.subwindow_about_pysills["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_about_pysills, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_about_pysills, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_about_pysills.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_about_pysills.grid_columnconfigure(i, minsize=column_min)

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

        start_row = 0
        start_column = 0

        # LABELS
        str_lbl_01 = self.language_dict["Development"][self.var_language]
        str_lbl_02 = self.language_dict["Additional Information"][self.var_language]
        str_lbl_03 = self.language_dict["Citation"][self.var_language]
        str_lbl_04 = self.language_dict["References"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_about_pysills, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01a = SE(
            parent=self.subwindow_about_pysills, row_id=start_row, column_id=start_column + 10, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Maximilian A. Beeskow", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01b = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 2, column_id=start_column + 10, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Thomas Wagner", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01c = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 3, column_id=start_column + 10, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Tobias Fusswinkel", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001a = SE(
            parent=self.subwindow_about_pysills, row_id=start_row, column_id=start_column + 20, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="RWTH Aachen University", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001b = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 2, column_id=start_column + 20, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="RWTH Aachen University", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_001b = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 3, column_id=start_column + 20, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="RWTH Aachen University", relief=tk.FLAT, fontsize="sans 10 bold")

        lbl_02 = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02a = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 5, column_id=start_column + 11, n_rows=1,
            n_columns=10, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="PySILLS on GitHub", relief=tk.FLAT, fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_02b = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 6, column_id=start_column + 11, n_rows=1,
            n_columns=10, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="PySILLS on ReadTheDocs", relief=tk.FLAT, fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_02c = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 7, column_id=start_column + 11, n_rows=1,
            n_columns=10, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="PySILLS on YouTube", relief=tk.FLAT, fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_02d = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 8, column_id=start_column + 11, n_rows=1,
            n_columns=10, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="PySILLS on Blogger", relief=tk.FLAT, fontsize="sans 10 bold underline", link=True, anchor=tk.W)

        lbl_02a.bind("<Button-1>", self.callback_github)
        lbl_02b.bind("<Button-1>", self.callback_readthedocs)
        lbl_02c.bind("<Button-1>", self.callback_youtube)
        lbl_02d.bind("<Button-1>", self.callback_readthedocs)

        lbl_03 = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 10, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03a = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 10, column_id=start_column + 11, n_rows=1,
            n_columns=20, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="If you use PySILLS for your work, please cite the following", relief=tk.FLAT,
            fontsize="sans 10 bold", anchor=tk.W)
        lbl_03b = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 11, column_id=start_column + 11, n_rows=1,
            n_columns=20, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="journal article:", relief=tk.FLAT,
            fontsize="sans 10 bold", anchor=tk.W)
        lbl_03cb = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 12, column_id=start_column + 11, n_rows=1,
            n_columns=20, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Placeholder Journal Article", relief=tk.FLAT,
            fontsize="sans 10 bold", anchor=tk.W)

        lbl_04 = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 14, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04a = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 14, column_id=start_column + 11, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="SILLS Equation Summary", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_04b = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 15, column_id=start_column + 11, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Guillong et al. (2008)", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_04c = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 16, column_id=start_column + 11, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Heinrich et al. (2003)", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_04d = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 17, column_id=start_column + 11, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Longerich et al. (1996)", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_04e = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 18, column_id=start_column + 11, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Pettke et al. (2012)", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_04f = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 19, column_id=start_column + 11, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Halter et al. (2002)", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_04g = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 20, column_id=start_column + 11, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Borisova et al. (2021)", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_04h = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 14, column_id=start_column + 21, n_rows=1,
            n_columns=9, fg=self.accent_color, bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Liu et al. (2024)", relief=tk.FLAT,
            fontsize="sans 10 bold underline", link=True, anchor=tk.W)

        lbl_04a.bind("<Button-1>", self.callback_sills)
        lbl_04b.bind("<Button-1>", self.callback_guillong2008)
        lbl_04c.bind("<Button-1>", self.callback_heinrich2003)
        lbl_04d.bind("<Button-1>", self.callback_longerich1996)
        lbl_04e.bind("<Button-1>", self.callback_pettke2012)
        lbl_04f.bind("<Button-1>", self.callback_halter2002)
        lbl_04g.bind("<Button-1>", self.callback_borisova2021)
        lbl_04h.bind("<Button-1>", self.callback_liu2024)

    def callback_github(self, event):
        webbrowser.open_new(r"https://github.com/MABeeskow/PySILLS")

    def callback_readthedocs(self, event):
        webbrowser.open_new(r"https://pysills.readthedocs.io/en/latest/")

    def callback_youtube(self, event):
        webbrowser.open_new(r"https://www.youtube.com/@PySILLS")

    def callback_blogger(self, event):
        webbrowser.open_new(r"https://pysills.blogspot.com/")

    def callback_sills(self, event):
        webbrowser.open_new(r"https://mineralsystems.ethz.ch/software/sills.html")

    def callback_guillong2008(self, event):
        webbrowser.open_new(r"https://www.semanticscholar.org/paper/SILLS%3A-A-MATLAB-based-program-for-the-reduction-"
                            r"of-Guillong-Meier/1949b62d2282894b842ec5e94f7f6c759dd89865")

    def callback_heinrich2003(self, event):
        webbrowser.open_new(r"https://www.sciencedirect.com/science/article/pii/S001670370300084X")

    def callback_longerich1996(self, event):
        webbrowser.open_new(r"https://pubs.rsc.org/en/content/articlelanding/1996/ja/ja9961100899")

    def callback_pettke2012(self, event):
        webbrowser.open_new(r"https://www.sciencedirect.com/science/article/pii/S016913681100134X")

    def callback_halter2002(self, event):
        webbrowser.open_new(r"https://www.sciencedirect.com/science/article/pii/S0009254101003722")

    def callback_borisova2021(self, event):
        webbrowser.open_new(r"https://ejm.copernicus.org/articles/33/305/2021/")

    def callback_liu2024(self, event):
        webbrowser.open_new(r"https://www.sciencedirect.com/science/article/pii/S0009254123005648?via%3Dihub")

    def change_id_results(self, var_opt, mode="MA"):
        if mode == "MA":
            self.ma_datareduction_tables()
        elif mode == "FI":
            self.fi_datareduction_tables()

    def calculation_report_setup(self):
        ## Window Settings
        window_width = 260
        window_height = 225
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        subwindow_report_setup = tk.Toplevel(self.parent)
        subwindow_report_setup.title("Calculation Report - Setup")
        subwindow_report_setup.geometry(var_geometry)
        subwindow_report_setup.resizable(False, False)
        subwindow_report_setup["bg"] = self.bg_colors["Super Dark"]
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_report_setup, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_report_setup, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            subwindow_report_setup.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_report_setup.grid_columnconfigure(i, minsize=column_min)
        #
        ################################################################################################################
        #
        start_row = 0
        start_column = 0
        #
        ## LABELS
        lbl_01 = SE(
            parent=subwindow_report_setup, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=12, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Calculation Report Setup", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_report_setup, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=12, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Results sorted by ...", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        ## RADIOBUTTONS
        rb_01a = SE(
            parent=subwindow_report_setup, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=12, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.rb_report, value_rb=0, color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"],
            text="All results in one file", sticky="nesw", relief=tk.FLAT)
        rb_01b = SE(
            parent=subwindow_report_setup, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=12, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.rb_report, value_rb=1, color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"],
            text="file type (STD / SMPL)", sticky="nesw", relief=tk.FLAT)
        rb_01c = SE(
            parent=subwindow_report_setup, row_id=start_row + 4, column_id=start_column, n_rows=1,
            n_columns=12, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.rb_report, value_rb=2, color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"],
            text="data type (RAW / SMOOTHED)", sticky="nesw", relief=tk.FLAT)

        ## BUTTONS
        if self.pysills_mode == "MA":
            btn_06a = SE(
                parent=subwindow_report_setup, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=12,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Export Results", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.ma_export_calculation_report)
        elif self.pysills_mode == "FI":
            btn_06a = SE(
                parent=subwindow_report_setup, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=12,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Export Results", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.fi_export_calculation_report)
        elif self.pysills_mode == "MI":
            pass
        elif self.pysills_mode == "OA":
            pass

    #
    ########################################################################################################################
    # FLUID INCLUSION ANALYSIS #############################################################################################
    ########################################################################################################################
    def fi_settings(self):
        if self.file_system_need_update:
            path = os.getcwd()
            path = self.path_pysills
            parent = os.path.dirname(path)
            if self.demo_mode:
                self.var_opt_icp.set("Agilent 7900s")
                self.select_icp_ms(var_opt=self.var_opt_icp)
                fi_demo_files = {"ALL": [], "STD": [], "SMPL": []}

                try:
                    folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")
                    folder_path = folder_path.replace("\\", "/")
                    demo_files = os.listdir(path=folder_path)
                except:
                    if "pysills" not in self.path_pysills_main:
                        folder_path = os.path.join(self.path_pysills_main, "pysills", "lib", "demo_files")
                    else:
                        folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")

                    if self.var_os == "win32":
                        folder_path = folder_path.replace("\\", "/")

                    demo_files = os.listdir(path=folder_path)

                for file in demo_files:
                    if file.startswith("demo_fi"):
                        #folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")
                        #folder_path = self.path_pysills_main + str(r"/lib/demo_files/")
                        path_complete = os.path.join(folder_path, file)
                        if "_copy" not in path_complete:
                            path_raw = pathlib.PureWindowsPath(path_complete)
                            fi_demo_files["ALL"].append(str(path_raw.as_posix()))

                # try:
                #     demo_files = os.listdir(path=self.path_pysills_main + str("/lib/demo_files/"))
                # except:
                #     path += "/pysills"
                #     demo_files = os.listdir(path=path + str("/demo_files/"))
                #
                # for file in demo_files:
                #     if file.startswith("demo_fi"):
                #         path_complete = os.path.join(self.path_pysills_main + str("/lib/demo_files/"), file)
                #         if "_copy" not in path_complete:
                #             path_raw = pathlib.PureWindowsPath(path_complete)
                #             fi_demo_files["ALL"].append(str(path_raw.as_posix()))

                fi_demo_files["ALL"].sort()
                fi_demo_files["STD"].extend(fi_demo_files["ALL"][:4])
                fi_demo_files["STD"].extend(fi_demo_files["ALL"][-4:])
                fi_demo_files["SMPL"].extend(fi_demo_files["ALL"][4:-4])

                self.list_std = fi_demo_files["STD"]
                self.list_smpl = fi_demo_files["SMPL"]

            if len(self.list_std) > 0:
                self.fi_current_file_std = self.list_std[0]

            if len(self.list_smpl) > 0:
                self.fi_current_file_smpl = self.list_smpl[0]

            for file_std in self.list_std:
                file_parts = file_std.split("/")
                if file_std not in self.container_lists["STD"]["Long"]:
                    self.container_lists["STD"]["Long"].append(file_std)
                    self.container_lists["STD"]["Short"].append(file_parts[-1])
                if self.demo_mode:
                    self.lb_std.insert(tk.END, file_parts[-1])

                for item in ["Quickview", "File Setup", "Results Intensity", "Results Concentration",
                             "Results Sensitivity", "SE STD", "SE SMPL"]:
                    self.container_var["Subwindows"][self.pysills_mode][item] = {}

            for file_smpl in self.list_smpl:
                file_parts = file_smpl.split("/")
                if file_smpl not in self.container_lists["SMPL"]["Long"]:
                    self.container_lists["SMPL"]["Long"].append(file_smpl)
                    self.container_lists["SMPL"]["Short"].append(file_parts[-1])
                if self.demo_mode:
                    self.lb_smpl.insert(tk.END, file_parts[-1])

            for file_std in self.list_std:
                file_parts = file_std.split("/")
                if self.file_loaded == False:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_exmpl = DE(filename_long=file_std).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_exmpl = DE(filename_long=file_std).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                else:
                    file_parts = file_std.split("/")
                    try:
                        df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]
                    except:
                        print("File (" + str(file_std) + str(")"), "cannot be read.")

                self.times = DE().get_times(dataframe=df_exmpl)
                df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
                self.container_lists["ISOTOPES"] = df_isotopes
                self.container_lists["Measured Isotopes"][file_parts[-1]] = df_isotopes
                self.container_lists["Measured Isotopes"]["All"] = self.container_lists["ISOTOPES"]

                for isotope in self.container_lists["Measured Isotopes"][file_parts[-1]]:
                    if isotope.isdigit():
                        print("There is a problem with an isotope that is probably just a number. "
                              "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                        self.container_lists["Measured Isotopes"][file_parts[-1]].remove(isotope)
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        if key_element != None:
                            element = key_element.group(1)
                            if element not in self.container_lists["Measured Elements"]["All"]:
                                self.container_lists["Measured Elements"]["All"].append(element)

            for file_smpl in self.list_smpl:
                file_parts = file_smpl.split("/")
                if self.file_loaded == False:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_exmpl = DE(filename_long=file_smpl).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_exmpl = DE(filename_long=file_smpl).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                else:
                    file_parts = file_smpl.split("/")
                    try:
                        df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]
                    except:
                        print("File (" + str(file_smpl) + str(")"), "cannot be read.")

                self.times = DE().get_times(dataframe=df_exmpl)
                df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
                self.container_lists["ISOTOPES"] = df_isotopes
                self.container_lists["Measured Isotopes"][file_parts[-1]] = df_isotopes
                self.container_lists["Measured Isotopes"]["All"] = self.container_lists["ISOTOPES"]

                for isotope in self.container_lists["Measured Isotopes"][file_parts[-1]]:
                    if isotope.isdigit():
                        print("There is a problem with an isotope that is probably just a number. "
                              "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                        self.container_lists["Measured Isotopes"][file_parts[-1]].remove(isotope)
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        if key_element != None:
                            element = key_element.group(1)
                            if element not in self.container_lists["Measured Elements"]["All"]:
                                self.container_lists["Measured Elements"]["All"].append(element)

            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                if key_element != None:
                    element = key_element.group(1)
                    if element not in self.container_lists["Measured Elements"]["All"]:
                        self.container_lists["Measured Elements"]["All"].append(element)
                if isotope.isdigit():
                    print("There is a problem with an isotope (->", isotope, "<-) that is probably just a number. "
                          "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                else:
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    if key_element != None:
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"]["All"]:
                            self.container_lists["Measured Elements"]["All"].append(element)

            for filename_short in self.container_lists["STD"]["Short"]:
                self.container_lists["Measured Elements"][filename_short] = {}
                self.container_lists["Measured Isotopes"][filename_short] = df_isotopes
                for isotope in self.container_lists["Measured Isotopes"][filename_short]:
                    if isotope.isdigit():
                        pass
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"][filename_short]:
                            self.container_lists["Measured Elements"][filename_short][element] = [isotope]
                        else:
                            if isotope not in self.container_lists["Measured Elements"][filename_short][element]:
                                self.container_lists["Measured Elements"][filename_short][element].append(isotope)

            for filename_short in self.container_lists["SMPL"]["Short"]:
                self.container_lists["Measured Elements"][filename_short] = {}
                self.container_lists["Measured Isotopes"][filename_short] = df_isotopes
                for isotope in self.container_lists["Measured Isotopes"][filename_short]:
                    if isotope.isdigit():
                        pass
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"][filename_short]:
                            self.container_lists["Measured Elements"][filename_short][element] = [isotope]
                        else:
                            if isotope not in self.container_lists["Measured Elements"][filename_short][element]:
                                self.container_lists["Measured Elements"][filename_short][element].append(isotope)

            self.define_isotope_colors()
        else:
            self.fi_current_file_std = self.container_lists["STD"]["Long"][0]
            self.fi_current_file_smpl = self.container_lists["SMPL"]["Long"][0]
            self.define_isotope_colors()

        ## Window Settings
        window_width = 1340
        window_height = 1000
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_fi_settings = tk.Toplevel(self.parent)
        self.subwindow_fi_settings.title("FLUID INCLUSION ANALYSIS - Setup")
        self.subwindow_fi_settings.geometry(var_geometry)
        self.subwindow_fi_settings.resizable(False, False)
        self.subwindow_fi_settings["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_fi_settings, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_fi_settings, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_fi_settings.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_fi_settings.grid_columnconfigure(i, minsize=column_min)

        ## INITIALIZATION
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            if isotope.isdigit():
                pass
            else:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)

                if element not in self.container_lists["Elements"]:
                    self.container_lists["Elements"].append(element)
                if element not in self.container_lists["Measured Elements"]:
                    self.container_lists["Measured Elements"][element] = []
                if isotope not in self.container_lists["Measured Elements"][element]:
                    self.container_lists["Measured Elements"][element].append(isotope)
                if "Cations" not in self.container_lists["Measured Elements"]:
                    self.container_lists["Measured Elements"]["Cations"] = {}
                if element in ["Li", "Na", "K", "Rb", "Cs", "Ag", "Tl"]:
                    self.container_lists["Measured Elements"]["Cations"][element] = {"Cl": element + "Cl"}
                if element in ["Be", "Mg", "Ca", "Sr", "Ba", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ge", "Pd", "Cd", "Sn",
                               "W", "Os", "Pt", "Hg", "Pb"]:
                    self.container_lists["Measured Elements"]["Cations"][element] = {"Cl": element + "Cl2"}
                if element in ["Sc", "Y", "B", "Al", "Ga", "In", "Ti", "V", "Cr", "Ga", "Mo", "Ru", "Rh", "Re", "Ir",
                               "Au", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm" "Yb",
                               "Lu"]:
                    self.container_lists["Measured Elements"]["Cations"][element] = {"Cl": element + "Cl3"}
                if element in ["Zr", "Hf"]:
                    self.container_lists["Measured Elements"]["Cations"][element] = {"Cl": element + "Cl4"}
                if element in ["Nb", "Ta"]:
                    self.container_lists["Measured Elements"]["Cations"][element] = {"Cl": element + "Cl5"}

                if isotope not in self.container_var["Spike Elimination"]["Threshold"]:
                    self.container_var["Spike Elimination"]["Threshold"][isotope] = tk.StringVar()
                    self.container_var["Spike Elimination"]["Threshold"][isotope].set(var_threshold.get())

        ## Static
        # Build section 'Project Information'
        var_project_information = {"Row start": 0, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_project_information(var_geometry_info=var_project_information)
        # Build section 'Standard Reference Material'
        var_standard_reference_material = {"Row start": 3, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_standard_reference_material(var_geometry_info=var_standard_reference_material)
        # Build section 'Matrix Settings'
        var_sample_settings = {"Row start": 6, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_sample_settings(var_geometry_info=var_sample_settings)
        # Build section 'Quantification Method'
        var_quantification_method = {"Row start": 8, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_quantification_method(var_geometry_info=var_quantification_method)
        # Build section 'Assemblage Setup'
        var_assemblage_setup = {"Row start": 12, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_assemblage_setup(var_geometry_info=var_assemblage_setup)
        # Build section 'Dwell Time Setup'
        var_dwell_time_setup = {"Row start": 14, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_dwell_time_setup(var_geometry_info=var_dwell_time_setup)
        # Build section 'Calculation Window (Background) Setup'
        var_calculation_window_bg_setup = {"Row start": 16, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_calculation_window_bg(var_geometry_info=var_calculation_window_bg_setup)
        # Build section 'Calculation Window (Matrix) Setup'
        var_calculation_window_mat_setup = {"Row start": 20, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_calculation_window_smpl(var_geometry_info=var_calculation_window_mat_setup)
        # Build section 'Spike Elimination Setup'
        var_spike_elimination_setup = {"Row start": 24, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_spike_elimination_setup(var_geometry_info=var_spike_elimination_setup)
        # Build section 'Check-Up'
        var_checkup = {"Row start": 31, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_checkup_feature(var_geometry_info=var_checkup)
        # Build section 'Acquisition Times'
        var_acquisition_times_check = {"Row start": 18, "Column start": 48, "N rows": 1, "N columns": 18}
        self.place_acquisition_times_check(var_geometry_info=var_acquisition_times_check)
        # Build section 'Standard Files'
        var_standard_files = {"Row start": 0, "Column start": 19, "N rows": 16, "N columns": 28}
        self.place_standard_files_table(var_geometry_info=var_standard_files)
        # Build section 'Sample Files'
        var_sample_files = {"Row start": 18, "Column start": 19, "N rows": 19, "N columns": 28}
        self.place_sample_files_table(var_geometry_info=var_sample_files)
        # Build section 'Time-Signal Diagram Checker'
        self.define_isotope_colors()
        var_time_signal_diagram_check = {"Row start": 26, "Column start": 48, "N rows": 1, "N columns": 18}
        self.place_time_signal_plot_checker(var_geometry_info=var_time_signal_diagram_check)
        # Build section 'Measured Isotopes'
        var_measured_isotopes = {"Row start": 1, "Column start": 48, "N rows": 16, "N columns": 18}
        self.place_measured_isotopes_overview(var_geometry_info=var_measured_isotopes)

        ## INITIALIZATION
        self.btn_save_project.configure(state="normal")

        self.select_spike_elimination(
            var_opt=self.container_var["Spike Elimination Method"].get(),
            start_row=var_spike_elimination_setup["Row start"], mode="FI")

        if self.file_loaded:
            self.fi_select_srm_initialization()
            try:
                if len(self.container_spikes[filename_short]) > 0:
                    pass
                else:
                    if self.copied_file == False:
                        for filetype in ["STD", "SMPL"]:
                            if self.container_var["Spike Elimination"][filetype]["State"]:
                                if self.container_var["Spike Elimination Method"].get() in [
                                    "Grubbs-Test (SILLS)", "Grubbs-Test", "PySILLS Spike Finder", "Grubbs test",
                                    "Whisker analysis"]:
                                    var_method = "Grubbs"
                                    self.spike_elimination_all(filetype=filetype, algorithm=var_method)
            except:
                print("Problem with settings window creation. It has to be fixed one day.")
        else:
            self.fi_select_is_default(var_opt=self.container_var["IS"]["Default STD"].get())
            self.fi_select_id_default(var_opt=self.container_var["ID"]["Default SMPL"].get())

            if self.container_var["SRM"]["default"][0].get() != "Select SRM":
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][0].get())
            if self.container_var["SRM"]["default"][1].get() != "Select SRM":
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][1].get(), mode="ISOTOPES")
            if self.demo_mode:
                self.container_var["SRM"]["default"][0].set("NIST 610 (GeoReM)")
                self.container_var["SRM"]["default"][1].set("NIST 610 (GeoReM)")
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][0].get())
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][1].get(), mode="ISOTOPES")

        self.file_system_need_update = False
        self.select_opt_inclusion_is_quantification(
            var_opt="Mass Balance", dict_geometry_info=var_quantification_method)
        self.select_opt_inclusion_quantification(
            var_opt="Matrix-only Tracer (SILLS)", dict_geometry_info=var_quantification_method)

        if self.demo_mode:
            for index, filename_std_long in enumerate(self.container_lists["STD"]["Long"]):
                self.container_var["STD"][filename_std_long]["SRM"].set("NIST 610 (GeoReM)")
                if index in [2, 3, 6, 7]:
                    self.container_var["STD"][filename_std_long]["SRM"].set("Scapolite 17")

            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["IS Data"]["IS"].set("Na23")

            self.container_var["SRM"]["Cl35"].set("Scapolite 17")
            self.container_var["SRM"]["Br81"].set("Scapolite 17")

        self.build_srm_database()

    ####################################################################################################################
    ### MELT INCLUSIONS ################################################################################################
    ####################################################################################################################

    def mi_settings(self):
        if self.file_system_need_update:
            path = os.getcwd()
            path = self.path_pysills
            parent = os.path.dirname(path)
            if self.demo_mode:
                self.var_opt_icp.set("Agilent 7900s")
                self.select_icp_ms(var_opt=self.var_opt_icp)
                mi_demo_files = {"ALL": [], "STD": [], "SMPL": []}

                try:
                    folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")
                    folder_path = folder_path.replace("\\", "/")
                    demo_files = os.listdir(path=folder_path)
                except:
                    if "pysills" not in self.path_pysills_main:
                        folder_path = os.path.join(self.path_pysills_main, "pysills", "lib", "demo_files")
                    else:
                        folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")

                    if self.var_os == "win32":
                        folder_path = folder_path.replace("\\", "/")

                    demo_files = os.listdir(path=folder_path)

                for file in demo_files:
                    if file.startswith("demo_mi"):
                        #folder_path = os.path.join(self.path_pysills_main, "lib", "demo_files")
                        #folder_path = self.path_pysills_main + str(r"/lib/demo_files/")
                        path_complete = os.path.join(folder_path, file)
                        if "_copy" not in path_complete:
                            path_raw = pathlib.PureWindowsPath(path_complete)
                            mi_demo_files["ALL"].append(str(path_raw.as_posix()))

                # try:
                #     demo_files = os.listdir(path=self.path_pysills_main + str("/lib/demo_files/"))
                # except:
                #     path += "/pysills"
                #     demo_files = os.listdir(path=path + str("/demo_files/"))
                #
                # for file in demo_files:
                #     if file.startswith("demo_mi"):
                #         path_complete = os.path.join(self.path_pysills_main + str("/lib/demo_files/"), file)
                #         if "_copy" not in path_complete:
                #             path_raw = pathlib.PureWindowsPath(path_complete)
                #             mi_demo_files["ALL"].append(str(path_raw.as_posix()))

                mi_demo_files["ALL"].sort()
                mi_demo_files["STD"].extend(mi_demo_files["ALL"][:5])
                mi_demo_files["STD"].extend(mi_demo_files["ALL"][-5:])
                mi_demo_files["SMPL"].extend(mi_demo_files["ALL"][5:-5])

                self.list_std = mi_demo_files["STD"]
                self.list_smpl = mi_demo_files["SMPL"]

            if len(self.list_std) > 0:
                self.mi_current_file_std = self.list_std[0]

            if len(self.list_smpl) > 0:
                self.mi_current_file_smpl = self.list_smpl[0]

            for file_std in self.list_std:
                file_parts = file_std.split("/")
                if file_std not in self.container_lists["STD"]["Long"]:
                    self.container_lists["STD"]["Long"].append(file_std)
                    self.container_lists["STD"]["Short"].append(file_parts[-1])
                if self.demo_mode:
                    self.lb_std.insert(tk.END, file_parts[-1])

                for item in ["Quickview", "File Setup", "Results Intensity", "Results Concentration",
                             "Results Sensitivity", "SE STD", "SE SMPL"]:
                    self.container_var["Subwindows"][self.pysills_mode][item] = {}

            for file_smpl in self.list_smpl:
                file_parts = file_smpl.split("/")
                if file_smpl not in self.container_lists["SMPL"]["Long"]:
                    self.container_lists["SMPL"]["Long"].append(file_smpl)
                    self.container_lists["SMPL"]["Short"].append(file_parts[-1])
                if self.demo_mode:
                    self.lb_smpl.insert(tk.END, file_parts[-1])

            for file_std in self.list_std:
                file_parts = file_std.split("/")
                if self.file_loaded == False:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_exmpl = DE(filename_long=file_std).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_exmpl = DE(filename_long=file_std).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                else:
                    file_parts = file_std.split("/")
                    df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]

                self.times = DE().get_times(dataframe=df_exmpl)
                df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
                self.container_lists["ISOTOPES"] = df_isotopes
                self.container_lists["Measured Isotopes"][file_parts[-1]] = df_isotopes
                self.container_lists["Measured Isotopes"]["All"] = self.container_lists["ISOTOPES"]

                for isotope in self.container_lists["Measured Isotopes"][file_parts[-1]]:
                    if isotope.isdigit():
                        print("There is a problem with an isotope that is probably just a number. "
                              "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                        self.container_lists["Measured Isotopes"][file_parts[-1]].remove(isotope)
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        if key_element != None:
                            element = key_element.group(1)
                            if element not in self.container_lists["Measured Elements"]["All"]:
                                self.container_lists["Measured Elements"]["All"].append(element)

            for file_smpl in self.list_smpl:
                file_parts = file_smpl.split("/")
                if self.file_loaded == False:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_exmpl = DE(filename_long=file_smpl).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_exmpl = DE(filename_long=file_smpl).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                else:
                    file_parts = file_smpl.split("/")
                    df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]

                self.times = DE().get_times(dataframe=df_exmpl)
                df_isotopes = DE().get_isotopes(dataframe=df_exmpl)
                self.container_lists["ISOTOPES"] = df_isotopes
                self.container_lists["Measured Isotopes"][file_parts[-1]] = df_isotopes
                self.container_lists["Measured Isotopes"]["All"] = self.container_lists["ISOTOPES"]

                for isotope in self.container_lists["Measured Isotopes"][file_parts[-1]]:
                    if isotope.isdigit():
                        print("There is a problem with an isotope that is probably just a number. "
                              "Please check this out and correct it if possible. Otherwise, it will be ignored here.")
                        self.container_lists["Measured Isotopes"][file_parts[-1]].remove(isotope)
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        if key_element != None:
                            element = key_element.group(1)
                            if element not in self.container_lists["Measured Elements"]["All"]:
                                self.container_lists["Measured Elements"]["All"].append(element)

            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                if isotope.isdigit():
                    pass
                else:
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)
                    if element not in self.container_lists["Measured Elements"]["All"]:
                        self.container_lists["Measured Elements"]["All"].append(element)

            for filename_short in self.container_lists["STD"]["Short"]:
                self.container_lists["Measured Elements"][filename_short] = {}
                self.container_lists["Measured Isotopes"][filename_short] = df_isotopes
                for isotope in self.container_lists["Measured Isotopes"][filename_short]:
                    if isotope.isdigit():
                        pass
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"][filename_short]:
                            self.container_lists["Measured Elements"][filename_short][element] = [isotope]
                        else:
                            if isotope not in self.container_lists["Measured Elements"][filename_short][element]:
                                self.container_lists["Measured Elements"][filename_short][element].append(isotope)

            for filename_short in self.container_lists["SMPL"]["Short"]:
                self.container_lists["Measured Elements"][filename_short] = {}
                self.container_lists["Measured Isotopes"][filename_short] = df_isotopes
                for isotope in self.container_lists["Measured Isotopes"][filename_short]:
                    if isotope.isdigit():
                        pass
                    else:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element not in self.container_lists["Measured Elements"][filename_short]:
                            self.container_lists["Measured Elements"][filename_short][element] = [isotope]
                        else:
                            if isotope not in self.container_lists["Measured Elements"][filename_short][element]:
                                self.container_lists["Measured Elements"][filename_short][element].append(isotope)

            self.define_isotope_colors()
        else:
            self.mi_current_file_std = self.container_lists["STD"]["Long"][0]
            self.mi_current_file_smpl = self.container_lists["SMPL"]["Long"][0]
            self.define_isotope_colors()

        ## Window Settings
        window_width = 1260
        window_height = 1000
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_mi_settings = tk.Toplevel(self.parent)
        self.subwindow_mi_settings.title("MELT INCLUSION ANALYSIS - Setup")
        self.subwindow_mi_settings.geometry(var_geometry)
        self.subwindow_mi_settings.resizable(False, False)
        self.subwindow_mi_settings["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_mi_settings, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_mi_settings, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_mi_settings.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_mi_settings.grid_columnconfigure(i, minsize=column_min)

        ## INITIALIZATION
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            if isotope.isdigit():
                pass
            else:
                key_element = re.search(r"(\D+)(\d+)", isotope)
                element = key_element.group(1)
                if element not in self.container_lists["Elements"]:
                    self.container_lists["Elements"].append(element)
                if element not in self.container_lists["Measured Elements"]:
                    self.container_lists["Measured Elements"][element] = []
                if isotope not in self.container_lists["Measured Elements"][element]:
                    self.container_lists["Measured Elements"][element].append(isotope)

                if isotope not in self.container_var["Spike Elimination"]["Threshold"]:
                    self.container_var["Spike Elimination"]["Threshold"][isotope] = tk.StringVar()
                    self.container_var["Spike Elimination"]["Threshold"][isotope].set(var_threshold.get())

        ## Static
        # Build section 'Project Information'
        var_project_information = {"Row start": 0, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_project_information(var_geometry_info=var_project_information)
        # Build section 'Standard Reference Material'
        var_standard_reference_material = {"Row start": 3, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_standard_reference_material(var_geometry_info=var_standard_reference_material)
        # Build section 'Matrix Settings'
        var_sample_settings = {"Row start": 6, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_sample_settings(var_geometry_info=var_sample_settings)
        # Build section 'Quantification Method'
        var_quantification_method = {"Row start": 8, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_quantification_method(var_geometry_info=var_quantification_method)
        # Build section 'Assemblage Setup'
        var_assemblage_setup = {"Row start": 12, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_assemblage_setup(var_geometry_info=var_assemblage_setup)
        # Build section 'Dwell Time Setup'
        var_dwell_time_setup = {"Row start": 14, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_dwell_time_setup(var_geometry_info=var_dwell_time_setup)
        # Build section 'Calculation Window (Background) Setup'
        var_calculation_window_bg_setup = {"Row start": 16, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_calculation_window_bg(var_geometry_info=var_calculation_window_bg_setup)
        # Build section 'Calculation Window (Matrix) Setup'
        var_calculation_window_mat_setup = {"Row start": 20, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_calculation_window_smpl(var_geometry_info=var_calculation_window_mat_setup)
        # Build section 'Spike Elimination Setup'
        var_spike_elimination_setup = {"Row start": 24, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_spike_elimination_setup(var_geometry_info=var_spike_elimination_setup)
        # Build section 'Check-Up'
        var_checkup = {"Row start": 31, "Column start": 0, "N rows": 1, "N columns": 18}
        self.place_checkup_feature(var_geometry_info=var_checkup)
        # Build section 'Acquisition Times'
        var_acquisition_times_check = {"Row start": 18, "Column start": 44, "N rows": 1, "N columns": 18}
        self.place_acquisition_times_check(var_geometry_info=var_acquisition_times_check)
        # Build section 'Standard Files'
        var_standard_files = {"Row start": 0, "Column start": 19, "N rows": 16, "N columns": 24}
        self.place_standard_files_table(var_geometry_info=var_standard_files)
        # Build section 'Sample Files'
        var_sample_files = {"Row start": 18, "Column start": 19, "N rows": 19, "N columns": 24}
        self.place_sample_files_table(var_geometry_info=var_sample_files)
        # Build section 'Time-Signal Diagram Checker'
        self.define_isotope_colors()
        var_time_signal_diagram_check = {"Row start": 26, "Column start": 44, "N rows": 1, "N columns": 18}
        self.place_time_signal_plot_checker(var_geometry_info=var_time_signal_diagram_check)
        # Build section 'Measured Isotopes'
        var_measured_isotopes = {"Row start": 1, "Column start": 44, "N rows": 16, "N columns": 18}
        self.place_measured_isotopes_overview(var_geometry_info=var_measured_isotopes)

        ## INITIALIZATION
        self.btn_save_project.configure(state="normal")

        self.select_spike_elimination(
            var_opt=self.container_var["Spike Elimination Method"].get(),
            start_row=var_spike_elimination_setup["Row start"], mode="FI")

        if self.file_loaded:
            self.fi_select_srm_initialization()
            try:
                if len(self.container_spikes[filename_short]) > 0:
                    pass
                else:
                    if self.copied_file == False:
                        for filetype in ["STD", "SMPL"]:
                            if self.container_var["Spike Elimination"][filetype]["State"]:
                                if self.container_var["Spike Elimination Method"].get() in [
                                    "Grubbs-Test (SILLS)", "Grubbs-Test", "PySILLS Spike Finder", "Grubbs test",
                                    "Whisker analysis"]:
                                    var_method = "Grubbs"
                                    self.spike_elimination_all(filetype=filetype, algorithm=var_method)
            except:
                print("Problem with settings window creation. It has to be fixed one day.")
        else:
            self.fi_select_is_default(var_opt=self.container_var["IS"]["Default STD"].get())
            self.fi_select_id_default(var_opt=self.container_var["ID"]["Default SMPL"].get())

            if self.container_var["SRM"]["default"][0].get() != "Select SRM":
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][0].get())
            if self.container_var["SRM"]["default"][1].get() != "Select SRM":
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][1].get(), mode="ISOTOPES")
            if self.demo_mode:
                self.container_var["SRM"]["default"][0].set("NIST 610 (GeoReM)")
                self.container_var["SRM"]["default"][1].set("NIST 610 (GeoReM)")
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][0].get())
                self.fi_select_srm_default(var_opt=self.container_var["SRM"]["default"][1].get(), mode="ISOTOPES")

        self.file_system_need_update = False
        self.select_opt_inclusion_is_quantification(
            var_opt="100 wt.% Oxides", dict_geometry_info=var_quantification_method)
        self.select_opt_inclusion_quantification(
            var_opt="Matrix-only Tracer (SILLS)", dict_geometry_info=var_quantification_method)

        if self.demo_mode:
            for index, filename_std_long in enumerate(self.container_lists["STD"]["Long"]):
                self.container_var["STD"][filename_std_long]["SRM"].set("NIST 610 (GeoReM)")
                if index in [3, 4, 8, 9]:
                    self.container_var["STD"][filename_std_long]["SRM"].set("Scapolite 17")

            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["IS Data"]["IS"].set("Ca43")

            self.container_var["SRM"]["Cl35"].set("Scapolite 17")
            self.container_var["SRM"]["Br81"].set("Scapolite 17")
            self.container_var["SRM"]["I127"].set("Scapolite 17")

        self.build_srm_database()

    def change_rb_inclusion_setup(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Inclusion Setup Selection"].get() == 1:
            self.btn_setup_massbalance.configure(state="normal")
            self.btn_setup_chargebalance.configure(state="disabled")
            self.btn_setup_plugin.configure(state="disabled")
        elif self.container_var[key_setting]["Inclusion Setup Selection"].get() == 2:
            self.btn_setup_massbalance.configure(state="disabled")
            self.btn_setup_chargebalance.configure(state="normal")
            self.btn_setup_plugin.configure(state="disabled")
        elif self.container_var[key_setting]["Inclusion Setup Selection"].get() == 3:
            self.btn_setup_massbalance.configure(state="disabled")
            self.btn_setup_chargebalance.configure(state="disabled")
            self.btn_setup_plugin.configure(state="normal")

    #
    def change_rb_quantification_setup(self):
        if self.pysills_mode == "FI":
            var_setting_key = "fi_setting"
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"

        if self.container_var[var_setting_key]["Quantification Method"].get() == 1:
            self.btn_setup_quantification_matrixonly.configure(state="normal")
            self.btn_setup_quantification_secondinternal.configure(state="disabled")
            if self.pysills_mode == "FI":
                self.btn_setup_quantification_plugin.configure(state="disabled")
            elif self.pysills_mode == "MI":
                self.btn_setup_quantification_halter.configure(state="disabled")
                self.btn_setup_quantification_borisova.configure(state="disabled")
        elif self.container_var[var_setting_key]["Quantification Method"].get() == 2:
            self.btn_setup_quantification_matrixonly.configure(state="disabled")
            self.btn_setup_quantification_secondinternal.configure(state="normal")
            if self.pysills_mode == "FI":
                self.btn_setup_quantification_plugin.configure(state="disabled")
            elif self.pysills_mode == "MI":
                self.btn_setup_quantification_halter.configure(state="disabled")
                self.btn_setup_quantification_borisova.configure(state="disabled")
        elif self.container_var[var_setting_key]["Quantification Method"].get() == 3:
            self.btn_setup_quantification_matrixonly.configure(state="disabled")
            self.btn_setup_quantification_secondinternal.configure(state="disabled")
            if self.pysills_mode == "FI":
                self.btn_setup_quantification_plugin.configure(state="normal")
            elif self.pysills_mode == "MI":
                self.btn_setup_quantification_halter.configure(state="normal")
                self.btn_setup_quantification_borisova.configure(state="disabled")
        elif self.container_var[var_setting_key]["Quantification Method"].get() == 4:
            self.btn_setup_quantification_matrixonly.configure(state="disabled")
            self.btn_setup_quantification_secondinternal.configure(state="disabled")
            self.btn_setup_quantification_halter.configure(state="disabled")
            self.btn_setup_quantification_borisova.configure(state="normal")

    #########################
    ## Calculation Methods ##
    #########################
    def fi_get_intensity_mix(self, var_filetype, var_datatype, var_file_short, mode="Specific"):
        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                var_intensity_incl_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["INCL"][
                    isotope]
                var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                    isotope]

                var_result_i = var_intensity_incl_i - var_intensity_bg_i

                if var_result_i < 0:
                    var_result_i = 0.0

                self.container_intensity_mix[var_filetype][var_datatype][var_file_short][isotope] = var_result_i
        else:
            for var_filetype in ["SMPL"]:
                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                self.fi_get_intensity_mix(
                                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short)
                                var_result_i = self.container_intensity_mix[var_filetype][var_datatype][var_file_short][
                                    isotope]
                                helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)
                    self.container_intensity_mix[var_filetype][var_datatype][isotope] = var_result_i

    def fi_get_intensity_corrected(self, var_filetype, var_datatype, var_file_short, var_focus, mode="Specific"):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if mode == "Specific":
            run_calculation = True
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if run_calculation == True:
                    var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                        isotope]
                    var_intensity_mat_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["MAT"][
                        isotope]
                    if var_focus == "MAT":
                        var_result = var_intensity_mat_i - var_intensity_bg_i
                    elif var_focus == "INCL":
                        var_index = self.container_lists[var_filetype]["Short"].index(var_file_short)
                        var_file_long = self.container_lists[var_filetype]["Long"][var_index]

                        if self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                            var_t = self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].get()
                            if var_t == "Select Isotope":
                                var_t = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                                self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].set(var_t)
                        elif self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                            var_t = self.container_var["SMPL"][var_file_long]["Second Internal Standard"]["Name"].get()
                        elif self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                            var_t = self.container_var["Halter2002"]["Name"].get()
                        elif self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                            var_t = self.container_var["Borisova2021"]["Name"].get()

                        var_intensity_incl_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["INCL"][
                            isotope]
                        if var_t != "Select Isotope":
                            var_intensity_bg_t = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                                var_t]
                            var_intensity_mat_t = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "MAT"][var_t]
                            var_intensity_incl_t = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "INCL"][var_t]
                        else:
                            print("It seems that a variable was still not defined. Please check if the "
                                  "reference isotope for the matrix-only tracer method, the 2nd internal "
                                  "standard method or for the methods from Halter or Borisova was already defined.")
                            self.parent.bell()

                        # var_intensity_host_i = abs(var_intensity_mat_i - var_intensity_bg_i)
                        # var_intensity_mix_i = var_intensity_incl_i - var_intensity_bg_i
                        # var_intensity_host_t = var_intensity_mat_t - var_intensity_bg_t
                        # var_intensity_incl_host_t = var_intensity_incl_t - var_intensity_bg_t

                        if var_intensity_mat_i > var_intensity_bg_i:
                            var_intensity_host_i = var_intensity_mat_i - var_intensity_bg_i
                        else:
                            var_intensity_host_i = 0.0

                        if var_intensity_incl_i > var_intensity_bg_i:
                            var_intensity_mix_i = var_intensity_incl_i - var_intensity_bg_i
                        else:
                            var_intensity_mix_i = 0.0

                        if var_intensity_mat_t > var_intensity_bg_t:
                            var_intensity_host_t = var_intensity_mat_t - var_intensity_bg_t
                        else:
                            var_intensity_host_t = 0.0

                        if var_intensity_incl_t > var_intensity_bg_t:
                            var_intensity_incl_host_t = var_intensity_incl_t - var_intensity_bg_t
                        else:
                            var_intensity_incl_host_t = 0.0

                        var_intensity_mix_t = var_intensity_incl_host_t
                        # var_intensity_incl_host_i = (var_intensity_incl_host_t/var_intensity_host_t)*var_intensity_host_i

                        if var_intensity_host_t > 0:
                            var_intensity_incl_host_i = ((var_intensity_incl_host_t/var_intensity_host_t)*
                                                         var_intensity_host_i)
                        else:
                            var_intensity_incl_host_i = 0.0

                        if self.container_var[key_setting]["Inclusion Intensity Calculation"].get() == 0:
                            # Heinrich (2003)
                            var_result = round(self.calculate_intensity_incl_heinrich(
                                intensity_mix_i=var_intensity_mix_i, intensity_mix_t=var_intensity_mix_t,
                                intensity_mat_i=var_intensity_host_i, intensity_mat_t=var_intensity_host_t), 6)
                        elif self.container_var[key_setting]["Inclusion Intensity Calculation"].get() == 1:
                            # SILLS Equation Sheet
                            ## without R
                            var_result = round(self.calculate_intensity_incl_sills(
                                intensity_mix_i=var_intensity_mix_i, intensity_incl_mat_i=var_intensity_incl_host_i), 6)
                        elif self.container_var[key_setting]["Inclusion Intensity Calculation"].get() == 2:
                            # SILLS Equation Sheet
                            ## with R
                            var_result = round(self.calculate_intensity_incl_sills(
                                intensity_mix_i=var_intensity_mix_i, intensity_incl_mat_i=var_intensity_incl_host_i,
                                intensity_mat_i=var_intensity_host_i, with_r=True), 6)
                        elif self.container_var[key_setting]["Inclusion Intensity Calculation"].get() == 3:
                            # Theory
                            var_result = round(self.calculate_intensity_incl_theory(
                                intensity_incl_total_i=var_intensity_incl_i, intensity_bg_i=var_intensity_bg_i,
                                intensity_incl_mat_i=var_intensity_incl_host_i), 6)

                    elif var_focus == "BG":
                        var_result = var_intensity_bg_i

                    if var_result != None:
                        if var_result < 0:
                            var_result = 0.0
                    else:
                        print(
                            "There is a problem with the result for file", var_file_short, var_datatype,
                            ". Please check if all variables are set and if the spike elimination was refreshed. Thank you!"
                        )
                        run_calculation = False
                        self.parent.bell()

                    self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][var_focus][
                        isotope] = var_result
        elif mode == "All":
            run_calculation = True
            for var_filetype in ["STD", "SMPL"]:
                if var_filetype == "STD":
                    focus_set = ["BG", "MAT"]
                else:
                    focus_set = ["BG", "MAT", "INCL"]
                for var_focus in focus_set:
                    if var_focus not in self.container_intensity_corrected[var_filetype][var_datatype]:
                        self.container_intensity_corrected[var_filetype][var_datatype][var_focus] = {}
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        if run_calculation == True:
                            helper_results = []
                            for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                    var_file_short = self.container_lists[var_filetype]["Short"][index]
                                    file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                    if isotope in file_isotopes:
                                        self.fi_get_intensity_corrected(
                                            var_filetype=var_filetype, var_datatype=var_datatype,
                                            var_file_short=var_file_short, var_focus=var_focus)
                                        try:
                                            var_result_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                                var_file_short][var_focus][isotope]
                                            helper_results.append(var_result_i)
                                        except:
                                            print(
                                                "There is a problem with the calculated value for:", var_filetype,
                                                var_datatype, var_file_short, var_focus, isotope,
                                                "- Please check if a problem was already mentioned before and follow if "
                                                "possible the instructions. Thank you!")
                                            run_calculation = False
                                            self.parent.bell()

                            if self.container_var["General Settings"]["Desired Average"].get() == 1:
                                var_result_i = np.mean(helper_results)
                            else:
                                var_result_i = np.median(helper_results)
                            self.container_intensity_corrected[var_filetype][var_datatype][var_focus][
                                isotope] = var_result_i
        elif mode == "only STD":
            for var_filetype in ["STD"]:
                for var_focus in ["MAT"]:
                    if var_focus not in self.container_intensity_corrected[var_filetype][var_datatype]:
                        self.container_intensity_corrected[var_filetype][var_datatype][var_focus] = {}
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    self.fi_get_intensity_corrected(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_focus=var_focus)
                                    var_result_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                        var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_intensity_corrected[var_filetype][var_datatype][isotope] = var_result_i
                        self.container_intensity_corrected[var_filetype][var_datatype][var_focus][
                            isotope] = var_result_i
        elif mode == "only SMPL":
            for var_filetype in ["SMPL"]:
                for var_focus in ["MAT", "INCL"]:
                    if var_focus not in self.container_intensity_corrected[var_filetype][var_datatype]:
                        self.container_intensity_corrected[var_filetype][var_datatype][var_focus] = {}
                        #
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        #
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    self.fi_get_intensity_corrected(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_focus=var_focus)
                                    var_result_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                        var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_intensity_corrected[var_filetype][var_datatype][isotope] = var_result_i
                        self.container_intensity_corrected[var_filetype][var_datatype][var_focus][
                            isotope] = var_result_i

    def calculate_intensity_incl_heinrich(self, intensity_mix_i, intensity_mix_t, intensity_mat_i, intensity_mat_t):
        intensity_incl_i = intensity_mix_i - intensity_mix_t*(intensity_mat_i/intensity_mat_t)
        return intensity_incl_i

    def calculate_intensity_incl_sills(self, intensity_mix_i, intensity_incl_mat_i, intensity_mat_i=None, with_r=False):
        if with_r == False:
            intensity_incl_i = intensity_mix_i - intensity_incl_mat_i
        else:
            if intensity_mat_i > 0:
                factor_r = intensity_incl_mat_i/intensity_mat_i
            else:
                factor_r = 0.0

            intensity_incl_i = intensity_mix_i - factor_r*intensity_mat_i
        return intensity_incl_i

    def calculate_intensity_incl_theory(self, intensity_incl_total_i, intensity_bg_i, intensity_incl_mat_i):
        intensity_incl_i = intensity_incl_total_i - intensity_bg_i - intensity_incl_mat_i
        return intensity_incl_i

    def fi_get_intensity_ratio(self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus,
                               mode="Specific"):
        if mode == "Specific":
            if var_filetype == "STD":
                var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                for element, value in sorted(
                        self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                    if element in self.container_lists["Measured Elements"][var_file_short]:
                        var_is = self.container_lists["Measured Elements"][var_file_short][element][0]
                    break
            else:
                var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            if var_focus in ["MAT", "INCL"]:
                var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                    var_focus][var_is]
            else:
                var_intensity_is = self.container_intensity[var_filetype][var_datatype][var_file_short][
                    var_focus][var_is]
            for isotope in file_isotopes:
                if var_focus in ["MAT", "INCL"]:
                    var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        var_focus][isotope]
                else:
                    var_intensity_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                        var_focus][isotope]

                if var_intensity_is > 0:
                    var_result = var_intensity_i/var_intensity_is
                else:
                    var_result = 0.0

                self.container_intensity_ratio[var_filetype][var_datatype][var_file_short][var_focus][
                    isotope] = var_result

        else:
            for var_filetype in ["STD", "SMPL"]:
                for var_focus in ["BG", "MAT", "INCL"]:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []

                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    self.fi_get_intensity_ratio(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long, var_focus=var_focus)
                                    var_result_i = self.container_intensity_ratio[var_filetype][var_datatype][
                                        var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_intensity_ratio[var_filetype][var_datatype][isotope] = var_result_i

    def fi_get_normalized_sensitivity(
            self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus, mode="Specific"):
        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if var_filetype == "STD":
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)

                    var_concentration_i = self.srm_actual[var_srm_i][element]
                    var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        "MAT"][isotope]

                    if var_concentration_i > 0:
                        var_result_i = var_intensity_i/var_concentration_i
                    else:
                        var_result_i = 0.0

                    self.container_normalized_sensitivity[var_filetype][var_datatype][var_file_short]["MAT"][
                        isotope] = var_result_i

                else:
                    sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short][
                        var_focus][isotope]

                    if var_focus == "INCL":
                        var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    else:
                        var_is = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                        sensitivity_is = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_file_short][var_focus][var_is]
                        if sensitivity_is > 0:
                            sensitivity_i = sensitivity_i/sensitivity_is
                        else:
                            sensitivity_i = 0.0

                    concentration_is = self.container_concentration[var_filetype][var_datatype][var_file_short][
                        var_focus][var_is]
                    intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        var_focus][var_is]

                    if concentration_is != None:
                        if concentration_is > 0:
                            var_result_i = sensitivity_i*(intensity_is/concentration_is)
                        else:
                            var_result_i = np.nan
                    else:
                        var_result_i = np.nan

                    self.container_normalized_sensitivity[var_filetype][var_datatype][var_file_short][var_focus][
                        isotope] = var_result_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                if var_filetype == "STD":
                    list_focus = ["MAT"]
                else:
                    list_focus = ["MAT", "INCL"]

                for var_focus in list_focus:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []

                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    self.fi_get_normalized_sensitivity(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long, var_focus=var_focus)
                                    var_result_i = self.container_normalized_sensitivity[var_filetype][var_datatype][
                                        var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_normalized_sensitivity[var_filetype][var_datatype][isotope] = var_result_i

    def fi_get_rsf(self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus, mode="Specific"):
        """ Calculates the Relative Sensitivity Factor, RSF, based on the following two equations:
        1) Standard Files:  RSF_i = 1
        2) Sample Files:    RSF_i = sensitivity_i*(concentration_std_i/intensity_std_i)*
                                    (intensity_smpl_is/concentration_smpl_is)

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)
        var_focus : str
            The focus category, e.g. MAT

        Returns
        -------
        """
        #
        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            if var_filetype == "STD":
                for isotope in file_isotopes:
                    var_result_i = 1
                    self.container_rsf[var_filetype][var_datatype][var_file_short][var_focus][isotope] = var_result_i
            elif var_filetype == "SMPL":
                var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                var_concentration_is = float(self.container_var[var_filetype][var_file_long]["IS Data"][
                                                 "Concentration"].get())
                var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                    var_focus][var_is]
                for isotope in file_isotopes:
                    if isotope.isdigit():
                        pass
                    else:
                        var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_file_short]["MAT"][isotope]

                        var_srm_i = self.container_var["SRM"][isotope].get()
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        var_concentration_i = self.srm_actual[var_srm_i][element]

                        var_intensity_i = self.container_intensity_corrected["STD"][var_datatype]["MAT"][isotope]

                        if var_concentration_is > 0 and var_intensity_i > 0:
                            var_result_i = (var_sensitivity_i*(var_concentration_i/var_intensity_i)*
                                            (var_intensity_is/var_concentration_is))
                        else:
                            var_result_i = 0

                        self.container_rsf[var_filetype][var_datatype][var_file_short][var_focus][isotope] = var_result_i

        else:
            for var_filetype in ["STD", "SMPL"]:
                if var_filetype == "STD":
                    focus_set = ["MAT"]
                else:
                    focus_set = ["MAT", "INCL"]
                #
                for var_focus in focus_set:
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        #
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    self.fi_get_rsf(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long, var_focus=var_focus)
                                    var_result_i = self.container_rsf[var_filetype][var_datatype][var_file_short][
                                        var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_rsf[var_filetype][var_datatype][isotope] = var_result_i

    #
    # def fi_get_concentration(
    #         self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus="MAT", mode="Specific",
    #         pypitzer=False):
    #     """ Calculates the concentration, C, based on the following two equations:
    #     1) Standard Files:  C_i = SRM_dataset(element)
    #     2) Sample Files:    C_i = (intensity_smpl_i/intensity_smpl_is)*(concentration_smpl_is/sensitivity_i)
    #
    #     Parameters
    #     ----------
    #     var_filetype : str
    #         The file category, e.g. STD
    #     var_datatype : str
    #         The data category, e.g. RAW
    #     var_file_short : str
    #         The file as a short version (without the complete filepath)
    #     var_file_long : str
    #         The file as the long version (with the complete filepath)
    #
    #     Returns
    #     -------
    #     """
    #     if self.pysills_mode == "FI":
    #         key_setting = "fi_setting"
    #     elif self.pysills_mode == "MI":
    #         key_setting = "mi_setting"
    #
    #     if mode == "Specific":
    #         file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
    #         if var_filetype == "STD":
    #             for isotope in file_isotopes:
    #                 var_srm_i = self.container_var["SRM"][isotope].get()
    #                 key_element = re.search(r"(\D+)(\d+)", isotope)
    #                 element = key_element.group(1)
    #
    #                 var_result_i = self.srm_actual[var_srm_i][element]
    #                 var_result_sigma_i = 0.0
    #
    #                 self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
    #                     isotope] = var_result_i
    #                 self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
    #                     isotope] = var_result_sigma_i
    #         elif var_filetype == "SMPL":
    #             # Internal standard for the inclusion (e.g. Na)
    #             var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
    #             for index, isotope in enumerate(file_isotopes):
    #                 if var_focus == "MAT":
    #                     # Classical Mineral Analysis
    #                     if (self.container_var["Quantification Mineral"]["Method"].get() == "Internal Standard" and
    #                             self.oxide_calculation_mat.get() == 0):
    #                         # Internal standard for the matrix (e.g. Si)
    #                         var_host_is = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
    #                         var_concentration_host_is = float(
    #                             self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Concentration"].get())
    #                         var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
    #                             var_file_short]["MAT"][isotope]
    #                         var_intensity_host_is = self.container_intensity_corrected[var_filetype][var_datatype][
    #                             var_file_short]["MAT"][var_host_is]
    #                         var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                             var_file_short]["MAT"][isotope]
    #                         var_sensitivity_ishost = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                             var_file_short]["MAT"][var_host_is]
    #
    #                         if var_sensitivity_ishost > 0:
    #                             var_sensitivity_host_is = var_sensitivity_i/var_sensitivity_ishost
    #                         else:
    #                             var_sensitivity_host_is = 0.0
    #                         if var_intensity_host_is > 0 and var_sensitivity_host_is > 0:
    #                             var_result_i = (var_intensity_i/var_intensity_host_is)* \
    #                                            (var_concentration_host_is/var_sensitivity_i)
    #                         else:
    #                             var_result_i = np.nan
    #
    #                         self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
    #                             isotope] = var_result_i
    #
    #                         var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                             "BG"][isotope]
    #                         var_intensity_mat_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                             "MAT"][isotope]
    #                         var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
    #                             isotope]
    #                         var_n_mat = self.container_intensity[var_filetype][var_datatype][var_file_short]["N MAT"][
    #                             isotope]
    #                         var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
    #                         var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
    #                         var_sigma_mat_i = ((((var_intensity_mat_i*var_tau_i)/var_n_mat)**0.5/var_tau_i)**2)**0.5
    #                         var_sigma = (var_sigma_bg_i**2 + var_sigma_mat_i**2)**0.5
    #
    #                         if (var_intensity_host_is*var_sensitivity_host_is) > 0:
    #                             var_result_sigma_i = (var_concentration_host_is/(
    #                                     var_intensity_host_is*var_sensitivity_host_is))*var_sigma
    #                         else:
    #                             var_result_sigma_i = np.nan
    #
    #                         self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
    #                             isotope] = var_result_sigma_i
    #                     else:
    #                         # 100 wt.% total oxides
    #                         self.run_total_oxides_calculation(
    #                             filetype=var_filetype, datatype=var_datatype, filename_short=var_file_short,
    #                             list_isotopes=file_isotopes)
    #                 else:
    #                     if self.pysills_mode == "MI":
    #                         if (self.container_var[key_setting]["Inclusion Setup Option"].get() == "100 wt.% Oxides" or
    #                                 self.oxide_calculation_incl.get() == 1):
    #                             # 100 wt.% total oxides
    #                             self.run_total_oxides_calculation(
    #                                 filetype=var_filetype, datatype=var_datatype, filename_short=var_file_short,
    #                                 list_isotopes=file_isotopes, focus="INCL")
    #                     if self.pysills_mode == "FI" and self.oxide_calculation_incl.get() == 0:
    #                         # Matrix-only Tracer Method
    #                         if self.container_var[key_setting][
    #                             "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
    #                             if self.container_var[key_setting]["Inclusion Concentration Calculation"].get() == 0:
    #                                 # Simple Signals (SILLS)
    #                                 var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
    #
    #                                 if pypitzer == False:
    #                                     if self.pypitzer_performed == False:
    #                                         var_concentration_incl_is = float(
    #                                             self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].get())
    #                                     else:
    #                                         var_concentration_incl_is = float(
    #                                             self.container_var["SMPL"][var_file_long]["IS Data"][var_datatype][
    #                                                 "Concentration"].get())
    #                                 else:
    #                                     var_concentration_incl_is = 10000
    #
    #                                 var_intensity_incl_i = self.container_intensity_corrected[var_filetype][var_datatype][
    #                                     var_file_short]["INCL"][isotope]
    #                                 var_intensity_incl_is = self.container_intensity_corrected[var_filetype][var_datatype][
    #                                     var_file_short]["INCL"][var_is]
    #                                 var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                                     var_file_short]["INCL"][isotope]
    #
    #                                 if var_intensity_incl_is > 0 and var_sensitivity_i > 0:
    #                                     var_result_i = (var_intensity_incl_i/var_intensity_incl_is)*(
    #                                             var_concentration_incl_is/var_sensitivity_i)
    #                                 else:
    #                                     var_result_i = np.nan
    #
    #                                 var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
    #                                     var_file_short]["BG"][isotope]
    #                                 var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
    #                                     var_file_short]["INCL"][isotope]
    #                                 var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                                     "N BG"][isotope]
    #                                 var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                                     "N INCL"][isotope]
    #                                 var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
    #                                 var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
    #                                 var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
    #                                                      /var_tau_i)**2)**0.5
    #                                 var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5
    #
    #                                 ## Inclusion concentration
    #                                 if (var_intensity_incl_is*var_sensitivity_i) > 0:
    #                                     var_result_sigma_i = (var_concentration_incl_is/(
    #                                             var_intensity_incl_is*var_sensitivity_i))*var_sigma
    #                                 else:
    #                                     var_result_sigma_i = np.nan
    #                             else:
    #                                 # Using x
    #                                 var_t = self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].get()
    #
    #                                 var_intensity_mix_t = self.container_intensity_mix["SMPL"][var_datatype][
    #                                     var_file_short][var_t]
    #                                 var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][
    #                                     var_file_short][var_is]
    #                                 var_intensity_incl_i = self.container_intensity_corrected[var_filetype][var_datatype][
    #                                     var_file_short]["INCL"][isotope]
    #                                 var_intensity_sigma_i = self.container_intensity[var_filetype][var_datatype][
    #                                     var_file_short]["1 SIGMA INCL"][isotope]
    #                                 var_sensitivity_t = self.container_analytical_sensitivity["SMPL"][var_datatype][
    #                                     var_file_short]["INCL"][var_t]
    #
    #                                 ## Mixed concentration ratio a
    #                                 var_a = self.calculate_mixed_concentration_ratio(
    #                                     intensity_mix_i=var_intensity_mix_t, intensity_mix_IS=var_intensity_mix_is,
    #                                     sensitivity_IS_i=var_sensitivity_t)
    #
    #                                 var_concentration_host_t = self.container_concentration["SMPL"][var_datatype][
    #                                     var_file_short]["MAT"][var_t]
    #                                 var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][
    #                                     var_file_short]["MAT"][var_is]
    #
    #                                 if pypitzer == False:
    #                                     var_concentration_incl_is = float(
    #                                         self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].get())
    #                                 else:
    #                                     var_concentration_incl_is = 10000
    #
    #                                 ## Mixing ratio x
    #                                 var_x = self.calculate_mixing_ratio(
    #                                     factor_a=var_a, concentration_mat_i=var_concentration_host_t,
    #                                     concentration_mat_IS=var_concentration_host_is, concentraton_incl_i=0,
    #                                     concentration_incl_IS=var_concentration_incl_is)
    #
    #                                 var_concentration_mix_is = ((1 - var_x)*var_concentration_host_is + var_x*
    #                                                             var_concentration_incl_is)
    #
    #                                 var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][
    #                                     var_file_short][isotope]
    #                                 var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][
    #                                     var_file_short][var_is]
    #                                 var_intensity_host_i = self.container_intensity_corrected[var_filetype][var_datatype][
    #                                     var_file_short]["MAT"][isotope]
    #                                 var_intensity_host_is = self.container_intensity_corrected[var_filetype][var_datatype][
    #                                     var_file_short]["MAT"][var_is]
    #                                 var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][var_datatype][
    #                                     var_file_short]["INCL"][isotope]
    #
    #                                 var_intensity_incl_is = self.container_intensity_corrected[var_filetype][
    #                                     var_datatype][var_file_short]["INCL"][var_is]
    #                                 var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
    #                                     var_file_short]["BG"][isotope]
    #                                 var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
    #                                     var_file_short]["INCL"][isotope]
    #                                 var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                                     "N BG"][isotope]
    #                                 var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                                     "N INCL"][isotope]
    #                                 var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
    #                                 var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
    #                                 var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
    #                                                      /var_tau_i)**2)**0.5
    #                                 var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5
    #
    #                                 ## Inclusion concentration
    #                                 if (var_x*var_sensitivity_i > 0 and var_intensity_mix_is > 0
    #                                         and var_intensity_host_is > 0):
    #                                     var_result_i = (1/(var_x*var_sensitivity_i))*(
    #                                             (var_concentration_mix_is/var_intensity_mix_is)*var_intensity_mix_i +
    #                                             (var_x - 1)*(var_concentration_host_is/var_intensity_host_is)*
    #                                             var_intensity_host_i)
    #                                     var_result_sigma_i = (var_concentration_incl_is/(
    #                                             var_intensity_incl_is*var_sensitivity_i))*var_sigma
    #                                 else:
    #                                     var_result_i = np.nan
    #                                     var_result_sigma_i = 0.0
    #
    #                             if var_result_i < 0:
    #                                 var_result_i = 0.0
    #
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
    #                                 isotope] = var_result_i
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["Matrix-Only"][
    #                                 isotope] = var_result_i
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
    #                                 isotope] = var_result_sigma_i
    #                         # Second Internal Standard
    #                         elif self.container_var[key_setting][
    #                             "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
    #                             var_is1 = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
    #                             var_is2 = self.container_var["SMPL"][var_file_long]["Second Internal Standard"][
    #                                 "Name"].get()
    #
    #                             ## Mixed concentration ratio a
    #                             var_intensity_mix_is1 = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
    #                                 var_is1]
    #                             var_intensity_mix_is2 = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
    #                                 var_is2]
    #                             var_sensitivity_is2 = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                                 var_file_short]["INCL"][var_is2]
    #
    #                             var_a = self.calculate_mixed_concentration_ratio(
    #                                 intensity_mix_i=var_intensity_mix_is2, intensity_mix_IS=var_intensity_mix_is1,
    #                                 sensitivity_IS_i=var_sensitivity_is2)
    #
    #                             ## Mixing ratio x
    #                             var_concentration_host_is1 = self.container_concentration["SMPL"][var_datatype][
    #                                 var_file_short]["MAT"][var_is1]
    #                             var_concentration_host_is2 = self.container_concentration["SMPL"][var_datatype][
    #                                 var_file_short]["MAT"][var_is2]
    #
    #                             if pypitzer == False:
    #                                 var_concentration_incl_is1 = float(
    #                                     self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].get())
    #                             else:
    #                                 var_concentration_incl_is1 = 10000
    #
    #                             var_concentration_incl_is2 = float(self.container_var["SMPL"][var_file_long][
    #                                                                    "Second Internal Standard"]["Value"].get())
    #
    #                             var_x = self.calculate_mixing_ratio(
    #                                 factor_a=var_a, concentration_mat_i=var_concentration_host_is2,
    #                                 concentration_mat_IS=var_concentration_host_is1,
    #                                 concentraton_incl_i=var_concentration_incl_is2,
    #                                 concentration_incl_IS=var_concentration_incl_is1)
    #
    #                             ## Mixed Concentration IS1
    #                             var_concentration_mix_is1 = ((1 - var_x)*var_concentration_host_is1 +
    #                                                          var_x*var_concentration_incl_is1)
    #
    #                             ## Mixed Concentrations
    #                             var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
    #                                 isotope]
    #                             var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                                 var_file_short]["INCL"][isotope]
    #
    #                             var_concentration_mix_i = (var_intensity_mix_i/var_intensity_mix_is1)*(
    #                                     var_concentration_mix_is1/var_sensitivity_i)
    #                             var_concentration_host_i = self.container_concentration["SMPL"][var_datatype][
    #                                 var_file_short]["MAT"][isotope]
    #
    #                             var_intensity_incl_is = self.container_intensity_corrected[var_filetype][var_datatype][
    #                                 var_file_short]["INCL"][var_is]
    #                             var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
    #                                 var_file_short]["BG"][isotope]
    #                             var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
    #                                 var_file_short]["INCL"][isotope]
    #                             var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
    #                                 isotope]
    #                             var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                                 "N INCL"][isotope]
    #                             var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
    #                             var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
    #                             var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
    #                                                  /var_tau_i)**2)**0.5
    #                             var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5
    #
    #                             ## Inclusion Concentrations
    #                             if var_x > 0:
    #                                 var_result_i = (var_concentration_mix_i - (1 - var_x)*var_concentration_host_i)/var_x
    #                                 var_result_sigma_i = (var_concentration_incl_is1/(
    #                                         var_intensity_incl_is*var_sensitivity_i))*var_sigma
    #                             else:
    #                                 var_result_i = np.nan
    #                                 var_result_sigma_i = 0.0
    #
    #                             if var_result_i < 0:
    #                                 var_result_i = 0.0
    #
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
    #                                 isotope] = var_result_i
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["Second-Internal"][
    #                                 isotope] = var_result_i
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
    #                                 isotope] = var_result_sigma_i
    #                         elif self.container_var[key_setting][
    #                             "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
    #                             # Mixing ratio x
    #                             if index == 0:
    #                                 var_x, var_concentration_mix_is = self.estimate_x_halter2002(
    #                                     datatype=var_datatype, filename_long=var_file_long, filename_short=var_file_short)
    #                             var_concentration_host_i = self.container_concentration["SMPL"][var_datatype][
    #                                 var_file_short]["MAT"][isotope]
    #                             var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                                 var_file_short]["INCL"][isotope]
    #                             var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
    #                                 isotope]
    #                             var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
    #                                 var_is]
    #                             var_concentration_mix_i = (var_intensity_mix_i/var_intensity_mix_is)*(
    #                                     var_concentration_mix_is/var_sensitivity_i)
    #
    #                             if var_x > 0:
    #                                 var_result_i = (var_concentration_mix_i + (var_x - 1)*var_concentration_host_i)/var_x
    #                             else:
    #                                 var_result_i = np.nan
    #
    #                             if var_result_i < 0:
    #                                 var_result_i = 0.0
    #
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
    #                                 isotope] = var_result_i
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["Halter2002"][
    #                                 isotope] = var_result_i
    #                         elif self.container_var[key_setting][
    #                             "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
    #                             var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][
    #                                 var_file_short]["MAT"][var_is]
    #                             var_rho_host_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
    #                                                        "rho(host)"].get())
    #                             var_rho_incl_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
    #                                                        "rho(incl)"].get())
    #                             var_radius_host_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
    #                                                           "R(host)"].get())
    #                             var_radius_incl_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
    #                                                           "R(incl)"].get())
    #                             var_normalized_sensitivity_i = self.container_normalized_sensitivity["SMPL"][var_datatype][
    #                                 var_file_short]["MAT"][isotope]
    #                             var_normalized_sensitivity_is = self.container_normalized_sensitivity["SMPL"][var_datatype][
    #                                 var_file_short]["MAT"][var_is]
    #                             var_intensity_incl_i = self.container_intensity_corrected["SMPL"][var_datatype][
    #                                 var_file_short]["INCL"][isotope]
    #                             var_intensity_incl_is = self.container_intensity_corrected["SMPL"][var_datatype][
    #                                 var_file_short]["INCL"][var_is]
    #
    #                             if pypitzer == False:
    #                                 var_concentration_incl_is = float(
    #                                     self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].get())
    #                             else:
    #                                 var_concentration_incl_is = 10000
    #
    #                             var_factor_s_i = var_normalized_sensitivity_is/var_normalized_sensitivity_i
    #                             var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                                 var_file_short]["INCL"][isotope]
    #                             if var_sensitivity_i > 0:
    #                                 var_factor_s_i = 1/var_sensitivity_i
    #                             else:
    #                                 var_factor_s_i = 0.0
    #                             var_factor_k_i = ((var_rho_incl_i/var_rho_host_i)*
    #                                               (var_intensity_incl_i/var_intensity_incl_is)*
    #                                               (var_concentration_incl_is/var_concentration_host_is)*
    #                                               (var_radius_incl_i**2)/(1.5*var_radius_host_i**2 - var_radius_incl_i**2))
    #
    #                             var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
    #                                 var_file_short]["BG"][isotope]
    #                             var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
    #                                 var_file_short]["INCL"][isotope]
    #                             var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
    #                                 isotope]
    #                             var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                                 "N INCL"][isotope]
    #                             var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
    #                             var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
    #                             var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
    #                                                  /var_tau_i)**2)**0.5
    #                             var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5
    #
    #                             # Inclusion Concentration
    #                             if var_sensitivity_i > 0:
    #                                 var_result_i = (var_concentration_host_is*(var_rho_host_i/var_rho_incl_i)*
    #                                                 var_factor_s_i*var_factor_k_i*
    #                                                 (1.5*var_radius_host_i**2 - var_radius_incl_i**2)/
    #                                                 (var_radius_incl_i**2))
    #                                 var_result_sigma_i = (var_concentration_incl_is/(
    #                                         var_intensity_incl_is*var_sensitivity_i))*var_sigma
    #                             else:
    #                                 var_result_i = np.nan
    #                                 var_result_sigma_i = 0.0
    #
    #                             if var_result_i < 0:
    #                                 var_result_i = 0.0
    #
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
    #                                 isotope] = var_result_i
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["Borisova2021"][
    #                                 isotope] = var_result_i
    #                             self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
    #                                 isotope] = var_result_sigma_i
    #
    #             if (self.container_var[key_setting][
    #                 "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)"
    #                     and var_focus == "INCL"):
    #                 var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
    #                 var_concentration_incl_is = self.container_concentration[var_filetype][var_datatype][
    #                     var_file_short]["INCL"][var_is]
    #                 var_intensity_incl_is = self.container_intensity_corrected[var_filetype][var_datatype][
    #                     var_file_short]["INCL"][var_is]
    #
    #                 for index, isotope in enumerate(file_isotopes):
    #                     var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
    #                         var_file_short]["INCL"][isotope]
    #                     var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
    #                         var_file_short]["BG"][isotope]
    #                     var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
    #                         var_file_short]["INCL"][isotope]
    #                     var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
    #                         isotope]
    #                     var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
    #                         "N INCL"][isotope]
    #                     var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
    #                     var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
    #                     var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
    #                                          /var_tau_i)**2)**0.5
    #                     var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5
    #
    #                     var_result_sigma_i = (var_concentration_incl_is/(
    #                             var_intensity_incl_is*var_sensitivity_i))*var_sigma
    #                     self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
    #                         isotope] = var_result_sigma_i
    #     else:
    #         for var_filetype in ["STD", "SMPL"]:
    #             if var_filetype == "STD":
    #                 focus_set = ["MAT"]
    #             else:
    #                 focus_set = ["MAT", "INCL"]
    #
    #             for var_focus in focus_set:
    #                 if var_focus not in self.container_concentration[var_filetype][var_datatype]:
    #                     self.container_concentration[var_filetype][var_datatype][var_focus] = {}
    #
    #                 for isotope in self.container_lists["Measured Isotopes"]["All"]:
    #                     helper_results = []
    #
    #                     for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
    #                         if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
    #                             var_file_short = self.container_lists[var_filetype]["Short"][index]
    #                             file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
    #
    #                             if isotope in file_isotopes:
    #                                 self.fi_get_concentration(
    #                                     var_filetype=var_filetype, var_datatype=var_datatype,
    #                                     var_file_short=var_file_short, var_file_long=var_file_long, var_focus=var_focus,
    #                                     pypitzer=pypitzer)
    #                                 var_result_i = self.container_concentration[var_filetype][var_datatype][
    #                                     var_file_short][var_focus][isotope]
    #                                 helper_results.append(var_result_i)
    #
    #                     if self.container_var["General Settings"]["Desired Average"].get() == 1:
    #                         var_result_i = np.mean(helper_results)
    #                     else:
    #                         var_result_i = np.median(helper_results)
    #                     self.container_concentration[var_filetype][var_datatype][var_focus][isotope] = var_result_i

    def fi_get_concentration2(
            self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus="MAT", mode="Specific",
            pypitzer=False, var_incl_is=None):
        """ Calculates the concentration, C, based on the following two equations:
        1) Standard Files:  C_i = SRM_dataset(element)
        2) Sample Files:    C_i = (intensity_smpl_i/intensity_smpl_is)*(concentration_smpl_is/sensitivity_i)

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)

        Returns
        -------
        """
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            if var_filetype == "STD":
                for isotope in file_isotopes:
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)

                    var_result_i = self.srm_actual[var_srm_i][element]
                    var_result_sigma_i = 0.0

                    self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                        isotope] = var_result_i
                    self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
                        isotope] = var_result_sigma_i
            elif var_filetype == "SMPL":
                # Internal standard for the inclusion (e.g. Na)
                var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
                if var_focus == "MAT":
                    # Classical Mineral Analysis
                    if (self.container_var["Quantification Mineral"]["Method"].get() == "Internal Standard" and
                            self.oxide_calculation_mat.get() == 0):
                        for index, isotope in enumerate(file_isotopes):
                            # Internal standard for the matrix (e.g. Si)
                            var_host_is = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                            var_concentration_host_is = float(
                                self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Concentration"].get())
                            var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]
                            var_intensity_host_is = self.container_intensity_corrected[var_filetype][var_datatype][
                                var_file_short]["MAT"][var_host_is]
                            var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                var_file_short]["MAT"][isotope]
                            var_sensitivity_ishost = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                var_file_short]["MAT"][var_host_is]

                            if var_sensitivity_ishost > 0:
                                var_sensitivity_host_is = var_sensitivity_i/var_sensitivity_ishost
                            else:
                                var_sensitivity_host_is = 0.0
                            if var_intensity_host_is > 0 and var_sensitivity_host_is > 0:
                                var_result_i = (var_intensity_i/var_intensity_host_is)* \
                                               (var_concentration_host_is/var_sensitivity_i)
                            else:
                                var_result_i = np.nan

                            self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                                isotope] = var_result_i

                            var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "BG"][isotope]
                            var_intensity_mat_i = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                "MAT"][isotope]
                            var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
                                isotope]
                            var_n_mat = self.container_intensity[var_filetype][var_datatype][var_file_short]["N MAT"][
                                isotope]
                            var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                            var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
                            var_sigma_mat_i = ((((var_intensity_mat_i*var_tau_i)/var_n_mat)**0.5/var_tau_i)**2)**0.5
                            var_sigma = (var_sigma_bg_i**2 + var_sigma_mat_i**2)**0.5

                            if (var_intensity_host_is*var_sensitivity_host_is) > 0:
                                var_result_sigma_i = (var_concentration_host_is/(
                                        var_intensity_host_is*var_sensitivity_host_is))*var_sigma
                            else:
                                var_result_sigma_i = np.nan

                            self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA MAT"][
                                isotope] = var_result_sigma_i
                    else:
                        # 100 wt.% total oxides
                        self.run_total_oxides_calculation(
                            filetype=var_filetype, datatype=var_datatype, filename_short=var_file_short,
                            list_isotopes=file_isotopes)
                elif var_focus == "INCL":
                    if self.pysills_mode == "MI":
                        if (self.container_var[key_setting]["Inclusion Setup Option"].get() == "100 wt.% Oxides" or
                                self.oxide_calculation_incl.get() == 1):
                            # 100 wt.% total oxides
                            self.run_total_oxides_calculation(
                                filetype=var_filetype, datatype=var_datatype, filename_short=var_file_short,
                                list_isotopes=file_isotopes, focus="INCL")

                    if self.pysills_mode == "FI" and self.oxide_calculation_incl.get() == 0:
                        # Matrix-only Tracer Method
                        if self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                            for index, isotope in enumerate(file_isotopes):
                                if self.container_var[key_setting]["Inclusion Concentration Calculation"].get() == 0:
                                    # Simple Signals (SILLS)
                                    if var_incl_is == None:
                                        var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
                                    else:
                                        var_is = self.container_lists["Measured Elements"][var_file_short]["Na"][0]

                                    if pypitzer == False:
                                        if self.pypitzer_performed == False:
                                            var_concentration_incl_is = float(
                                                self.container_var["SMPL"][var_file_long]["IS Data"][
                                                    "Concentration"].get())
                                        else:
                                            var_concentration_incl_is = float(
                                                self.container_var["SMPL"][var_file_long]["IS Data"][var_datatype][
                                                    "Concentration"].get())
                                    else:
                                        var_concentration_incl_is = 10000

                                    if var_incl_is != None:
                                        var_concentration_incl_is = 10000

                                    var_intensity_incl_i = self.container_intensity_corrected[var_filetype][
                                        var_datatype][var_file_short]["INCL"][isotope]
                                    var_intensity_incl_is = self.container_intensity_corrected[var_filetype][
                                        var_datatype][var_file_short]["INCL"][var_is]
                                    var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][
                                        var_datatype][var_file_short]["INCL"][isotope]

                                    if var_intensity_incl_is > 0 and var_sensitivity_i > 0:
                                        var_result_i = (var_intensity_incl_i/var_intensity_incl_is)*(
                                                var_concentration_incl_is/var_sensitivity_i)
                                    else:
                                        var_result_i = np.nan

                                    var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
                                        var_file_short]["BG"][isotope]
                                    var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
                                        var_file_short]["INCL"][isotope]
                                    var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                        "N BG"][isotope]
                                    var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                        "N INCL"][isotope]
                                    var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                                    var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
                                    var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
                                                         /var_tau_i)**2)**0.5
                                    var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5

                                    ## Inclusion concentration
                                    if (var_intensity_incl_is*var_sensitivity_i) > 0:
                                        var_result_sigma_i = (var_concentration_incl_is/(
                                                var_intensity_incl_is*var_sensitivity_i))*var_sigma
                                    else:
                                        var_result_sigma_i = np.nan
                                else:
                                    # Using x
                                    var_t = self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].get()

                                    var_intensity_mix_t = self.container_intensity_mix["SMPL"][var_datatype][
                                        var_file_short][var_t]
                                    var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][
                                        var_file_short][var_is]

                                    var_intensity_incl_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                        var_file_short]["INCL"][isotope]
                                    var_intensity_sigma_i = self.container_intensity[var_filetype][var_datatype][
                                        var_file_short]["1 SIGMA INCL"][isotope]
                                    var_sensitivity_t = self.container_analytical_sensitivity["SMPL"][var_datatype][
                                        var_file_short]["INCL"][var_t]

                                    ## Mixed concentration ratio a
                                    var_a = self.calculate_mixed_concentration_ratio(
                                        intensity_mix_i=var_intensity_mix_t, intensity_mix_IS=var_intensity_mix_is,
                                        sensitivity_IS_i=var_sensitivity_t)

                                    var_concentration_host_t = self.container_concentration["SMPL"][var_datatype][
                                        var_file_short]["MAT"][var_t]
                                    var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][
                                        var_file_short]["MAT"][var_is]

                                    if pypitzer == False:
                                        var_concentration_incl_is = float(
                                            self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].get())
                                    else:
                                        var_concentration_incl_is = 10000

                                    ## Mixing ratio x
                                    var_x = self.calculate_mixing_ratio(
                                        factor_a=var_a, concentration_mat_i=var_concentration_host_t,
                                        concentration_mat_IS=var_concentration_host_is, concentraton_incl_i=0,
                                        concentration_incl_IS=var_concentration_incl_is)

                                    var_concentration_mix_is = ((1 - var_x)*var_concentration_host_is + var_x*
                                                                var_concentration_incl_is)

                                    var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][
                                        var_file_short][isotope]
                                    var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][
                                        var_file_short][var_is]
                                    var_intensity_host_i = self.container_intensity_corrected[var_filetype][var_datatype][
                                        var_file_short]["MAT"][isotope]
                                    var_intensity_host_is = self.container_intensity_corrected[var_filetype][var_datatype][
                                        var_file_short]["MAT"][var_is]
                                    var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][var_datatype][
                                        var_file_short]["INCL"][isotope]

                                    var_intensity_incl_is = self.container_intensity_corrected[var_filetype][var_datatype][
                                        var_file_short]["INCL"][var_is]
                                    var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
                                        var_file_short]["BG"][isotope]
                                    var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
                                        var_file_short]["INCL"][isotope]
                                    var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                        "N BG"][isotope]
                                    var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                        "N INCL"][isotope]
                                    var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                                    var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
                                    var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
                                                         /var_tau_i)**2)**0.5
                                    var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5

                                    ## Inclusion concentration
                                    if (var_x*var_sensitivity_i > 0 and var_intensity_mix_is > 0
                                            and var_intensity_host_is > 0):
                                        var_result_i = (1/(var_x*var_sensitivity_i))*(
                                                (var_concentration_mix_is/var_intensity_mix_is)*var_intensity_mix_i +
                                                (var_x - 1)*(var_concentration_host_is/var_intensity_host_is)*
                                                var_intensity_host_i)
                                        var_result_sigma_i = (var_concentration_incl_is/(
                                                var_intensity_incl_is*var_sensitivity_i))*var_sigma
                                    else:
                                        var_result_i = np.nan
                                        var_result_sigma_i = 0.0

                                    if var_result_i < 0:
                                        var_result_i = 0.0

                                if self.molality_based_quantification.get() == False:
                                    self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
                                        isotope] = var_result_i
                                else:
                                    var_result_i = self.container_concentration[var_filetype][var_datatype][
                                        var_file_short]["INCL"][isotope]
                                self.container_concentration[var_filetype][var_datatype][var_file_short]["Matrix-Only"][
                                    isotope] = var_result_i
                                self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
                                    isotope] = var_result_sigma_i
                        # Second Internal Standard
                        elif self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                            var_is1 = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
                            var_is2 = self.container_var["SMPL"][var_file_long]["Second Internal Standard"][
                                "Name"].get()

                            ## Mixed concentration ratio a
                            var_intensity_mix_is1 = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
                                var_is1]
                            var_intensity_mix_is2 = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
                                var_is2]
                            var_sensitivity_is2 = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                var_file_short]["INCL"][var_is2]

                            var_a = self.calculate_mixed_concentration_ratio(
                                intensity_mix_i=var_intensity_mix_is2, intensity_mix_IS=var_intensity_mix_is1,
                                sensitivity_IS_i=var_sensitivity_is2)

                            ## Mixing ratio x
                            var_concentration_host_is1 = self.container_concentration["SMPL"][var_datatype][
                                var_file_short]["MAT"][var_is1]
                            var_concentration_host_is2 = self.container_concentration["SMPL"][var_datatype][
                                var_file_short]["MAT"][var_is2]

                            if pypitzer == False:
                                var_concentration_incl_is1 = float(
                                    self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].get())
                            else:
                                var_concentration_incl_is1 = 10000

                            var_concentration_incl_is2 = float(self.container_var["SMPL"][var_file_long][
                                                                   "Second Internal Standard"]["Value"].get())

                            var_x = self.calculate_mixing_ratio(
                                factor_a=var_a, concentration_mat_i=var_concentration_host_is2,
                                concentration_mat_IS=var_concentration_host_is1,
                                concentraton_incl_i=var_concentration_incl_is2,
                                concentration_incl_IS=var_concentration_incl_is1)

                            ## Mixed Concentration IS1
                            var_concentration_mix_is1 = ((1 - var_x)*var_concentration_host_is1 +
                                                         var_x*var_concentration_incl_is1)

                            ## Mixed Concentrations
                            for index, isotope in enumerate(file_isotopes):
                                var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
                                    isotope]
                                var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                    var_file_short]["INCL"][isotope]

                                var_concentration_mix_i = (var_intensity_mix_i/var_intensity_mix_is1)*(
                                        var_concentration_mix_is1/var_sensitivity_i)
                                var_concentration_host_i = self.container_concentration["SMPL"][var_datatype][
                                    var_file_short]["MAT"][isotope]

                                var_intensity_incl_is = self.container_intensity_corrected[var_filetype][var_datatype][
                                    var_file_short]["INCL"][var_is]
                                var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
                                    var_file_short]["BG"][isotope]
                                var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
                                    var_file_short]["INCL"][isotope]
                                var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
                                    isotope]
                                var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                    "N INCL"][isotope]
                                var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                                var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
                                var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
                                                     /var_tau_i)**2)**0.5
                                var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5

                                ## Inclusion Concentrations
                                if var_x > 0:
                                    var_result_i = (var_concentration_mix_i - (1 - var_x)*var_concentration_host_i)/var_x
                                    var_result_sigma_i = (var_concentration_incl_is1/(
                                            var_intensity_incl_is*var_sensitivity_i))*var_sigma
                                else:
                                    var_result_i = np.nan
                                    var_result_sigma_i = 0.0

                                if var_result_i < 0:
                                    var_result_i = 0.0

                                self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
                                    isotope] = var_result_i
                                self.container_concentration[var_filetype][var_datatype][var_file_short]["Second-Internal"][
                                    isotope] = var_result_i
                                self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
                                    isotope] = var_result_sigma_i
                        elif self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                            # Mixing ratio x
                            for index, isotope in enumerate(file_isotopes):
                                if index == 0:
                                    var_x, var_concentration_mix_is = self.estimate_x_halter2002(
                                        datatype=var_datatype, filename_long=var_file_long, filename_short=var_file_short)
                                var_concentration_host_i = self.container_concentration["SMPL"][var_datatype][
                                    var_file_short]["MAT"][isotope]
                                var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                    var_file_short]["INCL"][isotope]
                                var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
                                    isotope]
                                var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][
                                    var_is]
                                var_concentration_mix_i = (var_intensity_mix_i/var_intensity_mix_is)*(
                                        var_concentration_mix_is/var_sensitivity_i)

                                if var_x > 0:
                                    var_result_i = (var_concentration_mix_i + (var_x - 1)*var_concentration_host_i)/var_x
                                else:
                                    var_result_i = np.nan

                                if var_result_i < 0:
                                    var_result_i = 0.0

                                self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
                                    isotope] = var_result_i
                                self.container_concentration[var_filetype][var_datatype][var_file_short]["Halter2002"][
                                    isotope] = var_result_i
                        elif self.container_var[key_setting][
                            "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                            var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][
                                var_file_short]["MAT"][var_is]
                            var_rho_host_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                       "rho(host)"].get())
                            var_rho_incl_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                       "rho(incl)"].get())
                            var_radius_host_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                          "R(host)"].get())
                            var_radius_incl_i = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                          "R(incl)"].get())

                            for index, isotope in enumerate(file_isotopes):
                                var_normalized_sensitivity_i = self.container_normalized_sensitivity["SMPL"][var_datatype][
                                    var_file_short]["MAT"][isotope]
                                var_normalized_sensitivity_is = self.container_normalized_sensitivity["SMPL"][var_datatype][
                                    var_file_short]["MAT"][var_is]
                                var_intensity_incl_i = self.container_intensity_corrected["SMPL"][var_datatype][
                                    var_file_short]["INCL"][isotope]
                                var_intensity_incl_is = self.container_intensity_corrected["SMPL"][var_datatype][
                                    var_file_short]["INCL"][var_is]

                                if pypitzer == False:
                                    var_concentration_incl_is = float(
                                        self.container_var["SMPL"][var_file_long]["IS Data"]["Concentration"].get())
                                else:
                                    var_concentration_incl_is = 10000

                                var_factor_s_i = var_normalized_sensitivity_is/var_normalized_sensitivity_i
                                var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                    var_file_short]["INCL"][isotope]
                                if var_sensitivity_i > 0:
                                    var_factor_s_i = 1/var_sensitivity_i
                                else:
                                    var_factor_s_i = 0.0
                                var_factor_k_i = ((var_rho_incl_i/var_rho_host_i)*
                                                  (var_intensity_incl_i/var_intensity_incl_is)*
                                                  (var_concentration_incl_is/var_concentration_host_is)*
                                                  (var_radius_incl_i**2)/(1.5*var_radius_host_i**2 - var_radius_incl_i**2))

                                var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
                                    var_file_short]["BG"][isotope]
                                var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
                                    var_file_short]["INCL"][isotope]
                                var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
                                    isotope]
                                var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
                                    "N INCL"][isotope]
                                var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                                var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
                                var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
                                                     /var_tau_i)**2)**0.5
                                var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5

                                # Inclusion Concentration
                                if var_sensitivity_i > 0:
                                    var_result_i = (var_concentration_host_is*(var_rho_host_i/var_rho_incl_i)*
                                                    var_factor_s_i*var_factor_k_i*
                                                    (1.5*var_radius_host_i**2 - var_radius_incl_i**2)/
                                                    (var_radius_incl_i**2))
                                    var_result_sigma_i = (var_concentration_incl_is/(
                                            var_intensity_incl_is*var_sensitivity_i))*var_sigma
                                else:
                                    var_result_i = np.nan
                                    var_result_sigma_i = 0.0

                                if var_result_i < 0:
                                    var_result_i = 0.0

                                self.container_concentration[var_filetype][var_datatype][var_file_short]["INCL"][
                                    isotope] = var_result_i
                                self.container_concentration[var_filetype][var_datatype][var_file_short]["Borisova2021"][
                                    isotope] = var_result_i
                                self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
                                    isotope] = var_result_sigma_i

                if (self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)"
                        and var_focus == "INCL"):
                    var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
                    var_concentration_incl_is = self.container_concentration[var_filetype][var_datatype][
                        var_file_short]["INCL"][var_is]
                    var_intensity_incl_is = self.container_intensity_corrected[var_filetype][var_datatype][
                        var_file_short]["INCL"][var_is]

                    for index, isotope in enumerate(file_isotopes):
                        var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_file_short]["INCL"][isotope]
                        var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][
                            var_file_short]["BG"][isotope]
                        var_intensity_incl_total_i = self.container_intensity[var_filetype][var_datatype][
                            var_file_short]["INCL"][isotope]
                        var_n_bg = self.container_intensity[var_filetype][var_datatype][var_file_short]["N BG"][
                            isotope]
                        var_n_incl = self.container_intensity[var_filetype][var_datatype][var_file_short][
                            "N INCL"][isotope]
                        var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                        var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
                        var_sigma_incl_i = ((((var_intensity_incl_total_i*var_tau_i)/var_n_incl)**0.5
                                             /var_tau_i)**2)**0.5
                        var_sigma = (var_sigma_bg_i**2 + var_sigma_incl_i**2)**0.5

                        var_result_sigma_i = (var_concentration_incl_is/(
                                var_intensity_incl_is*var_sensitivity_i))*var_sigma
                        self.container_concentration[var_filetype][var_datatype][var_file_short]["1 SIGMA INCL"][
                            isotope] = var_result_sigma_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                if var_filetype == "STD":
                    focus_set = ["MAT"]
                else:
                    focus_set = ["MAT", "INCL"]

                for var_focus in focus_set:
                    if var_focus not in self.container_concentration[var_filetype][var_datatype]:
                        self.container_concentration[var_filetype][var_datatype][var_focus] = {}

                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []

                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

                                if isotope in file_isotopes:
                                    self.fi_get_concentration2(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long, var_focus=var_focus,
                                        pypitzer=pypitzer)
                                    var_result_i = self.container_concentration[var_filetype][var_datatype][
                                        var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_concentration[var_filetype][var_datatype][var_focus][isotope] = var_result_i

    def calculate_mixed_concentration_ratio(self, intensity_mix_i, intensity_mix_IS, sensitivity_IS_i):
        """ Calculates the mixed concentration ratio a.
        1) Matrix-only-Tracer:      a = C_t^MIX/C_IS^MIX    - i = t
        2) 2nd Internal Standard:   a = C_IS2^MIX/C_IS1^MIX - i = IS2, IS=IS1

        Parameters
        ----------
        intensity_mix_i : float
            The mixed intensity of i
        intensity_mix_IS : float
            The mixed intensity of IS
        sensitivity_IS_i : float
            The analytical sensitivity of i with respect to IS
        Returns
        -------
        """
        val_a = intensity_mix_i/(intensity_mix_IS*sensitivity_IS_i)
        return val_a

    def calculate_mixing_ratio_geometric_approach(self, filename_long):
        """ Calculates the mixing ratio x.
        Parameters
        ----------
        filename_long : string
            The long version of the filename (whole path)
        Returns
        -------
        val_x : float
            The mixing ratio
        """
        str_filename_long = filename_long

        val_a = float(self.container_var["SMPL"][str_filename_long]["Halter2002"]["a"].get())
        val_b = float(self.container_var["SMPL"][str_filename_long]["Halter2002"]["b"].get())
        val_rho_incl = float(self.container_var["SMPL"][str_filename_long]["Halter2002"]["rho(incl)"].get())
        val_rho_host = float(self.container_var["SMPL"][str_filename_long]["Halter2002"]["rho(host)"].get())
        val_radius = float(self.container_var["SMPL"][str_filename_long]["Halter2002"]["R"].get())

        upper_term = (4/3)*np.pi*val_a*val_b*val_rho_incl
        lower_term = ((2*np.pi*val_radius**2 - (4/3)*np.pi*val_a*val_b)*val_rho_host + (4/3)*np.pi*val_a*val_b*
                      val_rho_incl)
        val_x = upper_term/lower_term

        return val_x

    def calculate_mixing_ratio(self, factor_a, concentration_mat_i, concentration_mat_IS, concentraton_incl_i,
                               concentration_incl_IS):
        """ Calculates the mixing ratio x.
        1) Matrix-only-Tracer:      i = t
        2) 2nd Internal Standard:   i = IS2, IS=IS1
        Parameters
        ----------
        factor_a : float
            The mixed concentration ratio
        concentration_mat_i : float
            The matrix concentration of i
        concentration_mat_IS : float
            The matrix concentration of IS
        concentraton_incl_i : float
            The inclusion concentration of i
        concentration_incl_IS : float
            The inclusion concentration of IS
        Returns
        -------
        val_x : float
            The mixing ratio
        """
        upper_term = concentration_mat_i - factor_a*concentration_mat_IS
        lower_term = concentration_mat_i - concentraton_incl_i - factor_a*(concentration_mat_IS - concentration_incl_IS)
        val_x = upper_term/lower_term
        return val_x

    def fi_get_mixed_concentration_ratio(self, var_datatype, var_file_short, var_file_long, mode="Specific"):
        """ Calculates the mixed concentration ratio a.
        1) Matrix-only-Tracer:      a = C_t^MIX/C_IS^MIX
        2) 2nd Internal Standard:   a = C_IS2^MIX/C_IS1^MIX

        Parameters
        ----------
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)
        mode : str
            The calculation mode, e.g. "Specific"

        Returns
        -------
        """
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if mode == "Specific":
            var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

            if self.container_var[key_setting][
                "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                var_mo = self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].get()
            elif self.container_var[key_setting][
                "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                var_mo = self.container_var["SMPL"][var_file_long]["Second Internal Standard"]["Name"].get()
            elif self.container_var[key_setting][
                "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                var_mo = self.container_var["Halter2002"]["Name"].get()
            elif self.container_var[key_setting][
                "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                var_mo = self.container_var["Borisova2021"]["Name"].get()

            for isotope in file_isotopes:
                if self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                    var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_mo]
                    var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_is]
                    var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file_short][
                        "INCL"][var_mo]
                elif self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                    var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_mo]
                    var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_is]
                    var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file_short][
                        "INCL"][var_mo]
                elif self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                    var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_mo]
                    var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_is]
                    var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file_short][
                        "INCL"][var_mo]
                elif self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                    var_intensity_mix_i = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_mo]
                    var_intensity_mix_is = self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_is]
                    var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file_short][
                        "INCL"][var_mo]

                if (var_intensity_mix_is*var_sensitivity_i) > 0:
                    var_result_i = var_intensity_mix_i/(var_intensity_mix_is*var_sensitivity_i)
                else:
                    var_result_i = np.nan

                self.container_mixed_concentration_ratio["SMPL"][var_datatype][var_file_short][isotope] = var_result_i
        else:
            for var_filetype in ["SMPL"]:
                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    #
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                self.fi_get_mixed_concentration_ratio(
                                    var_datatype=var_datatype, var_file_short=var_file_short,
                                    var_file_long=var_file_long)
                                var_result_i = self.container_mixed_concentration_ratio[var_filetype][var_datatype][
                                    var_file_short][isotope]
                                helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)
                    self.container_mixed_concentration_ratio[var_filetype][var_datatype][isotope] = var_result_i

    def fi_get_mixing_ratio(self, var_datatype, var_file_short, var_file_long, mode="Specific"):
        """ Calculates the mixing ratio x based on the following equation:
        Sample Files:   1) x = (C_HOST_MO - a*C_HOST_IS)/(C_HOST_MO - a*(C_HOST_IS - C_INCL_IS))
                        2) x = (C_HOST_IS2 - a*C_HOST_IS1)/(C_HOST_IS2 - C_INCL_IS2 - a*(C_HOST_IS1 - C_INCL_IS1))
                        --> MO = 'Matrix-Only', IS2 = 'Second Internal Standard'
        Parameters
        ----------
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as a long version (with the complete filepath)
        mode : str
            The analysis mode, e.g. 'Specific'

        Returns
        -------
        """
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if mode == "Specific":
            var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

            if self.container_var[key_setting][
                "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                var_mo = self.container_var["SMPL"][var_file_long]["Host Only Tracer"]["Name"].get()
            elif self.container_var[key_setting][
                "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                var_is1 = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
                var_is2 = self.container_var["SMPL"][var_file_long]["Second Internal Standard"]["Name"].get()
            elif self.container_var[key_setting][
                "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                var_mo = self.container_var["Halter2002"]["Name"].get()
            elif self.container_var[key_setting][
                "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                var_mo = self.container_var["Borisova2021"]["Name"].get()

            for isotope in file_isotopes:
                if self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                    var_a = self.container_mixed_concentration_ratio["SMPL"][var_datatype][var_file_short][isotope]
                    var_concentration_host_mo = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "MAT"][var_mo]
                    var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "MAT"][var_is]
                    var_concentration_incl_is = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "INCL"][var_is]

                    if None not in (var_a, var_concentration_host_mo, var_concentration_host_is,
                                    var_concentration_incl_is):
                        upper_term = var_concentration_host_mo - var_a*var_concentration_host_is
                        lower_term = (var_concentration_host_mo - var_a*
                                      (var_concentration_host_is - var_concentration_incl_is))
                    else:
                        upper_term = np.nan
                        lower_term = np.nan
                elif self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                    var_a = self.container_mixed_concentration_ratio["SMPL"][var_datatype][var_file_short][isotope]
                    var_concentration_host_is1 = self.container_concentration["SMPL"][var_datatype][
                        var_file_short]["MAT"][var_is1]
                    var_concentration_host_is2 = self.container_concentration["SMPL"][var_datatype][
                        var_file_short]["MAT"][var_is2]
                    var_concentration_incl_is1 = float(self.container_var["SMPL"][var_file_long]["IS Data"][
                                                           "Concentration"].get())
                    var_concentration_incl_is2 = float(self.container_var["SMPL"][var_file_long][
                                                           "Second Internal Standard"]["Value"].get())

                    upper_term = var_concentration_host_is2 - var_a*var_concentration_host_is1
                    lower_term = var_concentration_host_is2 - var_concentration_incl_is2 - var_a*(
                            var_concentration_host_is1 - var_concentration_incl_is1)
                elif self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Geometric Approach (Halter et al. 2002)":
                    var_a = self.container_mixed_concentration_ratio["SMPL"][var_datatype][var_file_short][isotope]
                    var_concentration_host_mo = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "MAT"][var_mo]
                    var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "MAT"][var_is]
                    var_concentration_incl_is = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "INCL"][var_is]

                    upper_term = var_concentration_host_mo - var_a*var_concentration_host_is
                    lower_term = var_concentration_host_mo - var_a*(
                            var_concentration_host_is - var_concentration_incl_is)
                elif self.container_var[key_setting][
                    "Quantification Method Option"].get() == "Geometric Approach (Borisova et al. 2021)":
                    var_a = self.container_mixed_concentration_ratio["SMPL"][var_datatype][var_file_short][isotope]
                    var_concentration_host_mo = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "MAT"][var_mo]
                    var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "MAT"][var_is]
                    var_concentration_incl_is = self.container_concentration["SMPL"][var_datatype][var_file_short][
                        "INCL"][var_is]

                    upper_term = var_concentration_host_mo - var_a*var_concentration_host_is
                    lower_term = var_concentration_host_mo - var_a*(
                            var_concentration_host_is - var_concentration_incl_is)

                if lower_term != 0:
                    var_result_i = upper_term/lower_term
                else:
                    var_result_i = 0

                self.container_mixing_ratio["SMPL"][var_datatype][var_file_short][isotope] = var_result_i
        else:
            for var_filetype in ["SMPL"]:
                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                self.fi_get_mixing_ratio(
                                    var_datatype=var_datatype, var_file_short=var_file_short,
                                    var_file_long=var_file_long)
                                var_result_i = self.container_mixing_ratio[var_filetype][var_datatype][var_file_short][
                                    isotope]
                                helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)
                    self.container_mixing_ratio["SMPL"][var_datatype][isotope] = var_result_i

    def fi_get_concentration_mixed(self, var_datatype, var_file_short, mode="Specific"):
        """ Calculates the mixed concentration, C_MIX_i, based on the following equation:
        Sample Files:    C_MIX_i = (1 - x)*C_HOST_i + x*C_INCL_i

        Parameters
        ----------
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        mode : str
            The analysis mode, e.g. 'Specific'

        Returns
        -------
        """
        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            var_index = self.container_lists["SMPL"]["Short"].index(var_file_short)
            var_file_long = self.container_lists["SMPL"]["Long"][var_index]
            var_is = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()

            var_intensity_mix_is =  self.container_intensity_mix["SMPL"][var_datatype][var_file_short][var_is]
            var_x = self.container_mixing_ratio["SMPL"][var_datatype][var_file_short][var_is]
            var_concentration_host_is = self.container_concentration["SMPL"][var_datatype][var_file_short]["MAT"][
                var_is]
            var_concentration_incl_is = self.container_concentration["SMPL"][var_datatype][var_file_short]["INCL"][
                var_is]

            if None not in (var_x, var_concentration_host_is, var_concentration_incl_is):
                var_concentration_mix_is = (1 - var_x)*var_concentration_host_is + var_x*var_concentration_incl_is
            else:
                var_concentration_mix_is = np.nan

            for isotope in file_isotopes:
                var_x = self.container_mixing_ratio["SMPL"][var_datatype][var_file_short][isotope]
                var_concentration_host_i = self.container_concentration["SMPL"][var_datatype][var_file_short]["MAT"][
                    isotope]
                var_concentration_incl_i = self.container_concentration["SMPL"][var_datatype][var_file_short]["INCL"][
                    isotope]

                if None not in (var_x, var_concentration_host_i, var_concentration_incl_i):
                    var_result_i = (1 - var_x)*var_concentration_host_i + var_x*var_concentration_incl_i
                else:
                    var_result_i = np.nan

                self.container_mixed_concentration["SMPL"][var_datatype][var_file_short][isotope] = var_result_i

                var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file_short][
                    "INCL"][isotope]
                var_intensity_bg_i = self.container_intensity["SMPL"][var_datatype][var_file_short]["BG"][isotope]
                var_intensity_mix_i =  self.container_intensity["SMPL"][var_datatype][var_file_short]["INCL"][isotope]
                var_n_bg = self.container_intensity["SMPL"][var_datatype][var_file_short]["N BG"][isotope]
                var_n_mix = self.container_intensity["SMPL"][var_datatype][var_file_short]["N INCL"][isotope]
                var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                var_sigma_bg_i = ((((var_intensity_bg_i*var_tau_i)/var_n_bg)**0.5/var_tau_i)**2)**0.5
                var_sigma_mix_i = ((((var_intensity_mix_i*var_tau_i)/var_n_mix)**0.5/var_tau_i)**2)**0.5
                var_sigma = (var_sigma_bg_i**2 + var_sigma_mix_i**2)**0.5

                if (var_intensity_mix_is*var_sensitivity_i) > 0:
                    var_result_sigma_i = (var_concentration_mix_is/(var_intensity_mix_is*var_sensitivity_i))*var_sigma
                else:
                    var_result_sigma_i = 0.0

                self.container_mixed_concentration_error["SMPL"][var_datatype][var_file_short][
                    isotope] = var_result_sigma_i
        else:
            for var_filetype in ["SMPL"]:
                for isotope in self.container_lists["Measured Isotopes"]["All"]:
                    helper_results = []
                    for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                        if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                            var_file_short = self.container_lists[var_filetype]["Short"][index]
                            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                            if isotope in file_isotopes:
                                self.fi_get_concentration_mixed(
                                    var_datatype=var_datatype, var_file_short=var_file_short)
                                var_result_i = self.container_mixed_concentration[var_filetype][var_datatype][
                                    var_file_short][isotope]
                                helper_results.append(var_result_i)

                    if self.container_var["General Settings"]["Desired Average"].get() == 1:
                        var_result_i = np.mean(helper_results)
                    else:
                        var_result_i = np.median(helper_results)
                    self.container_mixed_concentration[var_filetype][var_datatype][isotope] = var_result_i

    def fi_get_concentration_ratio(self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus,
                                   mode="Specific"):
        """ Calculates the concentration ratio, C_i/C_is, based on the following two equations:
        1) Standard Files:  C_i = C_std_i/C_std_is
        2) Sample Files:    C_i = C_smpl_i/C_smpl_is

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)
        var_focus : str
            The focus category, e.g. MAT

        Returns
        -------
        """
        if mode == "Specific":
            if var_filetype == "STD":
                var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                for element, value in sorted(
                        self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                    if element in self.container_lists["Measured Elements"][var_file_short]:
                        var_is = self.container_lists["Measured Elements"][var_file_short][element][0]
                    break
            else:
                var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()

            var_concentration_is = self.container_concentration[var_filetype][var_datatype][var_file_short][var_focus][
                var_is]
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

            for isotope in file_isotopes:
                var_concentration_i = self.container_concentration[var_filetype][var_datatype][var_file_short][
                    var_focus][isotope]
                if var_concentration_is != None:
                    if var_concentration_is > 0:
                        var_result_i = var_concentration_i/var_concentration_is
                    else:
                        var_result_i = 0
                else:
                    var_result_i = np.nan

                self.container_concentration_ratio[var_filetype][var_datatype][var_file_short][var_focus][
                    isotope] = var_result_i
        else:
            for var_filetype in ["STD", "SMPL"]:
                if var_filetype == "STD":
                    focus_set = ["MAT"]
                else:
                    focus_set = ["MAT", "INCL"]

                for var_focus in focus_set:
                    if var_focus not in self.container_concentration_ratio[var_filetype][var_datatype]:
                        self.container_concentration_ratio[var_filetype][var_datatype][var_focus] = {}

                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    self.fi_get_concentration_ratio(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long, var_focus=var_focus)
                                    var_result_i = self.container_concentration_ratio[var_filetype][var_datatype][
                                        var_file_short][var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_concentration_ratio[var_filetype][var_datatype][var_focus][
                            isotope] = var_result_i

    #
    def fi_get_lod(self, var_filetype, var_datatype, var_file_short, var_file_long, var_focus, mode="Specific"):
        """ Calculates the Limit of Detection, LoD, based on the following two equations:
        1) Standard Files:  C_i = C_std_i/C_std_is
        2) Sample Files:    C_i = C_smpl_i/C_smpl_is

        Parameters
        ----------
        var_filetype : str
            The file category, e.g. STD
        var_datatype : str
            The data category, e.g. RAW
        var_file_short : str
            The file as a short version (without the complete filepath)
        var_file_long : str
            The file as the long version (with the complete filepath)

        Returns
        -------
        """
        if mode == "Specific":
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            if var_filetype == "STD":
                for isotope in file_isotopes:
                    var_n_bg = 0
                    var_n_mat = 0
                    helper_sigma_i = []

                    for key, items in self.container_helper[var_filetype][var_file_short]["BG"]["Content"].items():
                        var_indices = items["Indices"]
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1]]
                        var_n_bg += len(var_data)
                        helper_sigma_i.append(np.std(var_data, ddof=1))

                    for key, items in self.container_helper[var_filetype][var_file_short]["MAT"]["Content"].items():
                        var_indices = items["Indices"]
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1]]
                        var_n_mat += len(var_data)

                    var_concentration_i = \
                    self.container_concentration[var_filetype][var_datatype][var_file_short]["MAT"][
                        isotope]
                    var_intensity_i = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        "MAT"][isotope]

                    if self.container_var["General Settings"]["LOD Selection"].get() == 0:
                        var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                            isotope]
                        var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())

                        if var_n_bg > 0 and var_intensity_i > 0:
                            var_result_i = (3.29*(
                                    var_intensity_bg_i*var_tau_i*var_n_mat*(1 + var_n_mat/var_n_bg))**(0.5) + 2.71)/(
                                                   var_n_mat*var_tau_i)*(var_concentration_i/var_intensity_i)
                        else:
                            var_result_i = 0.0

                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i

                    elif self.container_var["General Settings"]["LOD Selection"].get() == 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_sigma_bg_i = np.mean(helper_sigma_i)
                        else:
                            var_sigma_bg_i = np.median(helper_sigma_i)

                        var_result_i = (3*var_sigma_bg_i*var_concentration_i)/(var_intensity_i)*(
                                1/var_n_bg + 1/var_n_mat)**(0.5)
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i

            elif var_filetype == "SMPL":
                for isotope in file_isotopes:
                    var_n_bg = 0
                    var_n_mat = 0
                    helper_sigma_i = []
                    #
                    for key, items in self.container_helper[var_filetype][var_file_short]["BG"]["Content"].items():
                        var_indices = items["Indices"]
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_bg += len(var_data)
                        helper_sigma_i.append(np.std(var_data, ddof=1))
                    #
                    for key, items in self.container_helper[var_filetype][var_file_short][var_focus]["Content"].items():
                        var_indices = items["Indices"]
                        var_key = "Data " + str(var_datatype)
                        var_data = self.container_spikes[var_file_short][isotope][var_key][
                                   var_indices[0]:var_indices[1] + 1]
                        var_n_mat += len(var_data)

                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                    var_concentration_is = self.container_concentration[var_filetype][var_datatype][var_file_short][
                        var_focus][var_is]
                    var_intensity_is = self.container_intensity_corrected[var_filetype][var_datatype][var_file_short][
                        var_focus][var_is]
                    #
                    if self.container_var["General Settings"]["LOD Selection"].get() == 0:
                        var_intensity_bg_i = self.container_intensity[var_filetype][var_datatype][var_file_short]["BG"][
                            isotope]
                        var_tau_i = float(self.container_var["dwell_times"]["Entry"][isotope].get())
                        var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_file_short]["MAT"][isotope]

                        if var_n_bg > 0 and var_intensity_is > 0:
                            var_result_i = (3.29*(
                                    var_intensity_bg_i*var_tau_i*var_n_mat*(1 + var_n_mat/var_n_bg))**(0.5) + 2.71)/(
                                                   var_n_mat*var_tau_i*var_sensitivity_i)*(
                                                       var_concentration_is/var_intensity_is)
                        else:
                            var_result_i = 0.0
                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = var_result_i
                        #
                    elif self.container_var["General Settings"]["LOD Selection"].get() == 1:
                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_sigma_bg_i = np.mean(helper_sigma_i)
                        else:
                            var_sigma_bg_i = np.median(helper_sigma_i)
                        var_sensitivity_i = self.container_analytical_sensitivity[var_filetype][var_datatype][
                            var_file_short]["MAT"][isotope]

                        if var_n_bg > 0 and var_n_mat > 0:
                            var_result_i = (3*var_sigma_bg_i*var_concentration_is)/(
                                    var_sensitivity_i*var_intensity_is)*(1/var_n_bg + 1/var_n_mat)**(0.5)
                        else:
                            var_result_i = 0.0
                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = var_result_i
            #
        else:
            for var_filetype in ["STD", "SMPL"]:
                if var_filetype == "STD":
                    focus_set = ["MAT"]
                else:
                    focus_set = ["MAT", "INCL"]

                for var_focus in focus_set:
                    if var_focus not in self.container_lod[var_filetype][var_datatype]:
                        self.container_lod[var_filetype][var_datatype][var_focus] = {}

                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        helper_results = []
                        for index, var_file_long in enumerate(self.container_lists[var_filetype]["Long"]):
                            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                                var_file_short = self.container_lists[var_filetype]["Short"][index]
                                file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                                if isotope in file_isotopes:
                                    self.fi_get_lod(
                                        var_filetype=var_filetype, var_datatype=var_datatype,
                                        var_file_short=var_file_short, var_file_long=var_file_long, var_focus=var_focus)
                                    var_result_i = self.container_lod[var_filetype][var_datatype][var_file_short][
                                        var_focus][isotope]
                                    helper_results.append(var_result_i)

                        if self.container_var["General Settings"]["Desired Average"].get() == 1:
                            var_result_i = np.mean(helper_results)
                        else:
                            var_result_i = np.median(helper_results)
                        self.container_lod[var_filetype][var_datatype][var_focus][isotope] = var_result_i

    #
    ####################################################################################################################
    #
    def fi_datareduction_tables(self, init=False):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Initialization
        if init:
            for var_filetype in ["STD", "SMPL"]:
                for var_file_short in self.container_lists[var_filetype]["Short"]:
                    self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)
            var_filetype = "None"
            var_file_short = "None"
            var_file_long = "None"
            var_focus = "None"
            self.var_init_fi_datareduction = True

            for var_datatype in ["RAW", "SMOOTHED"]:
                # Intensity Results
                self.get_intensity(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_focus=var_focus, mode="All")
                self.fi_get_intensity_corrected(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_focus=var_focus, mode="All")
                self.fi_get_intensity_mix(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short, mode="All")
                # Sensitivity Results
                self.get_analytical_sensitivity(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, mode="All")
                results_is = self.determine_possible_is(filetype="ALL")
                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_ratio).get_intensity_ratio(
                    data_container=self.container_intensity_corrected, dict_is=results_is, datatype=var_datatype)
                self.fi_get_rsf(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=var_focus, mode="All")
                # Concentration Results
                self.fi_get_concentration2(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=var_focus, mode="All")
                # SQ(dataframe_01=self.container_intensity_corrected[var_filetype][var_datatype][var_file_short],
                #    dataframe_02=self.container_concentration[var_filetype][var_datatype][var_file_short],
                #    results_container=self.container_normalized_sensitivity[var_filetype][
                #        var_datatype]).get_normalized_sensitivity(
                #     filename_short=var_file_short, filetype=var_filetype,
                #     data_sensitivity=self.container_analytical_sensitivity[var_filetype][var_datatype][var_file_short],
                #     dict_is=results_is)
                self.fi_get_normalized_sensitivity(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=var_focus, mode="All")
                self.fi_get_concentration_ratio(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=var_focus, mode="All")
                self.get_lod(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=None, mode="All")
                self.fi_get_mixed_concentration_ratio(
                    var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long, mode="All")
                self.fi_get_mixing_ratio(
                    var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long, mode="All")
                self.fi_get_concentration_mixed(var_datatype=var_datatype, var_file_short=var_file_short, mode="All")

        if self.container_var["fi_datareduction_files"]["File Type"].get() == 0:
            var_filetype = "STD"

            self.rb_04b.configure(state="disabled")  # Inclusion
            self.rb_05d.configure(state="disabled")  # Mixing Ratio a
            self.rb_05e.configure(state="disabled")  # Mixing Ratio x
            self.rb_05f.configure(state="disabled")  # Mixed Concentration
            self.rb_05h.configure(state="disabled")  # Intensity Mix

            if self.container_var["fi_datareduction_files"]["Result Category"].get() not in [0, 1, 2, 6, 8, 9, 10]:
                self.container_var["fi_datareduction_files"]["Result Category"].set(0)
        elif self.container_var["fi_datareduction_files"]["File Type"].get() == 1:
            var_filetype = "SMPL"

            self.rb_04b.configure(state="normal")  # Inclusion
            self.rb_05d.configure(state="normal")  # Mixing Ratio a
            self.rb_05e.configure(state="normal")  # Mixing Ratio x
            self.rb_05f.configure(state="normal")  # Mixed Concentration
            self.rb_05h.configure(state="normal")  # Intensity Mix

        if self.container_var["fi_datareduction_files"]["Data Type"].get() == 0:
            var_datatype = "RAW"
        elif self.container_var["fi_datareduction_files"]["Data Type"].get() == 1:
            var_datatype = "SMOOTHED"

        if self.container_var["fi_datareduction_files"]["Focus"].get() == 0:
            var_focus = "MAT"

            self.rb_01a.configure(state="normal")  # Standard Files
            self.rb_05d.configure(state="disabled")  # Mixing Ratio a
            self.rb_05e.configure(state="disabled")  # Mixing Ratio x
            self.rb_05f.configure(state="disabled")  # Mixed Concentration
            self.rb_05h.configure(state="disabled")  # Intensity Mix

        elif self.container_var["fi_datareduction_files"]["Focus"].get() == 1:
            var_focus = "INCL"

            self.rb_01a.configure(state="disabled")  # Standard Files
            self.rb_05d.configure(state="normal")  # Mixing Ratio a
            self.rb_05e.configure(state="normal")  # Mixing Ratio x
            self.rb_05f.configure(state="normal")  # Mixed Concentration
            self.rb_05h.configure(state="normal")  # Intensity Mix

        if len(self.tv_results_files.get_children()) > 0:
            for item in self.tv_results_files.get_children():
                self.tv_results_files.delete(item)

        var_id = self.container_var["ID"]["Results Files"].get()
        helper_values = {}
        helper_separator = ["-"]
        for isotope in self.container_lists["ISOTOPES"]:
            if isotope not in helper_values:
                helper_values[isotope] = []
                helper_separator.append("-")

        if self.container_var["fi_datareduction_files"]["Result Category"].get() == 0:  # Concentration
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_concentration[var_filetype][var_datatype][var_file][var_focus][
                                isotope]
                            value_lod = self.container_lod[var_filetype][var_datatype][var_file][var_focus][isotope]

                            if var_filetype == "SMPL":
                                n_digits = 4
                            else:
                                n_digits = 1

                            if value >= value_lod or var_filetype == "STD":
                                entries_container.append(f"{value:.{n_digits}f}")
                                helper_values[isotope].append(value)
                            else:
                                if str(value) == "nan":
                                    entries_container.append("undefined")
                                else:
                                    if str(value_lod) == "nan" and str(value) != "nan":
                                        entries_container.append(f"{value:.{n_digits}f}")
                                        helper_values[isotope].append(value)
                                    else:
                                        entries_container.append("< LoD")

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 1:  # Concentration Ratio
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_concentration_ratio[var_filetype][var_datatype][var_file][var_focus][
                                isotope]
                            entries_container.append(f"{value:.{4}E}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 2:  # Limit of Detection
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_lod[var_filetype][var_datatype][var_file][var_focus][isotope]
                            n_digits = 4

                            entries_container.append(f"{value:.{n_digits}f}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 3:  # Mixing Ratio a
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_mixed_concentration_ratio[var_filetype][var_datatype][var_file][
                                isotope]
                            n_digits = 4

                            entries_container.append(f"{value:.{n_digits}f}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 4:  # Mixing Ratio x
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_mixing_ratio[var_filetype][var_datatype][var_file][isotope]

                            if str(value) in ["nan", "NAN"]:
                                entries_container.append("undefined")
                            else:
                                entries_container.append(f"{value:.{4}E}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 5:  # Mixed Concentration
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_mixed_concentration[var_filetype][var_datatype][var_file][isotope]
                            n_digits = 4

                            if str(value) in ["nan", "NAN"]:
                                entries_container.append("undefined")
                            else:
                                entries_container.append(f"{value:.{n_digits}f}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 6:  # Intensity
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_intensity_corrected[var_filetype][var_datatype][var_file][var_focus][
                                isotope]
                            n_digits = 4
                            #
                            entries_container.append(f"{value:.{n_digits}f}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 7:  # Intensity Mix
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_intensity_mix[var_filetype][var_datatype][var_file][isotope]
                            n_digits = 4

                            entries_container.append(f"{value:.{n_digits}f}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 8:  # Analytical Sensitivity
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                        var_srm_file = None
                        if var_focus == "INCL":
                            var_is_file = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                        else:
                            var_is_file = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                    else:
                        var_id_i = None
                        var_srm_file = self.container_var[var_filetype][var_file_long]["SRM"].get()
                        var_is_file = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]
                        str_is = None
                        for isotope in file_isotopes:
                            value = self.container_analytical_sensitivity[var_filetype][var_datatype][var_file][
                                var_focus][isotope]
                            if var_filetype == "SMPL":
                                y_value = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file]["INCL"][
                                    isotope]

                            if var_is_file != None:
                                value_is = self.container_analytical_sensitivity[var_filetype][var_datatype][var_file][
                                    var_focus][var_is_file]
                                value = value/value_is

                            if value == 1.00:
                                str_is = isotope

                            if value != None:
                                n_digits = 4
                                entries_container.append(f"{value:.{n_digits}f}")
                            else:
                                if str_is == None:
                                    for isotope_2 in file_isotopes:
                                        value = self.container_analytical_sensitivity[var_filetype][var_datatype][
                                            var_file]["MAT"][isotope_2]

                                        if value == 1.00:
                                            str_is = isotope_2
                                            break

                                value_s_i = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file][
                                    var_focus][isotope]
                                value_s_is = self.container_normalized_sensitivity[var_filetype][var_datatype][
                                    var_file][var_focus][str_is]
                                value = value_s_i/value_s_is
                                n_digits = self.ma_determine_ndigits(var_value=value)
                                entries_container.append(f"{value:.{n_digits}f}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 9:  # Normalized Sensitivity
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]
                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None
                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file][
                                var_focus][isotope]
                            n_digits = 4
                            #
                            entries_container.append(f"{value:.{n_digits}f}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

        elif self.container_var["fi_datareduction_files"]["Result Category"].get() == 10:  # RSF
            for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
                var_file_long = self.container_lists[var_filetype]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][var_file]

                if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                    if var_filetype == "SMPL":
                        var_id_i = self.container_var[var_filetype][var_file_long]["ID"].get()
                    else:
                        var_id_i = None

                    if var_id_i == var_id or var_filetype == "STD":
                        entries_container = [var_file]

                        for isotope in file_isotopes:
                            value = self.container_rsf[var_filetype][var_datatype][var_file]["MAT"][isotope]
                            entries_container.append(f"{value:.{4}E}")
                            helper_values[isotope].append(value)

                        self.tv_results_files.insert("", tk.END, values=entries_container)
                    else:
                        for isotope in file_isotopes:
                            if isotope not in helper_values:
                                helper_values[isotope] = []
                                helper_separator.append("-")

            self.tv_results_files.insert("", tk.END, values=helper_separator)
            self.ma_calculate_statistics_table(var_data=helper_values)

    def fi_show_diagrams_intensity(self):
        pass

    def show_diagrams_sensitivity(self):
        ## Window Settings
        window_width = 1400
        window_height = 800
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_fi_graphical_sensitivity = tk.Toplevel(self.parent)
        if self.pysills_mode == "MA":
            self.subwindow_fi_graphical_sensitivity.title("MINERAL ANALYSIS - Sensitivity Results")
        elif self.pysills_mode == "FI":
            self.subwindow_fi_graphical_sensitivity.title("FLUID INCLUSION ANALYSIS - Sensitivity Results")
        elif self.pysills_mode == "MI":
            self.subwindow_fi_graphical_sensitivity.title("MELT INCLUSION ANALYSIS - Sensitivity Results")
        self.subwindow_fi_graphical_sensitivity.geometry(var_geometry)
        self.subwindow_fi_graphical_sensitivity.resizable(False, False)
        self.subwindow_fi_graphical_sensitivity["bg"] = self.bg_colors["Very Light"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_fi_graphical_sensitivity, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_fi_graphical_sensitivity, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_fi_graphical_sensitivity.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_fi_graphical_sensitivity.grid_columnconfigure(i, minsize=column_min)

        # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --

        start_row = 0
        start_column = 0

        ## FRAMES
        frm_00 = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row, column_id=start_column,
            n_rows=n_rows, n_columns=11, fg=self.bg_colors["Very Light"],
            bg=self.bg_colors["Super Dark"]).create_frame(relief=tk.FLAT)

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="File Type", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Data Type", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 6, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Focus", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 9, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Primary Isotope", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 11, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Secondary Isotope", relief=tk.FLAT, fontsize="sans 10 bold")

        ## RADIOBUTTONS
        self.var_opt_iso_04 = tk.StringVar()
        self.var_opt_iso_04.set(self.container_lists["ISOTOPES"][0])
        self.var_opt_iso_05 = tk.StringVar()
        self.var_opt_iso_05.set(self.container_lists["ISOTOPES"][1])

        self.rb_01a_std = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.var_rb_01, value_rb=0, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Standard Files", sticky="nesw", relief=tk.FLAT, command=self.fi_change_sensitivity_drift_diagram)
        rb_01b = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.var_rb_01, value_rb=1, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Sample Files", sticky="nesw", relief=tk.FLAT, command=self.fi_change_sensitivity_drift_diagram)

        rb_02a = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 4, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.var_rb_02, value_rb=0, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="RAW Data", sticky="nesw", relief=tk.FLAT, command=self.fi_change_sensitivity_drift_diagram)
        rb_02b = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.var_rb_02, value_rb=1, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="SMOOTHED Data", sticky="nesw", relief=tk.FLAT, command=self.fi_change_sensitivity_drift_diagram)

        rb_03a = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 7, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.var_rb_03, value_rb=0, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Matrix (MAT)", sticky="nesw", relief=tk.FLAT, command=self.fi_change_sensitivity_drift_diagram)
        self.rb_03b = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 8, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.var_rb_03, value_rb=1, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Inclusion (INCL)", sticky="nesw", relief=tk.FLAT, command=self.fi_change_sensitivity_drift_diagram)

        ## OPTION MENUS
        opt_04a = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 10, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.var_opt_iso_04, option_list=self.container_lists["ISOTOPES"],
            text_set=self.var_opt_iso_04.get(), fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=self.fi_change_sensitivity_drift_diagram)
        opt_04a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_04a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        opt_05a = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row + 12, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.var_opt_iso_05, option_list=self.container_lists["ISOTOPES"],
            text_set=self.var_opt_iso_05.get(), fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=self.change_normalized_sensitivity_scatter)
        opt_05a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_05a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        ## INITIALIZATION
        self.show_sensitivity_drift_diagram()
        self.show_normalized_sensitivity_scatter()
        self.show_relative_sensitivity_comparison()

    def show_sensitivity_drift_diagram(self, mode=None):
        if self.var_rb_01.get() == 0:
            var_filetype = "STD"
            self.rb_03b.configure(state="disabled")
        else:
            var_filetype = "SMPL"
            self.rb_03b.configure(state="normal")

        if self.var_rb_02.get() == 0:
            var_datatype = "RAW"
        else:
            var_datatype = "SMOOTHED"

        try:
            var_iso_01 = self.var_opt_iso_04.get()
        except:
            var_iso_01 = self.var_opt_iso_04

        self.fig_sensitivity_03a = Figure(
            figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.canvas_sensitivity_03a = FigureCanvasTkAgg(
            self.fig_sensitivity_03a, master=self.subwindow_fi_graphical_sensitivity)
        self.canvas_sensitivity_03a.get_tk_widget().grid(row=0, column=11, rowspan=16, columnspan=28, sticky="nesw")
        self.ax_sensitivity_03a = self.fig_sensitivity_03a.add_subplot(label=np.random.uniform())

        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Drift"][
            "FIG"] = self.fig_sensitivity_03a
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Drift"][
            "CANVAS"] = self.canvas_sensitivity_03a
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Drift"][
            "AX"] = self.ax_sensitivity_03a

        x_values = []
        y_values = []

        if self.var_rb_03.get() == 0:
            str_focus = "MAT"
            self.rb_01a_std.configure(state="normal")
        elif self.var_rb_03.get() == 1:
            str_focus = "INCL"
            self.rb_01a_std.configure(state="disabled")

        for key, value in self.container_lists["Acquisition Times Delta"].items():
            var_file = key

            if var_file in self.container_lists["STD"]["Short"]:
                var_filetype_2 = "STD"
            elif var_file in self.container_lists["SMPL"]["Short"]:
                var_filetype_2 = "SMPL"
            var_index = self.container_lists[var_filetype_2]["Short"].index(var_file)
            var_file_long = self.container_lists[var_filetype_2]["Long"][var_index]

            if self.container_var[var_filetype_2][var_file_long]["Checkbox"].get() == 1:
                if var_filetype == "STD" and var_file in self.container_lists[var_filetype]["Short"]:
                    var_srm_isotope = self.container_var["SRM"][var_iso_01].get()
                    var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_srm_isotope == var_srm_file:
                        x_value = value
                        y_value = self.container_analytical_sensitivity["STD"][var_datatype][var_file]["MAT"][
                            var_iso_01]
                        x_values.append(x_value)

                        if str_focus == "MAT":
                            str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                            if self.pysills_mode == "MA":
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                            else:
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                    "Name"].get()
                            y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                "MAT"][str_is_host]
                            y_value = y_value/y_value_is

                        self.ax_sensitivity_03a.scatter(
                            x=x_value, y=y_value, color=self.bg_colors["Dark"], edgecolor="black", s=80, marker="o")
                elif var_filetype == "SMPL":
                    if (var_file in self.container_analytical_sensitivity["STD"][var_datatype]
                            and var_file in self.container_lists["STD"]["Short"]):
                        var_srm_isotope = self.container_var["SRM"][var_iso_01].get()
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                        if var_srm_isotope == var_srm_file:
                            x_value = value
                            x_values.append(x_value)
                            y_value = self.container_analytical_sensitivity["STD"][var_datatype][var_file]["MAT"][
                                var_iso_01]

                            if str_focus == "MAT":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                    "MAT"][str_is_host]
                                y_value = y_value/y_value_is

                            dot_color = self.bg_colors["Dark"]
                            self.ax_sensitivity_03a.scatter(
                                x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="o")
                    elif (var_file in self.container_analytical_sensitivity["SMPL"][var_datatype]
                          and var_file in self.container_lists["SMPL"]["Short"]):
                        x_value = value
                        x_values.append(x_value)
                        y_value = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file][str_focus][
                            var_iso_01]

                        if str_focus == "MAT":
                            if self.pysills_mode == "MA":
                                str_is_host = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
                            else:
                                str_is_host = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"][
                                    "Name"].get()
                            y_value_is = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file][
                                "MAT"][str_is_host]
                            y_value = y_value/y_value_is

                        dot_color = self.bg_colors["Light"]
                        self.ax_sensitivity_03a.scatter(
                            x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="D")

                if var_file in self.container_lists["SMPL"]["Short"]:
                    if var_datatype == "RAW":
                        y_value = self.container_lists["Analytical Sensitivity Regression RAW"][var_iso_01][
                                      "a"]*x_value + self.container_lists[
                            "Analytical Sensitivity Regression RAW"][var_iso_01]["b"]

                        if str_focus == "MAT":
                            str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                            if self.pysills_mode == "MA":
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                            else:
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                    "Name"].get()
                            y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][str_is_host][
                                             "a"]*x_value + self.container_lists[
                                             "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                            y_value = y_value/y_value_is

                    elif var_datatype == "SMOOTHED":
                        y_value = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][var_iso_01][
                                      "a"]*x_value + self.container_lists[
                            "Analytical Sensitivity Regression SMOOTHED"][var_iso_01]["b"]

                        if str_focus == "MAT":
                            str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                            if self.pysills_mode == "MA":
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                            else:
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                    "Name"].get()
                            y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                             str_is_host]["a"]*x_value + self.container_lists[
                                             "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                            y_value = y_value/y_value_is

                    y_values.append(y_value)
                else:
                    if var_srm_isotope == var_srm_file:
                        if var_datatype == "RAW":
                            y_value = self.container_lists["Analytical Sensitivity Regression RAW"][var_iso_01][
                                          "a"]*x_value + self.container_lists[
                                "Analytical Sensitivity Regression RAW"][var_iso_01]["b"]

                            if str_focus == "MAT":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][str_is_host][
                                                 "a"]*x_value + self.container_lists[
                                    "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                                y_value = y_value/y_value_is

                        elif var_datatype == "SMOOTHED":
                            y_value = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][var_iso_01][
                                          "a"]*x_value + self.container_lists[
                                "Analytical Sensitivity Regression SMOOTHED"][var_iso_01]["b"]

                            if str_focus == "MAT":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                                 str_is_host]["a"]*x_value + self.container_lists[
                                    "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                                y_value = y_value/y_value_is

                        y_values.append(y_value)

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5

        if var_file in self.container_lists["SMPL"]["Short"]:
            zipped_lists = zip(x_values, y_values)
            sorted_zipped_lists = sorted(zipped_lists)
            x_data = []
            y_data = []
            for element in sorted_zipped_lists:
                x_data.append(element[0])
                y_data.append(element[1])

            self.ax_sensitivity_03a.plot(
                x_data, y_data, color=self.accent_color, linewidth=var_lw, linestyle="dashed")
        else:
            if var_srm_isotope == var_srm_file:
                zipped_lists = zip(x_values, y_values)
                sorted_zipped_lists = sorted(zipped_lists)
                x_data = []
                y_data = []
                for element in sorted_zipped_lists:
                    x_data.append(element[0])
                    y_data.append(element[1])

                self.ax_sensitivity_03a.plot(
                    x_data, y_data, color=self.accent_color, linewidth=var_lw, linestyle="dashed")

        self.ax_sensitivity_03a.grid(True)
        self.ax_sensitivity_03a.grid(which="major", linestyle="-", linewidth=1)
        self.ax_sensitivity_03a.minorticks_on()
        self.ax_sensitivity_03a.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        self.ax_sensitivity_03a.set_axisbelow(True)
        self.ax_sensitivity_03a.set_title("Analytical Sensitivity Drift", fontsize=9)
        self.ax_sensitivity_03a.set_xlabel("Experiment Time $t$ (s)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a.set_ylabel(
            "Analytical Sensitivity $\\xi$ of " + str(var_iso_01) + " (1)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a.xaxis.set_tick_params(labelsize=8)
        self.ax_sensitivity_03a.yaxis.set_tick_params(labelsize=8)

        self.canvas_sensitivity_03a.draw()

        if self.pysills_mode == "MA":
            self.rb_03b.configure(state="disabled")

    def fi_change_sensitivity_drift_diagram(self, mode=None):
        try:
            self.ax_sensitivity_03a.clear()
        except AttributeError:
            pass

        if self.var_rb_01.get() == 0:
            var_filetype = "STD"
            self.rb_03b.configure(state="disabled")
        else:
            var_filetype = "SMPL"
            self.rb_03b.configure(state="normal")

        if self.var_rb_02.get() == 0:
            var_datatype = "RAW"
        else:
            var_datatype = "SMOOTHED"

        x_values = []
        y_values = []

        if self.var_rb_03.get() == 0:
            str_focus = "MAT"
            self.rb_01a_std.configure(state="normal")
        elif self.var_rb_03.get() == 1:
            str_focus = "INCL"
            self.rb_01a_std.configure(state="disabled")

        try:
            var_iso_01 = self.var_opt_iso_04.get()
        except:
            var_iso_01 = self.var_opt_iso_04

        for key, value in self.container_lists["Acquisition Times Delta"].items():
            var_file = key

            if var_file in self.container_lists["STD"]["Short"]:
                var_filetype_2 = "STD"
            elif var_file in self.container_lists["SMPL"]["Short"]:
                var_filetype_2 = "SMPL"

            var_index = self.container_lists[var_filetype_2]["Short"].index(var_file)
            var_file_long = self.container_lists[var_filetype_2]["Long"][var_index]

            if str_focus == "INCL":
                var_file_long2 = self.container_lists["SMPL"]["Long"][0]
                str_is = self.container_var["SMPL"][var_file_long2]["IS Data"]["IS"].get()

            if self.container_var[var_filetype_2][var_file_long]["Checkbox"].get() == 1:
                if var_filetype == "STD" and var_file in self.container_lists[var_filetype]["Short"]:
                    var_srm_isotope = self.container_var["SRM"][var_iso_01].get()
                    var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_srm_isotope == var_srm_file:
                        x_value_std = value
                        y_value_std = self.container_analytical_sensitivity["STD"][var_datatype][var_file][str_focus][
                            var_iso_01]

                        if str_focus == "MAT":
                            str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                            if self.pysills_mode == "MA":
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                            else:
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                    "Name"].get()

                            y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                str_focus][str_is_host]

                            if y_value_is != None:
                                y_value_std = y_value_std/y_value_is
                        else:
                            y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                str_focus][str_is]

                            if y_value_is != None:
                                y_value_std = y_value_std/y_value_is

                        self.ax_sensitivity_03a.scatter(
                            x=x_value_std, y=y_value_std, color=self.bg_colors["Dark"], edgecolor="black", s=80,
                            marker="o")
                        x_value = value

                        if var_datatype == "RAW":
                            y_value = (self.container_lists["Analytical Sensitivity Regression RAW"][var_iso_01]["a"]*
                                       x_value + self.container_lists["Analytical Sensitivity Regression RAW"][
                                           var_iso_01]["b"])

                            if str_focus == "MAT" and var_filetype == "SMPL":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][str_is_host][
                                                 "a"]*x_value + self.container_lists[
                                                 "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                                y_value = y_value/y_value_is
                            else:
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][str_is_host][
                                                 "a"]*x_value + self.container_lists[
                                                 "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                                y_value = y_value/y_value_is

                        elif var_datatype == "SMOOTHED":
                            y_value = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][var_iso_01][
                                          "a"]*x_value + self.container_lists[
                                          "Analytical Sensitivity Regression SMOOTHED"][var_iso_01]["b"]

                            if str_focus == "MAT" and var_filetype == "SMPL":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                                 str_is_host]["a"]*x_value + self.container_lists[
                                    "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                                y_value = y_value/y_value_is
                            else:
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                                 str_is_host]["a"]*x_value + self.container_lists[
                                    "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                                y_value = y_value/y_value_is

                        x_values.append(x_value)
                        y_values.append(y_value)
                elif var_filetype == "SMPL":
                    if (var_file in self.container_analytical_sensitivity["STD"][var_datatype]
                            and var_file in self.container_lists["STD"]["Short"]):
                        var_srm_isotope = self.container_var["SRM"][var_iso_01].get()
                        var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()

                        if var_srm_isotope == var_srm_file:
                            x_value = value
                            y_value = self.container_analytical_sensitivity["STD"][var_datatype][var_file]["MAT"][
                                var_iso_01]
                            if str_focus == "MAT" and var_filetype == "SMPL":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()
                                if str_is_host in self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                    "MAT"]:
                                    y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                        "MAT"][str_is_host]
                                    if y_value_is == None:
                                        str_is = self.container_var["SMPL"][self.container_lists["SMPL"]["Long"][0]][
                                            "IS Data"]["IS"].get()
                                        y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][
                                            var_file]["MAT"][str_is]
                                else:
                                    str_is = self.container_var["SMPL"][self.container_lists["SMPL"]["Long"][0]][
                                        "IS Data"]["IS"].get()
                                    y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                        "MAT"][str_is]

                                if y_value_is == None:
                                    y_value_is = 1.0

                                y_value = y_value/y_value_is
                            else:
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                str_is_incl = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()

                                if str_is_incl in self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                    "MAT"]:
                                    y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                        "MAT"][str_is_incl]
                                    if y_value_is == None:
                                        str_is = self.container_var["SMPL"][self.container_lists["SMPL"]["Long"][0]][
                                            "IS Data"]["IS"].get()
                                        y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][
                                            var_file]["MAT"][str_is]
                                else:
                                    str_is = self.container_var["SMPL"][self.container_lists["SMPL"]["Long"][0]][
                                        "IS Data"]["IS"].get()
                                    y_value_is = self.container_analytical_sensitivity["STD"][var_datatype][var_file][
                                        "MAT"][str_is]
                                    if y_value_is == None:
                                        y_value_is = self.container_analytical_sensitivity[var_srm_file][var_file][
                                            str_is]

                                if y_value_is == None:
                                    y_value_is = 1.0

                                y_value = y_value/y_value_is

                            dot_color = self.bg_colors["Dark"]
                            self.ax_sensitivity_03a.scatter(
                                x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="o")
                    elif (var_file in self.container_analytical_sensitivity["SMPL"][var_datatype]
                          and var_file in self.container_lists["SMPL"]["Short"]):
                        x_value = value
                        y_value = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file][str_focus][
                            var_iso_01]
                        y_value_true_smpl = y_value

                        var_srm_isotope = self.container_var["SRM"][var_iso_01].get()

                        if str_focus == "MAT":
                            if self.pysills_mode == "MA":
                                str_is_host = self.container_var["SMPL"][var_file_long]["IS Data"]["IS"].get()
                            else:
                                str_is_host = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"][
                                    "Name"].get()

                            y_value_is = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file][
                                "MAT"][str_is_host]
                            y_value = y_value/y_value_is
                        else:
                            str_is_host = self.container_var["SMPL"][var_file_long]["Matrix Setup"]["IS"]["Name"].get()
                            var_srm_is_host = self.container_var["SRM"][str_is_host].get()

                            if var_srm_is_host == var_srm_isotope:
                                y_value_is = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file][
                                    "MAT"][str_is_host]
                            else:
                                y_value_is = 1.0

                            y_value = y_value/y_value_is
                            y_value = self.container_analytical_sensitivity["SMPL"][var_datatype][var_file][str_focus][
                                var_iso_01]

                        dot_color = self.bg_colors["Light"]
                        self.ax_sensitivity_03a.scatter(
                            x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="D")

                    if var_file in self.container_lists["SMPL"]["Short"]:   # Sample files
                        if var_datatype == "RAW":
                            y_value = (self.container_lists["Analytical Sensitivity Regression RAW"][var_iso_01]["a"]*
                                       x_value + self.container_lists["Analytical Sensitivity Regression RAW"][
                                           var_iso_01]["b"])

                            if str_focus == "MAT" and var_filetype == "SMPL":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                str_file_smpl = var_file_long

                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()

                                var_srm_host = self.container_var["SRM"][str_is_host].get()
                                var_srm_iso_01 = self.container_var["SRM"][var_iso_01].get()

                                if var_srm_host != var_srm_iso_01 and y_value_true_smpl != y_value:
                                    y_value = y_value_true_smpl
                                else:
                                    y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][
                                                     str_is_host]["a"]*x_value + self.container_lists[
                                        "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                                    y_value = y_value/y_value_is
                            else:
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                str_file_smpl = var_file_long
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                var_srm_host = self.container_var["SRM"][str_is_host].get()
                                var_srm_iso_01 = self.container_var["SRM"][var_iso_01].get()

                                if var_srm_host != var_srm_iso_01 and y_value_true_smpl != y_value:
                                    y_value = y_value_true_smpl
                                else:
                                    y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][
                                                     str_is_host]["a"]*x_value + self.container_lists[
                                                     "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                                    y_value = y_value/y_value_is

                        elif var_datatype == "SMOOTHED":
                            y_value = (self.container_lists["Analytical Sensitivity Regression SMOOTHED"][var_iso_01][
                                           "a"]*
                                       x_value + self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                           var_iso_01]["b"])

                            if str_focus == "MAT" and var_filetype == "SMPL":
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                str_file_smpl = var_file_long

                                if self.pysills_mode == "MA":
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                else:
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                        "Name"].get()

                                y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                                 str_is_host]["a"]*x_value + self.container_lists[
                                    "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                                y_value = y_value/y_value_is
                            else:
                                str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                                 str_is_host]["a"]*x_value + self.container_lists[
                                                 "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                                y_value = y_value/y_value_is

                        x_values.append(x_value)
                        y_values.append(y_value)
                    else:   # Standard files
                        if var_srm_isotope == var_srm_file:
                            if var_datatype == "RAW":
                                y_value = (self.container_lists["Analytical Sensitivity Regression RAW"][var_iso_01][
                                               "a"]*x_value + self.container_lists[
                                    "Analytical Sensitivity Regression RAW"][var_iso_01]["b"])

                                if str_focus == "MAT" and var_filetype == "SMPL":
                                    str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                    if self.pysills_mode == "MA":
                                        str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                    else:
                                        str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                            "Name"].get()
                                    y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][
                                                     str_is_host]["a"]*x_value + self.container_lists[
                                        "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                                    y_value = y_value/y_value_is
                                else:
                                    str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                    y_value_is = self.container_lists["Analytical Sensitivity Regression RAW"][
                                                     str_is_host]["a"]*x_value + self.container_lists[
                                                     "Analytical Sensitivity Regression RAW"][str_is_host]["b"]
                                    y_value = y_value/y_value_is

                            elif var_datatype == "SMOOTHED":
                                y_value = (self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                               var_iso_01]["a"]*x_value + self.container_lists[
                                    "Analytical Sensitivity Regression SMOOTHED"][var_iso_01]["b"])

                                if str_focus == "MAT" and var_filetype == "SMPL":
                                    str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                    if self.pysills_mode == "MA":
                                        str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                    else:
                                        str_is_host = self.container_var["SMPL"][str_file_smpl]["Matrix Setup"]["IS"][
                                            "Name"].get()
                                    y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                                     str_is_host]["a"]*x_value + self.container_lists[
                                        "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                                    y_value = y_value/y_value_is
                                else:
                                    str_file_smpl = self.container_lists["SMPL"]["Long"][0]
                                    str_is_host = self.container_var["SMPL"][str_file_smpl]["IS Data"]["IS"].get()
                                    y_value_is = self.container_lists["Analytical Sensitivity Regression SMOOTHED"][
                                                     str_is_host]["a"]*x_value + self.container_lists[
                                                     "Analytical Sensitivity Regression SMOOTHED"][str_is_host]["b"]
                                    y_value = y_value/y_value_is

                            x_values.append(x_value)
                            y_values.append(y_value)

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5

        try:
            if var_srm_host != var_srm_iso_01:
                x_values_new = x_values[4:]
                y_values_new = y_values[4:]
                x0 = x_values_new[0]
                x1 = x_values_new[-1]
                y0 = y_values_new[0]
                y1 = y_values_new[-1]

                a = (y1 - y0)/(x1 - x0)
                b = (x1*y0 - x0*y1)/(x1 - x0)

                y_new_0 = a*x_values[0] + b
                y_new_1 = a*x_values[1] + b
                y_new_2 = a*x_values[2] + b
                y_new_3 = a*x_values[3] + b
                y_values[0] = y_new_0
                y_values[1] = y_new_1
                y_values[2] = y_new_2
                y_values[3] = y_new_3
        except:
            pass

        if var_file in self.container_lists["SMPL"]["Short"]:
            zipped_lists = zip(x_values, y_values)
            sorted_zipped_lists = sorted(zipped_lists)
            x_data = []
            y_data = []
            for element in sorted_zipped_lists:
                x_data.append(element[0])
                y_data.append(element[1])

            self.ax_sensitivity_03a.plot(
                x_data, y_data, color=self.accent_color, linewidth=var_lw, linestyle="dashed")
        else:
            if var_srm_isotope == var_srm_file:
                zipped_lists = zip(x_values, y_values)
                sorted_zipped_lists = sorted(zipped_lists)
                x_data = []
                y_data = []
                for element in sorted_zipped_lists:
                    x_data.append(element[0])
                    y_data.append(element[1])

                self.ax_sensitivity_03a.plot(
                    x_data, y_data, color=self.accent_color, linewidth=var_lw, linestyle="dashed")

        self.ax_sensitivity_03a.grid(True)
        self.ax_sensitivity_03a.grid(which="major", linestyle="-", linewidth=1)
        self.ax_sensitivity_03a.minorticks_on()
        self.ax_sensitivity_03a.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        self.ax_sensitivity_03a.set_axisbelow(True)
        self.ax_sensitivity_03a.set_title("Analytical Sensitivity Drift", fontsize=9)
        self.ax_sensitivity_03a.set_xlabel("Experiment Time $t$ (s)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a.set_ylabel(
            "Analytical Sensitivity $\\xi$ of " + str(var_iso_01) + " (1)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a.xaxis.set_tick_params(labelsize=8)
        self.ax_sensitivity_03a.yaxis.set_tick_params(labelsize=8)

        self.canvas_sensitivity_03a.draw()

        self.change_normalized_sensitivity_scatter()

        if self.pysills_mode == "MA":
            self.rb_03b.configure(state="disabled")

    def show_normalized_sensitivity_scatter(self, mode=None):
        if self.var_rb_01.get() == 0:
            var_filetype = "STD"
        else:
            var_filetype = "SMPL"
        #
        if self.var_rb_02.get() == 0:
            var_datatype = "RAW"
        else:
            var_datatype = "SMOOTHED"
        #
        try:
            var_iso_01 = self.var_opt_iso_04.get()
        except:
            var_iso_01 = self.var_opt_iso_04
        try:
            var_iso_02 = self.var_opt_iso_05.get()
        except:
            var_iso_02 = self.var_opt_iso_05
        #
        self.fig_sensitivity_03a2 = Figure(
            figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.canvas_sensitivity_03a2 = FigureCanvasTkAgg(
            self.fig_sensitivity_03a2, master=self.subwindow_fi_graphical_sensitivity)
        self.canvas_sensitivity_03a2.get_tk_widget().grid(row=16, column=11, rowspan=16, columnspan=28, sticky="nesw")
        self.ax_sensitivity_03a2 = self.fig_sensitivity_03a2.add_subplot(label=np.random.uniform())
        #
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Drift Change"][
            "FIG"] = self.fig_sensitivity_03a2
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Drift Change"][
            "CANVAS"] = self.canvas_sensitivity_03a2
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Drift Change"][
            "AX"] = self.ax_sensitivity_03a2
        #
        x_all = []
        y_all = []

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5
        var_filetype = "STD"
        for index, var_file in enumerate(self.container_lists["STD"]["Short"]):
            var_file_long = self.container_lists[var_filetype]["Long"][index]
            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                if var_filetype == "SMPL":
                    x_values_02 = [0]
                    y_values_02 = [0]
                    dot_color = self.bg_colors["Dark"]
                    x_value = self.container_normalized_sensitivity["STD"][var_datatype][var_file]["MAT"][
                        var_iso_01]
                    y_value = self.container_normalized_sensitivity["STD"][var_datatype][var_file]["MAT"][
                        var_iso_02]
                    #
                    x_values_02.append(x_value)
                    y_values_02.append(y_value)
                    x_all.append(x_value)
                    y_all.append(y_value)
                    #
                    self.ax_sensitivity_03a2.scatter(
                        x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="o")
                    self.ax_sensitivity_03a2.plot(
                        x_values_02, y_values_02, color=self.accent_color, linewidth=var_lw, linestyle="--")
                else:
                    var_srm_isotope_01 = self.container_var["SRM"][var_iso_01].get()
                    var_srm_isotope_02 = self.container_var["SRM"][var_iso_02].get()
                    var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_srm_isotope_01 == var_srm_file and var_srm_isotope_02 == var_srm_file:
                        x_values_02 = [0]
                        y_values_02 = [0]
                        dot_color = self.bg_colors["Dark"]
                        x_value = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file]["MAT"][
                            var_iso_01]
                        y_value = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file]["MAT"][
                            var_iso_02]
                        #
                        x_values_02.append(x_value)
                        y_values_02.append(y_value)
                        x_all.append(x_value)
                        y_all.append(y_value)
                        #
                        self.ax_sensitivity_03a2.scatter(
                            x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="o")
                        self.ax_sensitivity_03a2.plot(
                            x_values_02, y_values_02, color=self.accent_color, linewidth=var_lw, linestyle="--")
        #
        self.ax_sensitivity_03a2.grid(True)
        self.ax_sensitivity_03a2.set_xlim(left=0, right=1.1*max(x_all))
        self.ax_sensitivity_03a2.set_ylim(bottom=0, top=1.1*max(y_all))
        self.ax_sensitivity_03a2.grid(which="major", linestyle="-", linewidth=1)
        self.ax_sensitivity_03a2.minorticks_on()
        self.ax_sensitivity_03a2.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        self.ax_sensitivity_03a2.set_axisbelow(True)
        self.ax_sensitivity_03a2.set_title("Analytical Sensitivity", fontsize=9)
        self.ax_sensitivity_03a2.set_xlabel(
            "Normalized Sensitivity $S$ of " + str(var_iso_01) + " (cps/ppm)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a2.set_ylabel(
            "Normalized Sensitivity $S$ of " + str(var_iso_02) + " (cps/ppm)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a2.xaxis.set_tick_params(labelsize=8)
        self.ax_sensitivity_03a2.yaxis.set_tick_params(labelsize=8)
        #
        self.canvas_sensitivity_03a2.draw()

        if self.pysills_mode == "MA":
            self.rb_03b.configure(state="disabled")

    def change_normalized_sensitivity_scatter(self, mode=None):
        try:
            self.ax_sensitivity_03a2.clear()
        except AttributeError:
            pass
        #
        if self.var_rb_01.get() == 0:
            var_filetype = "STD"
        else:
            var_filetype = "SMPL"
        #
        if self.var_rb_02.get() == 0:
            var_datatype = "RAW"
        else:
            var_datatype = "SMOOTHED"
        #
        x_all = []
        y_all = []
        #
        try:
            var_iso_01 = self.var_opt_iso_04.get()
        except:
            var_iso_01 = self.var_opt_iso_04
        try:
            var_iso_02 = self.var_opt_iso_05.get()
        except:
            var_iso_02 = self.var_opt_iso_05

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5
        var_filetype = "STD"
        for index, var_file in enumerate(self.container_lists[var_filetype]["Short"]):
            var_file_long = self.container_lists[var_filetype]["Long"][index]
            if self.container_var[var_filetype][var_file_long]["Checkbox"].get() == 1:
                if var_filetype == "SMPL":
                    x_values_02 = [0]
                    y_values_02 = [0]
                    dot_color = self.bg_colors["Dark"]
                    x_value = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file]["MAT"][
                        var_iso_01]
                    y_value = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file]["MAT"][
                        var_iso_02]
                    #
                    x_values_02.append(x_value)
                    y_values_02.append(y_value)
                    x_all.append(x_value)
                    y_all.append(y_value)

                    self.ax_sensitivity_03a2.scatter(
                        x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="o")
                    self.ax_sensitivity_03a2.plot(
                        x_values_02, y_values_02, color=self.accent_color, linewidth=var_lw, linestyle="--")
                else:
                    var_srm_isotope_01 = self.container_var["SRM"][var_iso_01].get()
                    var_srm_isotope_02 = self.container_var["SRM"][var_iso_02].get()
                    var_srm_file = self.container_var["STD"][var_file_long]["SRM"].get()
                    if var_srm_isotope_02 == var_srm_file:
                        x_values_02 = [0]
                        y_values_02 = [0]
                        dot_color = self.bg_colors["Dark"]
                        x_value = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file]["MAT"][
                            var_iso_01]
                        y_value = self.container_normalized_sensitivity[var_filetype][var_datatype][var_file]["MAT"][
                            var_iso_02]

                        x_values_02.append(x_value)
                        y_values_02.append(y_value)
                        x_all.append(x_value)
                        y_all.append(y_value)

                        self.ax_sensitivity_03a2.scatter(
                            x=x_value, y=y_value, color=dot_color, edgecolor="black", s=80, marker="o")
                        self.ax_sensitivity_03a2.plot(
                            x_values_02, y_values_02, color=self.accent_color, linewidth=var_lw, linestyle="--")
        #
        self.ax_sensitivity_03a2.grid(True)
        self.ax_sensitivity_03a2.set_xlim(left=0, right=1.1*max(x_all))
        self.ax_sensitivity_03a2.set_ylim(bottom=0, top=1.1*max(y_all))
        self.ax_sensitivity_03a2.grid(which="major", linestyle="-", linewidth=1)
        self.ax_sensitivity_03a2.minorticks_on()
        self.ax_sensitivity_03a2.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        self.ax_sensitivity_03a2.set_axisbelow(True)
        self.ax_sensitivity_03a2.set_title("Analytical Sensitivity", fontsize=9)
        self.ax_sensitivity_03a2.set_xlabel(
            "Normalized Sensitivity $S$ of " + str(var_iso_01) + " (cps/ppm)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a2.set_ylabel(
            "Normalized Sensitivity $S$ of " + str(var_iso_02) + " (cps/ppm)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a2.xaxis.set_tick_params(labelsize=8)
        self.ax_sensitivity_03a2.yaxis.set_tick_params(labelsize=8)
        #
        self.canvas_sensitivity_03a2.draw()

        if self.pysills_mode == "MA":
            self.rb_03b.configure(state="disabled")

    def show_relative_sensitivity_comparison(self, mode=None):
        if self.var_rb_01.get() == 0:
            var_filetype = "STD"
        else:
            var_filetype = "SMPL"

        if self.var_rb_02.get() == 0:
            var_datatype = "RAW"
        else:
            var_datatype = "SMOOTHED"

        try:
            var_iso_01 = self.var_opt_iso_04.get()
        except:
            var_iso_01 = self.var_opt_iso_04
        try:
            var_iso_02 = self.var_opt_iso_05.get()
        except:
            var_iso_02 = self.var_opt_iso_05

        if self.var_rb_03.get() == 0:
            str_focus = "MAT"
            self.rb_01a_std.configure(state="normal")
        elif self.var_rb_03.get() == 1:
            str_focus = "INCL"
            self.rb_01a_std.configure(state="disabled")

        self.fig_sensitivity_03a3 = Figure(
            figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.canvas_sensitivity_03a3 = FigureCanvasTkAgg(
            self.fig_sensitivity_03a3, master=self.subwindow_fi_graphical_sensitivity)
        self.canvas_sensitivity_03a3.get_tk_widget().grid(row=0, column=39, rowspan=16, columnspan=31, sticky="nesw")
        self.ax_sensitivity_03a3 = self.fig_sensitivity_03a3.add_subplot(label=np.random.uniform())

        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Comparison"][
            "FIG"] = self.fig_sensitivity_03a3
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Comparison"][
            "CANVAS"] = self.canvas_sensitivity_03a3
        self.container_var["fi_datareduction_isotopes"]["Sensitivity Plots"]["Sensitivity Comparison"][
            "AX"] = self.ax_sensitivity_03a3

        helper_srm_isotopes = {}
        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            var_srm_i = self.container_var["SRM"][isotope].get()
            if var_srm_i not in helper_srm_isotopes:
                helper_srm_isotopes[var_srm_i] = []
            if isotope not in helper_srm_isotopes[var_srm_i]:
                helper_srm_isotopes[var_srm_i].append(isotope)

        helper_srm_files = {}
        for index, file_long in enumerate(self.container_lists["STD"]["Long"]):
            file_short = self.container_lists["STD"]["Short"][index]
            var_srm_i = self.container_var["STD"][file_long]["SRM"].get()
            if var_srm_i not in helper_srm_files:
                helper_srm_files[var_srm_i] = []
            if file_short not in helper_srm_files[var_srm_i]:
                helper_srm_files[var_srm_i].append(file_short)

        self.helper_xi_files = {}
        for srm_file, list_files in helper_srm_files.items():
            self.helper_xi_files[srm_file] = {"Start": None, "End": None, "Counter": 0}
            for file_short in list_files:
                var_id = self.container_lists["STD"]["Short"].index(file_short)
                file_long = self.container_lists["STD"]["Long"][var_id]
                cb_i = self.container_var["STD"][file_long]["Checkbox"].get()
                if cb_i == 1 and self.helper_xi_files[srm_file]["Counter"] == 0:
                    self.helper_xi_files[srm_file]["Start"] = file_short
                    self.helper_xi_files[srm_file]["Counter"] += 1
                elif cb_i == 1:
                    self.helper_xi_files[srm_file]["End"] = file_short

        var_file_long_first = self.container_lists["SMPL"]["Long"][0]
        if str_focus == "MAT":
            if self.pysills_mode == "MA":
                var_is = self.container_var["SMPL"][var_file_long_first]["IS Data"]["IS"].get()
            else:
                var_is = self.container_var["SMPL"][var_file_long_first]["Matrix Setup"]["IS"]["Name"].get()
        elif str_focus == "INCL":
            var_is = self.container_var["SMPL"][var_file_long_first]["IS Data"]["IS"].get()

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            var_srm_i = self.container_var["SRM"][isotope].get()
            file_short_first = self.helper_xi_files[var_srm_i]["Start"]
            file_short_last = self.helper_xi_files[var_srm_i]["End"]

            sensitivity_i_first = self.container_analytical_sensitivity["STD"][var_datatype][file_short_first][
                "MAT"][isotope]
            sensitivity_is_first = self.container_analytical_sensitivity["STD"][var_datatype][file_short_first][
                "MAT"][var_is]
            sensitivity_i_last = self.container_analytical_sensitivity["STD"][var_datatype][file_short_last][
                "MAT"][isotope]
            sensitivity_is_last = self.container_analytical_sensitivity["STD"][var_datatype][file_short_last][
                "MAT"][var_is]

            if sensitivity_is_first == None:
                sensitivity_is_first = 1.0

            if sensitivity_is_last == None:
                sensitivity_is_last = 1.0

            sensitivity_i_first = sensitivity_i_first/sensitivity_is_first
            sensitivity_i_last = sensitivity_i_last/sensitivity_is_last
            sensitivity_change_i = (sensitivity_i_last/sensitivity_i_first - 1)*100

            self.ax_sensitivity_03a3.bar(
                x=isotope, height=sensitivity_change_i, color=self.isotope_colors[isotope], edgecolor="black")

        self.ax_sensitivity_03a3.axhline(0, color="black", linestyle="dashed")

        if len(self.container_lists["Measured Isotopes"]["All"]) > 20:
            self.ax_sensitivity_03a3.set_xticklabels(self.container_lists["Measured Isotopes"]["All"], rotation=90)
        else:
            self.ax_sensitivity_03a3.set_xticklabels(self.container_lists["Measured Isotopes"]["All"], rotation=45)

        self.ax_sensitivity_03a3.grid(True)
        self.ax_sensitivity_03a3.grid(which="major", linestyle="-", linewidth=1)
        self.ax_sensitivity_03a3.minorticks_on()
        self.ax_sensitivity_03a3.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        self.ax_sensitivity_03a3.set_axisbelow(True)
        self.ax_sensitivity_03a3.set_title("% drift in analytical sensitivity", fontsize=9)
        self.ax_sensitivity_03a3.set_xlabel(
            "Isotope", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a3.set_ylabel(
            "% change in analytical sensitivity", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a3.xaxis.set_tick_params(labelsize=8)
        self.ax_sensitivity_03a3.yaxis.set_tick_params(labelsize=8)

        self.canvas_sensitivity_03a3.draw()

    def fi_show_diagrams_concentration(self):
        pass

    def fi_datareduction_files(self):  # FI - DATAREDUCTION FILES #####################################################
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 1260
        window_height = 725
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        self.subwindow_fi_datareduction_files = tk.Toplevel(self.parent)
        self.subwindow_fi_datareduction_files.title("FLUID INCLUSION ANALYSIS - Data Reduction (Files)")
        self.subwindow_fi_datareduction_files.geometry(var_geometry)
        self.subwindow_fi_datareduction_files.resizable(False, False)
        self.subwindow_fi_datareduction_files["bg"] = self.bg_colors["Super Dark"]
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_fi_datareduction_files, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_fi_datareduction_files, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            self.subwindow_fi_datareduction_files.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_fi_datareduction_files.grid_columnconfigure(i, minsize=column_min)
        #
        ################################################################################################################
        #
        start_row = 0
        start_column = 0
        #
        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="File Type Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Data Type Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 6, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Assemblage Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 8, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Focus Selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 11, column_id=start_column,
            n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Result Selection", relief=tk.FLAT, fontsize="sans 10 bold")

        ## RADIOBUTTONS
        self.rb_01a = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["File Type"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Standard Files", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_01b = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["File Type"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Sample Files", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        #
        rb_02a = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 4, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Data Type"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="RAW Data", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_02b = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Data Type"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="SMOOTHED Data", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        #
        rb_04a = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 9, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Focus"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Matrix", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        self.rb_04b = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 10, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Focus"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Inclusion", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        #
        self.rb_05a = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 12, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=0,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Concentration",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_05b = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 13, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=1,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Concentration Ratio",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_05c = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 14, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=2,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Limit of Detection", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        self.rb_05d = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 15, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=3,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Mixing Ratio a",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        self.rb_05e = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 16, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=4,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Mixing Ratio x",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        self.rb_05f = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 17, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=5,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Mixed Concentration",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_05g = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 18, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=6,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Intensity", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        self.rb_05h = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 19, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=7,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Intensity Mix", sticky="nesw",
            relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_05f = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 20, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=8,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Analytical Sensitivity",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_05g = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 21, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=9,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Normalized Sensitivity",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        rb_05h = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 22, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=10,
            color_bg=self.bg_colors["Dark"], fg=self.bg_colors["Light Font"], text="Relative Sensitivity Factor",
            sticky="nesw", relief=tk.FLAT, command=self.fi_datareduction_tables)
        #
        ## OPTION MENUS
        if self.container_var["ID"]["Default SMPL"].get() != "Select ID":
            var_text = self.container_var["ID"]["Default SMPL"].get()
        else:
            var_text = "Select ID"
        #
        list_id_found = []
        for var_file_long in self.container_lists["SMPL"]["Long"]:
            var_id_i = self.container_var["SMPL"][var_file_long]["ID"].get()
            if var_id_i not in list_id_found:
                list_id_found.append(var_id_i)
        #
        opt_03a = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 7, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Dark"]).create_option_isotope(
            var_iso=self.container_var["ID"]["Results Files"], option_list=list_id_found, text_set=var_text,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var["ID"]["Results Files"], mode="FI":
            self.change_id_results(var_opt, mode))
        opt_03a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Dark"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_03a.config(
            bg=self.bg_colors["Dark"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        ## BUTTONS
        btn_06a = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 24, column_id=start_column, n_rows=2,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Export Results", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.calculation_report_setup)

        self.var_rb_01 = tk.IntVar()
        self.var_rb_01.set(1)
        self.var_rb_02 = tk.IntVar()
        self.var_rb_02.set(0)
        self.var_rb_03 = tk.IntVar()
        self.var_rb_03.set(0)

        btn_07c = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 27, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Medium"]).create_simple_button(
            text="Sensitivity Drift", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.show_diagrams_sensitivity)
        btn_07c = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row + 26, column_id=start_column, n_rows=1,
            n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Medium"]).create_simple_button(
            text="Detailed Data Analysis", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.detailed_data_analysis)

        ## FRAMES
        frm_a = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row, column_id=start_column + 11,
            n_rows=n_rows, n_columns=n_columns - 11, fg=self.bg_colors["Very Light"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)
        #
        ## TREEVIEW
        list_categories = ["Files"]
        list_categories.extend(self.container_lists["Measured Isotopes"]["All"])
        list_width = list(75*np.ones(len(list_categories)))
        list_width = [int(item) for item in list_width]
        list_width[0] = 125

        self.tv_results_files = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=0, column_id=11, n_rows=28, n_columns=51,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=len(list_categories), text_n=list_categories,
            width_n=list_width, individual=True)

        scb_v = ttk.Scrollbar(self.subwindow_fi_datareduction_files, orient="vertical")
        scb_h = ttk.Scrollbar(self.subwindow_fi_datareduction_files, orient="horizontal")
        self.tv_results_files.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
        scb_v.config(command=self.tv_results_files.yview)
        scb_h.config(command=self.tv_results_files.xview)
        scb_v.grid(row=0, column=62, rowspan=28, columnspan=1, sticky="ns")
        scb_h.grid(row=28, column=11, rowspan=1, columnspan=51, sticky="ew")

        ## INITIALIZATION
        self.fi_datareduction_tables(init=True)

    def fi_select_srm_initialization(self):
        for isotope in self.container_lists["ISOTOPES"]:
            var_srm_i = self.container_var["SRM"][isotope].get()

            if var_srm_i not in self.srm_actual:
                self.srm_actual[var_srm_i] = {}
                ESRM().place_srm_values(srm_name=var_srm_i, srm_dict=self.srm_actual)

            self.fill_srm_values(var_srm=var_srm_i)

    def select_srm_initialization(self):
        for isotope in self.container_lists["ISOTOPES"]:
            var_srm_i = self.container_var["SRM"][isotope].get()

            if var_srm_i not in self.srm_actual:
                self.srm_actual[var_srm_i] = {}
                ESRM().place_srm_values(srm_name=var_srm_i, srm_dict=self.srm_actual)

            self.fill_srm_values(var_srm=var_srm_i)

    def fi_select_srm_default(self, var_opt, mode="STD"):
        if mode == "STD":
            for file_std in self.list_std:
                parts = file_std.split("/")
                if self.container_var["STD"][file_std]["SRM"].get() == "Select SRM":
                    self.container_var["STD"][file_std]["SRM"].set(var_opt)
                    self.container_files["STD"][parts[-1]]["SRM"].set(var_opt)
        elif mode == "ISOTOPES":
            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                if isotope.isdigit():
                    pass
                else:
                    if self.container_var["SRM"][isotope].get() == "Select SRM":
                        self.container_var["SRM"][isotope].set(var_opt)
                        self.container_files["SRM"][isotope].set(var_opt)

        if var_opt not in self.srm_actual:
            self.srm_actual[var_opt] = {}
            ESRM().place_srm_values(srm_name=var_opt, srm_dict=self.srm_actual)

        self.fill_srm_values(var_srm=var_opt)

    def select_srm_default(self, var_opt, mode="STD"):
        if mode == "STD":
            for file_std in self.list_std:
                parts = file_std.split("/")
                self.container_var["STD"][file_std]["SRM"].set(var_opt)
                self.container_files["STD"][parts[-1]]["SRM"].set(var_opt)
        elif mode == "ISOTOPES":
            for isotope in self.container_lists["ISOTOPES"]:
                self.container_var["SRM"][isotope].set(var_opt)
                self.container_files["SRM"][isotope].set(var_opt)

        if var_opt not in self.srm_actual:
            self.srm_actual[var_opt] = {}
            ESRM().place_srm_values(srm_name=var_opt, srm_dict=self.srm_actual)

        self.fill_srm_values(var_srm=var_opt)

    def fi_change_srm_individual(self, var_opt, var_indiv, mode="STD"):
        if mode == "STD":
            parts = var_indiv.split("/")
            self.container_var["SRM"][var_indiv].set(var_opt)
            self.container_files["STD"][parts[-1]]["SRM"].set(var_opt)
        elif mode == "ISOTOPES":
            self.container_var["SRM"][var_indiv].set(var_opt)
            self.container_files["SRM"][var_indiv].set(var_opt)

        if var_opt not in self.srm_actual:
            self.srm_actual[var_opt] = {}
            ESRM().place_srm_values(srm_name=var_opt, srm_dict=self.srm_actual)

        self.fill_srm_values(var_srm=var_opt)

    def ma_select_is_default(self, var_opt, mode="STD"):
        if mode == "STD":
            var_is = var_opt
            if var_is != "Select IS":
                var_srm_is = self.container_var["SRM"][var_is].get()
                key_element = re.search(r"(\D+)(\d+)", var_is)
                element = key_element.group(1)
                var_concentration_is = self.srm_actual[var_srm_is][element]
            for file_std in self.container_lists["STD"]["Long"]:
                self.container_var["STD"][file_std]["IS Data"]["IS"].set(var_is)
                if var_is != "Select IS":
                    self.container_var["STD"][file_std]["IS Data"]["Concentration"].set(var_concentration_is)
        elif mode == "SMPL":
            var_is = var_opt
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file_smpl]["IS Data"]["IS"].set(var_is)

            if self.container_var["IS"]["Default STD"].get() == "Select IS":
                self.container_var["IS"]["Default STD"].set(var_is)
                for file_std in self.container_lists["STD"]["Long"]:
                    self.container_var["STD"][file_std]["IS Data"]["IS"].set(var_is)

    def fi_select_is_default(self, var_opt, mode="STD"):
        if mode == "STD":
            var_is = var_opt
            for file_std in self.list_std:
                self.container_var["STD"][file_std]["IS Data"]["IS"].set(var_is)

    def select_is_default(self, var_opt, mode="STD"):
        if mode == "STD":
            var_is = var_opt
            for file_std in self.list_std:
                self.container_var["STD"][file_std]["IS Data"]["IS"].set(var_is)

    def fi_select_id_default(self, var_opt):
        var_id = var_opt
        for file_smpl in self.list_smpl:
            self.container_var["SMPL"][file_smpl]["ID"].set(var_id)

    def select_id_default(self, var_opt):
        var_id = var_opt
        for file_smpl in self.list_smpl:
            self.container_var["SMPL"][file_smpl]["ID"].set(var_id)

    ## GENERAL CALCULATIONS ############################################################################################

    def calculate_regression(self, data, isotope, file_data):
        x_data = []
        y_data = []
        for file in file_data:
            if file in data:
                if isotope in data[file]:
                    x_data.append(data[file][isotope][0])
                    y_data.append(data[file][isotope][1])
        #
        A = np.vstack([x_data, np.ones(len(x_data))]).T
        m, c = np.linalg.lstsq(A, y_data, rcond=None)[0]  # m*x + c
        results = [m, c]
        #
        return results

    def define_setup_halter2002(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 680
        window_height = 600
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_quantification_setup_halter2002 = tk.Toplevel(self.parent)
        self.subwindow_quantification_setup_halter2002.title(
            "Quantification Setup - Geometric Approach (Halter et al. 2002)")
        self.subwindow_quantification_setup_halter2002.geometry(var_geometry)
        self.subwindow_quantification_setup_halter2002.resizable(False, False)
        self.subwindow_quantification_setup_halter2002["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_quantification_setup_halter2002, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_quantification_setup_halter2002, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_quantification_setup_halter2002.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_quantification_setup_halter2002.grid_columnconfigure(i, minsize=column_min)

        start_row = 0
        start_column = 0

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Default Settings", relief=tk.FLAT,
            fontsize="sans 10 bold")
        lbl_002 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 1, column_id=start_column,
            n_rows=1, n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Inclusion Dimensions (\u03bcm)", relief=tk.FLAT,
            fontsize="sans 10 bold")
        lbl_002a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 2, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Length of semi-axis a", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_002b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 3, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Length of semi-axis b", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_003 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 4, column_id=start_column,
            n_rows=1, n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Sample Densities (g/cm3)", relief=tk.FLAT,
            fontsize="sans 10 bold")
        lbl_003a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 5, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Host Density", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_003b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 6, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Inclusion Density", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_004 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 7, column_id=start_column,
            n_rows=1, n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Laser Setup (\u03bcm)", relief=tk.FLAT,
            fontsize="sans 10 bold")
        lbl_004a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 8, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Ablation Radius / Pit Size", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_005 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 10, column_id=start_column,
            n_rows=1, n_columns=33, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_006 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Inclusion Intensity Calculation", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_006a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 1, column_id=start_column + 19,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Matrix-only Tracer", relief=tk.FLAT, fontsize="sans 10 bold")

        # OPTION MENUS
        list_isotopes_all = self.container_lists["Measured Isotopes"]["All"]
        opt_03a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 1, column_id=start_column + 27,
            n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Halter2002"]["Name"], option_list=list_isotopes_all,
            text_set=self.container_var["Halter2002"]["Name"].get(), fg_active=self.bg_colors["Dark Font"],
            bg_active=self.accent_color)
        opt_03a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_03a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        ## BUTTONS
        btn_001 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 9, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Apply to all", bg_active=self.accent_color, fg_active=self.bg_colors["Light Font"],
            command=self.change_values_halter2002_all)

        # RADIOBUTTONS
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 2, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Heinrich et al. (2003)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 3, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (without R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 4, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (with R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 5, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Theory (simple intensity composition)", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        ## ENTRIES
        entr_002a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 2, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Halter2002"]["Dimension a"],
            text_default=self.container_var["Halter2002"]["Dimension a"].get(),
            command=lambda event, entr=self.container_var["Halter2002"]["Dimension a"], mode="a":
            self.change_values_halter2002(entr, mode, event))
        entr_002b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 3, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Halter2002"]["Dimension b"],
            text_default=self.container_var["Halter2002"]["Dimension b"].get(),
            command=lambda event, entr=self.container_var["Halter2002"]["Dimension b"], mode="b":
            self.change_values_halter2002(entr, mode, event))
        entr_003a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 5, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Halter2002"]["Rho(Host)"],
            text_default=self.container_var["Halter2002"]["Rho(Host)"].get(),
            command=lambda event, entr=self.container_var["Halter2002"]["Rho(Host)"], mode="rho(host)":
            self.change_values_halter2002(entr, mode, event))
        entr_003b = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 6, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Halter2002"]["Rho(Incl)"],
            text_default=self.container_var["Halter2002"]["Rho(Incl)"].get(),
            command=lambda event, entr=self.container_var["Halter2002"]["Rho(Incl)"], mode="rho(incl)":
            self.change_values_halter2002(entr, mode, event))
        entr_004a = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 8, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Halter2002"]["Laser Radius"],
            text_default=self.container_var["Halter2002"]["Laser Radius"].get(),
            command=lambda event, entr=self.container_var["Halter2002"]["Laser Radius"], mode="R":
            self.change_values_halter2002(entr, mode, event))

        ## TREEVIEWS
        frm_smpl = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row + 11, column_id=start_column,
            n_rows=12, n_columns=33, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_frame()
        vsb_smpl = ttk.Scrollbar(master=frm_smpl, orient="vertical")
        text_smpl = tk.Text(
            master=frm_smpl, width=25, height=25, yscrollcommand=vsb_smpl.set, bg=self.bg_colors["Very Light"])
        vsb_smpl.config(command=text_smpl.yview)
        vsb_smpl.pack(side="right", fill="y")
        text_smpl.pack(side="left", fill="both", expand=True)

        lbl_file = tk.Label(frm_smpl, text="Filename", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_file)
        text_smpl.insert("end", "\t")
        lbl_a = tk.Label(frm_smpl, text="Semi-Axis a", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_a)
        text_smpl.insert("end", "\t")
        lbl_b = tk.Label(frm_smpl, text="Semi-Axis b", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_b)
        text_smpl.insert("end", "\t")
        lbl_rhohost = tk.Label(
            frm_smpl, text="Host Density", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_rhohost)
        text_smpl.insert("end", "\t")
        lbl_rhoincl = tk.Label(
            frm_smpl, text="Inclusion Density", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_rhoincl)
        text_smpl.insert("end", "\t")
        lbl_ablationradius = tk.Label(
            frm_smpl, text="Ablation Radius", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_ablationradius)
        text_smpl.insert("end", "\n")

        for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_smpl, text=file_smpl, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("end", window=lbl_i)
            text_smpl.insert("end", "\t")

            entr_1_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Halter2002"]["a"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_1_i)
            text_smpl.insert("end", "\t")

            entr_2_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Halter2002"]["b"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_2_i)
            text_smpl.insert("end", "\t")

            entr_3_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Halter2002"]["rho(host)"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_3_i)
            text_smpl.insert("end", "\t")

            entr_4_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Halter2002"]["rho(incl)"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_4_i)
            text_smpl.insert("end", "\t")

            entr_5_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Halter2002"]["R"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_5_i)
            text_smpl.insert("end", "\n")

    def change_values_halter2002(self, entr, mode, event):
        val_default = entr.get()
        if mode == "a":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["a"].set(val_default)
        elif mode == "b":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["b"].set(val_default)
        elif mode == "rho(host)":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["rho(host)"].set(val_default)
        elif mode == "rho(incl)":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["rho(incl)"].set(val_default)
        elif mode == "R":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["R"].set(val_default)

    def change_values_halter2002_all(self):
        val_default_a = self.container_var["Halter2002"]["Dimension a"].get()
        val_default_b = self.container_var["Halter2002"]["Dimension b"].get()
        val_default_rho_host = self.container_var["Halter2002"]["Rho(Host)"].get()
        val_default_rho_incl = self.container_var["Halter2002"]["Rho(Incl)"].get()
        val_default_r = self.container_var["Halter2002"]["Laser Radius"].get()
        for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["a"].set(val_default_a)
            self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["b"].set(val_default_b)
            self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["rho(host)"].set(val_default_rho_host)
            self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["rho(incl)"].set(val_default_rho_incl)
            self.container_var["SMPL"][filename_smpl_long]["Halter2002"]["R"].set(val_default_r)

    def estimate_x_halter2002(self, datatype, filename_long, filename_short):
        # Initial conditions
        x_star = self.calculate_mixing_ratio_geometric_approach(filename_long=filename_long)
        # x_star = 0.5
        x_low = 0.0
        x_high = 1.0
        x_min = 0.0001
        x_max = 1.0
        var_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
        var_t = self.container_var["Halter2002"]["Name"].get()

        var_intensity_mix_is = self.container_intensity_mix["SMPL"][datatype][filename_short][var_is]
        var_concentration_host_t = self.container_concentration["SMPL"][datatype][filename_short]["MAT"][var_t]
        var_intensity_mix_t = self.container_intensity_mix["SMPL"][datatype][filename_short][var_t]
        var_sensitivity_t = self.container_analytical_sensitivity["SMPL"][datatype][filename_short]["MAT"][var_t]

        # Calculate C(MIX,IS)*
        var_concentration_incl_is = float(self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].get())

        var_concentration_mix_is_star_min = self.helper_calculate_concentration_mix_is_star_alternative(
            x_now=x_min, concentration_host_t=var_concentration_host_t, intensity_mix_t=var_intensity_mix_t,
            intensity_mix_is=var_intensity_mix_is, sensitivity_t=var_sensitivity_t)
        var_concentration_mix_is_star_max = self.helper_calculate_concentration_mix_is_star_alternative(
            x_now=x_max, concentration_host_t=var_concentration_host_t, intensity_mix_t=var_intensity_mix_t,
            intensity_mix_is=var_intensity_mix_is, sensitivity_t=var_sensitivity_t)
        # Calculate C(INCL,i)*
        var_concentration_host_is = self.container_concentration["SMPL"][datatype][filename_short]["MAT"][var_is]

        var_concentration_incl_is_star_min = self.helper_calculate_concentration_incl_i_star(
            x_now=x_min, concentration_host_i=var_concentration_host_is,
            concentration_mix_i=var_concentration_mix_is_star_min)
        var_concentration_incl_is_star_max = self.helper_calculate_concentration_incl_i_star(
            x_now=x_max, concentration_host_i=var_concentration_host_is,
            concentration_mix_i=var_concentration_mix_is_star_max)
        # Determine slope
        if var_concentration_incl_is_star_min < var_concentration_incl_is_star_max:
            var_slope = 1
        else:
            var_slope = -1
        # Test run
        # Calculate C(MIX,IS)*
        var_concentration_mix_is_star = self.helper_calculate_concentration_mix_is_star_alternative(
            x_now=x_star, concentration_host_t=var_concentration_host_t, intensity_mix_t=var_intensity_mix_t,
            intensity_mix_is=var_intensity_mix_is, sensitivity_t=var_sensitivity_t)
        # Calculate C(INCL,IS)*
        var_concentration_incl_is_star = self.helper_calculate_concentration_incl_i_star(
            x_now=x_star, concentration_host_i=var_concentration_host_is,
            concentration_mix_i=var_concentration_mix_is_star)

        magicnumber_star = abs((var_concentration_incl_is_star - var_concentration_incl_is)/var_concentration_incl_is)
        # Determine x
        index = 0
        magicnumber = 0.0001
        if magicnumber_star > magicnumber:
            while magicnumber_star > magicnumber and index < 100:
                # Calculate C(MIX,IS)*
                var_concentration_mix_is_star = self.helper_calculate_concentration_mix_is_star_alternative(
                    x_now=x_star, concentration_host_t=var_concentration_host_t, intensity_mix_t=var_intensity_mix_t,
                    intensity_mix_is=var_intensity_mix_is, sensitivity_t=var_sensitivity_t)
                # Calculate C(INCL,IS)*
                var_concentration_incl_is_star = self.helper_calculate_concentration_incl_i_star(
                    x_now=x_star, concentration_host_i=var_concentration_host_is,
                    concentration_mix_i=var_concentration_mix_is_star)
                # Update x_star
                if var_slope == 1:
                    if var_concentration_incl_is_star < var_concentration_incl_is:
                        x_low = x_star
                    else:
                        x_high = x_star
                else:
                    if var_concentration_incl_is_star < var_concentration_incl_is:
                        x_high = x_star
                    else:
                        x_low = x_star

                x_star = (x_low + x_high)/2
                magicnumber_star = abs((var_concentration_incl_is_star - var_concentration_incl_is)/
                                       var_concentration_incl_is)

                index += 1

        return x_star, var_concentration_mix_is_star

    def helper_calculate_concentration_mix_is_star_alternative(self, x_now, concentration_host_t, intensity_mix_t,
                                                               intensity_mix_is, sensitivity_t):
        var_concentration_mix_is_star = ((1 - x_now)*concentration_host_t*(intensity_mix_is/intensity_mix_t)*
                                         sensitivity_t)
        return var_concentration_mix_is_star

    def helper_calculate_concentration_mix_is_star(self, x_now, concentration_host_is, concentration_incl_is):
        var_concentration_mix_is_star = (1 - x_now)*concentration_host_is + x_now*concentration_incl_is
        return var_concentration_mix_is_star

    def helper_calculate_concentration_mix_i_star(self, intensity_mix_i, intensity_mix_is, concentration_mix_is_star,
                                                  sensitivity_i):
        var_concentration_mix_i = (intensity_mix_i/intensity_mix_is)*(concentration_mix_is_star/sensitivity_i)
        return var_concentration_mix_i

    def helper_calculate_concentration_incl_i_star(self, x_now, concentration_host_i, concentration_mix_i):
        var_concentration_incl_i_star = concentration_host_i - (concentration_host_i - concentration_mix_i)/x_now
        return var_concentration_incl_i_star

    def define_setup_borisova2021(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 680
        window_height = 550
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_quantification_setup_borisova2021 = tk.Toplevel(self.parent)
        self.subwindow_quantification_setup_borisova2021.title(
            "Quantification Setup - Geometric Approach (Borisova et al. 2021)")
        self.subwindow_quantification_setup_borisova2021.geometry(var_geometry)
        self.subwindow_quantification_setup_borisova2021.resizable(False, False)
        self.subwindow_quantification_setup_borisova2021["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_quantification_setup_borisova2021, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_quantification_setup_borisova2021, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_quantification_setup_borisova2021.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_quantification_setup_borisova2021.grid_columnconfigure(i, minsize=column_min)

        start_row = 0
        start_column = 0

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Default Settings", relief=tk.FLAT,
            fontsize="sans 10 bold")
        lbl_002 = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 1, column_id=start_column,
            n_rows=1, n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Sample Dimensions (\u03bcm)", relief=tk.FLAT,
            fontsize="sans 10 bold")
        lbl_002a = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 2, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Inclusion Radius", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_002b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 3, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Ablation Radius / Pit Size", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_003 = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 4, column_id=start_column,
            n_rows=1, n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Sample Densities (g/cm3)", relief=tk.FLAT,
            fontsize="sans 10 bold")
        lbl_003a = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 5, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Host Density", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_003b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 6, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Inclusion Density", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_005 = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 8, column_id=start_column,
            n_rows=1, n_columns=18, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_006 = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Inclusion Intensity Calculation", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_006a = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 1, column_id=start_column + 19,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Matrix-only Tracer", relief=tk.FLAT, fontsize="sans 10 bold")

        # OPTION MENUS
        list_isotopes_all = self.container_lists["Measured Isotopes"]["All"]
        opt_03a = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 1, column_id=start_column + 27,
            n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var["Borisova2021"]["Name"], option_list=list_isotopes_all,
            text_set=self.container_var["Borisova2021"]["Name"].get(), fg_active=self.bg_colors["Dark Font"],
            bg_active=self.accent_color)
        opt_03a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_03a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        ## BUTTONS
        btn_001 = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 7, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Apply to all", bg_active=self.accent_color, fg_active=self.bg_colors["Light Font"],
            command=self.change_values_borisova2021_all)

        # RADIOBUTTONS
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 2, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Heinrich et al. (2003)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 3, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (without R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 4, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (with R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 5, column_id=start_column + 19,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Theory (simple intensity composition)", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        ## ENTRIES
        entr_002a = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 2, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Borisova2021"]["Radius Inclusion"],
            text_default=self.container_var["Borisova2021"]["Radius Inclusion"].get(),
            command=lambda event, entr=self.container_var["Borisova2021"]["Radius Inclusion"], mode="R(incl)":
            self.change_values_borisova2021(entr, mode, event))
        entr_002b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 3, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Borisova2021"]["Radius Host"],
            text_default=self.container_var["Borisova2021"]["Radius Host"].get(),
            command=lambda event, entr=self.container_var["Borisova2021"]["Radius Host"], mode="R(host)":
            self.change_values_borisova2021(entr, mode, event))
        entr_003a = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 5, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Borisova2021"]["Rho(Host)"],
            text_default=self.container_var["Borisova2021"]["Rho(Host)"].get(),
            command=lambda event, entr=self.container_var["Borisova2021"]["Rho(Host)"], mode="rho(host)":
            self.change_values_borisova2021(entr, mode, event))
        entr_003b = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 6, column_id=start_column + 10,
            n_rows=1, n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Borisova2021"]["Rho(Incl)"],
            text_default=self.container_var["Borisova2021"]["Rho(Incl)"].get(),
            command=lambda event, entr=self.container_var["Borisova2021"]["Rho(Incl)"], mode="rho(incl)":
            self.change_values_borisova2021(entr, mode, event))

        ## TREEVIEWS
        frm_smpl = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row + 9, column_id=start_column,
            n_rows=12, n_columns=33, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_frame()
        vsb_smpl = ttk.Scrollbar(master=frm_smpl, orient="vertical")
        text_smpl = tk.Text(
            master=frm_smpl, width=25, height=25, yscrollcommand=vsb_smpl.set, bg=self.bg_colors["Very Light"])
        vsb_smpl.config(command=text_smpl.yview)
        vsb_smpl.pack(side="right", fill="y")
        text_smpl.pack(side="left", fill="both", expand=True)

        lbl_file = tk.Label(frm_smpl, text="Filename", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_file)
        text_smpl.insert("end", "\t")
        lbl_a = tk.Label(
            frm_smpl, text="Inclusion Radius ", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_a)
        text_smpl.insert("end", "\t")
        lbl_b = tk.Label(
            frm_smpl, text="Ablation Radius", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_b)
        text_smpl.insert("end", "\t")
        lbl_rhohost = tk.Label(
            frm_smpl, text="Host Density", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_rhohost)
        text_smpl.insert("end", "\t")
        lbl_rhoincl = tk.Label(
            frm_smpl, text="Inclusion Density", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
        text_smpl.window_create("end", window=lbl_rhoincl)
        text_smpl.insert("end", "\n")

        for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_smpl, text=file_smpl, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("end", window=lbl_i)
            text_smpl.insert("end", "\t")

            entr_2_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Borisova2021"]["R(incl)"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_2_i)
            text_smpl.insert("end", "\t")

            entr_3_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Borisova2021"]["R(host)"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_3_i)
            text_smpl.insert("end", "\t")

            entr_4_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Borisova2021"]["rho(host)"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_4_i)
            text_smpl.insert("end", "\t")

            entr_5_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Borisova2021"]["rho(incl)"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_5_i)
            text_smpl.insert("end", "\n")

    def change_values_borisova2021(self, entr, mode, event):
        val_default = entr.get()
        if mode == "R(host)":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["R(host)"].set(val_default)
        elif mode == "R(incl)":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["R(incl)"].set(val_default)
        elif mode == "rho(host)":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["rho(host)"].set(val_default)
        elif mode == "rho(incl)":
            for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["rho(incl)"].set(val_default)

    def change_values_borisova2021_all(self):
        val_default_r_host = self.container_var["Borisova2021"]["Radius Host"].get()
        val_default_r_incl = self.container_var["Borisova2021"]["Radius Inclusion"].get()
        val_default_rho_host = self.container_var["Borisova2021"]["Rho(Host)"].get()
        val_default_rho_incl = self.container_var["Borisova2021"]["Rho(Incl)"].get()
        for filename_smpl_long in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["R(host)"].set(val_default_r_host)
            self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["R(incl)"].set(val_default_r_incl)
            self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["rho(host)"].set(val_default_rho_host)
            self.container_var["SMPL"][filename_smpl_long]["Borisova2021"]["rho(incl)"].set(val_default_rho_incl)

    def fi_setup_matrix_only_tracer(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 820
        window_height = 375
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_fi_setup_matrixonlytracer = tk.Toplevel(self.parent)
        self.subwindow_fi_setup_matrixonlytracer.title("Fluid Inclusion Analysis - Matrix-only Tracer Setup")
        self.subwindow_fi_setup_matrixonlytracer.geometry(var_geometry)
        self.subwindow_fi_setup_matrixonlytracer.resizable(False, False)
        self.subwindow_fi_setup_matrixonlytracer["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_fi_setup_matrixonlytracer, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_fi_setup_matrixonlytracer, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_fi_setup_matrixonlytracer.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_fi_setup_matrixonlytracer.grid_columnconfigure(i, minsize=column_min)

        start_row = 0
        start_column = 0

        ## INITIAL VALUES
        list_oxides = sorted(self.container_lists["Oxides"])

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=25, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Default Settings - Matrix-Only Tracer", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01a = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=13, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Matrix Amount", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=13, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Matrix", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01c = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=13, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Matrix-Only Tracer", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01d = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 4, column_id=start_column, n_rows=1,
            n_columns=13, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Concentration (ppm)", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=25, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row, column_id=start_column + 26, n_rows=1,
            n_columns=14, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Inclusion Intensity Calculation", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 5, column_id=start_column + 26,
            n_rows=1, n_columns=14, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Inclusion Concentration Calculation", relief=tk.FLAT, fontsize="sans 10 bold")

        ## ENTRIES
        entr_01a = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 1, column_id=start_column + 13,
            n_rows=1, n_columns=12, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[key_setting]["Matrix Amount Default"],
            text_default=self.container_var[key_setting]["Matrix Amount Default"].get(),
            command=lambda var_entr=self.container_var[key_setting]["Matrix Amount Default"]:
            self.fi_change_default_matrix_amount(var_entr))
        entr_01d = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 4, column_id=start_column + 13,
            n_rows=1, n_columns=12, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var[key_setting]["Matrix-Only Concentration Default"],
            text_default=self.container_var[key_setting]["Matrix-Only Concentration Default"].get(),
            command=lambda var_entr=self.container_var[key_setting]["Matrix-Only Concentration Default"]:
            self.fi_change_default_matrixonly_is_concentration(var_entr))

        # RADIOBUTTONS
        rb_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 1, column_id=start_column + 26,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Heinrich et al. (2003)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 2, column_id=start_column + 26,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (without R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 3, column_id=start_column + 26,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (with R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 4, column_id=start_column + 26,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Theory (simple intensity composition)", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 6, column_id=start_column + 26,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Concentration Calculation"], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="without x", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 7, column_id=start_column + 26,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Concentration Calculation"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="with x", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        ## OPTION MENUES
        var_text_01b = self.container_var[key_setting]["Oxide"].get()
        opt_01b = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 2, column_id=start_column + 13,
            n_rows=1, n_columns=12, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var[key_setting]["Oxide"], option_list=list_oxides,
            text_set=var_text_01b, fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var[key_setting]["Oxide"], var_file=None, state_default=True,
                           matrix_only=True:
            self.fi_change_matrix_compound(var_opt, var_file, state_default, matrix_only))
        opt_01b["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_01b.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        var_text_01c = self.container_var[key_setting]["Host Only"].get()
        self.opt_01c = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 3, column_id=start_column + 13,
            n_rows=1, n_columns=12, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var[key_setting]["Host Only"],
            option_list=self.container_lists["Measured Isotopes"]["All"], text_set=var_text_01c,
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var[key_setting]["Host Only"], var_file=None, state_default=True:
            self.change_matrix_only_tracer(var_opt, var_file, state_default))
        self.opt_01c["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        self.opt_01c.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        ## TREEVIEWS
        frm_smpl = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 6, column_id=start_column,
            n_rows=n_rows - 7, n_columns=25, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()
        vsb_smpl = ttk.Scrollbar(master=frm_smpl, orient="vertical")
        text_smpl = tk.Text(
            master=frm_smpl, width=25, height=25, yscrollcommand=vsb_smpl.set, bg=self.bg_colors["Very Light"])
        vsb_smpl.config(command=text_smpl.yview)
        vsb_smpl.pack(side="right", fill="y")
        text_smpl.pack(side="left", fill="both", expand=True)

        for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_smpl, text=file_smpl, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("end", window=lbl_i)
            text_smpl.insert("end", "\t")

            if float(self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Amount"].get()) > 100.0:
                self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Amount"].set("100.0")

            if float(self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Amount"].get()) < 0.0:
                self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Amount"].set("0.0")

            if (self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Name"].get() ==
                    self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["IS"]["Name"].get()):
                self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["Oxide"]["Concentration"].set(
                    self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Amount"].get())

            entr_1_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Amount"],
                width=8, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            entr_1_i.bind(
                "<Return>", lambda event, var_file=file_smpl_long: self.change_specific_matrix_amount(var_file, event))
            text_smpl.window_create("insert", window=entr_1_i)
            text_smpl.insert("end", "\t")

            if self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["Oxide"]["Name"].get() != "Select Oxide":
                self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Matrix"].set(
                    self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["Oxide"]["Name"].get())

            opt_1_i = tk.OptionMenu(
                frm_smpl, self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Matrix"],
                *np.sort(list_oxides))
            opt_1_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_1_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
            text_smpl.window_create("end", window=opt_1_i)
            text_smpl.insert("end", "\t")

            if self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["IS"]["Name"].get() != "Select Isotope":
                self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Name"].set(
                    self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["IS"]["Name"].get())

            opt_2_i = tk.OptionMenu(
                frm_smpl, self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Name"],
                *np.sort(self.container_lists["ISOTOPES"]))
            opt_2_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_2_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
            text_smpl.window_create("end", window=opt_2_i)
            text_smpl.insert("end", "\t")

            if self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["IS"]["Concentration"].get() != "1000000":
                self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Value"].set(
                    self.container_var["SMPL"][file_smpl_long]["Matrix Setup"]["IS"]["Concentration"].get())

            entr_2_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Host Only Tracer"]["Value"],
                width=15, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_2_i)
            text_smpl.insert("end", "\n")

    def fi_setup_second_internal_standard(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 720
        window_height = 375
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        self.subwindow_fi_setup_secondinternalstandard = tk.Toplevel(self.parent)
        self.subwindow_fi_setup_secondinternalstandard.title(
            "FI - Quantification Setup")
        self.subwindow_fi_setup_secondinternalstandard.geometry(var_geometry)
        self.subwindow_fi_setup_secondinternalstandard.resizable(False, False)
        self.subwindow_fi_setup_secondinternalstandard["bg"] = self.bg_colors["Super Dark"]
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_fi_setup_secondinternalstandard, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_fi_setup_secondinternalstandard, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            self.subwindow_fi_setup_secondinternalstandard.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_fi_setup_secondinternalstandard.grid_columnconfigure(i, minsize=column_min)
        #
        start_row = 0
        start_column = 0
        #
        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=20, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Default Settings - Second Internal Standard", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01a = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 1, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Second Internal Standard", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 2, column_id=start_column,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Concentration (ppm)", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 3, column_id=start_column,
            n_rows=1, n_columns=20, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Inclusion Intensity Calculation", relief=tk.FLAT, fontsize="sans 10 bold")

        ## OPTION MENUES
        var_text = self.container_var[key_setting]["2nd Internal"].get()
        opt_01a = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 1, column_id=start_column + 10,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var[key_setting]["2nd Internal"], option_list=self.container_lists["ISOTOPES"],
            text_set=var_text, fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var[key_setting]["2nd Internal"]:
            self.fi_change_default_2nd_is(var_opt))
        opt_01a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_01a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
            activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        # RADIOBUTTONS
        rb_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 1, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Heinrich et al. (2003)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 2, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (without R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 3, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SILLS (with R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 4, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Theory (simple intensity composition)", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        ## ENTRIES
        entr_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 2, column_id=start_column + 10,
            n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_simple_entry(
            var=self.container_var[key_setting]["2nd Internal Concentration Default"],
            text_default=self.container_var[key_setting]["2nd Internal Concentration Default"].get(),
            command=lambda var_entr=self.container_var[key_setting]["2nd Internal Concentration Default"]:
            self.fi_change_default_2nd_is_concentration(var_entr))
        #
        ## TREEVIEWS
        frm_smpl = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 4, column_id=start_column,
            n_rows=10, n_columns=20, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_smpl = ttk.Scrollbar(master=frm_smpl, orient="vertical")
        text_smpl = tk.Text(
            master=frm_smpl, width=30, height=25, yscrollcommand=vsb_smpl.set, bg=self.bg_colors["Very Light"])
        vsb_smpl.config(command=text_smpl.yview)
        vsb_smpl.pack(side="right", fill="y")
        text_smpl.pack(side="left", fill="both", expand=True)
        #
        for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_smpl, text=file_smpl, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("end", window=lbl_i)
            text_smpl.insert("end", "\t")
            #
            opt_i = tk.OptionMenu(
                frm_smpl, self.container_var["SMPL"][file_smpl_long]["Second Internal Standard"]["Name"],
                *np.sort(self.container_lists["ISOTOPES"]))
            opt_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)
            text_smpl.window_create("end", window=opt_i)
            text_smpl.insert("end", "\t")
            #
            entr_i = tk.Entry(
                frm_smpl, textvariable=self.container_var["SMPL"][file_smpl_long]["Second Internal Standard"]["Value"],
                width=15, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("insert", window=entr_i)
            text_smpl.insert("end", "\n")

    def fi_change_default_2nd_is(self, var_opt):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        var_opt_default = self.container_var[key_setting]["2nd Internal"].get()
        for file_smpl in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][file_smpl]["Second Internal Standard"]["Name"].set(var_opt_default)

    def fi_change_default_2nd_is_concentration(self, var_entr):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        var_entr_default = self.container_var[key_setting]["2nd Internal Concentration Default"].get()
        for file_smpl in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][file_smpl]["Second Internal Standard"]["Value"].set(var_entr_default)

    def fi_change_default_matrixonly_is_concentration(self, var_entr):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        var_entr_default = float(self.container_var[key_setting]["Matrix-Only Concentration Default"].get())
        var_entr_default_amount = (float(self.container_var[key_setting]["Matrix Amount Default"].get()))/100

        if var_entr_default > 1000000:
            var_entr_default = 1000000
            self.container_var[key_setting]["Matrix-Only Concentration Default"].set(1000000)
        elif var_entr_default < 0:
            var_entr_default = 0
            self.container_var[key_setting]["Matrix-Only Concentration Default"].set(0)

        if var_entr_default_amount > 1.0:
            var_entr_default_amount = 1.0
            self.container_var[key_setting]["Matrix Amount Default"].set(100)

        for file_smpl in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Value"].set(
                var_entr_default_amount*var_entr_default)

    def fi_change_default_matrix_amount(self, var_entr):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        var_entr_default = float("%g"%(float(self.container_var[key_setting]["Matrix Amount Default"].get())/100))

        if var_entr_default > 1.0:
            var_entr_default = 1.0
            self.container_var[key_setting]["Matrix Amount Default"].set(100)
        elif var_entr_default < 0.0:
            var_entr_default = 0.0
            self.container_var[key_setting]["Matrix Amount Default"].set(0)

        var_entr_conc_default = float(self.container_var[key_setting]["Matrix-Only Concentration Default"].get())
        value_amount_i = "%g"%(var_entr_default*100)

        for file_smpl in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Amount"].set(value_amount_i)
            self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Value"].set(
                var_entr_default*var_entr_conc_default)

    ## FILE-SPECIFIC ANALYSIS ##########################################################################################

    def fi_check_specific_file(self, var_file, var_type="STD", checkup_mode=False):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
            str_title = "FLUID INCLUSION ANALYSIS - File Analysis of "
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"
            str_title = "MELT INCLUSION ANALYSIS - File Analysis of "

        str_filename_long = var_file
        str_filetype = var_type

        if str_filetype == "STD":
            self.index_file_std = self.container_lists[str_filetype]["Long"].index(str_filename_long)
        elif str_filetype == "SMPL":
            self.index_file_smpl = self.container_lists[str_filetype]["Long"].index(str_filename_long)

        if checkup_mode:
            if str_filetype == "STD":
                str_filename_long = self.fi_current_file_std
            elif str_filetype == "SMPL":
                str_filename_long = self.fi_current_file_smpl

        ## INPUT
        parts = str_filename_long.split("/")
        str_filename_short = parts[-1]
        self.helper_intervals = {"BG": [], "MAT": [], "INCL": []}

        ## Window Settings
        window_width = 1360
        window_height = 800
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_fi_checkfile = tk.Toplevel(self.parent)
        self.subwindow_fi_checkfile.title(str_title + str(str_filename_short))
        self.subwindow_fi_checkfile.geometry(var_geometry)
        self.subwindow_fi_checkfile.resizable(False, False)
        self.subwindow_fi_checkfile["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_fi_checkfile, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_fi_checkfile, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_fi_checkfile.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_fi_checkfile.grid_columnconfigure(i, minsize=column_min)

        start_row = 0
        start_column = 0

        ## FRAMES
        frm_00 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row, column_id=start_column + 14, n_rows=n_rows - 10,
            n_columns=n_columns - 14, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame(
            relief=tk.SOLID)

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row, column_id=start_column, n_rows=1, n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Measured Isotopes", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 15, column_id=start_column, n_rows=1, n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Display Options", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 18, column_id=start_column, n_rows=1, n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Anaylsis Mode", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 22, column_id=start_column, n_rows=1, n_columns=14,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Interval Setup", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04a = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="Start", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04b = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 24, column_id=start_column, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
            text="End", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 22, column_id=start_column + 53, n_rows=1,
            n_columns=n_columns - (start_column + 53) - 6, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Parallelism", relief=tk.FLAT, fontsize="sans 10 bold")

        ## BUTTONS
        btn_02a = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 16, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Show All", bg_active=self.accent_color, fg_active=self.bg_colors["Light Font"],
            command=lambda var_type=str_filetype, var_file_short=str_filename_short: self.fi_show_all_lines(
                var_type, var_file_short, ))
        btn_02b = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 17, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Hide All", bg_active=self.accent_color, fg_active=self.bg_colors["Light Font"],
            command=lambda var_type=str_filetype, var_file_short=str_filename_short: self.fi_hide_all_lines(
                var_type, var_file_short))
        btn_04a = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 25, column_id=0, n_rows=2, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Remove Interval", bg_active=self.accent_color, fg_active=self.bg_colors["Light Font"],
            command=lambda var_type=str_filetype, var_file_short=str_filename_short:
            self.fi_remove_interval(var_type, var_file_short))
        btn_05a = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 28, column_id=0, n_rows=2, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Previous file", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda filetype=str_filetype, mode="back": self.switch_to_another_file(filetype, mode))
        btn_05b = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 28, column_id=7, n_rows=2, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Next file", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda filetype=str_filetype, mode="next": self.switch_to_another_file(filetype, mode))
        btn_08 = SE(
            parent=self.subwindow_fi_checkfile, row_id=n_rows - 2, column_id=0, n_rows=2, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Confirm and Update \nData", bg_active=self.accent_color, fg_active=self.bg_colors["Light Font"],
            command=lambda var_parent=self.subwindow_fi_checkfile, var_type=str_filetype,
                           var_file_long=str_filename_long:
            self.confirm_specific_file_setup(var_parent, var_type, var_file_long))
        btn_09 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 22, column_id=n_columns - 6, n_rows=1, n_columns=6,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Update", bg_active=self.bg_colors["Dark"], fg_active=self.bg_colors["Light Font"],
            command=lambda var_filetype=str_filetype, var_filename_short=str_filename_short,
                           var_filename_long=str_filename_long:
            self.update_parallelism_values(var_filetype, var_filename_short, var_filename_long))

        if str_filetype == "STD":
            btn_09.configure(state="disabled")

        ## RADIOBUTTONS
        rb_02a = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 16, column_id=0, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Data Type Plot"][str_filetype][str_filename_short], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="RAW", sticky="nesw",
            relief=tk.FLAT)
        rb_02b = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 17, column_id=0, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Data Type Plot"][str_filetype][str_filename_short], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="SMOOTHED", sticky="nesw",
            relief=tk.FLAT)

        rb_03a = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 19, column_id=0, n_rows=1, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Analyse Mode Plot"][str_filetype][str_filename_short], value_rb=0,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Time-Signal Plot", sticky="nesw",
            relief=tk.FLAT, command=lambda var_type=str_filetype, var_file=str_filename_long, var_lb_state=False:
            self.fi_show_time_signal_diagram(var_type, var_file, var_lb_state))
        rb_03b = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 20, column_id=0, n_rows=1, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Analyse Mode Plot"][str_filetype][str_filename_short], value_rb=1,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Time-Ratio Plot", sticky="nesw",
            relief=tk.FLAT, command=lambda var_type=str_filetype, var_file=str_filename_long:
            self.fi_show_time_ratio_diagram(var_type, var_file))
        rb_03c = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 21, column_id=0, n_rows=1, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Analyse Mode Plot"][str_filetype][str_filename_short], value_rb=2,
            color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], text="Quick Analysis", sticky="nesw",
            relief=tk.FLAT, command=lambda var_type=str_filetype, var_file=str_filename_long:
            self.fi_show_quick_results(var_type, var_file))

        rb_05 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column + 14, n_rows=1,
            n_columns=13, fg=self.bg_colors["Light Font"], bg=self.colors_intervals["BG"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Calculation Interval"][str_filetype][str_filename_short],
            value_rb=0, color_bg=self.colors_intervals["BG"], fg=self.bg_colors["Light Font"],
            text="Background Interval", sticky="nesw", relief=tk.FLAT)
        rb_06 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column + 27, n_rows=1,
            n_columns=13, fg=self.bg_colors["Light Font"], bg=self.colors_intervals["MAT"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Calculation Interval"][str_filetype][str_filename_short],
            value_rb=1, color_bg=self.colors_intervals["MAT"], fg=self.bg_colors["Light Font"], text="Matrix Interval",
            sticky="nesw", relief=tk.FLAT)
        rb_07 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column + 40, n_rows=1,
            n_columns=13, fg=self.bg_colors["Dark Font"], bg=self.colors_intervals["INCL"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Calculation Interval"][str_filetype][str_filename_short],
            value_rb=2, color_bg=self.colors_intervals["INCL"], fg=self.bg_colors["Dark Font"],
            text="Inclusion Interval", sticky="nesw", relief=tk.FLAT)
        rb_08 = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 22, column_id=start_column + 14, n_rows=1,
            n_columns=39, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_radiobutton(
            var_rb=self.container_var[key_setting]["Calculation Interval"][str_filetype][str_filename_short],
            value_rb=3, color_bg=self.bg_colors["Super Dark"], fg=self.bg_colors["Light Font"], text="No Selection",
            sticky="nesw", relief=tk.FLAT)

        ## CHECKBOXES
        if "BG" not in self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][
            str_filename_short]:
            self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][str_filename_short] = {
                "BG": tk.IntVar(), "MAT": tk.IntVar(), "INCL": tk.IntVar()}
            self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][str_filename_short][
                "BG"].set(1)
            self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][str_filename_short][
                "MAT"].set(1)
            self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][str_filename_short][
                "INCL"].set(1)

        cb_bg = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column + 25,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=2,
            bg=self.colors_intervals["BG"]).create_simple_checkbox(
            var_cb=self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][
                str_filename_short]["BG"], text="", set_sticky="", own_color=True,
            command=lambda var_key="BG", var_type=str_filetype, var_file_short=str_filename_short:
            self.fi_change_interval_visibility(var_key, var_type, var_file_short))
        cb_mat = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column + 38,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=2,
            bg=self.colors_intervals["MAT"]).create_simple_checkbox(
            var_cb=self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][
                str_filename_short]["MAT"], text="", set_sticky="", own_color=True,
            command=lambda var_key="MAT", var_type=str_filetype, var_file_short=str_filename_short:
            self.fi_change_interval_visibility(var_key, var_type, var_file_short))
        cb_incl = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column + 51,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=2,
            bg=self.colors_intervals["INCL"]).create_simple_checkbox(
            var_cb=self.container_var[key_setting]["Calculation Interval Visibility"][str_filetype][
                str_filename_short]["INCL"], text="", set_sticky="", own_color=True,
            command=lambda var_key="INCL", var_type=str_filetype, var_file_short=str_filename_short:
            self.fi_change_interval_visibility(var_key, var_type, var_file_short))

        if str_filetype == "STD":
            rb_07.configure(state=tk.DISABLED)
            cb_incl.deselect()
            cb_incl.configure(state=tk.DISABLED)

        ## ENTRIES
        var_entr_start = tk.StringVar()
        var_entr_start.set("Set start value")
        var_entr_end = tk.StringVar()
        var_entr_end.set("Set end value")
        self.helper_time_entries = {"Start": var_entr_start, "End": var_entr_end}

        entr_04a = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_start, text_default=var_entr_start.get(),
            command=lambda event, var_entr=var_entr_start, var_key="Start", mode=str_filename_long:
            self.fi_set_bg_interval(var_entr, var_key, mode, event))
        entr_04b = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 24, column_id=7, n_rows=1, n_columns=7,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr_end, text_default=var_entr_end.get(),
            command=lambda event, var_entr=var_entr_end, var_key="End", mode=str_filename_long:
            self.fi_set_bg_interval(var_entr, var_key, mode, event))

        ## MEASURED ISOTOPES
        frm_iso = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 1, column_id=start_column, n_rows=14, n_columns=14,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_iso = ttk.Scrollbar(master=frm_iso, orient="vertical")
        text_iso = tk.Text(
            master=frm_iso, width=30, height=25, yscrollcommand=vsb_iso.set, bg=self.bg_colors["Very Light"])
        vsb_iso.config(command=text_iso.yview)
        vsb_iso.pack(side="right", fill="y")
        text_iso.pack(side="left", fill="both", expand=True)

        file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]

        for index, isotope in enumerate(file_isotopes):
            if isotope.isdigit():
                print("There is a problem with an isotope that is probably just a number. "
                      "Please check this and correct it. Thank you!")
                self.container_lists["Measured Isotopes"][str_filename_short].remove(isotope)
                file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]
            else:
                frm_i = tk.Frame(frm_iso, bg=self.isotope_colors[isotope], relief=tk.SOLID, height=15, width=15,
                                 highlightbackground="black", bd=1)
                text_iso.window_create("end", window=frm_i)
                text_iso.insert("end", "")

                lbl_i = tk.Label(frm_iso, text=isotope, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
                text_iso.window_create("end", window=lbl_i)
                text_iso.insert("end", "\t")

                if isotope not in self.container_var[key_setting]["Display RAW"][str_filetype][str_filename_short]:
                    self.container_var[key_setting]["Display RAW"][str_filetype][str_filename_short][
                        isotope] = tk.IntVar()

                cb_raw_i = tk.Checkbutton(
                    frm_iso, variable=self.container_var[key_setting]["Display RAW"][str_filetype][str_filename_short][
                        isotope], text="RAW", onvalue=1, offvalue=0, bg=self.bg_colors["Very Light"],
                    fg=self.bg_colors["Dark Font"], command=lambda var_type=str_filetype, var_file_short=str_filename_short,
                                                                   var_datatype="RAW", var_isotope=isotope:
                    self.fi_change_line_visibility(var_type, var_file_short, var_datatype, var_isotope))
                text_iso.window_create("end", window=cb_raw_i)
                text_iso.insert("end", "\t")

                if isotope not in self.container_var[key_setting]["Display SMOOTHED"][str_filetype][str_filename_short]:
                    self.container_var[key_setting]["Display SMOOTHED"][str_filetype][str_filename_short][
                        isotope] = tk.IntVar()

                cb_smoothed_i = tk.Checkbutton(
                    frm_iso, variable=self.container_var[key_setting]["Display SMOOTHED"][str_filetype][
                        str_filename_short][isotope], text="SMOOTHED", onvalue=1, offvalue=0,
                    bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"],
                    command=lambda var_type=str_filetype, var_file_short=str_filename_short, var_datatype="SMOOTHED",
                                   var_isotope=isotope: self.fi_change_line_visibility(
                        var_type, var_file_short, var_datatype, var_isotope))

                if self.container_var["Spike Elimination"][str_filetype]["State"] == False:
                    cb_smoothed_i.configure(state="disabled")
                else:
                    cb_smoothed_i.configure(state="normal")

                text_iso.window_create("end", window=cb_smoothed_i)
                text_iso.insert("end", "\n")

        ## BACKGROUND INTERVAL
        lb_bg, scrollbar_bg_y = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 24, column_id=start_column + 14, n_rows=8,
            n_columns=13, fg=self.bg_colors["Dark Font"], bg=self.colors_intervals["BG LB"]).create_simple_listbox_grid(
            include_scrb_x=False)
        self.container_helper[str_filetype][str_filename_short]["BG"]["Listbox"] = lb_bg

        ## MATRIX INTERVAL
        lb_mat, scrollbar_mat_y = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 24, column_id=start_column + 27, n_rows=8,
            n_columns=13, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["MAT LB"]).create_simple_listbox_grid(include_scrb_x=False)
        self.container_helper[str_filetype][str_filename_short]["MAT"]["Listbox"] = lb_mat

        ## INCLUSION INTERVAL
        lb_incl, scrollbar_incl_y = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 24, column_id=start_column + 40, n_rows=8,
            n_columns=13, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["INCL LB"]).create_simple_listbox_grid(include_scrb_x=False)
        self.container_helper[str_filetype][str_filename_short]["INCL"]["Listbox"] = lb_incl

        ## TREEVIEWS
        self.tv_parallelism = SE(
            parent=self.subwindow_fi_checkfile, row_id=start_row + 23, column_id=start_column + 53, n_rows=9,
            n_columns=n_columns - 53, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
            n_categories=3, text_n=["Isotope", "Matrix", "Inclusion"],
            width_n=["90", "100", "100"], individual=True)

        ## INITIALIZATION
        self.container_var[key_setting]["Analyse Mode Plot"][str_filetype][str_filename_short].set(0)
        self.fi_show_time_signal_diagram(var_type=str_filetype, var_file=str_filename_long)

        for isotope in file_isotopes:
            entry_parallelism = [isotope, "---", "---"]
            self.tv_parallelism.insert("", tk.END, values=entry_parallelism)

    def fi_show_time_signal_diagram(self, var_type, var_file, var_lb_state=True):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        str_filename_long = var_file
        str_filetype = var_type
        parts = str_filename_long.split("/")
        str_filename_short = parts[-1]
        file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]

        ## Cleaning
        try:
            canvas_ratio = self.container_helper[str_filetype][str_filename_short]["CANVAS RATIO"]
            toolbarframe_ratio = self.container_helper[str_filetype][str_filename_short]["TOOLBARFRAME RATIO"]
            if canvas_ratio == None:
                canvas_ratio.get_tk_widget().grid_remove()
                toolbarframe_ratio.grid_remove()
        except AttributeError:
            pass

        try:
            resultsframe = self.container_helper[str_filetype][str_filename_short]["RESULTS FRAME"]
            if resultsframe != None:
                resultsframe.destroy()
        except AttributeError:
            pass

        self.fig_specific = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.canvas_specific = FigureCanvasTkAgg(self.fig_specific, master=self.subwindow_fi_checkfile)
        self.canvas_specific.get_tk_widget().grid(row=0, column=14, rowspan=20, columnspan=54, sticky="nesw")
        self.toolbarFrame = tk.Frame(master=self.subwindow_fi_checkfile)
        self.toolbarFrame.grid(row=20, column=14, rowspan=2, columnspan=54, sticky="w")
        self.toolbar_specific = NavigationToolbar2Tk(self.canvas_specific, self.toolbarFrame)
        self.toolbar_specific.config(background=self.bg_colors["Very Light"])
        self.toolbar_specific._message_label.config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_specific.winfo_children()[-2].config(background=self.bg_colors["Very Light"])

        self.container_helper[str_filetype][str_filename_short]["FIGURE"] = self.fig_specific
        self.container_helper[str_filetype][str_filename_short]["CANVAS"] = self.canvas_specific
        self.container_helper[str_filetype][str_filename_short]["TOOLBARFRAME"] = self.toolbarFrame

        if self.file_loaded == False:
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=str_filename_long).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=str_filename_long).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
        else:
            if str_filename_short not in self.container_measurements["Dataframe"] and "_copy" in str_filename_short:
                str_filename_short_original = str_filename_short.replace("_copy", "")
                df_data = self.container_measurements["Dataframe"][str_filename_short_original]
            else:
                df_data = self.container_measurements["Dataframe"][str_filename_short]

        self.dataset_time = list(DE().get_times(dataframe=df_data))
        x_max = max(self.dataset_time)
        icp_measurements = np.array([[df_data[isotope] for isotope in file_isotopes]])
        y_max = np.amax(icp_measurements)

        var_lw = float(self.container_var["General Settings"]["Line width"].get())
        if var_lw < 0.25:
            var_lw = 0.25
        elif var_lw > 2.5:
            var_lw = 2.5

        ## DIAGRAMS
        ax = self.fig_specific.add_subplot(label=np.random.uniform())
        self.container_helper[str_filetype][str_filename_short]["AXES"] = {"Time-Signal": ax}
        for isotope in file_isotopes:
            if isotope.isdigit():
                print("There is a problem with an isotope that is probably just a number. "
                      "Please check this and correct it. Thank you!")
            else:
                ln_raw = ax.plot(self.dataset_time, df_data[isotope], label=isotope,
                                 color=self.isotope_colors[isotope], linewidth=var_lw, visible=True)
                self.container_var[key_setting]["Time-Signal Lines"][str_filetype][str_filename_short][isotope][
                    "RAW"] = ln_raw

                if self.container_var["Spike Elimination"][str_filetype]["State"] == True:
                    if isotope in self.container_spikes[str_filename_short]:
                        ln_smoothed = ax.plot(
                            self.dataset_time, self.container_spikes[str_filename_short][isotope]["Data IMPROVED"],
                            label=isotope, color=self.isotope_colors[isotope], linewidth=var_lw, visible=True)
                        self.container_var[key_setting]["Time-Signal Lines"][str_filetype][str_filename_short][isotope][
                            "SMOOTHED"] = ln_smoothed
                        self.container_var[key_setting]["Display SMOOTHED"][str_filetype][str_filename_short][
                            isotope].set(1)

        if self.pysills_mode in ["FI", "MI"]:
            var_check_bg = self.container_helper[str_filetype][str_filename_short]["BG"]["Content"]
        else:
            var_check_bg = self.container_helper[str_filetype][str_filename_short]["BG"]

        if len(var_check_bg) > 0:
            if self.pysills_mode in ["FI", "MI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short]["BG"][
                    "Content"].items():
                    times_bg = var_content["Times"]
                    if times_bg[0] != None and times_bg[1] != None:
                        box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.35, color=self.colors_intervals["BG"])
                        var_content["Object"] = box_bg

                        if var_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["BG"]["Listbox"].insert(
                                tk.END, "BG" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["BG"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["BG"]["Content"][var_id]
            else:
                times_bg = self.container_helper[str_filetype][str_filename_short]["BG"][1]["Times"]
                box_bg = ax.axvspan(times_bg[0], times_bg[1], alpha=0.35, color=self.colors_intervals["BG"])
                self.container_helper[str_filetype][str_filename_short]["BG"][1]["Object"] = box_bg

        if self.pysills_mode == "MA":
            signal_key = "SIG"
            var_check_sig = self.container_helper[str_filetype][str_filename_short][signal_key]
        else:
            signal_key = "MAT"
            var_check_sig = self.container_helper[str_filetype][str_filename_short][signal_key]["Content"]

        if len(var_check_sig) > 0:
            if self.pysills_mode in ["FI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][signal_key][
                    "Content"].items():
                    times_sig = var_content["Times"]
                    var_color = self.colors_intervals["MAT"]
                    if times_sig[0] != None and times_sig[1] != None:
                        box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                        var_content["Object"] = box_mat

                        if var_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["MAT"]["Listbox"].insert(
                                tk.END, "MAT" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["MAT"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["MAT"]["Content"][var_id]
            elif self.pysills_mode in ["MI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][signal_key][
                    "Content"].items():
                    times_sig = var_content["Times"]
                    var_color = self.colors_intervals["MAT"]
                    if times_sig[0] != None and times_sig[1] != None:
                        box_mat = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                        var_content["Object"] = box_mat

                        if var_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["MAT"]["Listbox"].insert(
                                tk.END, "MAT" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["MAT"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["MAT"]["Content"][var_id]
            else:
                times_sig = self.container_helper[str_filetype][str_filename_short][signal_key][1]["Times"]
                var_color = self.colors_intervals["SIG"]
                if times_sig[0] != None and times_sig[1] != None:
                    box_sig = ax.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                    var_content["Object"] = box_sig

        if self.pysills_mode == "MA":
            inclusion_key = "INCL"
            var_check_incl = []
        else:
            inclusion_key = "INCL"
            var_check_incl = self.container_helper[str_filetype][str_filename_short][inclusion_key]["Content"]

        if len(var_check_incl) > 0:
            if self.pysills_mode in ["FI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][inclusion_key][
                    "Content"].items():
                    times_incl = var_content["Times"]
                    if times_incl[0] != None and times_incl[1] != None:
                        box_incl = ax.axvspan(times_incl[0], times_incl[1], alpha=0.35, color=self.colors_intervals[
                            "INCL"])
                        var_content["Object"] = box_incl

                        if var_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["INCL"]["Listbox"].insert(
                                tk.END, "INCL" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["INCL"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["INCL"]["Content"][var_id]

            elif self.pysills_mode in ["MI"]:
                critical_id = []
                for var_id, var_content in self.container_helper[str_filetype][str_filename_short][inclusion_key][
                    "Content"].items():
                    times_incl = var_content["Times"]
                    if times_incl[0] != None and times_incl[1] != None:
                        box_incl = ax.axvspan(times_incl[0], times_incl[1], alpha=0.35, color=self.colors_intervals[
                            "INCL"])
                        var_content["Object"] = box_incl

                        if var_lb_state:
                            self.container_helper[str_filetype][str_filename_short]["INCL"]["Listbox"].insert(
                                tk.END, "INCL" + str(var_id) + " [" + str(var_content["Times"][0]) + "-" +
                                        str(var_content["Times"][1]) + "]")
                    else:
                        critical_id.append(var_id)

                for var_id in critical_id:
                    self.container_helper[str_filetype][str_filename_short]["INCL"]["Indices"].remove(var_id)
                    del self.container_helper[str_filetype][str_filename_short]["INCL"]["Content"][var_id]

        ax.grid(True)
        ax.set_yscale("log")
        ax.set_xlim(left=0, right=x_max)
        ax.set_xticks(np.arange(0, x_max, 20))
        ax.set_ylim(bottom=100, top=1.5*y_max)
        ax.grid(which="major", linestyle="-", linewidth=1)
        ax.minorticks_on()
        ax.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        ax.set_axisbelow(True)
        ax.set_title(str_filename_short, fontsize=9)
        ax.set_xlabel("Experiment Time $t$ (s)", labelpad=0.5, fontsize=8)
        ax.set_ylabel("Signal Intensity $I$ (cps)", labelpad=0.5, fontsize=8)
        ax.xaxis.set_tick_params(labelsize=8)
        ax.yaxis.set_tick_params(labelsize=8)

        self.canvas_specific.draw()

        self.canvas_specific.mpl_connect(
            "button_press_event",
            lambda event, var_type=str_filetype, var_file_short=str_filename_short, var_file_long=str_filename_long:
            self.fi_add_interval_to_diagram(var_type, var_file_short, var_file_long, event))

    def fi_show_time_ratio_diagram(self, var_type, var_file):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        parts = var_file.split("/")
        var_file_short = parts[-1]
        file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

        ## Cleaning
        try:
            canvas = self.container_helper[var_type][var_file_short]["CANVAS"]
            toolbarframe = self.container_helper[var_type][var_file_short]["TOOLBARFRAME"]
            #
            if canvas == None:
                canvas.get_tk_widget().grid_remove()
                toolbarframe.grid_remove()
        except AttributeError:
            pass

        try:
            resultsframe = self.container_helper[var_type][var_file_short]["RESULTS FRAME"]
            #
            if resultsframe != None:
                resultsframe.destroy()
        except AttributeError:
            pass

        if var_type == "STD":
            var_srm_file = self.container_var["STD"][var_file]["SRM"].get()
            for element, value in sorted(self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                if element in self.container_lists["Measured Elements"][var_file_short]:
                    var_key_isotope = self.container_lists["Measured Elements"][var_file_short][element][0]
                break
        else:
            if self.container_var[key_setting][
                "Quantification Method Option"].get() == "Matrix-only Tracer (SILLS)":
                var_key_isotope = self.container_var["SMPL"][var_file]["Host Only Tracer"]["Name"].get()
            elif self.container_var[key_setting][
                "Quantification Method Option"].get() == "Second Internal Standard (SILLS)":
                var_key_isotope = self.container_var["SMPL"][var_file]["Second Internal Standard"]["Name"].get()

        var_id = self.container_lists[var_type]["Long"].index(var_file)
        var_file_short = self.container_lists[var_type]["Short"][var_id]

        self.fig_specific_ratio = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        ax_ratio = self.fig_specific_ratio.add_subplot(label=np.random.uniform())
        self.container_helper[var_type][var_file_short]["AXES"] = {"Time-Ratio": ax_ratio}

        self.canvas_specific_ratio = FigureCanvasTkAgg(self.fig_specific_ratio, master=self.subwindow_fi_checkfile)
        self.canvas_specific_ratio.get_tk_widget().grid(row=0, column=14, rowspan=20, columnspan=54, sticky="nesw")
        self.toolbarFrame_specific_ratio = tk.Frame(master=self.subwindow_fi_checkfile)
        self.toolbarFrame_specific_ratio.grid(row=20, column=14, rowspan=2, columnspan=54, sticky="w")
        self.toolbar_specific_ratio = NavigationToolbar2Tk(self.canvas_specific_ratio, self.toolbarFrame_specific_ratio)
        self.toolbar_specific_ratio.config(background=self.bg_colors["Very Light"])
        self.toolbar_specific_ratio._message_label.config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_specific_ratio.winfo_children()[-2].config(background=self.bg_colors["Very Light"])

        self.container_helper[var_type][var_file_short]["FIGURE RATIO"] = self.fig_specific_ratio
        self.container_helper[var_type][var_file_short]["CANVAS RATIO"] = self.canvas_specific_ratio
        self.container_helper[var_type][var_file_short]["TOOLBARFRAME RATIO"] = self.toolbarFrame_specific_ratio

        if self.file_loaded == False:
            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
        else:
            if var_file_short not in self.container_measurements["Dataframe"] and "_copy" in var_file_short:
                file_short_original = var_file_short.replace("_copy", "")
                df_data = self.container_measurements["Dataframe"][file_short_original]
            else:
                df_data = self.container_measurements["Dataframe"][var_file_short]

        self.dataset_time = list(DE().get_times(dataframe=df_data))
        x_max = max(self.dataset_time)
        if var_key_isotope != "Select Isotope":
            icp_measurements = np.array(
                [[df_data[isotope]/df_data[var_key_isotope] for isotope in file_isotopes]])
            y_max = np.amax(icp_measurements)

            var_lw = float(self.container_var["General Settings"]["Line width"].get())
            if var_lw < 0.25:
                var_lw = 0.25
            elif var_lw > 2.5:
                var_lw = 2.5

            for isotope in file_isotopes:
                ln_raw = ax_ratio.plot(
                    self.dataset_time, df_data[isotope]/df_data[var_key_isotope], label=isotope,
                    color=self.isotope_colors[isotope], linewidth=var_lw, visible=True)
                self.container_var[key_setting]["Time-Ratio Lines"][var_type][var_file_short][isotope]["RAW"] = ln_raw

            ax_ratio.grid(True)
            ax_ratio.set_yscale("log")
            ax_ratio.set_xlim(left=0, right=x_max)
            ax_ratio.set_xticks(np.arange(0, x_max, 20))
            ax_ratio.set_ylim(bottom=10**(-5), top=1.5*y_max)
            ax_ratio.grid(which="major", linestyle="-", linewidth=1)
            ax_ratio.minorticks_on()
            ax_ratio.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
            ax_ratio.set_axisbelow(True)
            ax_ratio.set_title(var_file_short, fontsize=9)
            ax_ratio.set_xlabel("Experiment Time $t$ (s)", labelpad=0.5, fontsize=8)
            ax_ratio.set_ylabel("Signal Intensity Ratio $I$ (cps/cps)", labelpad=0.5, fontsize=8)
            ax_ratio.xaxis.set_tick_params(labelsize=8)
            ax_ratio.yaxis.set_tick_params(labelsize=8)

            self.canvas_specific_ratio.draw()

    def fi_show_quick_results(self, var_type, var_file):
        parts = var_file.split("/")
        var_file_short = parts[-1]

        ## Cleaning
        try:
            canvas = self.container_helper[var_type][var_file_short]["CANVAS"]
            toolbarframe = self.container_helper[var_type][var_file_short]["TOOLBARFRAME"]

            if canvas == None:
                canvas.get_tk_widget().grid_remove()
                toolbarframe.grid_remove()
        except AttributeError:
            pass

        try:
            canvas_ratio = self.container_helper[var_type][var_file_short]["CANVAS RATIO"]
            toolbarframe_ratio = self.container_helper[var_type][var_file_short]["TOOLBARFRAME RATIO"]

            if canvas_ratio == None:
                canvas_ratio.get_tk_widget().grid_remove()
                toolbarframe_ratio.grid_remove()
        except AttributeError:
            pass

        var_id = self.container_lists[var_type]["Long"].index(var_file)
        var_file_short = self.container_lists[var_type]["Short"][var_id]

        ## FRAMES
        frm_quick = SE(
            parent=self.subwindow_fi_checkfile, row_id=0, column_id=14, n_rows=32, n_columns=54,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)

        self.container_helper[var_type][var_file_short]["RESULTS FRAME"] = frm_quick

        ## TREEVIEWS
        list_categories = ["Category"]
        var_is_smpl = None
        var_is_host = None
        if var_type == "STD":
            var_srm_file = self.container_var["STD"][var_file]["SRM"].get()
            for element, value in sorted(self.srm_actual[var_srm_file].items(), key=lambda item: item[1], reverse=True):
                if element in self.container_lists["Measured Elements"][var_file_short]:
                    var_is = self.container_lists["Measured Elements"][var_file_short][element][0]
                break
            list_considered_isotopes = []
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            for isotope in file_isotopes:
                if isotope.isdigit():
                    print("There is a problem with an isotope that is probably just a number. "
                          "Please check this and correct it. Thank you!")
                else:
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    if var_srm_i == var_srm_file:
                        list_considered_isotopes.append(isotope)

            list_categories.extend(list_considered_isotopes)

            key_element_is = re.search(r"(\D+)(\d+)", var_is)
            element_is = key_element_is.group(1)
            stop_calculation = False
            if element_is in self.srm_actual[var_srm_file]:
                stop_calculation = False
            else:
                stop_calculation = True
        else:
            var_is = self.container_var[var_type][var_file]["IS Data"]["IS"].get()
            var_is_smpl = var_is
            var_is_host = self.container_var[var_type][var_file]["Matrix Setup"]["IS"]["Name"].get()
            list_considered_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
            list_categories.extend(list_considered_isotopes)
            stop_calculation = False
        list_width = list(85*np.ones(len(list_categories)))
        list_width = [int(item) for item in list_width]
        list_width[0] = 200

        n_intervals_bg = len(self.container_helper[var_type][var_file_short]["BG"]["Content"])
        n_intervals_mat = len(self.container_helper[var_type][var_file_short]["MAT"]["Content"])
        if var_type == "STD":
            n_intervals_incl = 1
        else:
            n_intervals_incl = len(self.container_helper[var_type][var_file_short]["INCL"]["Content"])

        if len(list_categories) > 1 and stop_calculation == False:
            self.tv_results_quick = SE(
                parent=self.subwindow_fi_checkfile, row_id=0, column_id=14, n_rows=18, n_columns=53,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_treeview(
                n_categories=len(list_categories), text_n=list_categories,
                width_n=list_width, individual=True)

            scb_v = ttk.Scrollbar(self.subwindow_fi_checkfile, orient="vertical")
            scb_h = ttk.Scrollbar(self.subwindow_fi_checkfile, orient="horizontal")
            self.tv_results_quick.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
            scb_v.config(command=self.tv_results_quick.yview)
            scb_h.config(command=self.tv_results_quick.xview)
            scb_v.grid(row=0, column=67, rowspan=18, columnspan=1, sticky="ns")
            scb_h.grid(row=18, column=14, rowspan=1, columnspan=53, sticky="ew")

            if var_is != "Select IS" and n_intervals_bg > 0 and n_intervals_mat > 0 and n_intervals_incl > 0:
                ## INITIALIZATION
                if var_type == "STD":
                    # Intensity analysis
                    self.get_intensity(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, mode="Specific")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_focus="MAT",
                        mode="Specific")
                else:
                    # Intensity analysis
                    for file_std_short in self.container_lists["STD"]["Short"]:
                        self.get_intensity(
                            var_filetype="STD", var_datatype="RAW", var_file_short=file_std_short, mode="Specific")

                    self.fi_get_intensity_corrected(
                        var_filetype="STD", var_datatype="RAW", var_file_short=None, var_focus="MAT", mode="only STD")

                    self.get_intensity(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, mode="Specific")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_focus="MAT",
                        mode="Specific")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_focus="INCL",
                        mode="Specific")
                    self.fi_get_intensity_ratio(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="INCL")
                    self.fi_get_intensity_mix(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, mode="Specific")
                    self.get_analytical_sensitivity_std(
                        var_datatype="RAW", mode="all", var_is_host=var_is_host, var_is_smpl=var_is_smpl)
                    #self.get_analytical_sensitivity_std_alternative(
                    #    var_datatype="RAW", mode="all", var_is_host=var_is_host, var_is_smpl=var_is_smpl)

                self.fi_get_intensity_ratio(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file,
                    var_focus="MAT")
                # Sensitivity analysis
                self.get_analytical_sensitivity(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file)
                results_is = self.determine_possible_is(filetype="ALL")

                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_ratio[var_type]["RAW"]).get_intensity_ratio(
                    data_container=self.container_intensity_corrected[var_type]["RAW"], dict_is=results_is,
                    filename_short=var_file_short)
                self.fi_get_rsf(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file,
                    var_focus="MAT")
                # Concentration analysis
                self.fi_get_concentration2(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file)
                # Normalized Sensitivity
                # SQ(dataframe_01=self.container_intensity_corrected[var_type]["RAW"][var_file_short],
                #    dataframe_02=self.container_concentration[var_type]["RAW"][var_file_short],
                #    results_container=self.container_normalized_sensitivity[var_type]["RAW"]).get_normalized_sensitivity(
                #     filename_short=var_file_short, filetype=var_type,
                #     data_sensitivity=self.container_analytical_sensitivity[var_type]["RAW"][var_file_short],
                #     dict_is=results_is)
                self.fi_get_normalized_sensitivity(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                    var_file_long=var_file, var_focus="MAT")
                self.fi_get_concentration_ratio(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file,
                    var_focus="MAT")
                # self.fi_get_lod(
                #     var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file,
                #     var_focus="MAT")
                self.get_lod(
                    var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                    var_file_long=var_file, var_focus="MAT")

                if var_type == "SMPL":
                    if self.molality_based_quantification.get() == False:
                        self.fi_get_concentration2(
                            var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                            var_file_long=var_file, var_focus="INCL")
                    self.fi_get_normalized_sensitivity(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="INCL")
                    self.fi_get_concentration_ratio(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="INCL")
                    self.get_lod(
                        var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="INCL")
                    # self.fi_get_lod(
                    #     var_filetype=var_type, var_datatype="RAW", var_file_short=var_file_short,
                    #     var_file_long=var_file, var_focus="INCL")
                    self.fi_get_mixed_concentration_ratio(
                        var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file)
                    self.fi_get_mixing_ratio(
                        var_datatype="RAW", var_file_short=var_file_short, var_file_long=var_file)
                    self.fi_get_concentration_mixed(var_datatype="RAW", var_file_short=var_file_short)

                entries_intensity_bg_i = ["Intensity BG"]
                entries_intensity_mat_i = ["Intensity MAT"]
                entries_intensity_incl_i = ["Intensity INCL"]
                entries_intensity_mix_i = ["Intensity MIX"]
                entries_intensity_ratio_i = ["Intensity Ratio MAT"]
                entries_analytical_sensitivity_i = ["Analytical Sensitivity MAT"]
                entries_normalized_sensitivity_i = ["Normalized Sensitivity MAT"]
                entries_rsf_i = ["Relative Sensitivity Factor MAT"]
                entries_concentration_i = ["Concentration MAT"]
                entries_concentration_ratio_i = ["Concentration Ratio MAT"]
                entries_concentration_sigma_mat_i = ["Concentration 1 SIGMA MAT"]
                entries_lod_i = ["Limit of Detection MAT"]
                entries_empty = [""]

                if var_type == "SMPL":
                    entries_intensity_incl_i = ["Intensity INCL"]
                    entries_intensity_ratio_incl_i = ["Intensity Ratio INCL"]
                    entries_analytical_sensitivity_incl_i = ["Analytical Sensitivity INCL"]
                    entries_normalized_sensitivity_incl_i = ["Normalized Sensitivity INCL"]
                    entries_concentration_incl_i = ["Concentration INCL"]
                    entries_concentration_ratio__incl_i = ["Concentration Ratio INCL"]
                    entries_concentration_sigma_incl_i = ["Concentration 1 SIGMA INCL"]
                    entries_concentration_mix_i = ["Concentration MIX"]
                    entries_concentration_sigma_mix_i = ["Concentration 1 SIGMA MIX"]
                    entries_a_i = ["Mixed Concentration Ratio"]
                    entries_x_i = ["Mixing Ratio"]
                    entries_lod_incl_i = ["Limit of Detection INCL"]

                for isotope in list_considered_isotopes:
                    entries_empty.append("")
                    # Intensity Results
                    intensity_bg_i = self.container_intensity[var_type]["RAW"][var_file_short]["BG"][isotope]
                    intensity_mat_i = self.container_intensity_corrected[var_type]["RAW"][var_file_short]["MAT"][
                        isotope]
                    intensity_ratio_i = self.container_intensity_ratio[var_type]["RAW"][var_file_short]["MAT"][isotope]

                    if var_type == "SMPL":
                        intensity_incl_i = self.container_intensity_corrected[var_type]["RAW"][var_file_short]["INCL"][
                            isotope]
                        intensity_mix_i = self.container_intensity_mix[var_type]["RAW"][var_file_short][isotope]
                        intensity_ratio_incl_i = self.container_intensity_ratio[var_type]["RAW"][var_file_short][
                            "INCL"][isotope]

                    # Sensitivity Results
                    analytical_sensitivity_i = self.container_analytical_sensitivity[var_type]["RAW"][var_file_short][
                        "MAT"][isotope]

                    if var_type == "SMPL":
                        var_is = self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Name"].get()
                        analytical_sensitivity_is = self.container_analytical_sensitivity[var_type]["RAW"][
                            var_file_short]["MAT"][var_is]
                        if analytical_sensitivity_is > 0:
                            analytical_sensitivity_i = analytical_sensitivity_i/analytical_sensitivity_is
                        else:
                            analytical_sensitivity_i = 0.0

                    normalized_sensitivity_i = self.container_normalized_sensitivity[var_type]["RAW"][var_file_short][
                        "MAT"][isotope]
                    rsf_i = self.container_rsf[var_type]["RAW"][var_file_short]["MAT"][isotope]

                    if var_type == "SMPL":
                        analytical_sensitivity_incl_i = self.container_analytical_sensitivity[var_type]["RAW"][
                            var_file_short]["INCL"][isotope]
                        normalized_sensitivity_incl_i = self.container_normalized_sensitivity[var_type]["RAW"][
                            var_file_short]["INCL"][isotope]

                    # Concentration Results
                    concentration_i = self.container_concentration[var_type]["RAW"][var_file_short]["MAT"][isotope]

                    if isotope in self.container_concentration[var_type]["RAW"][var_file_short]["1 SIGMA MAT"]:
                        concentration_sigma_mat_i = self.container_concentration[var_type]["RAW"][var_file_short][
                            "1 SIGMA MAT"][isotope]
                    else:
                        concentration_sigma_mat_i = np.nan

                    concentration_ratio_i = self.container_concentration_ratio[var_type]["RAW"][var_file_short]["MAT"][
                        isotope]
                    lod_i = self.container_lod[var_type]["RAW"][var_file_short]["MAT"][isotope]

                    if var_type == "SMPL":
                        concentration_incl_i = self.container_concentration[var_type]["RAW"][var_file_short]["INCL"][
                            isotope]
                        concentration_ratio_incl_i = self.container_concentration_ratio[var_type]["RAW"][
                            var_file_short]["INCL"][isotope]
                        concentration_sigma_incl_i = self.container_concentration[var_type]["RAW"][var_file_short][
                            "1 SIGMA INCL"][isotope]
                        concentration_mix_i = self.container_mixed_concentration["SMPL"]["RAW"][var_file_short][isotope]
                        concentration_sigma_mix_i = self.container_mixed_concentration_error["SMPL"]["RAW"][
                            var_file_short][isotope]
                        lod_incl_i = self.container_lod[var_type]["RAW"][var_file_short]["INCL"][isotope]
                        a_i = self.container_mixed_concentration_ratio[var_type]["RAW"][var_file_short][isotope]
                        x_i = self.container_mixing_ratio[var_type]["RAW"][var_file_short][isotope]

                    # Filling results container
                    entries_intensity_bg_i.append(f"{intensity_bg_i:.{4}f}")
                    entries_intensity_mat_i.append(f"{intensity_mat_i:.{4}f}")

                    if var_type == "SMPL":
                        entries_intensity_ratio_i.append(f"{intensity_ratio_i:.{4}E}")
                        entries_intensity_incl_i.append(f"{intensity_incl_i:.{4}f}")
                        entries_intensity_mix_i.append(f"{intensity_mix_i:.{4}f}")
                        entries_intensity_ratio_incl_i.append(f"{intensity_ratio_incl_i:.{4}E}")

                    entries_analytical_sensitivity_i.append(f"{analytical_sensitivity_i:.{4}f}")
                    entries_normalized_sensitivity_i.append(f"{normalized_sensitivity_i:.{4}f}")

                    if var_type == "SMPL":
                        entries_analytical_sensitivity_incl_i.append(f"{analytical_sensitivity_incl_i:.{4}f}")
                        entries_normalized_sensitivity_incl_i.append(f"{normalized_sensitivity_incl_i:.{4}f}")
                        entries_rsf_i.append(f"{rsf_i:.{4}E}")

                    if None not in [concentration_i]:
                        entries_concentration_i.append(f"{concentration_i:.{4}f}")
                    else:
                        entries_concentration_i.append(np.nan)

                    if None not in [concentration_sigma_mat_i]:
                        entries_concentration_sigma_mat_i.append(f"{concentration_sigma_mat_i:.{4}f}")
                    else:
                        entries_concentration_sigma_mat_i.append(np.nan)

                    if var_type == "SMPL":
                        entries_concentration_ratio_i.append(f"{concentration_ratio_i:.{4}E}")
                        entries_lod_i.append(f"{lod_i:.{4}f}")
                        entries_concentration_incl_i.append(f"{concentration_incl_i:.{4}f}")
                        entries_concentration_ratio__incl_i.append(f"{concentration_ratio_incl_i:.{4}E}")
                        entries_concentration_sigma_incl_i.append(f"{concentration_sigma_incl_i:.{4}f}")
                        entries_concentration_mix_i.append(f"{concentration_mix_i:.{4}f}")
                        entries_concentration_sigma_mix_i.append(f"{concentration_sigma_mix_i:.{4}f}")
                        entries_a_i.append(f"{a_i:.{4}f}")
                        entries_x_i.append(f"{x_i:.{4}E}")
                        entries_lod_incl_i.append(f"{lod_incl_i:.{4}f}")

                # Intensity Results
                self.tv_results_quick.insert("", tk.END, values=entries_intensity_bg_i)
                self.tv_results_quick.insert("", tk.END, values=entries_intensity_mat_i)

                if var_type == "SMPL":
                    self.tv_results_quick.insert("", tk.END, values=entries_intensity_ratio_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_intensity_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_intensity_ratio_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_intensity_mix_i)

                self.tv_results_quick.insert("", tk.END, values=entries_empty)

                # Sensitivity Results
                self.tv_results_quick.insert("", tk.END, values=entries_analytical_sensitivity_i)
                self.tv_results_quick.insert("", tk.END, values=entries_normalized_sensitivity_i)

                if var_type == "SMPL":
                    self.tv_results_quick.insert("", tk.END, values=entries_analytical_sensitivity_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_normalized_sensitivity_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_rsf_i)

                self.tv_results_quick.insert("", tk.END, values=entries_empty)

                # Concentration Results
                self.tv_results_quick.insert("", tk.END, values=entries_concentration_i)
                self.tv_results_quick.insert("", tk.END, values=entries_concentration_sigma_mat_i)

                if var_type == "SMPL":
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_ratio_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_lod_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_sigma_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_ratio__incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_mix_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_sigma_mix_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_lod_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_a_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_x_i)

    def fi_show_all_lines(self, var_type, var_file_short):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Data Type Plot"][var_type][var_file_short].get() == 0:
            for isotope in self.container_lists["ISOTOPES"]:
                if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
                    self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "RAW"][0].set_visible(True)
                    #
                elif self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 1:
                    try:
                        self.container_var[key_setting]["Time-Ratio Lines"][var_type][var_file_short][isotope][
                            "RAW"][0].set_visible(True)
                    except AttributeError:
                        pass
                #
                self.container_var[key_setting]["Display RAW"][var_type][var_file_short][isotope].set(1)
        elif self.container_var[key_setting]["Data Type Plot"][var_type][var_file_short].get() == 1:
            for isotope in self.container_lists["ISOTOPES"]:
                if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
                    self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "SMOOTHED"][0].set_visible(True)
                elif self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 1:
                    try:
                        self.container_var[key_setting]["Time-Ratio Lines"][var_type][var_file_short][isotope][
                            "SMOOTHED"][0].set_visible(True)
                    except AttributeError:
                        pass
                #
                self.container_var[key_setting]["Display SMOOTHED"][var_type][var_file_short][isotope].set(1)
        #
        if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
            self.canvas_specific.draw()
        elif self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 1:
            self.canvas_specific_ratio.draw()

    #
    def fi_hide_all_lines(self, var_type, var_file_short):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Data Type Plot"][var_type][var_file_short].get() == 0:
            for isotope in self.container_lists["ISOTOPES"]:
                if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
                    self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "RAW"][0].set_visible(False)
                    #
                elif self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 1:
                    try:
                        self.container_var[key_setting]["Time-Ratio Lines"][var_type][var_file_short][isotope][
                            "RAW"][0].set_visible(False)
                    except AttributeError:
                        pass
                #
                self.container_var[key_setting]["Display RAW"][var_type][var_file_short][isotope].set(0)
        elif self.container_var[key_setting]["Data Type Plot"][var_type][var_file_short].get() == 1:
            for isotope in self.container_lists["ISOTOPES"]:
                if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
                    self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][isotope][
                        "SMOOTHED"][0].set_visible(False)
                    #
                elif self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 1:
                    try:
                        self.container_var[key_setting]["Time-Ratio Lines"][var_type][var_file_short][isotope][
                            "SMOOTHED"][0].set_visible(False)
                    except AttributeError:
                        pass
                #
                self.container_var[key_setting]["Display SMOOTHED"][var_type][var_file_short][isotope].set(0)
        #
        if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
            self.canvas_specific.draw()
        elif self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 1:
            self.canvas_specific_ratio.draw()

    #
    def fi_change_line_visibility(self, var_type, var_file_short, var_datatype, var_isotope):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        var_key = "Display " + str(var_datatype)
        if self.container_var[key_setting][var_key][var_type][var_file_short][var_isotope].get() == 1:
            if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
                self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][var_isotope][
                    var_datatype][0].set_visible(True)
            else:
                self.container_var[key_setting]["Time-Ratio Lines"][var_type][var_file_short][var_isotope][
                    var_datatype][0].set_visible(True)
        elif self.container_var[key_setting][var_key][var_type][var_file_short][var_isotope].get() == 0:
            if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
                self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][var_isotope][
                    var_datatype][0].set_visible(False)
            else:
                self.container_var[key_setting]["Time-Ratio Lines"][var_type][var_file_short][var_isotope][
                    var_datatype][0].set_visible(False)
        #
        if self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 0:
            self.canvas_specific.draw()
        elif self.container_var[key_setting]["Analyse Mode Plot"][var_type][var_file_short].get() == 1:
            self.canvas_specific_ratio.draw()

    #
    def fi_add_interval_to_diagram(self, var_type, var_file_short, var_file_long, event):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Calculation Interval"][var_type][var_file_short].get() == 0:  # BG
            var_key = "BG"
            var_color = self.colors_intervals[var_key]
        elif self.container_var[key_setting]["Calculation Interval"][var_type][var_file_short].get() == 1:  # MAT
            var_key = "MAT"
            var_color = self.colors_intervals[var_key]
        elif self.container_var[key_setting]["Calculation Interval"][var_type][var_file_short].get() == 2:  # INCL
            var_key = "INCL"
            var_color = self.colors_intervals[var_key]
        #
        if self.container_var[key_setting]["Calculation Interval"][var_type][var_file_short].get() in [0, 1, 2]:
            x_nearest = min(self.dataset_time, key=lambda x: abs(x - event.xdata))
            #
            if len(self.helper_intervals[var_key]) < 1:
                x_id = self.dataset_time.index(x_nearest)
                self.helper_intervals[var_key].append([x_nearest, x_id])
            else:
                x_id = self.dataset_time.index(x_nearest)
                self.helper_intervals[var_key].append([x_nearest, x_id])
                #
                key_id = self.container_helper[var_type][var_file_short][var_key]["ID"] + 1
                time_0_pre = self.helper_intervals[var_key][0][0]
                time_1_pre = self.helper_intervals[var_key][1][0]
                index_0_pre = self.helper_intervals[var_key][0][1]
                index_1_pre = self.helper_intervals[var_key][1][1]

                if time_1_pre < time_0_pre:
                    time_0 = time_1_pre
                    time_1 = time_0_pre
                    index_0 = index_1_pre
                    index_1 = index_0_pre
                else:
                    time_0 = time_0_pre
                    time_1 = time_1_pre
                    index_0 = index_0_pre
                    index_1 = index_1_pre

                box_key = self.container_helper[var_type][var_file_short]["AXES"]["Time-Signal"].axvspan(
                    time_0, time_1, alpha=0.35, color=var_color)
                self.canvas_specific.draw()
                #
                self.container_helper[var_type][var_file_short][var_key]["Content"][key_id] = {
                    "Times": [time_0, time_1], "Indices": [index_0, index_1], "Object": box_key}
                #
                self.container_helper[var_type][var_file_short][var_key]["Listbox"].insert(
                    tk.END, var_key + str(key_id) + " [" + str(time_0) + "-" + str(time_1) + "]")
                #
                self.helper_intervals[var_key].clear()
                self.container_helper[var_type][var_file_short][var_key]["ID"] = key_id
                self.container_helper[var_type][var_file_short][var_key]["Indices"].append(key_id)
                #
                self.canvas_specific.draw()
        #
        if var_type == "STD":
            if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) + \
                    len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) < 2:
                self.container_var[var_type][var_file_long]["Frame"].config(background=self.sign_yellow, bd=1)
                self.container_var[var_type][var_file_long]["Sign Color"].set(self.sign_yellow)
            else:
                if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) > 0 and \
                        len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) > 0:
                    self.container_var[var_type][var_file_long]["Frame"].config(background=self.sign_green, bd=1)
                    self.container_var[var_type][var_file_long]["Sign Color"].set(self.sign_green)
                else:
                    self.container_var[var_type][var_file_long]["Frame"].config(background=self.sign_yellow, bd=1)
                    self.container_var[var_type][var_file_long]["Sign Color"].set(self.sign_yellow)
            #
        else:
            if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) + \
                    len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) + \
                    len(self.container_helper[var_type][var_file_short]["INCL"]["Content"]) < 3:
                self.container_var[var_type][var_file_long]["Frame"].config(background=self.sign_yellow, bd=1)
                self.container_var[var_type][var_file_long]["Sign Color"].set(self.sign_yellow)
            else:
                if len(self.container_helper[var_type][var_file_short]["BG"]["Content"]) > 0 and \
                        len(self.container_helper[var_type][var_file_short]["MAT"]["Content"]) > 0 and \
                        len(self.container_helper[var_type][var_file_short]["INCL"]["Content"]) > 0:
                    self.container_var[var_type][var_file_long]["Frame"].config(background=self.sign_green, bd=1)
                    self.container_var[var_type][var_file_long]["Sign Color"].set(self.sign_green)
                else:
                    self.container_var[var_type][var_file_long]["Frame"].config(background=self.sign_yellow, bd=1)
                    self.container_var[var_type][var_file_long]["Sign Color"].set(self.sign_yellow)

    #
    def fi_change_interval_visibility(self, var_key, var_type, var_file_short):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Calculation Interval Visibility"][var_type][var_file_short][
            var_key].get() == 0:
            var_state = False
        else:
            var_state = True

        for var_id, var_content in self.container_helper[var_type][var_file_short][var_key]["Content"].items():
            var_content["Object"].set_visible(var_state)

        self.canvas_specific.draw()

    def fi_remove_interval(self, var_type, var_file_short):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Calculation Interval"][var_type][var_file_short].get() == 0:
            var_key = "BG"
        elif self.container_var[key_setting]["Calculation Interval"][var_type][var_file_short].get() == 1:
            var_key = "MAT"
        elif self.container_var[key_setting]["Calculation Interval"][var_type][var_file_short].get() == 2:
            var_key = "INCL"

        var_lb = self.container_helper[var_type][var_file_short][var_key]["Listbox"]

        item = self.container_helper[var_type][var_file_short][var_key]["Listbox"].curselection()[0]
        value = var_lb.get(item)
        value_parts = value.split(" ")
        key_id = re.search(r"(\D+)(\d+)", value_parts[0])
        var_id = int(key_id.group(2))

        self.container_helper[var_type][var_file_short][var_key]["Indices"].remove(var_id)
        var_lb.delete(tk.ANCHOR)
        self.container_helper[var_type][var_file_short][var_key]["Content"][var_id]["Object"].set_visible(False)
        del self.container_helper[var_type][var_file_short][var_key]["Content"][var_id]

        self.canvas_specific.draw()

    def fi_set_bg_interval(self, var_entr, var_key, mode, event):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if mode == "default":
            time = var_entr.get()
            time = time.replace(",", ".")
            #
            for var_type in ["STD", "SMPL"]:
                for var_file in self.container_lists[var_type]["Long"]:
                    if self.container_icpms["name"] != None:
                        var_skipheader = self.container_icpms["skipheader"]
                        var_skipfooter = self.container_icpms["skipfooter"]
                        df_data = DE(filename_long=var_file).get_measurements(
                            delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                    else:
                        df_data = DE(filename_long=var_file).get_measurements(
                            delimiter=",", skip_header=3, skip_footer=1)
                    dataset_time = list(DE().get_times(dataframe=df_data))
                    var_file_short = var_file.split("/")[-1]
                    #
                    if 1 not in self.container_helper[var_type][var_file_short]["BG"]["Content"]:
                        self.container_helper[var_type][var_file_short]["BG"]["Content"][1] = {
                            "Times": [None, None], "Indices": [None, None], "Object": None}
                        self.container_helper[var_type][var_file_short]["BG"]["ID"] += 1
                        self.container_helper[var_type][var_file_short]["BG"]["Indices"].append(1)
                    #
                    x_nearest = round(min(dataset_time, key=lambda x: abs(x - float(time))), 8)
                    if var_key == "Start":
                        var_entr.set("Start value set!")
                        var_time = x_nearest
                        var_index = dataset_time.index(var_time)
                        #
                        self.container_helper[var_type][var_file_short]["BG"]["Content"][1]["Times"][0] = var_time
                        self.container_helper[var_type][var_file_short]["BG"]["Content"][1]["Indices"][0] = var_index
                    elif var_key == "End":
                        var_entr.set("End value set!")
                        var_time = x_nearest
                        var_index = dataset_time.index(var_time)
                        #
                        self.container_helper[var_type][var_file_short]["BG"]["Content"][1]["Times"][1] = var_time
                        self.container_helper[var_type][var_file_short]["BG"]["Content"][1]["Indices"][1] = var_index
                    #
        elif mode in self.container_lists["STD"]["Long"]:
            var_file = mode
            filetype = "STD"

            if self.container_icpms["name"] != None:
                var_skipheader = self.container_icpms["skipheader"]
                var_skipfooter = self.container_icpms["skipfooter"]
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            else:
                df_data = DE(filename_long=var_file).get_measurements(
                    delimiter=",", skip_header=3, skip_footer=1)
            dataset_time = list(DE().get_times(dataframe=df_data))
            var_file_short = var_file.split("/")[-1]

            if self.container_var[key_setting]["Calculation Interval"]["STD"][var_file_short].get() == 0:
                var_category = "BG"
            elif self.container_var[key_setting]["Calculation Interval"]["STD"][var_file_short].get() == 1:
                var_category = "MAT"
            elif self.container_var[key_setting]["Calculation Interval"]["STD"][var_file_short].get() == 2:
                var_category = "INCL"

            time = var_entr.get()
            time = time.replace(",", ".")
            x_nearest = round(min(dataset_time, key=lambda x: abs(x - float(time))), 8)

            current_id = self.container_helper["STD"][var_file_short][var_category]["ID"]
            if var_key == "Start":
                var_id = current_id + 1
            elif var_key == "End":
                var_id = current_id
                if var_id == 0:
                    var_id = 1
                elif var_id == 1:
                    if var_id in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                        if self.container_helper["STD"][var_file_short][var_category]["Content"][1]["Times"][1] == None:
                            var_id = var_id
                        else:
                            var_id = current_id + 1
                        if var_id not in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                            self.container_helper["STD"][var_file_short][var_category]["Content"][var_id] = {
                                "Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper["STD"][var_file_short][var_category]["ID"] = var_id
                            self.container_helper["STD"][var_file_short][var_category]["Indices"].append(var_id)

            var_entr.set(x_nearest)
            var_time = x_nearest
            var_index = dataset_time.index(var_time)

            if var_id > 1:
                condition = False
                var_id_previous = var_id - 1
                while condition == False:
                    if var_id_previous in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                        condition = True
                    elif len(self.container_helper["STD"][var_file_short][var_category]["Content"]) == 0:
                        var_id_previous = 1
                        if var_id_previous not in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                            self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous] = {
                                "Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper["STD"][var_file_short][var_category]["ID"] = var_id_previous
                            self.container_helper["STD"][var_file_short][var_category]["Indices"].append(
                                var_id_previous)
                        condition = True
                    else:
                        var_id_previous -= 1

                if var_key == "Start":
                    if self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous]["Times"][
                        1] == None:
                        var_id = var_id_previous
                    else:
                        if self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous][
                            "Times"][0] == None:
                            var_id = var_id_previous
                elif var_key == "End":
                    if self.container_helper["STD"][var_file_short][var_category]["Content"][var_id_previous]["Times"][
                        0] == None:
                        var_id = var_id_previous
                    elif self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][
                        0] != None and self.container_helper["STD"][var_file_short][var_category]["Content"][var_id][
                        "Times"][1] != None:
                            var_id = var_id + 1

            if var_id not in self.container_helper["STD"][var_file_short][var_category]["Content"]:
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id] = {
                    "Times": [None, None], "Indices": [None, None], "Object": None}
                self.container_helper["STD"][var_file_short][var_category]["ID"] = var_id
                self.container_helper["STD"][var_file_short][var_category]["Indices"].append(var_id)
            #
            if var_key == "Start":
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][0] = var_time
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Indices"][0] = var_index

                time_0 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper["STD"][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Object"] = box_key

                    self.container_helper["STD"][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.canvas_specific.draw()

                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")
            elif var_key == "End":
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][1] = var_time
                self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Indices"][1] = var_index
                #
                time_0 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper["STD"][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper["STD"][var_file_short][var_category]["Content"][var_id]["Object"] = box_key
                    #
                    self.container_helper["STD"][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")
                    #
                    self.canvas_specific.draw()
                    #
                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")
        elif mode in self.container_lists["SMPL"]["Long"]:
            filetype = "SMPL"
            var_file = mode
            filename_long = var_file
            index_filename = self.container_lists[filetype]["Long"].index(filename_long)
            filename_short = self.container_lists[filetype]["Short"][index_filename]

            df_data, times = self.load_data_as_dataframe(
                filename_short=filename_short, filename_long=filename_long)
            dataset_time = list(times)

            var_file_short = filename_short

            if self.container_var[key_setting]["Calculation Interval"][filetype][var_file_short].get() == 0:
                var_category = "BG"
            elif self.container_var[key_setting]["Calculation Interval"][filetype][var_file_short].get() == 1:
                var_category = "MAT"
            elif self.container_var[key_setting]["Calculation Interval"][filetype][var_file_short].get() == 2:
                var_category = "INCL"

            time = var_entr.get()
            time = time.replace(",", ".")
            x_nearest = round(min(dataset_time, key=lambda x: abs(x - float(time))), 8)

            current_id = self.container_helper[filetype][var_file_short][var_category]["ID"]
            if var_key == "Start":
                var_id = current_id + 1
            elif var_key == "End":
                var_id = current_id
                if var_id == 0:
                    var_id = 1
                elif var_id == 1:
                    if var_id in self.container_helper[filetype][var_file_short][var_category]["Content"]:
                        if self.container_helper[filetype][var_file_short][var_category]["Content"][1]["Times"][
                            1] == None:
                            var_id = var_id
                        else:
                            var_id = current_id + 1
                        if var_id not in self.container_helper[filetype][var_file_short][var_category]["Content"]:
                            self.container_helper[filetype][var_file_short][var_category]["Content"][var_id] = {
                                "Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper[filetype][var_file_short][var_category]["ID"] = var_id
                            self.container_helper[filetype][var_file_short][var_category]["Indices"].append(var_id)

            var_entr.set(x_nearest)
            var_time = x_nearest
            var_index = dataset_time.index(var_time)

            if var_id > 1:
                condition = False
                var_id_previous = var_id - 1
                while condition == False:
                    if var_id_previous in self.container_helper[filetype][var_file_short][var_category]["Content"]:
                        condition = True
                    elif len(self.container_helper[filetype][var_file_short][var_category]["Content"]) == 0:
                        var_id_previous = 1
                        if var_id_previous not in self.container_helper[filetype][var_file_short][var_category][
                            "Content"]:
                            self.container_helper[filetype][var_file_short][var_category]["Content"][
                                var_id_previous] = {"Times": [None, None], "Indices": [None, None], "Object": None}
                            self.container_helper[filetype][var_file_short][var_category]["ID"] = var_id_previous
                            self.container_helper[filetype][var_file_short][var_category]["Indices"].append(
                                var_id_previous)
                        condition = True
                    else:
                        var_id_previous -= 1

                if var_key == "Start":
                    if self.container_helper[filetype][var_file_short][var_category]["Content"][var_id_previous][
                        "Times"][1] == None:
                        var_id = var_id_previous
                    else:
                        if self.container_helper[filetype][var_file_short][var_category]["Content"][var_id_previous][
                            "Times"][0] == None:
                            var_id = var_id_previous
                elif var_key == "End":
                    if self.container_helper[filetype][var_file_short][var_category]["Content"][var_id_previous][
                        "Times"][0] == None:
                        var_id = var_id_previous
                    elif self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"][
                        0] != None and self.container_helper[filetype][var_file_short][var_category]["Content"][var_id][
                        "Times"][1] != None:
                            var_id = var_id + 1

            if var_id not in self.container_helper[filetype][var_file_short][var_category]["Content"]:
                self.container_helper[filetype][var_file_short][var_category]["Content"][var_id] = {
                    "Times": [None, None], "Indices": [None, None], "Object": None}
                self.container_helper[filetype][var_file_short][var_category]["ID"] = var_id
                self.container_helper[filetype][var_file_short][var_category]["Indices"].append(var_id)

            if var_key == "Start":
                self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"][0] = var_time
                self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Indices"][
                    0] = var_index

                time_0 = self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper[filetype][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Object"] = box_key

                    self.container_helper[filetype][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.canvas_specific.draw()

                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")
            elif var_key == "End":
                self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"][1] = var_time
                self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Indices"][
                    1] = var_index

                time_0 = self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"][0]
                time_1 = self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"][1]

                if time_0 != None and time_1 != None:
                    val_time_0 = float(time_0)
                    val_time_1 = float(time_1)
                    if val_time_1 < val_time_0:
                        time_0 = val_time_1
                        time_1 = val_time_0
                        self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Times"] = [
                            time_0, time_1]

                    box_key = self.container_helper[filetype][var_file_short]["AXES"]["Time-Signal"].axvspan(
                        time_0, time_1, alpha=0.35, color=self.colors_intervals[var_category])
                    self.container_helper[filetype][var_file_short][var_category]["Content"][var_id]["Object"] = box_key

                    self.container_helper[filetype][var_file_short][var_category]["Listbox"].insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.canvas_specific.draw()

                    for key, item in self.helper_time_entries.items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")

    ## MATRIX SETTINGS
    #
    def fi_matrix_concentration_setup(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 700
        window_height = 450
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        #
        subwindow_fi_matrix_concentration = tk.Toplevel(self.parent)
        subwindow_fi_matrix_concentration.title("FLUID INCLUSION ANALYSIS - Matrix Concentration Setup")
        subwindow_fi_matrix_concentration.geometry(var_geometry)
        subwindow_fi_matrix_concentration.resizable(False, False)
        subwindow_fi_matrix_concentration["bg"] = self.bg_colors["Very Dark"]
        #
        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_fi_matrix_concentration, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_fi_matrix_concentration, y, weight=1)
        #
        # Rows
        for i in range(0, n_rows):
            subwindow_fi_matrix_concentration.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_fi_matrix_concentration.grid_columnconfigure(i, minsize=column_min)
        #
        start_row = 0
        start_column = 0

        ## INITIAL VALUES
        list_oxides = sorted(self.container_lists["Oxides"])

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_fi_matrix_concentration, row_id=start_row, column_id=start_column, n_rows=1, n_columns=24,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Sample Files", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_fi_matrix_concentration, row_id=start_row, column_id=start_column + 25, n_rows=1,
            n_columns=9, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Default Settings", relief=tk.FLAT, fontsize="sans 10 bold")
        #
        ## OPTION MENUS
        if self.container_var[key_setting]["Host Setup Selection"].get() == 1:
            list_elements = []
            var_list_comp = []
            for isotope in self.container_lists["ISOTOPES"]:
                key = re.search(r"(\D+)(\d*)", isotope)
                element_isotope = key.group(1)
                if element_isotope not in list_elements:
                    list_elements.append(element_isotope)
            for oxide in list_oxides:
                key = re.search(r"(\D+)(\d*)(\D+)(\d*)", oxide)
                element_oxide = key.group(1)
                if element_oxide in list_elements:
                    if oxide not in var_list_comp:
                        var_list_comp.append(oxide)

            var_list_is = self.container_lists["ISOTOPES"]
            var_opt_default_comp = self.container_var[key_setting]["Oxide"]
            var_opt_default_is = self.container_var[key_setting]["IS MAT Default"]
            var_entr_default = self.container_var[key_setting]["Oxide Concentration"]
            var_entr_default_is = self.container_var[key_setting]["IS MAT Default Concentration"]
            #
            if self.container_var[key_setting]["Oxide"].get() != "Select Oxide":
                var_opt_default_text = self.container_var[key_setting]["Oxide"].get()
            else:
                var_opt_default_text = "Select Oxide"
            #
            if self.container_var[key_setting]["Oxide Concentration"].get() != "0.0":
                var_entr_default_text = self.container_var[key_setting]["Oxide Concentration"].get()
            else:
                var_entr_default_text = "0.0"
            #
            if self.container_var[key_setting]["IS MAT Default"].get() != "Select IS":
                var_opt_default_is_text = self.container_var[key_setting]["IS MAT Default"].get()
            else:
                var_opt_default_is_text = "Select IS"
            #
            if self.container_var[key_setting]["IS MAT Default Concentration"].get() != "1000000":
                var_entr_default_is_text = self.container_var[key_setting]["IS MAT Default Concentration"].get()
            else:
                var_entr_default_is_text = "1000000"
            #
        elif self.container_var[key_setting]["Host Setup Selection"].get() == 2:
            list_elements = []
            var_list_comp = []
            for isotope in self.container_lists["ISOTOPES"]:
                key = re.search(r"(\D+)(\d*)", isotope)
                element_isotope = key.group(1)
                if element_isotope not in list_elements:
                    list_elements.append(element_isotope)
            for element in self.container_lists["Elements"]:
                if element in list_elements:
                    if element not in var_list_comp:
                        var_list_comp.append(element)
            # var_list_comp = self.container_lists["Elements"]
            var_list_is = self.container_lists["ISOTOPES"]
            var_opt_default_comp = self.container_var[key_setting]["Element"]
            var_opt_default_is = self.container_var[key_setting]["IS MAT Default"]
            var_entr_default = self.container_var[key_setting]["Element Concentration"]
            var_entr_default_is = self.container_var[key_setting]["IS MAT Default Concentration"]
            #
            if self.container_var[key_setting]["Element"].get() != "Select Element":
                var_opt_default_text = self.container_var[key_setting]["Element"].get()
            else:
                var_opt_default_text = "Select Element"
            #
            if self.container_var[key_setting]["Element Concentration"].get() != "1000000":
                var_entr_default_text = self.container_var[key_setting]["Element Concentration"].get()
            else:
                var_entr_default_text = "1000000"
            #
            if self.container_var[key_setting]["IS MAT Default"].get() != "Select IS":
                var_opt_default_is_text = self.container_var[key_setting]["IS MAT Default"].get()
            else:
                var_opt_default_is_text = "Select IS"
            #
            if self.container_var[key_setting]["IS MAT Default Concentration"].get() != "1000000":
                var_entr_default_is_text = self.container_var[key_setting]["IS MAT Default Concentration"].get()
            else:
                var_entr_default_is_text = "1000000"
        #
        opt_02a = SE(
            parent=subwindow_fi_matrix_concentration, row_id=start_row + 1, column_id=start_column + 25, n_rows=1,
            n_columns=9, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=var_opt_default_comp, option_list=var_list_comp, text_set=var_opt_default_text,
            fg_active=self.bg_colors["Light Font"], bg_active=self.accent_color,
            command=lambda var_opt=var_opt_default_comp, var_file=None, state_default=True:
            self.fi_change_matrix_compound(var_opt, var_file, state_default))
        opt_02a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_02a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)
        #
        self.opt_02b = SE(
            parent=subwindow_fi_matrix_concentration, row_id=start_row + 2, column_id=start_column + 25, n_rows=1,
            n_columns=9, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=var_opt_default_is, option_list=var_list_is, text_set=var_opt_default_is_text,
            fg_active=self.bg_colors["Light Font"], bg_active=self.accent_color,
            command=lambda var_opt=var_opt_default_is, var_file=None, state_default=True:
            self.fi_change_matrix_compound(var_opt, var_file, state_default))
        self.opt_02b["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        self.opt_02b.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"], activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)
        #
        ## ENTRIES
        entr_02b = SE(
            parent=subwindow_fi_matrix_concentration, row_id=start_row + 3, column_id=start_column + 25, n_rows=1,
            n_columns=9, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_entry(
            var=var_entr_default_is, text_default=var_entr_default_is_text,
            command=lambda event, var_entr=var_entr_default_is, var_file=None, state_default=True:
            self.fi_change_matrix_concentration(var_entr, var_file, state_default, event))
        #
        ## SAMPLE FILES
        frm_smpl = SE(
            parent=subwindow_fi_matrix_concentration, row_id=start_row + 1, column_id=start_column, n_rows=16,
            n_columns=24, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
        vsb_smpl = ttk.Scrollbar(master=frm_smpl, orient="vertical")
        text_smpl = tk.Text(
            master=frm_smpl, width=30, height=25, yscrollcommand=vsb_smpl.set, bg=self.bg_colors["Very Light"])
        vsb_smpl.config(command=text_smpl.yview)
        vsb_smpl.pack(side="right", fill="y")
        text_smpl.pack(side="left", fill="both", expand=True)
        #
        for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_smpl, text=file_smpl_short, bg=self.bg_colors["Very Light"],
                             fg=self.bg_colors["Dark Font"])
            text_smpl.window_create("end", window=lbl_i)
            text_smpl.insert("end", "\t")

            if self.container_var[key_setting]["Host Setup Selection"].get() == 1:  # Oxide Selection
                var_list_is = self.container_lists["ISOTOPES"]
                var_opt_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"]
                var_entr_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"]
                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"].get() != "Select IS":
                    var_opt_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"].get()
                else:
                    var_opt_i_default = "Select IS"
                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"].get() != "1000000":
                    var_entr_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"][
                        "Concentration"].get()
                else:
                    var_entr_i_default = "1000000"
            elif self.container_var[key_setting]["Host Setup Selection"].get() == 2:  # Element Selection
                var_list_is = self.container_lists["ISOTOPES"]
                var_opt_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"]
                var_entr_i = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"]
                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"].get() != "Select IS":
                    var_opt_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"].get()
                else:
                    var_opt_i_default = "Select IS"
                if self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"].get() != "1000000":
                    var_entr_i_default = self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"][
                        "Concentration"].get()
                else:
                    var_entr_i_default = "1000000"
            #
            var_opt_i.set(var_opt_i_default)
            #
            opt_is_i = tk.OptionMenu(
                frm_smpl, var_opt_i, *var_list_is,
                command=lambda var_opt=var_opt_i, var_file=file_smpl, state_default=False:
                self.fi_change_matrix_is(var_opt, var_file, state_default))
            opt_is_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_is_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)
            text_smpl.window_create("end", window=opt_is_i)
            text_smpl.insert("end", " \t")
            #
            var_entr_i.set(var_entr_i_default)
            #
            entr_i = tk.Entry(frm_smpl, textvariable=var_entr_i)
            entr_i.bind(
                "<Return>", lambda event, var_entr=var_entr_i, var_file=file_smpl, state_default=False:
                self.fi_change_matrix_concentration(var_entr, var_file, state_default, event))
            text_smpl.window_create("insert", window=entr_i)
            text_smpl.insert("end", "\n")
        #

    def fi_change_matrix_compound(self, var_opt, var_file=None, state_default=False, matrix_only=False):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Host Setup Selection"].get() == 1:
            var_key = "Oxide"
        else:
            var_key = "Element"

        if state_default:
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file_smpl]["Matrix Setup"][var_key]["Name"].set(var_opt)

                if matrix_only:
                    self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Matrix"].set(var_opt)

            self.container_var[key_setting]["IS MAT Default Concentration"].set(1000000)
            if var_key == "Oxide":
                key = re.search(r"(\D+)(\d*)(\D+)(\d*)", var_opt)
                var_opt_element = key.group(1)
            else:
                var_opt_element = var_opt
            possible_is = []

            for isotope in self.container_lists["ISOTOPES"]:
                if isotope.isdigit():
                    pass
                else:
                    key_02 = re.search(r"(\D+)(\d+)", isotope)
                    element = key_02.group(1)
                    if element == var_opt_element:
                        possible_is.append(isotope)

            self.container_var[key_setting]["IS MAT Default"].set("Select IS")
            for index, isotope in enumerate(possible_is):
                if matrix_only:
                    if index == 0:
                        self.opt_01c["menu"].delete(0, "end")

                    self.opt_01c["menu"].add_command(
                        label=isotope, command=lambda var_opt=isotope, var_file=None, state_default=True:
                        self.change_matrix_only_tracer(var_opt, var_file, state_default))
                else:
                    if index == 0:
                        self.opt_02b["menu"].delete(0, "end")

                    self.opt_02b["menu"].add_command(
                        label=isotope, command=lambda var_opt=isotope, var_file=None, state_default=True:
                        self.fi_change_matrix_is(var_opt, var_file, state_default))

        else:
            self.container_var["SMPL"][var_file]["Matrix Setup"][var_key]["Name"].set(var_opt)

    def change_matrix_only_tracer(self, var_opt, var_file, state_default):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if state_default:
            self.container_var[key_setting]["Host Only"].set(var_opt)
            #
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Name"].set(var_opt)
                #
                var_oxide = self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Matrix"].get()
                key = re.search(r"(\D+)(\d*)(\D+)(\d*)", var_oxide)
                list_elements = []
                list_amounts = []
                list_fraction = {}
                #
                for index, item in enumerate(key.groups()):
                    if index in [0, 2]:
                        list_elements.append(item)
                    else:
                        if item == "":
                            list_amounts.append(1)
                        else:
                            list_amounts.append(int(item))
                #
                mass_total = 0
                for index, element in enumerate(list_elements):
                    if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                        mass_total += list_amounts[index]*self.chemistry_data[element]
                    else:
                        mass_total += list_amounts[index]*self.chemistry_data_sills[element]
                #
                for index, element in enumerate(list_elements):
                    if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                        list_fraction[element] = (list_amounts[index]*self.chemistry_data[element])/mass_total
                    else:
                        list_fraction[element] = (list_amounts[index]*self.chemistry_data_sills[element])/mass_total
                    #
                    if index == 0:
                        oxide_weight = float(
                            self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Amount"].get())/100
                        is_concentration = round(list_fraction[element]*10**6, 4)
                        self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Value"].set(round(
                            oxide_weight*is_concentration, 4))
            #
            oxide_weight = float(self.container_var[key_setting]["Matrix Amount Default"].get())/100
            self.container_var[key_setting]["Matrix-Only Concentration Default"].set(round(
                oxide_weight*is_concentration, 4))
            #
        else:
            self.container_var["SMPL"][var_file]["Host Only Tracer"]["Name"].set(var_opt)

    #
    def change_specific_matrix_amount(self, var_file, event):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        var_amount = float(self.container_var["SMPL"][var_file]["Host Only Tracer"]["Amount"].get())/100
        var_concentration_before = float(self.container_var[key_setting]["Matrix-Only Concentration Default"].get())
        #
        var_concentration = var_amount*var_concentration_before
        #
        self.container_var["SMPL"][var_file]["Host Only Tracer"]["Value"].set(round(var_concentration, 4))

    def fi_change_matrix_is(self, var_opt, var_file, state_default):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var[key_setting]["Host Setup Selection"].get() == 1:
            var_key = "Oxide"
        else:
            var_key = "Element"

        self.container_var[key_setting]["IS MAT Default"].set(var_opt)

        if state_default:
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Name"].set(var_opt)

                if var_key == "Oxide":
                    var_oxide = self.container_var["SMPL"][file_smpl]["Matrix Setup"][var_key]["Name"].get()
                    key = re.search(r"(\D+)(\d*)(\D+)(\d*)", var_oxide)
                    list_elements = []
                    list_amounts = []
                    list_fraction = {}

                    for index, item in enumerate(key.groups()):
                        if index in [0, 2]:
                            list_elements.append(item)
                        else:
                            if item == "":
                                list_amounts.append(1)
                            else:
                                list_amounts.append(int(item))

                    mass_total = 0
                    for index, element in enumerate(list_elements):
                        if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                            mass_total += list_amounts[index]*self.chemistry_data[element]
                        else:
                            mass_total += list_amounts[index]*self.chemistry_data_sills[element]

                    for index, element in enumerate(list_elements):
                        if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                            list_fraction[element] = (list_amounts[index]*self.chemistry_data[element])/mass_total
                        else:
                            list_fraction[element] = (list_amounts[index]*self.chemistry_data_sills[element])/mass_total

                        if index == 0:
                            oxide_weight = 1
                            is_concentration = round(list_fraction[element]*10**6, 4)
                            self.container_var[key_setting]["IS MAT Default Concentration"].set(is_concentration)
                            self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"].set(round(
                                oxide_weight*is_concentration, 4))
                            self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Name"].set(var_opt)
                            self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Value"].set(round(
                                oxide_weight*is_concentration, 4))
                else:
                    oxide_weight = 1
                    is_concentration = round(1*10**6, 4)
                    self.container_var[key_setting]["IS MAT Default Concentration"].set(is_concentration)
                    self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"].set(round(
                        oxide_weight*is_concentration, 4))
                    self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Name"].set(var_opt)
                    self.container_var["SMPL"][file_smpl]["Host Only Tracer"]["Value"].set(round(
                        oxide_weight*is_concentration, 4))
        else:
            self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Name"].set(var_opt)

    def fi_change_matrix_concentration(self, var_entr, var_file, state_default, event):
        if state_default:
            for file_smpl in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][file_smpl]["Matrix Setup"]["IS"]["Concentration"].set(var_entr.get())
        else:
            self.container_var["SMPL"][var_file]["Matrix Setup"]["IS"]["Concentration"].set(var_entr.get())

    #
    ## INCLUSION SETUP #################################################################################################

    def fi_change_is_default(self, var_isotope, var_key):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        for file_long in self.container_lists[var_key]["Long"]:
            self.container_var["SMPL"][file_long]["IS Data"]["IS"].set(var_isotope)

        self.container_var[key_setting]["Salt Correction"]["Default IS"].set(var_isotope)

    def fi_change_is_specific(self, var_isotope, var_file, var_key):
        self.container_var[var_key][var_file]["IS Data"]["IS"].set(var_isotope)

    def fi_check_elements_checkbutton(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        list_halogen_isotopes = []
        for halogen in ["Cl", "Br", "I"]:
            if halogen in self.container_lists["Measured Elements"]:
                for isotope in self.container_lists["Measured Elements"][halogen]:
                    list_halogen_isotopes.append(isotope)

        self.container_lists["Possible IS SMPL"].clear()
        self.container_lists["Selected Salts"].clear()
        for category in ["Chlorides", "Carbonates", "Sulfates"]:
            for salt, values in self.container_var[key_setting]["Salt Correction"][category].items():
                if category == "Chlorides":
                    parts_salt = re.search(r"([A-Z]{,1}[a-z]{,1})(\d*)([A-Z]{,1}[a-z]{,1})(\d*)", salt)
                elif category == "Carbonates":
                    parts_salt = re.search(
                        r"([A-Z]{,1}[a-z]{,1})(\d*)([A-Z]{,1}[a-z]{,1})(\d*)([A-Z]{,1}[a-z]{,1})(\d*)([A-Z]{,1}[a-z]{,1})(\d*)", salt)
                else:
                    parts_salt = re.search(
                        r"([A-Z]{,1}[a-z]{,1})(\d*)([A-Z]{,1}[a-z]{,1})(\d*)([A-Z]{,1}[a-z]{,1})(\d*)", salt)
                if values["State"].get() == 1:
                    self.container_lists["Salt Chemistry"][salt] = {}
                    self.container_lists["Selected Salts"].append(salt)
                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        key = re.search(r"(\D+)(\d+)", isotope)
                        for item in parts_salt.groups():
                            if item == "":
                                item = str(1)

                            if item.isalpha():
                                last_letter = item
                                if item == key.group(1):
                                    # if (isotope not in self.container_lists["Possible IS SMPL"]
                                    #         and isotope not in list_halogen_isotopes):
                                    #     self.container_lists["Possible IS SMPL"].append(isotope)
                                    if isotope not in self.container_lists["Possible IS SMPL"]:
                                        self.container_lists["Possible IS SMPL"].append(isotope)
                            if item.isnumeric():
                                last_number = item
                                self.container_lists["Salt Chemistry"][salt][last_letter] = last_number

        self.opt_is_smpl_def["menu"].delete(0, "end")

        for file_smpl, gui_opt in self.container_optionmenu["SMPL"]["IS"].items():
            gui_opt["menu"].delete(0, "end")

        for isotope in self.container_lists["Possible IS SMPL"]:
            self.opt_is_smpl_def["menu"].add_command(
                label=isotope, command=lambda var_isotope=isotope, var_key="SMPL":
                self.fi_change_is_default(var_isotope, var_key))

            for file_smpl, gui_opt in self.container_optionmenu["SMPL"]["IS"].items():
                gui_opt["menu"].add_command(
                    label=isotope, command=lambda var_isotope=isotope, var_file=file_smpl, var_key="SMPL":
                    self.fi_change_is_specific(var_isotope, var_file, var_key))

    def calculate_fluid_data(self):
        if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
            elements_masses = self.chemistry_data
            # elements_masses = {
            #     "H": 1.008, "Li": 6.94, "C": 12.011, "O": 15.999, "Na": 22.99, "Mg": 24.305, "S": 32.06, "Cl": 35.45,
            #     "K": 39.098, "Ca": 40.078, "Fe": 55.845}
        else:
            elements_masses = self.chemistry_data_sills
            # elements_masses = {
            #     "H": 1.008, "Li": 6.941, "C": 12.010, "O": 16.000, "Na": 22.990, "Mg": 24.300, "S": 32.070, "Cl": 35.45,
            #     "K": 39.100, "Ca": 40.080, "Fe": 55.850}

        for fluid in ["H2O"]:
            if fluid not in self.molar_masses_compounds:
                self.molar_masses_compounds[fluid] = {}
                if fluid == "H2O":
                    total = round(2*elements_masses["H"] + elements_masses["O"], 3)
                    self.molar_masses_compounds[fluid]["H"] = round((2*elements_masses["H"])/total, 3)
                    self.molar_masses_compounds[fluid]["O"] = round((elements_masses["O"])/total, 3)
                    self.molar_masses_compounds[fluid]["Total"] = total
                    self.molar_masses_compounds[fluid]["Cation"] = "H"

    def calculate_chloride_data(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
            elements_masses =  self.chemistry_data
            # elements_masses = {
            #     "H": 1.008, "Li": 6.94, "C": 12.011, "O": 15.999, "Na": 22.99, "Mg": 24.305, "S": 32.06, "Cl": 35.45,
            #     "K": 39.098, "Ca": 40.078, "Fe": 55.845}
        else:
            elements_masses =  self.chemistry_data_sills
            # elements_masses = {
            #     "H": 1.008, "Li": 6.941, "C": 12.010, "O": 16.000, "Na": 22.990, "Mg": 24.300, "S": 32.070, "Cl": 35.45,
            #     "K": 39.100, "Ca": 40.080, "Fe": 55.850}

        for salt in list(self.container_var[key_setting]["Salt Correction"]["Chlorides"].keys()):
            if salt not in self.molar_masses_compounds:
                self.molar_masses_compounds[salt] = {}
                # monovalent compounds
                if salt == "LiCl":
                    total = round(elements_masses["Li"] + elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Li"] = round((elements_masses["Li"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Li"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 1
                elif salt == "NaCl":
                    total = round(elements_masses["Na"] + elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Na"] = round((elements_masses["Na"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Na"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 1
                elif salt == "KCl":
                    total = round(elements_masses["K"] + elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["K"] = round((elements_masses["K"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "K"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 1
                elif salt == "RbCl":
                    total = round(elements_masses["Rb"] + elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Rb"] = round((elements_masses["Rb"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Rb"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 1
                elif salt == "AgCl":
                    total = round(elements_masses["Ag"] + elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Ag"] = round((elements_masses["Ag"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Ag"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 1
                elif salt == "CsCl":
                    total = round(elements_masses["Cs"] + elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Cs"] = round((elements_masses["Cs"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Cs"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 1
                # divalent compounds
                elif salt == "MgCl2":
                    total = round(elements_masses["Mg"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Mg"] = round((elements_masses["Mg"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Mg"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "CaCl2":
                    total = round(elements_masses["Ca"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Ca"] = round((elements_masses["Ca"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Ca"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "MnCl2":
                    total = round(elements_masses["Mn"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Mn"] = round((elements_masses["Mn"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Mn"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "FeCl2":
                    total = round(elements_masses["Fe"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Fe"] = round((elements_masses["Fe"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Fe"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "CoCl2":
                    total = round(elements_masses["Co"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Co"] = round((elements_masses["Co"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Co"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "NiCl2":
                    total = round(elements_masses["Ni"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Ni"] = round((elements_masses["Ni"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Ni"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "CuCl2":
                    total = round(elements_masses["Cu"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Cu"] = round((elements_masses["Cu"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Cu"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "ZnCl2":
                    total = round(elements_masses["Zn"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Zn"] = round((elements_masses["Zn"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Zn"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "SrCl2":
                    total = round(elements_masses["Sr"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Sr"] = round((elements_masses["Sr"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Sr"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "SnCl2":
                    total = round(elements_masses["Sn"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Sn"] = round((elements_masses["Sn"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Sn"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "BaCl2":
                    total = round(elements_masses["Ba"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Ba"] = round((elements_masses["Ba"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Ba"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "WCl2":
                    total = round(elements_masses["W"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["W"] = round((elements_masses["W"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "W"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                elif salt == "PbCl2":
                    total = round(elements_masses["Pb"] + 2*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Pb"] = round((elements_masses["Pb"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((2*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Pb"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 2
                # trivalent compounds
                elif salt == "BCl3":
                    total = round(elements_masses["B"] + 3*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["B"] = round((elements_masses["B"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "B"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 3
                elif salt == "AlCl3":
                    total = round(elements_masses["Al"] + 3*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Al"] = round((elements_masses["Al"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Al"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 3
                elif salt == "ScCl3":
                    total = round(elements_masses["Sc"] + 3*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Sc"] = round((elements_masses["Sc"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Sc"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 3
                elif salt == "TiCl3":
                    total = round(elements_masses["Ti"] + 3*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Ti"] = round((elements_masses["Ti"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Ti"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 3
                elif salt == "VCl3":
                    total = round(elements_masses["V"] + 3*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["V"] = round((elements_masses["V"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "V"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 3
                elif salt == "AuCl3":
                    total = round(elements_masses["Au"] + 3*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Au"] = round((elements_masses["Au"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Au"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 3
                # tetravalent compounds
                elif salt == "ZrCl4":
                    total = round(elements_masses["Zr"] + 4*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Zr"] = round((elements_masses["Zr"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Zr"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 4
                elif salt == "HfCl4":
                    total = round(elements_masses["Hf"] + 4*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Hf"] = round((elements_masses["Hf"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Hf"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 4
                # pentavalent compounds
                elif salt == "NbCl5":
                    total = round(elements_masses["Nb"] + 5*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Nb"] = round((elements_masses["Nb"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Nb"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 5
                elif salt == "TaCl5":
                    total = round(elements_masses["Ta"] + 5*elements_masses["Cl"], 3)
                    self.molar_masses_compounds[salt]["Ta"] = round((elements_masses["Ta"])/total, 3)
                    self.molar_masses_compounds[salt]["Cl"] = round((3*elements_masses["Cl"])/total, 3)
                    self.molar_masses_compounds[salt]["Total"] = total
                    self.molar_masses_compounds[salt]["Cation"] = "Ta"
                    self.molar_masses_compounds[salt]["Cation Charge"] = 5

    def prepare_nacl_equivalents(self, amount_fluid, amount_nacl_equiv, total_ppm):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
            elements_masses = self.chemistry_data
            # elements_masses = {
            #     "H": 1.008, "Li": 6.94, "C": 12.011, "O": 15.999, "Na": 22.99, "Mg": 24.305, "S": 32.06, "Cl": 35.45,
            #     "K": 39.098, "Ca": 40.078, "Fe": 55.845}
        else:
            elements_masses = self.chemistry_data_sills
            # elements_masses = {
            #     "H": 1.008, "Li": 6.941, "C": 12.010, "O": 16.000, "Na": 22.990, "Mg": 24.300, "S": 32.070, "Cl": 35.45,
            #     "K": 39.100, "Ca": 40.080, "Fe": 55.850}

        self.helper_nacl_equivalents = {}

        for element in list(elements_masses.keys()):
            self.helper_nacl_equivalents[element] = 0

        for salt in self.molar_masses_compounds:
            if salt in self.container_var[key_setting]["Salt Correction"]["Chlorides"]:
                var_class = "Chlorides"
            else:
                continue

            for element in list(elements_masses.keys()):
                if self.container_var[key_setting]["Salt Correction"][var_class][salt]["State"].get() != 0:
                    if element in self.molar_masses_compounds[salt]:
                        salt_weight = float(
                            self.container_var[key_setting]["Salt Correction"][var_class][salt]["Weight"].get())
                        self.helper_nacl_equivalents[element] += int(round(
                            amount_nacl_equiv*salt_weight*self.molar_masses_compounds[salt][element]*total_ppm, 0))

        for fluid in self.molar_masses_compounds:
            if fluid in ["H2O"]:
                for element in list(elements_masses.keys()):
                    if element in self.molar_masses_compounds[fluid]:
                        self.helper_nacl_equivalents[element] += int(round(
                            amount_fluid*self.molar_masses_compounds[fluid][element]*total_ppm, 0))

    def fi_calculate_chargebalance(self, var_entr, mode, var_file, event):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        condition_std, condition_smpl = self.check_file_flags()
        self.pypitzer_performed = False

        is_defined = self.check_if_is_was_defined()

        if condition_std == True and condition_smpl == True and is_defined == True:
            amount_fluid = (100 - float(var_entr.get()))/100
            amount_nacl_equiv = float(var_entr.get())/100
            total_ppm = 10**6

            # Calculate fluid data
            self.calculate_fluid_data()
            # Calculate chloride data
            self.calculate_chloride_data()
            # Prepare NaCl equivalents  calculation
            self.prepare_nacl_equivalents(
                amount_fluid=amount_fluid, amount_nacl_equiv=amount_nacl_equiv, total_ppm=total_ppm)

            if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                elements_masses = self.chemistry_data
            else:
                elements_masses = self.chemistry_data_sills

            val_molar_mass_na = elements_masses["Na"]
            val_molar_mass_cl = elements_masses["Cl"]
            val_molar_mass_nacl = val_molar_mass_na + val_molar_mass_cl

            if mode == "default":
                helper = []
                helper_is = []
                helper_cl = []
                helper2 = {}
                helper3 = {}
                for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
                    file_smpl = self.container_lists["SMPL"]["Long"][index]
                    if self.container_var["SMPL"][file_smpl]["Checkbox"].get() == 1:
                        salt_composition = "NaCl"
                        helper2[file_smpl_short] = {}
                        var_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"].get()
                        var_na = self.container_lists["Measured Elements"][file_smpl_short]["Na"][0]
                        var_na_equiv = (val_molar_mass_na/val_molar_mass_nacl)*amount_nacl_equiv
                        var_cl_equiv = (val_molar_mass_cl/val_molar_mass_nacl)*amount_nacl_equiv
                        var_na_true_base = var_na_equiv
                        var_nacl_equiv = amount_nacl_equiv
                        var_na_true_base = var_nacl_equiv*(val_molar_mass_na/val_molar_mass_nacl)
                        file_isotopes = self.container_lists["Measured Isotopes"][file_smpl_short]
                        salt_factor = 1
                        salt_contribution = 0
                        for salt in self.container_lists["Selected Salts"]:
                            if salt != "NaCl":
                                molar_mass_salt = self.molar_masses_compounds[salt]["Total"]
                                element = self.molar_masses_compounds[salt]["Cation"]
                                charge_i = self.molar_masses_compounds[salt]["Cation Charge"]
                                molar_mass_na = elements_masses["Na"]
                                salt_composition += ", " + str(salt)
                                for isotope in file_isotopes:
                                    key_isotope = re.search(r"(\D+)(\d+)", isotope)
                                    isotope_atom = key_isotope.group(1)

                                    if element == isotope_atom:
                                        molar_mass_element = elements_masses[element]
                                        helper3[salt] = molar_mass_element/molar_mass_salt

                                        try:
                                            var_intensity_i = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                                file_smpl_short]["INCL"][isotope]
                                            var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                                file_smpl_short]["INCL"][var_na]
                                            var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][
                                                "SMOOTHED"][file_smpl_short]["INCL"][isotope]
                                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"][
                                                "SMOOTHED"][file_smpl_short]["INCL"][var_na]  # SMOOTHED
                                        except:
                                            var_intensity_i = self.container_intensity_corrected["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][isotope]
                                            var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][var_na]
                                            var_sensitivity_i = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][isotope]
                                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][var_na]

                                        if var_sensitivity_i != None and var_sensitivity_na != None:
                                            var_sensitivity_i = var_sensitivity_i/var_sensitivity_na
                                            try:
                                                var_conc_ratio = var_intensity_i/(var_intensity_na*var_sensitivity_i)
                                                var_salt_contribution = charge_i*var_conc_ratio*(
                                                        val_molar_mass_na/molar_mass_element)
                                                helper2[file_smpl_short][salt] = var_salt_contribution
                                                salt_contribution += var_salt_contribution
                                            except:
                                                print("Error Mass Balance:", var_intensity_i, var_intensity_na,
                                                      var_sensitivity_i, molar_mass_salt,
                                                      molar_mass_element, val_molar_mass_na, val_molar_mass_nacl)
                                        else:
                                            print("Please close the window for the mass/charge balance calculation and "
                                                  "open it again. The next time, the zeros on the left should also be "
                                                  "replaced by intensity inclusion ratios. Please run again the "
                                                  "mass/charge balance calculation. Thank you!")
                                            self.parent.bell()
                            else:
                                salt_factor += 0

                        b_nacl = amount_nacl_equiv/val_molar_mass_nacl
                        b_cl = b_nacl
                        b_na = b_cl/(1 + salt_contribution)
                        val_concentration_is = round(b_na*val_molar_mass_na*total_ppm, 4)
                        helper.append(val_concentration_is)
                        val_concentration_cl = round(b_cl*val_molar_mass_cl*total_ppm, 4)
                        concentration_nacl = val_concentration_is*(val_molar_mass_nacl/val_molar_mass_na)
                        concentration_na_true = val_concentration_is
                        concentration_cl_true = val_concentration_cl
                        helper.append(val_concentration_is)
                        helper_cl.append(val_concentration_cl)

                        if var_is_i != var_na:
                            try:
                                var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_na]
                                var_intensity_is = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_na]  # SMOOTHED
                            except:
                                var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_na]
                                var_intensity_is = self.container_intensity_corrected["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_na]

                            val_concentration_is = round(var_intensity_is/var_intensity_na*(concentration_na_true/(
                                    var_sensitivity_is/var_sensitivity_na)), 4)

                        helper_is.append(val_concentration_is)

                        self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][file_smpl_short].set(
                            var_entr.get())

                        self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].set(val_concentration_is)
                        if file_smpl_short in self.container_files["SMPL"]:
                            self.container_files["SMPL"][file_smpl_short]["IS Concentration"].set(val_concentration_is)

                        self.helper_salt_composition[file_smpl_short].set(salt_composition)
                        self.check_chargebalance(filename_long=file_smpl)

                        if self.molality_based_quantification.get() == True:
                            self.quantify_inclusion_based_on_molalities(
                                var_filename_short=file_smpl_short, var_is_i=var_is_i,
                                var_concentration_na=concentration_na_true, var_concentration_cl=concentration_cl_true,
                                var_concentration_is=val_concentration_is)

                if self.container_var["General Settings"]["Desired Average"].get() == 1:
                    self.container_var[key_setting]["Salt Correction"]["Default Concentration"].set(
                        round(np.mean(helper), 4))
                else:
                    self.container_var[key_setting]["Salt Correction"]["Default Concentration"].set(
                        round(np.median(helper), 4))
            elif mode == "specific":
                file_smpl = var_file
                if self.container_var["SMPL"][file_smpl]["Checkbox"].get() == 1:
                    helper = []
                    helper_is = []
                    helper_cl = []
                    helper2 = {}
                    helper3 = {}

                    salt_composition = "NaCl"
                    file_smpl_short = file_smpl.split("/")[-1]
                    helper2[file_smpl_short] = {}
                    var_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"].get()
                    var_na = self.container_lists["Measured Elements"][file_smpl_short]["Na"][0]
                    var_na_equiv = (val_molar_mass_na/val_molar_mass_nacl)*amount_nacl_equiv
                    var_cl_equiv = (val_molar_mass_cl/val_molar_mass_nacl)*amount_nacl_equiv
                    var_na_true_base = var_na_equiv
                    var_nacl_equiv = amount_nacl_equiv
                    var_na_true_base = var_nacl_equiv*(val_molar_mass_na/val_molar_mass_nacl)
                    file_isotopes = self.container_lists["Measured Isotopes"][file_smpl_short]
                    salt_factor = 1
                    salt_contribution = 0
                    for salt in self.container_lists["Selected Salts"]:
                        if salt != "NaCl":
                            molar_mass_salt = self.molar_masses_compounds[salt]["Total"]
                            element = self.molar_masses_compounds[salt]["Cation"]
                            charge_i = self.molar_masses_compounds[salt]["Cation Charge"]
                            molar_mass_na = elements_masses["Na"]
                            salt_composition += ", " + str(salt)
                            for isotope in file_isotopes:
                                key_isotope = re.search(r"(\D+)(\d+)", isotope)
                                isotope_atom = key_isotope.group(1)

                                if element == isotope_atom:
                                    molar_mass_element = elements_masses[element]
                                    helper3[salt] = molar_mass_element/molar_mass_salt

                                    try:
                                        var_intensity_i = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][var_na]
                                        var_sensitivity_i = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][var_na]  # SMOOTHED
                                    except:
                                        var_intensity_i = self.container_intensity_corrected["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][var_na]
                                        var_sensitivity_i = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][var_na]

                                    if var_sensitivity_i != None and var_sensitivity_na != None:
                                        var_sensitivity_i = var_sensitivity_i/var_sensitivity_na
                                        try:
                                            var_conc_ratio = var_intensity_i/(var_intensity_na*var_sensitivity_i)
                                            var_salt_contribution = charge_i*var_conc_ratio*(
                                                    val_molar_mass_na/molar_mass_element)
                                            helper2[file_smpl_short][salt] = var_salt_contribution
                                            salt_contribution += var_salt_contribution
                                        except:
                                            print("Error Mass Balance:", var_intensity_i, var_intensity_na,
                                                  var_sensitivity_i, molar_mass_salt,
                                                  molar_mass_element, val_molar_mass_na, val_molar_mass_nacl)
                                    else:
                                        print("Please close the window for the mass/charge balance calculation and "
                                              "open it again. The next time, the zeros on the left should also be "
                                              "replaced by intensity inclusion ratios. Please run again the "
                                              "mass/charge balance calculation. Thank you!")
                                        self.parent.bell()
                        else:
                            salt_factor += 0

                    b_nacl = amount_nacl_equiv/val_molar_mass_nacl
                    b_cl = b_nacl
                    b_na = b_cl/(1 + salt_contribution)
                    val_concentration_is = round(b_na*val_molar_mass_na*total_ppm, 4)
                    helper.append(val_concentration_is)
                    val_concentration_cl = round(b_cl*val_molar_mass_cl*total_ppm, 4)
                    concentration_nacl = val_concentration_is*(val_molar_mass_nacl/val_molar_mass_na)
                    concentration_na_true = val_concentration_is
                    concentration_cl_true = val_concentration_cl
                    helper.append(val_concentration_is)
                    helper_cl.append(val_concentration_cl)

                    if var_is_i != var_na:
                        try:
                            var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_na]
                            var_intensity_is = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_na]  # SMOOTHED
                        except:
                            var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_na]
                            var_intensity_is = self.container_intensity_corrected["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_na]

                        val_concentration_is = round(var_intensity_is/var_intensity_na*(concentration_na_true/(
                                var_sensitivity_is/var_sensitivity_na)), 4)

                    self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].set(val_concentration_is)
                    if file_smpl_short in self.container_files["SMPL"]:
                        self.container_files["SMPL"][file_smpl_short]["IS Concentration"].set(val_concentration_is)

                    self.check_chargebalance(filename_long=file_smpl)

                    self.helper_salt_composition[file_smpl_short].set(salt_composition)

                    if self.molality_based_quantification.get() == True:
                        self.quantify_inclusion_based_on_molalities(
                            var_filename_short=file_smpl_short, var_is_i=var_is_i,
                            var_concentration_na=concentration_na_true, var_concentration_cl=concentration_cl_true,
                            var_concentration_is=val_concentration_is)
        else:
            print("Please set the internal standard before you start any calculation. Thank you very much!")
            self.parent.bell()

    def check_file_flags(self):
        helper_flags = {"STD": {"Total": 0, "Currently": 0}, "SMPL": {"Total": 0, "Currently": 0}}
        for str_filetype in ["STD", "SMPL"]:
            helper_flags[str_filetype]["Total"] = len(self.container_lists[str_filetype]["Long"])
            for str_filename_long in self.container_lists[str_filetype]["Long"]:
                str_color = self.container_var[str_filetype][str_filename_long]["Sign Color"].get()
                if str_color == "#B0D8A4":
                    helper_flags[str_filetype]["Currently"] += 1

        condition_std = False
        condition_smpl = False

        if helper_flags["STD"]["Total"] == helper_flags["STD"]["Currently"]:
            condition_std = True

        if helper_flags["SMPL"]["Total"] == helper_flags["SMPL"]["Currently"]:
            condition_smpl = True

        return condition_std, condition_smpl

    def check_if_is_was_defined(self):
        is_defined = False
        for filename_long in self.container_lists["SMPL"]["Long"]:
            var_is_i = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
            if var_is_i != "Select IS":
                is_defined = True
            else:
                is_defined = False

        return is_defined

    def check_chargebalance(self, filename_long):
        file_id = self.container_lists["SMPL"]["Long"].index(filename_long)
        filename_short = self.container_lists["SMPL"]["Short"][file_id]
        val_a = 0
        val_b = 0

        for salt in ["NaCl"]:
            element = self.molar_masses_compounds[salt]["Cation"]
            molar_mass_na = self.chemistry_data[element]
            charge_na = self.molar_masses_compounds[salt]["Cation Charge"]
            concentration_na = float(self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].get())
            val_a += concentration_na/(molar_mass_na*charge_na)
            var_na = self.container_lists["Measured Elements"][filename_short]["Na"][0]

            var_cl = self.container_lists["Measured Elements"][filename_short]["Cl"][0]
            molar_mass_cl = self.chemistry_data["Cl"]
            charge_cl = -1
            intensity_cl = self.container_intensity_corrected["SMPL"]["SMOOTHED"][filename_short][
                "INCL"][var_cl]
            intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][filename_short][
                "INCL"][var_na]
            var_sensitivity_cl = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][filename_short][
                "INCL"][var_cl]
            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][filename_short][
                "INCL"][var_na]
            sensitivity_cl = var_sensitivity_cl/var_sensitivity_na

            if intensity_na > 0 and sensitivity_cl > 0:
                concentration_cl = (intensity_cl/intensity_na)*(concentration_na/sensitivity_cl)
            else:
                print("Attention (charge balance check) -", filename_short, "I(Na):", intensity_na, "xi(Cl):",
                      sensitivity_cl)
                concentration_cl = np.nan

            if (molar_mass_cl*charge_cl) != 0:
                val_b += concentration_cl/(molar_mass_cl*charge_cl)
            else:
                val_b += np.nan

        for salt in self.container_lists["Selected Salts"]:
            element = self.molar_masses_compounds[salt]["Cation"]
            molar_mass_i = self.chemistry_data[element]
            charge_i = self.molar_masses_compounds[salt]["Cation Charge"]
            if salt != "NaCl":
                for isotope in self.container_lists["Measured Elements"][filename_short][element]:
                    intensity_i = self.container_intensity_corrected["SMPL"]["SMOOTHED"][filename_short][
                        "INCL"][isotope]
                    intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][filename_short][
                        "INCL"][var_na]
                    var_sensitivity_i = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][filename_short][
                        "INCL"][isotope]
                    var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][filename_short][
                        "INCL"][var_na]
                    sensitivity_i = var_sensitivity_i/var_sensitivity_na

                    if intensity_na > 0 and sensitivity_i > 0:
                        concentration_i = (intensity_i/intensity_na)*(concentration_na/sensitivity_i)
                    else:
                        print("Attention (charge balance check) -", filename_short, "I(Na):",
                              intensity_na, "xi(" + isotope + "):", sensitivity_i)
                        concentration_i = np.nan

                    if (molar_mass_i*charge_i) != 0:
                        val_a += concentration_i/(molar_mass_i*charge_i)
                    else:
                        val_a += np.nan

        if val_b != 0:
            val_c = -val_a/val_b
        else:
            val_c = np.nan

        self.charge_balance_check[filename_short].set(round(val_c, 3))

    def fi_calculate_massbalance(self, var_entr, mode, var_file, event):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        condition_std, condition_smpl = self.check_file_flags()
        self.pypitzer_performed = False

        is_defined = self.check_if_is_was_defined()
        val_max_na = round((self.chemistry_data["Na"]/(self.chemistry_data["Na"] + self.chemistry_data["Cl"]))*10**6, 4)
        val_max_cl = round((self.chemistry_data["Cl"]/(self.chemistry_data["Na"] + self.chemistry_data["Cl"]))*10**6, 4)

        if condition_std == True and condition_smpl == True and is_defined == True:
            amount_fluid = (100 - float(var_entr.get()))/100
            amount_nacl_equiv = float(var_entr.get())/100
            total_ppm = 10**6

            # Calculate fluid data
            self.calculate_fluid_data()
            # Calculate chloride data
            self.calculate_chloride_data()
            # Prepare NaCl equivalents  calculation
            self.prepare_nacl_equivalents(
                amount_fluid=amount_fluid, amount_nacl_equiv=amount_nacl_equiv, total_ppm=total_ppm)

            if self.container_var["General Settings"]["Calculation Accuracy"].get() == 1:
                elements_masses = self.chemistry_data
            else:
                elements_masses =  self.chemistry_data_sills

            val_molar_mass_na = elements_masses["Na"]
            val_molar_mass_cl = elements_masses["Cl"]
            val_molar_mass_nacl = val_molar_mass_na + val_molar_mass_cl

            if mode == "default":
                helper = []
                helper_is = []
                helper_cl = []
                helper2 = {}
                helper3 = {}
                molar_mass_nacl = self.molar_masses_compounds["NaCl"]["Total"]
                for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
                    file_smpl = self.container_lists["SMPL"]["Long"][index]
                    if self.container_var["SMPL"][file_smpl]["Checkbox"].get() == 1:
                        salt_composition = "NaCl"
                        helper2[file_smpl_short] = {}
                        var_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"].get()
                        var_na = self.container_lists["Measured Elements"][file_smpl_short]["Na"][0]
                        var_na_equiv = (val_molar_mass_na/val_molar_mass_nacl)*amount_nacl_equiv
                        var_cl_equiv = (val_molar_mass_cl/val_molar_mass_nacl)*amount_nacl_equiv
                        var_salt_contribution_2 = 0
                        file_isotopes = self.container_lists["Measured Isotopes"][file_smpl_short]
                        for salt in self.container_lists["Selected Salts"]:
                            if salt in self.container_var[key_setting]["Salt Correction"]["Chlorides"]:
                                var_weight = float(self.container_var[key_setting]["Salt Correction"]["Chlorides"][
                                                       salt]["Weight"].get())
                                var_weight_sum = var_weight*elements_masses["Na"]/molar_mass_nacl

                            if salt != "NaCl":
                                molar_mass_salt = self.molar_masses_compounds[salt]["Total"]
                                element = self.molar_masses_compounds[salt]["Cation"]
                                salt_composition += ", " + str(salt)

                                for isotope in file_isotopes:
                                    key_isotope = re.search(r"(\D+)(\d+)", isotope)
                                    isotope_atom = key_isotope.group(1)

                                    if element == isotope_atom:
                                        molar_mass_element = elements_masses[element]
                                        helper3[salt] = molar_mass_element/molar_mass_salt
                                        try:
                                            var_intensity_i = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                                file_smpl_short]["INCL"][isotope]
                                            var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                                file_smpl_short]["INCL"][var_na]
                                            var_sensitivity_i = self.container_analytical_sensitivity["SMPL"][
                                                "SMOOTHED"][file_smpl_short]["INCL"][isotope]
                                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"][
                                                "SMOOTHED"][file_smpl_short]["INCL"][var_na]  # SMOOTHED
                                        except:
                                            var_intensity_i = self.container_intensity_corrected["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][isotope]
                                            var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][var_na]
                                            var_sensitivity_i = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][isotope]
                                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                                file_smpl_short]["INCL"][var_na]

                                        if var_sensitivity_i != None and var_sensitivity_na != None:
                                            var_sensitivity_i = var_sensitivity_i/var_sensitivity_na
                                            try:
                                                if (var_intensity_na*var_sensitivity_i) > 0:
                                                    var_conc_ratio = var_intensity_i/(var_intensity_na*var_sensitivity_i)
                                                else:
                                                    var_conc_ratio = np.nan

                                                var_salt_contribution_3 = var_conc_ratio*(
                                                        molar_mass_salt/molar_mass_element)
                                                helper2[file_smpl_short][salt] = var_salt_contribution_3
                                                var_salt_contribution_2 += var_weight*var_conc_ratio*(
                                                        val_molar_mass_na*molar_mass_salt)/(
                                                        val_molar_mass_nacl*molar_mass_element)
                                            except:
                                                print("Error Mass Balance:", var_weight_sum, var_intensity_i,
                                                      var_intensity_na, var_sensitivity_i, molar_mass_salt,
                                                      molar_mass_element, val_molar_mass_na, val_molar_mass_nacl)
                                        else:
                                            print("Please close the window for the mass/charge balance calculation and "
                                                  "open it again. The next time, the zeros on the left should also be "
                                                  "replaced by intensity inclusion ratios. Please run again the "
                                                  "mass/charge balance calculation. Thank you!")
                                            self.parent.bell()
                            else:
                                var_na_equiv *= 1

                        val_concentration_is = round((var_na_equiv/(1 + var_salt_contribution_2))*total_ppm, 4)
                        val_concentration_cl = round((var_cl_equiv/(1 + var_salt_contribution_2))*total_ppm, 4)
                        concentration_nacl = val_concentration_is*(val_molar_mass_nacl/val_molar_mass_na)
                        concentration_na_true = val_concentration_is
                        concentration_cl_true = val_concentration_cl
                        helper.append(val_concentration_is)
                        helper_cl.append(val_concentration_cl)

                        if var_is_i != var_na:
                            try:
                                var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_na]
                                var_intensity_is = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                    file_smpl_short]["INCL"][var_na]  # SMOOTHED
                            except:
                                var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_na]
                                var_intensity_is = self.container_intensity_corrected["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_is_i]
                                var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                    file_smpl_short]["INCL"][var_na]

                            val_concentration_is = round(var_intensity_is/var_intensity_na*(concentration_na_true/(
                                    var_sensitivity_is/var_sensitivity_na)), 4)

                            if "Cl" in var_is_i:
                                if val_concentration_is > val_max_cl:
                                    val_concentration_is = val_max_na
                                    self.parent.bell()
                                    print("The concentration of the internal standard,", var_is_i + ",",
                                          "was higher than the highest possible value, assuming that the whole "
                                          "inclusion is composed of 100 % halite.")
                        else:
                            if val_concentration_is > val_max_na:
                                val_concentration_is = val_max_na
                                self.parent.bell()
                                print("The concentration of the internal standard,", var_na+",",
                                      "was higher than the highest possible value, assuming that the whole inclusion "
                                      "is composed of 100 % halite.")

                        helper_is.append(val_concentration_is)

                        self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][file_smpl_short].set(
                            var_entr.get())
                        self.container_var["SMPL"][file_smpl]["IS Data"]["IS"].set(var_is_i)
                        self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].set(val_concentration_is)
                        if file_smpl_short in self.container_files["SMPL"]:
                            self.container_files["SMPL"][file_smpl_short]["IS Concentration"].set(val_concentration_is)

                        self.helper_salt_composition[file_smpl_short].set(salt_composition)
                        self.check_chargebalance(filename_long=file_smpl)

                        if self.molality_based_quantification.get() == True:
                            self.quantify_inclusion_based_on_molalities(
                                var_filename_short=file_smpl_short, var_is_i=var_is_i,
                                var_concentration_na=concentration_na_true, var_concentration_cl=concentration_cl_true,
                                var_concentration_is=val_concentration_is)

                if self.container_var["General Settings"]["Desired Average"].get() == 1:
                    self.container_var[key_setting]["Salt Correction"]["Default Concentration"].set(
                        round(np.mean(helper_is), 4))
                else:
                    self.container_var[key_setting]["Salt Correction"]["Default Concentration"].set(
                        round(np.median(helper_is), 4))
            elif mode == "specific":
                file_smpl = var_file
                if self.container_var["SMPL"][file_smpl]["Checkbox"].get() == 1:
                    helper = []
                    helper_cl = []
                    helper2 = {}
                    helper3 = {}

                    salt_composition = "NaCl"
                    file_smpl_short = file_smpl.split("/")[-1]
                    helper2[file_smpl_short] = {}
                    var_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"].get()
                    var_na = self.container_lists["Measured Elements"][file_smpl_short]["Na"][0]
                    var_na_equiv = (val_molar_mass_na/val_molar_mass_nacl)*amount_nacl_equiv
                    var_cl_equiv = (val_molar_mass_cl/val_molar_mass_nacl)*amount_nacl_equiv
                    var_salt_contribution_2 = 0
                    file_isotopes = self.container_lists["Measured Isotopes"][file_smpl_short]
                    for salt in self.container_lists["Selected Salts"]:
                        if salt in self.container_var[key_setting]["Salt Correction"]["Chlorides"]:
                            var_weight = float(
                                self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["Weight"].get())
                            var_weight_sum = var_weight*(elements_masses["Na"]/self.molar_masses_compounds["NaCl"][
                                "Total"])

                        if salt != "NaCl":
                            molar_mass_salt = self.molar_masses_compounds[salt]["Total"]
                            element = self.molar_masses_compounds[salt]["Cation"]
                            salt_composition += ", " + str(salt)

                            for isotope in file_isotopes:
                                key_isotope = re.search(r"(\D+)(\d+)", isotope)
                                isotope_atom = key_isotope.group(1)

                                if element == isotope_atom:
                                    molar_mass_element = elements_masses[element]
                                    helper3[salt] = molar_mass_element/molar_mass_salt
                                    try:
                                        var_intensity_i = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][var_na]
                                        var_sensitivity_i = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                            file_smpl_short]["INCL"][var_na]  # SMOOTHED
                                    except:
                                        var_intensity_i = self.container_intensity_corrected["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][var_na]
                                        var_sensitivity_i = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][isotope]
                                        var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                            file_smpl_short]["INCL"][var_na]

                                    var_sensitivity_i = var_sensitivity_i/var_sensitivity_na
                                    try:
                                        var_conc_ratio = var_intensity_i/(var_intensity_na*var_sensitivity_i)
                                        var_salt_contribution_3 = var_conc_ratio*(molar_mass_salt/molar_mass_element)
                                        helper2[file_smpl_short][salt] = var_salt_contribution_3
                                        var_salt_contribution_2 += var_weight*var_conc_ratio*(
                                                val_molar_mass_na*molar_mass_salt)/(
                                                val_molar_mass_nacl*molar_mass_element)
                                    except:
                                        print("Error Mass Balance:", var_weight_sum, var_intensity_i, var_intensity_na,
                                              var_sensitivity_i, molar_mass_salt, molar_mass_element, val_molar_mass_na,
                                              val_molar_mass_nacl)
                        else:
                            var_na_equiv *= 1

                    val_concentration_is = round((var_na_equiv/(1 + var_salt_contribution_2))*total_ppm, 4)
                    val_concentration_cl = round((var_cl_equiv/(1 + var_salt_contribution_2))*total_ppm, 4)
                    concentration_nacl = val_concentration_is*(val_molar_mass_nacl/val_molar_mass_na)
                    concentration_na_true = val_concentration_is
                    concentration_cl_true = val_concentration_cl
                    helper.append(val_concentration_is)
                    helper_cl.append(val_concentration_cl)

                    self.helper_salt_composition[file_smpl_short].set(salt_composition)

                    if var_is_i != var_na:
                        try:
                            var_intensity_na = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_na]
                            var_intensity_is = self.container_intensity_corrected["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["SMOOTHED"][
                                file_smpl_short]["INCL"][var_na]  # SMOOTHED
                        except:
                            var_intensity_na = self.container_intensity_corrected["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_na]
                            var_intensity_is = self.container_intensity_corrected["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_is = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_is_i]
                            var_sensitivity_na = self.container_analytical_sensitivity["SMPL"]["RAW"][
                                file_smpl_short]["INCL"][var_na]

                        val_concentration_is = round(var_intensity_is/var_intensity_na*(concentration_na_true/(
                                var_sensitivity_is/var_sensitivity_na)), 4)

                    self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"].set(val_concentration_is)
                    if file_smpl_short in self.container_files["SMPL"]:
                        self.container_files["SMPL"][file_smpl_short]["IS Concentration"].set(val_concentration_is)

                    self.check_chargebalance(filename_long=file_smpl)

                    if self.molality_based_quantification.get() == True:
                        self.quantify_inclusion_based_on_molalities(
                            var_filename_short=file_smpl_short, var_is_i=var_is_i,
                            var_concentration_na=concentration_na_true, var_concentration_cl=concentration_cl_true,
                            var_concentration_is=val_concentration_is)
        else:
            print("Please set the internal standard before you start any calculation. Thank you very much!")
            self.parent.bell()

    def quantify_inclusion_based_on_molalities(
            self, var_filename_short, var_is_i, var_concentration_na, var_concentration_cl, var_concentration_is):
        file_isotopes = self.container_lists["Measured Isotopes"][var_filename_short]
        index_file = self.container_lists["SMPL"]["Short"].index(var_filename_short)
        filename_long = self.container_lists["SMPL"]["Long"][index_file]

        key_element_is = re.search(r"(\D+)(\d+)", var_is_i)
        element_is = key_element_is.group(1)
        molar_mass_is = self.chemistry_data[element_is]
        molar_mass_na = self.chemistry_data["Na"]
        molar_mass_cl = self.chemistry_data["Cl"]
        molality_na = var_concentration_na/(molar_mass_na*1000)
        concentration_is = 10000
        # print(var_filename_short)
        # print("IS:", var_is_i, var_concentration_is, concentration_is, var_concentration_cl)
        for isotope in [var_is_i]:
            key_element_i = re.search(r"(\D+)(\d+)", isotope)
            element_i = key_element_i.group(1)
            molar_mass_i = self.chemistry_data[element_i]
            concentration_i = self.container_concentration["SMPL"]["RAW"][var_filename_short]["INCL"][
                isotope]
            concentration_ratio_is = self.container_concentration_ratio["SMPL"]["RAW"][var_filename_short][
                "INCL"][var_is_i]

            if concentration_ratio_is > 0:
                concentration_ratio_i = (concentration_i/concentration_is)/concentration_ratio_is
            else:
                concentration_ratio_i = np.nan

            factor_i = (molar_mass_is/molar_mass_i)*concentration_ratio_i
            molality_i = molality_na*factor_i

            concentration_i = round(molality_i*molar_mass_i*1000, 4)
            conversion_factor_i = concentration_i/var_concentration_is
            self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].set(var_concentration_is)

        for isotope in file_isotopes:
            key_element_i = re.search(r"(\D+)(\d+)", isotope)
            element_i = key_element_i.group(1)
            molar_mass_i = self.chemistry_data[element_i]
            concentration_i = self.container_concentration["SMPL"]["RAW"][var_filename_short]["INCL"][
                isotope]
            concentration_ratio_is = self.container_concentration_ratio["SMPL"]["RAW"][var_filename_short][
                "INCL"][var_is_i]

            if concentration_ratio_is > 0:
                concentration_ratio_i = (concentration_i/concentration_is)/concentration_ratio_is
            else:
                concentration_ratio_i = np.nan

            factor_i = (molar_mass_is/molar_mass_i)*concentration_ratio_i
            molality_i = molality_na*factor_i

            concentration_i = round(molality_i*molar_mass_i*1000/conversion_factor_i, 4)
            self.container_concentration["SMPL"]["RAW"][var_filename_short]["INCL"][isotope] = concentration_i
            # print(isotope, concentration_i)

    def fi_set_concentration_is_massbalance(self, event):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][file_smpl_short].set("unknown")
            self.container_var["SMPL"][file_smpl_long]["IS Data"]["Concentration"].set(
                self.container_var[key_setting]["Salt Correction"]["Default Concentration"].get())
            if file_smpl_short in self.container_files["SMPL"]:
                self.container_files["SMPL"][file_smpl_short]["IS Concentration"].set(
                    self.container_var[key_setting]["Salt Correction"]["Default Concentration"].get())

    def fi_set_concentration_is_chargebalance(self, event):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][file_smpl_short].set("unknown")
            self.container_var["SMPL"][file_smpl_long]["IS Data"]["Concentration"].set(
                self.container_var[key_setting]["Salt Correction"]["Default Concentration"].get())
            if file_smpl_short in self.container_files["SMPL"]:
                self.container_files["SMPL"][file_smpl_short]["IS Concentration"].set(
                    self.container_var[key_setting]["Salt Correction"]["Default Concentration"].get())

    def fi_pypitzer(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 1200
        window_height = 500
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_fi_inclusion_pypitzer = tk.Toplevel(self.parent)
        subwindow_fi_inclusion_pypitzer.title("FLUID INCLUSION ANALYSIS - PyPitzer")
        subwindow_fi_inclusion_pypitzer.geometry(var_geometry)
        subwindow_fi_inclusion_pypitzer.resizable(False, False)
        subwindow_fi_inclusion_pypitzer["bg"] = self.bg_colors["Very Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_fi_inclusion_pypitzer, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_fi_inclusion_pypitzer, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_fi_inclusion_pypitzer.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_fi_inclusion_pypitzer.grid_columnconfigure(i, minsize=column_min)

        # --------------------------------------------------------------------------------------------------------------

        if "IS" not in self.container_optionmenu["SMPL"]:
            self.container_optionmenu["SMPL"]["IS"] = {}

        start_row = 0
        start_column = 0

        str_btn_01 = self.language_dict["Import data"][self.var_language]

        ## LABELS
        lbl_00a = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row, column_id=start_column, n_rows=1, n_columns=7,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Fluid composition", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_00a = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row, column_id=start_column + 8, n_rows=1, n_columns=7,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Isotope selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_01 = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=7, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Cations", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 12, column_id=start_column, n_rows=1,
            n_columns=7, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Anions", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_00b = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row, column_id=start_column + 16, n_rows=1,
            n_columns=24, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Melting temperature of the last solid (in °C)", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_00b = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 1, column_id=start_column + 16, n_rows=1,
            n_columns=12, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Last solid (default)", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_00b = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 2, column_id=start_column + 16, n_rows=1,
            n_columns=12, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Melting temperature (default)", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_00b = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row, column_id=start_column + 41, n_rows=1,
            n_columns=18, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Internal standard concentration", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_00b = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 1, column_id=start_column + 41, n_rows=1,
            n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Internal standard (default)", relief=tk.FLAT, fontsize="sans 10 bold")

        ## BUTTONS
        btn_00c = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 3, column_id=start_column + 34, n_rows=1,
            n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"])
        btn_00c.configure(state="disabled")
        btn_00d = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=n_rows - 2, column_id=start_column + 51, n_rows=1,
            n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Run calculation", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.run_pypitzer)

        ## OPTION MENUS
        var_list_last_compound = [
            "Ice H2O", "Halite NaCl", "Hydrohalite NaCl*2H2O", "Sylvite KCl", "Antarcticite CaCl2*6H2O",
            "Bischofite MgCl2*6H2O", "MgCl2*8H2O", "MgCl2*12H2O", "Carnallite KCl*MgCl2*6H2O",
            "Tachyhydrite CaMg2Cl6*12H2O", "Mirabilite Na2SO4*10H2O", "Thenardite Na2SO4", "Hexahydrite MgSO4*6H2O",
            "Epsomite MgSO4*7H2O", "Arcanite K2SO4", "Picromerite K2Mg(SO4)2*6H2O", "LiCl", "LiCl*H2O", "LiCl*2H2O",
            "LiCl*3H2O", "LiCl*5H2O", "FeCl2*4H2O", "FeCl2*6H2O", "FeSO4*H2O", "FeSO4*7H2O"]

        var_list_last_compound_simple = [
            "H2O", "NaCl", "NaCl*2H2O", "KCl", "CaCl2*6H2O", "MgCl2*6H2O", "MgCl2*8H2O", "MgCl2*12H2O",
            "KCl*MgCl2*6H2O", "CaMg2Cl6*12H2O", "Na2SO4*10H2O", "Na2SO4", "MgSO4*6H2O", "MgSO4*7H2O", "K2SO4",
            "K2Mg(SO4)2*6H2O", "LiCl", "LiCl*H2O", "LiCl*2H2O", "LiCl*3H2O", "LiCl*5H2O", "FeCl2*4H2O", "FeCl2*6H2O",
            "FeSO4*H2O", "FeSO4*7H2O"]

        opt_last_solid_default = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 1, column_id=start_column + 28, n_rows=1,
            n_columns=12, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var[key_setting]["Last solid"], option_list=var_list_last_compound,
            text_set=self.container_var[key_setting]["Last solid"].get(), fg_active=self.bg_colors["Dark Font"],
            bg_active=self.accent_color, command=lambda opt=self.container_var[key_setting]["Last solid"]:
            self.change_last_solid_default(opt))
        opt_last_solid_default["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_last_solid_default.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        opt_is_default = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 1, column_id=start_column + 51, n_rows=1,
            n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var[key_setting]["Salt Correction"]["Default IS"],
            option_list=self.container_lists["Measured Isotopes"]["All"],
            text_set=self.container_var[key_setting]["Salt Correction"]["Default IS"].get(),
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var[key_setting]["Salt Correction"]["Default IS"],
                           var_key="SMPL":
            self.fi_change_is_default(var_opt, var_key))
        opt_is_default["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_is_default.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        ## ENTRIES
        var_entr = tk.StringVar()
        var_entr.set("0.0")

        entr_00 = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 2, column_id=start_column + 28, n_rows=1,
            n_columns=12, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
            var=var_entr, text_default=var_entr.get(), command=lambda event, entr=var_entr:
            self.default_melting_temperature(entr, event))

        ## TREEVIEWS
        frm_cations = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 2, column_id=start_column, n_rows=10,
            n_columns=7, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_frame()
        vsb_cations = ttk.Scrollbar(master=frm_cations, orient="vertical")
        text_cations = tk.Text(
            master=frm_cations, width=30, height=25, yscrollcommand=vsb_cations.set,
            bg=self.bg_colors["Very Light"])
        vsb_cations.config(command=text_cations.yview)
        vsb_cations.pack(side="right", fill="y")
        text_cations.pack(side="left", fill="both", expand=True)

        list_anions = []
        for var_cation in self.container_lists["Measured Elements"]["All"]:
            if var_cation not in ["Cl", "S", "Br", "I"]:
                if var_cation == "Na":
                    if var_cation not in self.temp_checkbuttons_pypitzer:
                        self.temp_checkbuttons_pypitzer[var_cation] = tk.IntVar(value=1)
                        if var_cation not in self.container_lists["Selected Cations"]:
                            self.container_lists["Selected Cations"].append(var_cation)
                        if var_cation not in self.container_lists["Possible Cations"]:
                            self.container_lists["Possible Cations"].append(var_cation)
                else:
                    if var_cation not in self.temp_checkbuttons_pypitzer:
                        self.temp_checkbuttons_pypitzer[var_cation] = tk.IntVar(value=0)
                        if var_cation in self.container_lists["Selected Cations"]:
                            self.temp_checkbuttons_pypitzer[var_cation] = tk.IntVar(value=1)

                if var_cation in ["Na", "K", "Mg", "Ca", "Fe", "Cs", "Sr"]:
                    if var_cation not in self.container_lists["Possible Cations"]:
                        self.container_lists["Possible Cations"].append(var_cation)
                    cb_i = tk.Checkbutton(
                        master=frm_cations, text=var_cation, fg=self.bg_colors["Dark Font"],
                        bg=self.bg_colors["Very Light"], variable=self.temp_checkbuttons_pypitzer[var_cation],
                        command=lambda cation=var_cation: self.select_cation(cation))
                    text_cations.window_create("end", window=cb_i)
                    text_cations.insert("end", "\n")
            else:
                list_anions.append(var_cation)

        frm_anions = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 13, column_id=start_column,
            n_rows=6, n_columns=7, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_frame()
        vsb_anions = ttk.Scrollbar(master=frm_anions, orient="vertical")
        text_anions = tk.Text(
            master=frm_anions, width=30, height=25, yscrollcommand=vsb_anions.set,
            bg=self.bg_colors["Very Light"])
        vsb_anions.config(command=text_anions.yview)
        vsb_anions.pack(side="right", fill="y")
        text_anions.pack(side="left", fill="both", expand=True)

        for var_anion in list_anions:
            if var_anion == "Cl":
                self.temp_checkbuttons_pypitzer[var_anion] = tk.IntVar(value=1)
            if var_anion not in self.temp_checkbuttons_pypitzer:
                self.temp_checkbuttons_pypitzer[var_anion] = tk.IntVar(value=0)
                if var_anion in self.container_lists["Selected Anions"]:
                    self.temp_checkbuttons_pypitzer[var_anion] = tk.IntVar(value=1)

            if var_anion == "S":
                var_anion_ext = "S (SO4-2)"
            else:
                var_anion_ext = var_anion

            if var_anion in ["Cl", "S"]:
                cb_i = tk.Checkbutton(
                    master=frm_anions, text=var_anion_ext, fg=self.bg_colors["Dark Font"],
                    bg=self.bg_colors["Very Light"], variable=self.temp_checkbuttons_pypitzer[var_anion])
                text_anions.window_create("end", window=cb_i)
                text_anions.insert("end", "\n")

                if var_anion != "Cl":
                    if var_anion not in self.container_lists["Selected Anions"]:
                        self.container_lists["Selected Anions"].append(var_anion)
                    if var_anion not in self.container_lists["Possible Anions"]:
                        self.container_lists["Possible Anions"].append(var_anion)

                if var_anion == "Cl":
                    cb_i.configure(state="disabled")

        frm_isotopes = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 1, column_id=start_column + 8,
            n_rows=18, n_columns=7, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_frame()
        vsb_isotopes = ttk.Scrollbar(master=frm_isotopes, orient="vertical")
        text_isotopes = tk.Text(
            master=frm_isotopes, width=30, height=25, yscrollcommand=vsb_isotopes.set,
            bg=self.bg_colors["Very Light"])
        vsb_isotopes.config(command=text_isotopes.yview)
        vsb_isotopes.pack(side="right", fill="y")
        text_isotopes.pack(side="left", fill="both", expand=True)

        for var_isotope in self.container_lists["Measured Isotopes"]["All"]:
            key_element_i = re.search(r"(\D+)(\d+)", var_isotope)
            element_i = key_element_i.group(1)
            if element_i in self.container_lists["Possible Cations"] or element_i in self.container_lists[
                "Possible Anions"]:
                if element_i != "Cl":
                    if element_i in ["Na", "S"]:
                        if element_i not in self.helper_checkbuttons["Isotopes"]:
                            self.helper_checkbuttons["Isotopes"][var_isotope] = tk.IntVar(value=0)
                            if (element_i in self.container_lists["Selected Cations"] or
                                    element_i in self.container_lists["Selected Anions"]):
                                self.helper_checkbuttons["Isotopes"][var_isotope] = tk.IntVar(value=1)
                    else:
                        if element_i not in self.helper_checkbuttons["Isotopes"]:
                            self.helper_checkbuttons["Isotopes"][var_isotope] = tk.IntVar(value=0)
                            if (element_i in self.container_lists["Selected Cations"] or
                                    element_i in self.container_lists["Selected Anions"]):
                                self.helper_checkbuttons["Isotopes"][var_isotope] = tk.IntVar(value=1)

                    cb_i = tk.Checkbutton(
                        master=frm_isotopes, text=var_isotope, fg=self.bg_colors["Dark Font"],
                        bg=self.bg_colors["Very Light"], variable=self.helper_checkbuttons["Isotopes"][var_isotope],
                        command=lambda isotope=var_isotope: self.select_isotope(isotope))
                    text_isotopes.window_create("end", window=cb_i)
                    text_isotopes.insert("end", "\n")

        frm_temperatures = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 4, column_id=start_column + 16,
            n_rows=n_rows - 5, n_columns=24, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_frame()
        vsb_temperatures = ttk.Scrollbar(master=frm_temperatures, orient="vertical")
        text_temperatures = tk.Text(
            master=frm_temperatures, width=30, height=25, yscrollcommand=vsb_temperatures.set,
            bg=self.bg_colors["Very Light"])
        vsb_temperatures.config(command=text_temperatures.yview)
        vsb_temperatures.pack(side="right", fill="y")
        text_temperatures.pack(side="left", fill="both", expand=True)

        for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            var_opt_i = self.container_var["SMPL"][file_smpl_long]["Last compound"]

            lbl_i = tk.Label(
                frm_temperatures, text=file_smpl, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_temperatures.window_create("end", window=lbl_i)
            text_temperatures.insert("end", "\t")

            entr_i = tk.Entry(
                frm_temperatures, textvariable=self.container_var["SMPL"][file_smpl_long]["Melting temperature"],
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0, width=8)
            text_temperatures.window_create("insert", window=entr_i)
            text_temperatures.insert("end", "\t")

            opt_last_compound_i = tk.OptionMenu(
                frm_temperatures, var_opt_i, *var_list_last_compound)
            opt_last_compound_i["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_last_compound_i.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)
            text_temperatures.window_create("end", window=opt_last_compound_i)
            text_temperatures.insert("end", " \n")

        frm_is = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row + 2, column_id=start_column + 41,
            n_rows=n_rows - 4, n_columns=18, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_frame()
        vsb_is = ttk.Scrollbar(master=frm_is, orient="vertical")
        text_is = tk.Text(
            master=frm_is, width=30, height=25, yscrollcommand=vsb_is.set,
            bg=self.bg_colors["Very Light"])
        vsb_is.config(command=text_is.yview)
        vsb_is.pack(side="right", fill="y")
        text_is.pack(side="left", fill="both", expand=True)

        for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl_long = self.container_lists["SMPL"]["Long"][index]
            var_opt_is = self.container_var["SMPL"][file_smpl_long]["IS Data"]["IS"]
            file_isotopes = self.container_lists["Measured Isotopes"][file_smpl]

            lbl_i = tk.Label(
                frm_is, text=file_smpl, bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_is.window_create("end", window=lbl_i)
            text_is.insert("end", "\t")

            opt_is = tk.OptionMenu(
                frm_is, var_opt_is, *file_isotopes)
            opt_is["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color)
            opt_is.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color, highlightthickness=0)
            text_is.window_create("end", window=opt_is)
            text_is.insert("end", " \t")

            entr_i = tk.Entry(
                frm_is, textvariable=self.container_var["SMPL"][file_smpl_long]["IS Data"]["Concentration"],
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"], highlightthickness=0, width=15)
            text_is.window_create("insert", window=entr_i)
            text_is.insert("end", "\n")

    def default_melting_temperature(self, entr, event):
        val_default_value = entr.get()
        for index, file_smpl_long in enumerate(self.container_lists["SMPL"]["Long"]):
            self.container_var["SMPL"][file_smpl_long]["Melting temperature"].set(val_default_value)

    def change_last_solid_default(self, opt):
        for index, file_smpl_long in enumerate(self.container_lists["SMPL"]["Long"]):
            self.container_var["SMPL"][file_smpl_long]["Last compound"].set(opt)

    def select_isotope(self, isotope):
        if self.helper_checkbuttons["Isotopes"][isotope].get() == 1:
            if isotope not in self.helper_checkbuttons["On"]:
                self.helper_checkbuttons["On"].append(isotope)
            if isotope in self.helper_checkbuttons["Off"]:
                self.helper_checkbuttons["Off"].remove(isotope)
        else:
            if isotope not in self.helper_checkbuttons["Off"]:
                self.helper_checkbuttons["Off"].append(isotope)
            if isotope in self.helper_checkbuttons["On"]:
                self.helper_checkbuttons["On"].remove(isotope)

    def select_cation(self, cation):
        if self.temp_checkbuttons_pypitzer[cation].get() == 1:
            if cation not in self.container_lists["Selected Cations"]:
                self.container_lists["Selected Cations"].append(cation)
        else:
            if cation in self.container_lists["Selected Cations"]:
                self.container_lists["Selected Cations"].remove(cation)

    def run_pypitzer(self):
        self.perform_complete_quantification(mode="PyPitzer")

        self.dict_species_pypitzer = {}
        var_list_last_compound = [
            "Ice H2O", "Halite NaCl", "Hydrohalite NaCl*2H2O", "Sylvite KCl", "Antarcticite CaCl2*6H2O",
            "Bischofite MgCl2*6H2O", "MgCl2*8H2O", "MgCl2*12H2O", "Carnallite KCl*MgCl2*6H2O",
            "Tachyhydrite CaMg2Cl6*12H2O", "Mirabilite Na2SO4*10H2O", "Thenardite Na2SO4", "Hexahydrite MgSO4*6H2O",
            "Epsomite MgSO4*7H2O", "Arcanite K2SO4", "Picromerite K2Mg(SO4)2*6H2O", "LiCl", "LiCl*H2O", "LiCl*2H2O",
            "LiCl*3H2O", "LiCl*5H2O", "FeCl2*4H2O", "FeCl2*6H2O", "FeSO4*H2O", "FeSO4*7H2O"]
        var_list_last_compound_simple = [
            "H2O(S)", "NaCl", "NaCl-2H2O", "KCl", "CaCl2-6H2O", "MgCl2-6H2O", "MgCl2-8H2O", "MgCl2-12H2O",
            "KCl-MgCl2-6H2O", "CaMg2Cl6-12H2O", "Na2SO4-10H2O", "Na2SO4", "MgSO4-6H2O", "MgSO4-7H2O", "K2SO4",
            "K2Mg(SO4)2-6H2O", "LiCl", "LiCl-H2O", "LiCl-2H2O", "LiCl-3H2O", "LiCl-5H2O", "FeCl2-4H2O", "FeCl2-6H2O",
            "FeSO4-H2O", "FeSO4-7H2O"]

        self.dict_species_helper = {}

        for cation in self.container_lists["Selected Cations"]:
            if cation in ["Li", "Na", "K", "Rb", "Cs"]:
                self.dict_species_helper[cation] = cation + "+"
            elif cation in ["Mg", "Ca", "Sr", "Fe"]:
                self.dict_species_helper[cation] = cation + "+2"
            else:
                self.dict_species_helper[cation] = cation

        for anion in self.container_lists["Selected Anions"]:
            if anion in ["F", "Br", "I", "At"]:
                self.dict_species_helper[anion] = anion + "-"
            elif anion == "S":
                self.dict_species_helper[anion] = anion + "O4-2"
            else:
                self.dict_species_helper[anion] = anion

        # Selected species (all)
        for var_datatype in ["RAW", "SMOOTHED"]:
            self.dict_species_pypitzer[var_datatype] = {}
            for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
                file_smpl_long = self.container_lists["SMPL"]["Long"][index]
                self.dict_species_pypitzer[var_datatype][file_smpl_short] = {}
                self.build_species_dictionary(
                    filename_short=file_smpl_short, filename_long=file_smpl_long, datatype=var_datatype)

            self.dict_inital_guess_pypitzer = {}
            helper_molalities_na = {}
            for index, file_smpl_long in enumerate(self.container_lists["SMPL"]["Long"]):
                file_smpl_short = self.container_lists["SMPL"]["Short"][index]
                self.dict_inital_guess_pypitzer[file_smpl_short] = (1, 1)
                # Last solid
                str_last_solid_i = self.container_var["SMPL"][file_smpl_long]["Last compound"].get()
                index_last_solid_i = var_list_last_compound.index(str_last_solid_i)
                str_last_solid_i = var_list_last_compound_simple[index_last_solid_i]
                # Melting temperature of last solid
                str_melting_temperature_i = self.container_var["SMPL"][file_smpl_long]["Melting temperature"].get()

                fluid_inclusion = FluidPitzer(
                    x0=self.dict_inital_guess_pypitzer[file_smpl_short],
                    species=self.dict_species_pypitzer[var_datatype][file_smpl_short],
                    solids=[str_last_solid_i],
                    t=float(str_melting_temperature_i))

                results_pypitzer = fluid_inclusion.optimize()

                b_na = results_pypitzer.x[0]
                b_cl = results_pypitzer.x[1]
                str_is = self.container_var["SMPL"][file_smpl_long]["IS Data"]["IS"].get()
                key_element_is = re.search(r"(\D+)(\d+)", str_is)
                element_is = key_element_is.group(1)
                val_molar_mass_is = self.chemistry_data[element_is]
                val_molar_mass_cl = self.chemistry_data["Cl"]
                val_concentration_incl_is = round(b_na*val_molar_mass_is*1000, 4)
                val_concentration_incl_cl = round(b_cl*val_molar_mass_cl*1000, 4)
                helper_molalities_na[file_smpl_short] = {"Na": b_na, "Cl": b_cl}

                self.container_var["SMPL"][file_smpl_long]["IS Data"]["Concentration"].set(val_concentration_incl_is)
                self.container_var["SMPL"][file_smpl_long]["IS Data"][var_datatype]["Concentration"].set(
                    val_concentration_incl_is)

            #     print(file_smpl_short)
            #     print("Species input:", self.dict_species_pypitzer[var_datatype][file_smpl_short])
            #     print("b(INCL,IS):", b_na, "mol/(kgH2O)", ":", "b(INCL,Cl):", b_cl,
            #           "mol/(kgH2O)", ":", "Ratio:", b_cl/b_na)
            #     print("C(INCL,IS):", val_concentration_incl_is, "ppm", ":", "C(INCL,Cl):", val_concentration_incl_cl,
            #           "ppm", ":", "Ratio:", val_concentration_incl_cl/val_concentration_incl_is)
            # print("")
            # print("PyPitzer calculation successfully terminated!\n")

            for file_smpl_short in self.container_lists["SMPL"]["Short"]:
                file_smpl_long = self.container_lists["SMPL"]["Long"][index]
                file_isotopes = self.container_lists["Measured Isotopes"][file_smpl_short]

                str_is = self.container_var["SMPL"][file_smpl_long]["IS Data"]["IS"].get()
                key_element_is = re.search(r"(\D+)(\d+)", str_is)
                element_is = key_element_is.group(1)
                val_molar_mass_is = self.chemistry_data[element_is]

                for isotope in file_isotopes:
                    key_element_i = re.search(r"(\D+)(\d+)", isotope)
                    element_i = key_element_i.group(1)
                    val_molar_mass_i = self.chemistry_data[element_i]
                    val_concentration_ratio_i = self.container_concentration_ratio["SMPL"][var_datatype][
                        file_smpl_short]["INCL"][isotope]
                    ratio_mod_i = (val_molar_mass_is/val_molar_mass_i)*val_concentration_ratio_i

                    if element_i == "Na":
                        b_i = helper_molalities_na[file_smpl_short]["Na"]
                        val_molar_mass_i = self.chemistry_data["Na"]
                        val_concentration_incl_i = round(b_i*val_molar_mass_i*1000, 4)
                        self.container_var["SMPL"][file_smpl_long]["IS Data"][var_datatype]["IS"].set(isotope)
                        self.container_var["SMPL"][file_smpl_long]["IS Data"][var_datatype][
                            "Concentration"].set(val_concentration_incl_i)
                    elif element_i == "Cl":
                        b_i = helper_molalities_na[file_smpl_short][element_i]
                    else:
                        b_i = helper_molalities_na[file_smpl_short]["Na"]*ratio_mod_i

                    val_concentration_incl_i = round(b_i*val_molar_mass_i*1000, 4)
                    self.container_concentration["SMPL"][var_datatype][file_smpl_short]["INCL"][
                        isotope] = val_concentration_incl_i

        self.pypitzer_performed = True

    def perform_complete_quantification(self, mode="normal"):
        if mode == "PyPitzer":
            bool_pypitzer = True
        else:
            bool_pypitzer = False

        # Perform quantification
        for var_filetype in ["STD", "SMPL"]:
            for var_file_short in self.container_lists[var_filetype]["Short"]:
                self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)

        var_filetype = "None"
        var_file_short = "None"
        var_file_long = "None"
        var_focus = "None"

        for var_datatype in ["RAW", "SMOOTHED"]:
            # Intensity Results
            self.get_intensity(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_focus=var_focus, mode="All")
            self.fi_get_intensity_corrected(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_focus=var_focus, mode="All")
            self.fi_get_intensity_mix(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short, mode="All")

            # Sensitivity Results
            self.get_analytical_sensitivity(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, mode="All")
            results_is = self.determine_possible_is(filetype="ALL")
            IQ(dataframe=None, project_type=self.pysills_mode,
               results_container=self.container_intensity_ratio).get_intensity_ratio(
                data_container=self.container_intensity_corrected, dict_is=results_is, datatype=var_datatype)
            self.fi_get_rsf(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, var_focus=var_focus, mode="All")

            # Concentration Results
            self.fi_get_concentration2(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, var_focus=var_focus, mode="All", pypitzer=bool_pypitzer)
            self.fi_get_normalized_sensitivity(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, var_focus=None, mode="All")
            self.fi_get_concentration_ratio(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, var_focus=var_focus, mode="All")
            self.get_lod(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, var_focus=None, mode="All")
            # self.fi_get_lod(
            #     var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
            #     var_file_long=var_file_long, var_focus=var_focus, mode="All")
            self.fi_get_mixed_concentration_ratio(
                var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long, mode="All")
            self.fi_get_mixing_ratio(
                var_datatype=var_datatype, var_file_short=var_file_short, var_file_long=var_file_long, mode="All")
            self.fi_get_concentration_mixed(var_datatype=var_datatype, var_file_short=var_file_short, mode="All")

    def perform_quantification_mass_charge_balance(self):
        var_filetype = "None"
        var_file_short = "None"
        var_file_long = "None"
        var_focus = "None"

        for var_datatype in ["RAW", "SMOOTHED"]:
            try:
                # Concentration Results
                self.fi_get_concentration2(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=var_focus, mode="All", pypitzer=False, var_incl_is=True)
                self.fi_get_concentration_ratio(
                    var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long=var_file_long, var_focus=var_focus, mode="All")
            except:
                print("It is necessary to define first the calculation intervals.")

    def build_species_dictionary(self, filename_short, filename_long, datatype):
        dict_chemistry = self.container_lists["Measured Elements"][filename_short]
        helper_ratios = {}

        str_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
        key_element_is = re.search(r"(\D+)(\d+)", str_is)
        element_is = key_element_is.group(1)
        val_molar_mass_is = self.chemistry_data[element_is]

        for element, ion in self.dict_species_helper.items():
            helper_ratios[element] = {}
            if element in dict_chemistry:
                list_isotopes = dict_chemistry[element]
            else:
                continue

            for isotope in list_isotopes:
                key_element_i = re.search(r"(\D+)(\d+)", isotope)
                element_i = key_element_i.group(1)

                if element_i in self.temp_checkbuttons_pypitzer:
                    if self.temp_checkbuttons_pypitzer[element_i].get() == 1:
                        val_molar_mass_i = self.chemistry_data[element_i]
                        val_concentration_ratio_i = self.container_concentration_ratio["SMPL"][datatype][
                            filename_short]["INCL"][isotope]
                        value_i = (val_molar_mass_is/val_molar_mass_i)*val_concentration_ratio_i

                        helper_ratios[element][isotope] = value_i
                    else:
                        del helper_ratios[element_i]

            if element in self.temp_checkbuttons_pypitzer:
                if self.temp_checkbuttons_pypitzer[element_i].get() == 1:
                    if element == element_i:
                        helper_values = []
                        for isotope, value in helper_ratios[element].items():
                            if self.helper_checkbuttons["Isotopes"][isotope].get() == 1:
                                helper_values.append(value)

                        self.dict_species_pypitzer[datatype][filename_short][ion] = np.mean(helper_values)

    def fi_mass_balance_new(self, mode="mass balance"):
        ## Window Settings
        window_width = 1100
        window_height = 600
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_fi_inclusion_massbalance_new = tk.Toplevel(self.parent)

        if mode == "mass balance":
            subwindow_fi_inclusion_massbalance_new.title("FLUID INCLUSION ANALYSIS - Mass balance")
        else:
            subwindow_fi_inclusion_massbalance_new.title("FLUID INCLUSION ANALYSIS - Charge balance")

        subwindow_fi_inclusion_massbalance_new.geometry(var_geometry)
        subwindow_fi_inclusion_massbalance_new.resizable(False, False)
        subwindow_fi_inclusion_massbalance_new["bg"] = self.bg_colors["Very Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_fi_inclusion_massbalance_new, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_fi_inclusion_massbalance_new, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_fi_inclusion_massbalance_new.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_fi_inclusion_massbalance_new.grid_columnconfigure(i, minsize=column_min)

        if self.pysills_mode == "FI":
            key_setting = "fi_setting"

        if "IS" not in self.container_optionmenu["SMPL"]:
            self.container_optionmenu["SMPL"]["IS"] = {}

        start_row = 0
        start_column = 0
        n_header = 16

        var_is = self.container_var["SMPL"][self.container_lists["SMPL"]["Long"][0]]["IS Data"]["IS"].get()

        if self.init_fi_massbalance == False and var_is != "Select IS":
            var_filetype = "None"
            var_file_short = "None"
            var_file_long = "None"
            var_focus = "None"
            if (self.container_var["Spike Elimination"]["STD"]["State"] == False and
                    self.container_var["Spike Elimination"]["SMPL"]["State"] == False):
                list_datatype = ["RAW"]
            else:
                list_datatype = ["RAW", "SMOOTHED"]

            for var_datatype in list_datatype:
                if len(self.container_spikes) > 0:
                    # Intensity Analysis
                    self.get_intensity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_focus=var_focus, mode="All")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_focus=var_focus, mode="All")
                    # Sensitivity Results
                    self.get_analytical_sensitivity(
                        var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                        var_file_long=var_file_long, mode="All")

            self.perform_quantification_mass_charge_balance()
            self.init_fi_massbalance = True

        ## Labels
        lbl_01 = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=n_header, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Composition: H2O + ...", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=start_row, column_id=start_column + n_header + 1,
            n_rows=1, n_columns=int(2*n_header), fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="File setup", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 3, column_id=start_column + n_header + 1,
            n_rows=1, n_columns=n_header - 8, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Default settings", relief=tk.FLAT, fontsize="sans 10 bold")

        ## Buttons
        btn_01a = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 2, column_id=n_header - 10, n_rows=1,
            n_columns=n_header - (n_header - 10), fg=self.bg_colors["Dark Font"],
            bg=self.accent_color).create_simple_button(
            text="Guess the composition", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.guess_salt_composition)
        btn_02a = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 2, column_id=n_header + 27, n_rows=1,
            n_columns=11, fg=self.bg_colors["Dark Font"],
            bg=self.accent_color).create_simple_button(
            text="Fix calculation", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=self.fix_mass_charge_balance_calculation)

        ## Option Menus
        self.container_lists["Possible IS SMPL"] = self.container_lists["Measured Isotopes"]["All"].copy()
        for halogen in ["Cl", "Br", "I"]:
            if halogen in self.container_lists["Measured Elements"]:
                for isotope in self.container_lists["Measured Elements"][halogen]:
                    self.container_lists["Possible IS SMPL"].remove(isotope)

        opt_05a = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 3, column_id=start_column + n_header + 9,
            n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
            var_iso=self.container_var[key_setting]["Salt Correction"]["Default IS"],
            option_list=self.container_lists["Possible IS SMPL"],
            text_set=self.container_var[key_setting]["Salt Correction"]["Default IS"].get(),
            fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
            command=lambda var_opt=self.container_var[key_setting]["Salt Correction"]["Default IS"],
                           var_key="SMPL":
            self.fi_change_is_default(var_opt, var_key))
        opt_05a["menu"].config(
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color)
        opt_05a.config(
            bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"],
            activeforeground=self.bg_colors["Dark Font"],
            activebackground=self.accent_color, highlightthickness=0)

        self.opt_is_smpl_def = opt_05a

        ## Entries
        if mode == "mass balance":
            entr_05a = SE(
                parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 3, column_id=n_header + 15,
                n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=self.container_var[key_setting]["Salt Correction"]["Default Salinity"],
                text_default=self.container_var[key_setting]["Salt Correction"]["Default Salinity"].get(),
                command=lambda event, var_entr=self.container_var[key_setting]["Salt Correction"]["Default Salinity"],
                               mode="default", var_file=None:
                self.fi_calculate_massbalance(var_entr, mode, var_file, event))
            entr_05b = SE(
                parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 3, column_id=n_header + 21,
                n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=self.container_var[key_setting]["Salt Correction"]["Default Concentration"],
                text_default=self.container_var[key_setting]["Salt Correction"]["Default Concentration"].get(),
                command=self.fi_set_concentration_is_massbalance)
        elif mode == "charge balance":
            entr_05a = SE(
                parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 3, column_id=n_header + 15,
                n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=self.container_var[key_setting]["Salt Correction"]["Default Salinity"],
                text_default=self.container_var[key_setting]["Salt Correction"]["Default Salinity"].get(),
                command=lambda event, var_entr=self.container_var[key_setting]["Salt Correction"]["Default Salinity"],
                               mode="default", var_file=None:
                self.fi_calculate_chargebalance(var_entr, mode, var_file, event))
            entr_05b = SE(
                parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 3, column_id=n_header + 21,
                n_rows=1, n_columns=6, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=self.container_var[key_setting]["Salt Correction"]["Default Concentration"],
                text_default=self.container_var[key_setting]["Salt Correction"]["Default Concentration"].get(),
                command=self.fi_set_concentration_is_chargebalance)

        ## CHECKBOXES
        cb_01a = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=n_rows - 3, column_id=n_header + 27,
            fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=11,
            bg=self.bg_colors["Light"]).create_simple_checkbox(
            var_cb=self.molality_based_quantification, text="Molality-based quantification", set_sticky="nesw",
            own_color=True, command=lambda var_cb=self.molality_based_quantification: self.change_checkbox(var_cb))
        cb_01a.configure(offvalue=False)
        #cb_01a.configure(state="disabled")

        ## Tables
        list_salts = []
        dict_salts = {}
        for element, dataset in self.container_lists["Measured Elements"]["Cations"].items():
            salt = dataset["Cl"]
            dict_salts[salt] = element
            if salt not in list_salts:
                list_salts.append(salt)

        frm_01 = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=start_row + 1, column_id=start_column,
            n_rows=n_rows - 3, n_columns=n_header, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()
        vsb_01 = ttk.Scrollbar(master=frm_01, orient="vertical")
        text_01 = tk.Text(
            master=frm_01, width=30, height=25, yscrollcommand=vsb_01.set, bg=self.bg_colors["Very Light"])
        vsb_01.config(command=text_01.yview)
        vsb_01.pack(side="right", fill="y")
        text_01.pack(side="left", fill="both", expand=True)

        self.helper_salt_selection = {}
        for salt in list_salts:
            if salt not in self.helper_salt_selection:
                self.helper_salt_selection[salt] = 0

            if salt not in self.container_var[key_setting]["Salt Correction"]["Chlorides"]:
                self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt] = {
                    "State": tk.IntVar(), "Weight": tk.StringVar()}
                self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["State"].set(0)
                self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["Weight"].set("1.0")

            cb_i = tk.Checkbutton(
                master=frm_01, text=salt+"\t", fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"],
                variable=self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["State"],
                command=self.fi_check_elements_checkbutton)
            text_01.window_create("end", window=cb_i)
            text_01.insert("end", "\t")

            entr_i = tk.Entry(
                frm_01, textvariable=self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["Weight"],
                width=5, highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_01.window_create("insert", window=entr_i)
            text_01.insert("end", "\t")

            element = dict_salts[salt]
            incl_i = []
            incl_na = []
            for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
                list_isotopes = self.container_lists["Measured Elements"][file_smpl_short][element]
                list_na = self.container_lists["Measured Elements"][file_smpl_short]["Na"]
                if index == 0:
                    text = ""
                    for isotope in list_isotopes:
                        text += isotope + ","
                    text = text[:-1]

                for isotope_na in list_na:
                    intensity_incl_na = self.container_intensity_corrected["SMPL"]["RAW"][file_smpl_short]["INCL"][
                        isotope_na]
                    if intensity_incl_na != None:
                        incl_na.append(intensity_incl_na)
                    else:
                        incl_na.append(0.0)

                for isotope in list_isotopes:
                    intensity_incl_i = self.container_intensity_corrected["SMPL"]["RAW"][file_smpl_short]["INCL"][
                        isotope]
                    if intensity_incl_i != None:
                        if intensity_incl_i > 0:
                            incl_i.append(intensity_incl_i)
                        else:
                            incl_i.append(0.0)
                    else:
                        incl_i.append(0.0)

            incl_i = round(np.mean(incl_i), 1)
            incl_na = round(np.mean(incl_na), 1)
            if incl_na > 0:
                magic_factor = round((incl_i/incl_na)*1000, 1)
            else:
                magic_factor = 0.0
            self.helper_salt_selection[salt] = magic_factor

            lbl_i = tk.Label(frm_01, text=text+"\t", bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])
            text_01.window_create("end", window=lbl_i)
            text_01.insert("end", "\t")

            lbl2_i = tk.Label(frm_01, text=magic_factor, bg=self.bg_colors["Very Light"],
                              fg=self.bg_colors["Dark Font"])
            text_01.window_create("end", window=lbl2_i)
            text_01.insert("end", "\n")

            if salt == "NaCl":
                cb_i.configure(state="disabled")
                entr_i.configure(state="disabled")
                lbl_i.configure(state="disabled")
                lbl2_i.configure(state="disabled")

        frm_02 = SE(
            parent=subwindow_fi_inclusion_massbalance_new, row_id=start_row + 1, column_id=start_column + n_header + 1,
            n_rows=n_rows - 4, n_columns=int(2*n_header + 5), fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame()
        vsb_02 = ttk.Scrollbar(master=frm_02, orient="vertical")
        text_02 = tk.Text(
            master=frm_02, width=30, height=25, yscrollcommand=vsb_02.set, bg=self.bg_colors["Very Light"])
        vsb_02.config(command=text_02.yview)
        vsb_02.pack(side="right", fill="y")
        text_02.pack(side="left", fill="both", expand=True)

        for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
            if file_smpl_short not in self.helper_salt_composition:
                self.helper_salt_composition[file_smpl_short] = tk.StringVar()
                self.helper_salt_composition[file_smpl_short].set("unknown composition")
            if file_smpl_short not in self.charge_balance_check:
                self.charge_balance_check[file_smpl_short] = tk.StringVar()
                self.charge_balance_check[file_smpl_short].set("1.0")

            file_smpl = self.container_lists["SMPL"]["Long"][index]
            lbl_i = tk.Label(frm_02, text=file_smpl_short + "\t", bg=self.bg_colors["Very Light"],
                             fg=self.bg_colors["Dark Font"])
            text_02.window_create("end", window=lbl_i)
            text_02.insert("end", "\t")

            opt_is_i = tk.OptionMenu(
                frm_02, self.container_var["SMPL"][file_smpl]["IS Data"]["IS"],
                *self.container_lists["Measured Isotopes"][file_smpl_short])
            opt_is_i["menu"].config(fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                                    activeforeground=self.bg_colors["Dark Font"],
                                    activebackground=self.accent_color)
            opt_is_i.config(bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                            activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                            highlightthickness=0)
            self.container_optionmenu["SMPL"]["IS"][file_smpl] = opt_is_i

            text_02.window_create("end", window=opt_is_i)
            text_02.insert("end", " \t")

            if mode == "mass balance":
                entr_i = tk.Entry(
                    frm_02, textvariable=self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                        file_smpl_short], width=10, highlightthickness=0, bg=self.bg_colors["White"],
                    fg=self.bg_colors["Dark Font"])
                entr_i.bind("<Return>", lambda event, var_entr=self.container_var[key_setting]["Salt Correction"][
                    "Salinity SMPL"][file_smpl_short], mode="specific", var_file=file_smpl:
                self.fi_calculate_massbalance(var_entr, mode, var_file, event))
            else:
                entr_i = tk.Entry(
                    frm_02, textvariable=self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                        file_smpl_short], width=10, highlightthickness=0, bg=self.bg_colors["White"],
                    fg=self.bg_colors["Dark Font"])
                entr_i.bind("<Return>", lambda event, var_entr=self.container_var[key_setting]["Salt Correction"][
                    "Salinity SMPL"][file_smpl_short], mode="specific", var_file=file_smpl:
                self.fi_calculate_chargebalance(var_entr, mode, var_file, event))

            text_02.window_create("insert", window=entr_i)
            text_02.insert("end", "\t")


            entr2_i = tk.Entry(
                frm_02, textvariable=self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"], width=15,
                highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_02.window_create("insert", window=entr2_i)
            text_02.insert("end", "\t")

            entr3_i = tk.Entry(
                frm_02, textvariable=self.charge_balance_check[file_smpl_short], width=5,
                highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_02.window_create("insert", window=entr3_i)
            text_02.insert("end", "\t")

            entr3_i.configure(state="disabled")

            entr4_i = tk.Entry(
                frm_02, textvariable=self.helper_salt_composition[file_smpl_short], width=40,
                highlightthickness=0, bg=self.bg_colors["White"], fg=self.bg_colors["Dark Font"])
            text_02.window_create("insert", window=entr4_i)
            text_02.insert("end", "\n")

            entr4_i.configure(state="disabled")

        ## INITIALIZATION
        self.fi_check_elements_checkbutton()

    def fix_mass_charge_balance_calculation(self):
        for var_filetype in ["STD", "SMPL"]:
            for index, var_file_short in enumerate(self.container_lists[var_filetype]["Short"]):
                filename_long = self.container_lists[var_filetype]["Long"][index]
                self.get_condensed_intervals_of_file(filetype=var_filetype, filename_short=var_file_short)
                if var_filetype == "SMPL":
                    var_na = self.container_lists["Measured Elements"][var_file_short]["Na"][0]
                    self.container_var["SMPL"][filename_long]["IS Data"]["IS"].set(var_na)

        self.container_var["fi_setting"]["Salt Correction"]["Default IS"].set(var_na)

        var_filetype = "None"
        var_file_short = "None"
        var_file_long = "None"
        var_focus = "None"
        self.var_init_fi_datareduction = True

        for var_datatype in ["RAW", "SMOOTHED"]:
            # Intensity Results
            self.get_intensity(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_focus=var_focus, mode="All")
            self.fi_get_intensity_corrected(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_focus=var_focus, mode="All")
            # Sensitivity Results
            self.get_analytical_sensitivity(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, mode="All")
            # Concentration Results
            self.fi_get_concentration2(
                var_filetype=var_filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_file_long=var_file_long, var_focus=var_focus, mode="All")

    def change_checkbox(self, var_cb):
        #print("State:", var_cb.get())
        pass

    def calculate_threshold_spike_elimination(self, mode="default"):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if mode == "default":
            val_dwell_time = float(self.container_var["dwell_times"]["Entry"]["Default"].get())     # in seconds
            factor = 10/val_dwell_time
            value = int(factor)
            self.container_var[key_setting]["SE Threshold"].set(value)
        elif mode == "specific":
            for isotope in self.container_lists["Measured Isotopes"]["All"]:
                val_dwell_time = float(self.container_var["dwell_times"]["Entry"][isotope].get())   # in seconds
                factor = 10/val_dwell_time
                value = int(factor)
                self.container_var["Spike Elimination"]["Threshold"][isotope].set(value)

    def guess_salt_composition(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        for salt, value in self.helper_salt_selection.items():
            if value >= 10:
                self.container_var[key_setting]["Salt Correction"]["Chlorides"][salt]["State"].set(1)

        self.fi_check_elements_checkbutton()

    def fi_inclusion_setup_plugin(self):
        if self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Window Settings
        window_width = 660
        window_height = 280
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        if self.bool_incl_is_custom:
            if self.pysills_mode == "FI":
                str_title = "FLUID INCLUSION ANALYSIS - Custom Data Setup"
            elif self.pysills_mode == "MI":
                str_title = "MELT INCLUSION ANALYSIS - Custom Data Setup"
        else:
            if self.pysills_mode == "FI":
                str_title = "FLUID INCLUSION ANALYSIS - Plugin-based Inclusion Setup"
            elif self.pysills_mode == "MI":
                str_title = "MELT INCLUSION ANALYSIS - Plugin-based Inclusion Setup"

        subwindow_fi_inclusion_plugin = tk.Toplevel(self.parent)
        subwindow_fi_inclusion_plugin.title(str_title)
        subwindow_fi_inclusion_plugin.geometry(var_geometry)
        subwindow_fi_inclusion_plugin.resizable(False, False)
        subwindow_fi_inclusion_plugin["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_fi_inclusion_plugin, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_fi_inclusion_plugin, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_fi_inclusion_plugin.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_fi_inclusion_plugin.grid_columnconfigure(i, minsize=column_min)

        start_row = 0
        start_column = 0

        str_btn_01 = self.language_dict["Import data"][self.var_language]

        ## LABELS
        if self.str_incl_is_custom_external == "External":
            lbl_01 = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row, column_id=start_column, n_rows=1, n_columns=10,
                fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="LA-ICP-MS Data Export", relief=tk.FLAT, fontsize="sans 10 bold")
            lbl_02 = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row, column_id=start_column + 11, n_rows=1,
                n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Import Plugin Data", relief=tk.FLAT, fontsize="sans 10 bold")
        else:
            lbl_02 = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row, column_id=start_column + 22, n_rows=1,
                n_columns=10, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Default Settings", relief=tk.FLAT, fontsize="sans 10 bold")
            lbl_02 = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row, column_id=start_column, n_rows=1, n_columns=10,
                fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
                text="Import Plugin Data", relief=tk.FLAT, fontsize="sans 10 bold")

        if self.str_incl_is_custom_external == "External":
            ## CHECKBOXES
            var_cb_01a = self.container_var[key_setting]["Inclusion Plugin"]["Intensity BG"]
            var_cb_01b = self.container_var[key_setting]["Inclusion Plugin"]["Intensity MAT"]
            var_cb_01c = self.container_var[key_setting]["Inclusion Plugin"]["Intensity MIX"]
            var_cb_01d = self.container_var[key_setting]["Inclusion Plugin"]["Intensity INCL"]
            var_cb_01e = self.container_var[key_setting]["Inclusion Plugin"]["Analytical Sensitivity"]
            var_cb_01f = self.container_var[key_setting]["Inclusion Plugin"]["Concentration SRM"]

            cb_01a = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 1, column_id=start_column,
                fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=10,
                bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_01a, text="Intensity (Background)", set_sticky="nesw", own_color=True)
            cb_01b = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 2, column_id=start_column,
                fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=10,
                bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_01b, text="Intensity (Matrix)", set_sticky="nesw", own_color=True)
            cb_01c = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 3, column_id=start_column,
                fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=10,
                bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_01c, text="Intensity (Mix)", set_sticky="nesw", own_color=True)
            cb_01d = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 4, column_id=start_column,
                fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=10,
                bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_01d, text="Intensity (Inclusion)", set_sticky="nesw", own_color=True)
            cb_01e = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 5, column_id=start_column,
                fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=10,
                bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_01e, text="Analytical Sensitivity", set_sticky="nesw", own_color=True)
            cb_01f = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 6, column_id=start_column,
                fg=self.bg_colors["Dark Font"], n_rows=1, n_columns=10,
                bg=self.bg_colors["Light"]).create_simple_checkbox(
                var_cb=var_cb_01f, text="Concentration (SRM)", set_sticky="nesw", own_color=True)

            cb_01a.configure(font="sans 10")
            cb_01b.configure(font="sans 10")
            cb_01c.configure(font="sans 10")
            cb_01d.configure(font="sans 10")
            cb_01e.configure(font="sans 10")
            cb_01f.configure(font="sans 10")

            ## BUTTONS
            btn_01h = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 7, column_id=start_column, n_rows=1,
                n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Export Data", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.export_data_for_external_calculations)
            btn_02a = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 1, column_id=start_column + 11, n_rows=1,
                n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda parent=subwindow_fi_inclusion_plugin, mode="FI": self.import_is_data(parent, mode))
        else:
            ## BUTTONS
            btn_02a = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 1, column_id=start_column, n_rows=1,
                n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda parent=subwindow_fi_inclusion_plugin, mode="FI": self.import_is_data(parent, mode))

            # OPTION MENU
            opt_05a = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 1, column_id=start_column + 22,
                n_rows=1, n_columns=10, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Light"]).create_option_isotope(
                var_iso=self.container_var[key_setting]["Salt Correction"]["Default IS"],
                option_list=self.container_lists["ISOTOPES"],
                text_set=self.container_var[key_setting]["Salt Correction"]["Default IS"].get(),
                fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
                command=lambda var_opt=self.container_var[key_setting]["Salt Correction"]["Default IS"],
                               var_key="SMPL":
                self.fi_change_is_default(var_opt, var_key))
            opt_05a["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            opt_05a.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Very Dark"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, highlightthickness=0)

            # ENTRY
            entr_04a = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 2, column_id=start_column + 22, n_rows=1,
                n_columns=10, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=self.container_var["IS SMPL Default"], text_default=self.container_var["IS SMPL Default"].get(),
                command=lambda event, var_entr=self.container_var["IS SMPL Default"]:
                self.change_is_value_default(var_entr, event))

        if self.str_incl_is_custom_external == "External":
            ## TREEVIEWS
            frm_incl_is = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 2, column_id=start_column + 11, n_rows=8,
                n_columns=21, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
            vsb_incl_is = ttk.Scrollbar(master=frm_incl_is, orient="vertical")
        else:
            ## TREEVIEWS
            frm_incl_is = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 2, column_id=start_column, n_rows=8,
                n_columns=21, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Very Light"]).create_frame()
            vsb_incl_is = ttk.Scrollbar(master=frm_incl_is, orient="vertical")

        text_incl_is = tk.Text(
            master=frm_incl_is, width=30, height=25, yscrollcommand=vsb_incl_is.set, bg=self.bg_colors["Very Light"])
        vsb_incl_is.config(command=text_incl_is.yview)
        vsb_incl_is.pack(side="right", fill="y")
        text_incl_is.pack(side="left", fill="both", expand=True)

        var_list_is = self.container_lists["ISOTOPES"]

        for index, file_smpl_short in enumerate(self.container_lists["SMPL"]["Short"]):
            file_smpl = self.container_lists["SMPL"]["Long"][index]
            var_opt_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["IS"]
            var_entr_is_i = self.container_var["SMPL"][file_smpl]["IS Data"]["Concentration"]

            lbl_i = tk.Label(frm_incl_is, text=file_smpl_short, bg=self.bg_colors["Very Light"],
                             fg=self.bg_colors["Dark Font"])
            text_incl_is.window_create("end", window=lbl_i)
            text_incl_is.insert("end", "\t")

            opt_is_i = tk.OptionMenu(
                frm_incl_is, var_opt_is_i, *var_list_is,
                command=lambda var_opt=var_opt_is_i, var_file=file_smpl, state_default=False:
                self.ma_change_matrix_compound(var_opt, var_file, state_default))
            opt_is_i["menu"].config(fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                                    activeforeground=self.bg_colors["Dark Font"],
                                    activebackground=self.accent_color)
            opt_is_i.config(bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
                            activeforeground=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                            highlightthickness=0)
            text_incl_is.window_create("end", window=opt_is_i)
            text_incl_is.insert("end", " \t")
            #
            entr_is_i = tk.Entry(
                frm_incl_is, textvariable=var_entr_is_i, width=15, highlightthickness=0, bg=self.bg_colors["White"],
                fg=self.bg_colors["Dark Font"])
            entr_is_i.bind(
                "<Return>", lambda event, var_entr=var_entr_is_i, var_file=file_smpl, state_default=False:
                self.ma_change_is_concentration(var_entr, var_file, state_default, event))
            text_incl_is.window_create("insert", window=entr_is_i)
            text_incl_is.insert("end", "\n")

    def calculate_linear_regression(self, x_values, y_values):
        x_values_updated = [x for x, y in zip(x_values, y_values) if y != None]
        y_values_updated = [y for y, y in zip(x_values, y_values) if y != None]

        mean_x = np.mean(x_values_updated)
        mean_y = np.mean(y_values_updated)
        helper_xy = 0
        helper_x2 = 0
        n = len(x_values_updated)

        for index, x_value in enumerate(x_values_updated):
            y_value = y_values_updated[index]
            helper_xy += x_value*y_value
            helper_x2 += x_value**2

        upper_term = helper_xy - n*mean_x*mean_y
        lower_term = helper_x2 - n*mean_x**2
        b = upper_term/lower_term
        a = mean_y - b*mean_x

        return a, b

    def export_data_for_external_calculations(self):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        filename_export = filedialog.asksaveasfile(
            mode="w", initialfile="PySILLS_exported_results", defaultextension=".csv", filetypes=[("csv", "*.csv")])
        filename_export = filename_export.name
        with open(filename_export, "w") as file_content:
            file_content.write("EXPORTED RESULTS" + ";\n")
            file_content.write("\n")

            for key, variable in self.container_var[key_setting]["Inclusion Plugin"].items():
                if key == "Intensity BG" and variable.get() == 1:
                    file_content.write("Signal Intensity (Background)" + ";\n")
                    for filetype in ["SMPL", "STD"]:
                        file_content.write("File type" + ";" + str(filetype) + ";\n")
                        for datatype in ["RAW", "SMOOTHED"]:
                            str_header = "Filename" + ";"
                            file_content.write("Data type" + ";" + str(datatype) + ";\n")
                            for index, filename_short in enumerate(self.container_lists[filetype]["Short"]):
                                self.get_intensity(
                                    var_filetype=filetype, var_datatype=datatype, var_file_short=filename_short,
                                    var_focus="BG", mode="Specific")

                                str_content = ""
                                str_content += str(filename_short) + ";"
                                file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                                for isotope in file_isotopes:
                                    value_i = self.container_intensity[filetype][datatype][filename_short]["BG"][
                                        isotope]
                                    if index == 0:
                                        str_header += str(isotope) + ";"
                                    str_content += str(value_i) + ";"
                                if index == 0:
                                    str_header += "\n"
                                str_content += "\n"
                                if index == 0:
                                    file_content.write(str(str_header))
                                    file_content.write(str(str_content))
                                else:
                                    file_content.write(str(str_content))
                        file_content.write("\n")

                elif key == "Intensity MAT" and variable.get() == 1:
                    file_content.write("Signal Intensity (Matrix)" + ";\n")
                    for filetype in ["SMPL", "STD"]:
                        file_content.write("File type" + ";" + str(filetype) + ";\n")
                        for datatype in ["RAW", "SMOOTHED"]:
                            str_header = "Filename" + ";"
                            file_content.write("Data type" + ";" + str(datatype) + ";\n")
                            for index, filename_short in enumerate(self.container_lists[filetype]["Short"]):
                                self.get_intensity(
                                    var_filetype=filetype, var_datatype=datatype, var_file_short=filename_short,
                                    var_focus="MAT", mode="Specific")
                                self.fi_get_intensity_corrected(
                                    var_filetype=filetype, var_datatype=datatype, var_file_short=filename_short,
                                    var_focus="MAT", mode="Specific")

                                str_content = ""
                                str_content += str(filename_short) + ";"
                                file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                                for isotope in file_isotopes:
                                    value_i = self.container_intensity_corrected[filetype][datatype][filename_short][
                                        "MAT"][isotope]
                                    if index == 0:
                                        str_header += str(isotope) + ";"
                                    str_content += str(value_i) + ";"
                                if index == 0:
                                    str_header += "\n"
                                str_content += "\n"
                                if index == 0:
                                    file_content.write(str(str_header))
                                    file_content.write(str(str_content))
                                else:
                                    file_content.write(str(str_content))
                        file_content.write("\n")

                elif key == "Intensity MIX" and variable.get() == 1:
                    file_content.write("Signal Intensity (Mixed)" + ";\n")
                    file_content.write("File type" + ";" + str("SMPL") + ";\n")
                    for datatype in ["RAW", "SMOOTHED"]:
                        str_header = "Filename" + ";"
                        file_content.write("Data type" + ";" + str(datatype) + ";\n")
                        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
                            self.get_intensity(
                                var_filetype="SMPL", var_datatype=datatype, var_file_short=filename_short,
                                var_focus="INCL", mode="Specific")
                            self.fi_get_intensity_mix(
                                var_filetype="SMPL", var_datatype=datatype, var_file_short=filename_short)

                            str_content = ""
                            str_content += str(filename_short) + ";"
                            file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                            for isotope in file_isotopes:
                                value_i = self.container_intensity_mix["SMPL"][datatype][filename_short][isotope]
                                if index == 0:
                                    str_header += str(isotope) + ";"
                                str_content += str(value_i) + ";"
                            if index == 0:
                                str_header += "\n"
                            str_content += "\n"
                            if index == 0:
                                file_content.write(str(str_header))
                                file_content.write(str(str_content))
                            else:
                                file_content.write(str(str_content))
                    file_content.write("\n")

                elif key == "Intensity INCL" and variable.get() == 1:
                    file_content.write("Signal Intensity (Inclusion)" + ";\n")
                    file_content.write("File type" + ";" + str("SMPL") + ";\n")
                    for datatype in ["RAW", "SMOOTHED"]:
                        str_header = "Filename" + ";"
                        file_content.write("Data type" + ";" + str(datatype) + ";\n")
                        for index, filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
                            self.fi_get_intensity_corrected(
                                var_filetype="SMPL", var_datatype=datatype, var_file_short=filename_short,
                                var_focus="INCL", mode="Specific")

                            str_content = ""
                            str_content += str(filename_short) + ";"
                            file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                            for isotope in file_isotopes:
                                value_i = self.container_intensity_corrected["SMPL"][datatype][filename_short][
                                    "INCL"][isotope]
                                if index == 0:
                                    str_header += str(isotope) + ";"
                                str_content += str(value_i) + ";"
                            if index == 0:
                                str_header += "\n"
                            str_content += "\n"
                            if index == 0:
                                file_content.write(str(str_header))
                                file_content.write(str(str_content))
                            else:
                                file_content.write(str(str_content))
                    file_content.write("\n")

                elif key == "Analytical Sensitivity" and variable.get() == 1:
                    file_content.write("Analytical Sensitivity" + ";\n")
                    for filetype in ["SMPL", "STD"]:
                        file_content.write("File type" + ";" + str(filetype) + ";\n")
                        for datatype in ["RAW", "SMOOTHED"]:
                            str_header = "Filename" + ";"
                            file_content.write("Data type" + ";" + str(datatype) + ";\n")
                            for index, filename_short in enumerate(self.container_lists[filetype]["Short"]):
                                filename_long = self.container_lists[filetype]["Long"][index]
                                self.get_analytical_sensitivity(
                                    var_filetype=filetype, var_datatype=datatype, var_file_short=filename_short,
                                    var_file_long=filename_long)

                                str_content = ""
                                str_content += str(filename_short) + ";"
                                file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                                for isotope in file_isotopes:
                                    value_i = self.container_analytical_sensitivity[filetype][datatype][filename_short][
                                        "MAT"][isotope]
                                    if index == 0:
                                        str_header += str(isotope) + ";"
                                    str_content += str(value_i) + ";"
                                if index == 0:
                                    str_header += "\n"
                                str_content += "\n"
                                if index == 0:
                                    file_content.write(str(str_header))
                                    file_content.write(str(str_content))
                                else:
                                    file_content.write(str(str_content))
                        file_content.write("\n")

                elif key == "Concentration SRM" and variable.get() == 1:
                    file_content.write("Concentration (Standard Reference Material)" + ";\n")
                    file_content.write("File type" + ";" + str("STD") + ";\n")
                    for datatype in ["RAW", "SMOOTHED"]:
                        str_header = "Filename" + ";"
                        file_content.write("Data type" + ";" + str(datatype) + ";\n")
                        for index, filename_short in enumerate(self.container_lists["STD"]["Short"]):
                            filename_long = self.container_lists[filetype]["Long"][index]
                            self.fi_get_concentration2(
                                var_filetype="STD", var_datatype=datatype, var_file_short=filename_short,
                                var_file_long=filename_long)

                            str_content = ""
                            str_content += str(filename_short) + ";"
                            file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
                            for isotope in file_isotopes:
                                value_i = self.container_concentration["STD"][datatype][filename_short]["MAT"][isotope]
                                if index == 0:
                                    str_header += str(isotope) + ";"
                                str_content += str(value_i) + ";"
                            if index == 0:
                                str_header += "\n"
                            str_content += "\n"
                            if index == 0:
                                file_content.write(str(str_header))
                                file_content.write(str(str_content))
                            else:
                                file_content.write(str(str_content))
                    file_content.write("\n")

    def clear_all_calculation_intervals(self, mode):
        if mode == "INCL":
            file_type_list = ["SMPL"]
        else:
            file_type_list = ["STD", "SMPL"]

        for var_file_type in file_type_list:
            for var_file_short in self.container_lists[var_file_type]["Short"]:
                self.container_helper[var_file_type][var_file_short][mode]["Content"].clear()

                if self.pysills_mode == "MA":
                    var_setting_key = "ma_setting"
                    self.temp_lines_checkup2[var_file_type][var_file_short] = 0
                    self.show_time_signal_diagram_checker(var_setting_key=var_setting_key)
                elif self.pysills_mode == "FI":
                    var_setting_key = "fi_setting"
                    self.temp_lines_checkup2[var_file_type][var_file_short] = 0
                    self.show_time_signal_diagram_checker(var_setting_key=var_setting_key)
                elif self.pysills_mode == "MI":
                    var_setting_key = "mi_setting"
                    self.temp_lines_checkup2[var_file_type][var_file_short] = 0
                    self.show_time_signal_diagram_checker(var_setting_key=var_setting_key)

        if mode == "BG":
            self.container_var[var_setting_key]["Time BG Start"].set("Set start time")
            self.container_var[var_setting_key]["Time BG End"].set("Set end time")
            self.autodetection_bg = False
        elif mode == "MAT":
            self.container_var[var_setting_key]["Time MAT Start"].set("Set start time")
            self.container_var[var_setting_key]["Time MAT End"].set("Set end time")
            self.autodetection_sig = False

    ## SPIKE ELIMINATION
    def select_spike_elimination(self, var_opt, start_row, var_relief=tk.FLAT, mode="FI"):
        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
            var_row_correction = -2
            var_alpha = self.container_var[var_setting_key]["SE Alpha"]
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "FI":
            var_parent = self.subwindow_fi_settings
            var_setting_key = "fi_setting"
            var_row_correction = -1
            var_alpha = self.container_var[var_setting_key]["SE Alpha"]
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings
            var_setting_key = "mi_setting"
            var_row_correction = -1
            var_alpha = self.container_var[var_setting_key]["SE Alpha"]
            var_threshold = self.container_var[var_setting_key]["SE Threshold"]

        start_row = start_row + 1 + var_row_correction

        str_lbl_01 = self.language_dict["Significance level"][self.var_language]
        str_lbl_02 = self.language_dict["Threshold"][self.var_language]
        str_lbl_03 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_04 = self.language_dict["Sample Files"][self.var_language]
        str_btn_01 = self.language_dict["Run"][self.var_language]
        str_btn_02 = self.language_dict["Check"][self.var_language]
        str_btn_03 = self.language_dict["Setup"][self.var_language]

        if var_opt in ["Grubbs-Test (SILLS)", "Grubbs-Test", "PySILLS Spike Finder", "Grubbs test", "Whisker analysis"]:
            ## GUI
            # Labels
            lbl_09c = SE(
                parent=var_parent, row_id=start_row + 3, column_id=0, n_rows=1, n_columns=7,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
                text=str_lbl_01, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
            lbl_09d = SE(
                parent=var_parent, row_id=start_row + 4, column_id=0, n_rows=1, n_columns=7,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
                text=str_lbl_02, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
            lbl_09e = SE(
                parent=var_parent, row_id=start_row + 5, column_id=0, n_rows=1, n_columns=7,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
                text=str_lbl_03, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)
            lbl_09f = SE(
                parent=var_parent, row_id=start_row + 6, column_id=0, n_rows=1, n_columns=7,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_label(
                text=str_lbl_04, relief=var_relief, fontsize="sans 10 bold", anchor=tk.W)

            # Entries
            var_entr_09c_default = var_alpha.get()
            entr_09c = SE(
                parent=var_parent, row_id=start_row + 3, column_id=7, n_rows=1, n_columns=11,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=var_alpha, text_default=var_entr_09c_default)
            var_entr_09d_default = var_threshold.get()
            entr_09d = SE(
                parent=var_parent, row_id=start_row + 4, column_id=7, n_rows=1, n_columns=11,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["White"]).create_simple_entry(
                var=var_threshold, text_default=var_entr_09d_default)

            # Buttons
            btn_09e1 = SE(
                parent=var_parent, row_id=start_row + 5, column_id=7, n_rows=1, n_columns=5,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda filetype="STD", algorithm="Grubbs": self.spike_elimination_all(filetype, algorithm))
            btn_09e2 = SE(
                parent=var_parent, row_id=start_row + 5, column_id=12, n_rows=1, n_columns=5,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda mode="STD": self.custom_spike_check(mode))
            btn_09f1 = SE(
                parent=var_parent, row_id=start_row + 6, column_id=7, n_rows=1, n_columns=5,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda filetype="SMPL", algorithm="Grubbs": self.spike_elimination_all(filetype, algorithm))
            btn_09f2 = SE(
                parent=var_parent, row_id=start_row + 6, column_id=12, n_rows=1, n_columns=5,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda mode="SMPL": self.custom_spike_check(mode))
            btn_09d = SE(
                parent=var_parent, row_id=start_row + 4, column_id=7, n_rows=1, n_columns=11,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
                text=str_btn_03, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=self.create_spike_elimination_threshold_window)

            # Frames
            if self.container_var["Spike Elimination"]["STD"]["State"]:
                color_std = self.sign_green
            else:
                color_std = self.sign_red

            if self.container_var["Spike Elimination"]["SMPL"]["State"]:
                color_smpl = self.sign_green
            else:
                color_smpl = self.sign_red

            self.frm_spk_std = SE(
                parent=var_parent, row_id=start_row + 5, column_id=17, n_rows=1, n_columns=1,
                fg=self.bg_colors["Very Dark"], bg=color_std).create_frame(relief=tk.SOLID)
            self.frm_spk_std.config(highlightbackground="black", bd=1)
            self.frm_spk_smpl = SE(
                parent=var_parent, row_id=start_row + 6, column_id=17, n_rows=1, n_columns=1,
                fg=self.bg_colors["Very Dark"], bg=color_smpl).create_frame(relief=tk.SOLID)
            self.frm_spk_smpl.config(highlightbackground="black", bd=1)

    def custom_spike_check(self, mode="SMPL"):
        ## Window Settings
        window_width = 900
        window_height = 600
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        #
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_spike_check = tk.Toplevel(self.parent)
        if self.pysills_mode == "MA":
            self.subwindow_spike_check.title("MINERAL ANALYSIS -  Spike Check")
        elif self.pysills_mode == "FI":
            self.subwindow_spike_check.title("FLUID INCLUSION ANALYSIS -  Spike Check")
        elif self.pysills_mode == "MI":
            self.subwindow_spike_check.title("MELT INCLUSION ANALYSIS -  Spike Check")
        self.subwindow_spike_check.geometry(var_geometry)
        self.subwindow_spike_check.resizable(False, False)
        self.subwindow_spike_check["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_spike_check, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_spike_check, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_spike_check.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_spike_check.grid_columnconfigure(i, minsize=column_min)

        start_row = 0
        start_column = 0

        var_list_files = self.container_lists[mode]["Short"]
        self.current_file_id = 0
        self.current_file_spk = var_list_files[self.current_file_id]
        self.current_original_value = 0
        self.current_suggested_value = 0
        self.current_current_value = 0
        self.current_nspikes = 0
        list_spk_isotopes = self.check_spikes_isotope()

        ## FRAMES
        frm_smpl = SE(
            parent=self.subwindow_spike_check, row_id=start_row, column_id=start_column + 13, n_rows=n_rows,
            n_columns=n_columns - 13, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)

        ## LABELS
        lbl_01 = SE(
            parent=self.subwindow_spike_check, row_id=start_row, column_id=start_column, n_rows=1, n_columns=12,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="File selection", relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_01a = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 1, column_id=start_column, n_rows=1, n_columns=12,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text=self.current_file_spk, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 3, column_id=start_column, n_rows=1, n_columns=12,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Isotope selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 9, column_id=start_column, n_rows=1, n_columns=12,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Spike correction", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03a1 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 10, column_id=start_column, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Original value", relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_03a = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 10, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.accent_color).create_simple_label(
            text=round(self.current_original_value, 2), relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03b1 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 11, column_id=start_column, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Smoothed value", relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_03b = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 11, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.accent_color).create_simple_label(
            text=round(self.current_suggested_value, 2), relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03c1 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 12, column_id=start_column, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Current value", relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_03c = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 12, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.accent_color).create_simple_label(
            text=round(self.current_current_value, 2), relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 5, column_id=start_column, n_rows=1, n_columns=12,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Spike selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04a1 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 6, column_id=start_column, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Dark"]).create_simple_label(
            text="Number of spikes", relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_04a2 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 6, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=self.bg_colors["Light Font"], bg=self.accent_color).create_simple_label(
            text=self.current_nspikes, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_05 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 13, column_id=start_column, n_rows=1, n_columns=12,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Value selection", relief=tk.FLAT, fontsize="sans 10 bold")

        ## BUTTONS
        btn_01 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 2, column_id=start_column, n_rows=1, n_columns=6,
            fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Before", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Before": self.change_file_spk(mode))
        btn_02 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 2, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
            text="Next", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda mode="Next": self.change_file_spk(mode))
        if len(list_spk_isotopes) > 0:
            btn_05a1 = SE(
                parent=self.subwindow_spike_check, row_id=start_row + 14, column_id=start_column, n_rows=1, n_columns=6,
                fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Original value", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda mode="RAW": self.replace_spike_value(mode))
            btn_05a2 = SE(
                parent=self.subwindow_spike_check, row_id=start_row + 14, column_id=start_column + 6, n_rows=1,
                n_columns=6, fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
                text="Smoothed value", bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
                command=lambda mode="SMOOTHED": self.replace_spike_value(mode))

        ## SCALES
        if len(list_spk_isotopes) > 0:
            self.scl_01 = tk.Scale(
                self.subwindow_spike_check, from_=1, to=10, tickinterval=1, orient=tk.HORIZONTAL,
                background=self.bg_colors["Light"], foreground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color, troughcolor=self.bg_colors["Dark"], highlightthickness=0,
                command=self.change_spk_id)
            self.scl_01.grid(row=start_row + 7, column=start_column, rowspan=2, columnspan=12, sticky="nesw")

        ## OPTION MENUS
        self.var_opt_spk_iso = tk.StringVar()
        self.var_opt_spk_iso.set("Select isotope")
        if len(list_spk_isotopes) > 0:
            self.current_isotope = list_spk_isotopes[0]
        else:
            self.current_isotope = "No isotope"
        var_opt_is_default = self.current_isotope

        if len(list_spk_isotopes) > 0:
            self.opt_02a = SE(
                parent=self.subwindow_spike_check, row_id=start_row + 4, column_id=start_column, n_rows=1, n_columns=12,
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_option_isotope(
                var_iso=self.var_opt_spk_iso, option_list=list_spk_isotopes, text_set=var_opt_is_default,
                fg_active=self.bg_colors["Dark Font"], bg_active=self.accent_color,
                command=lambda var_opt_iso=self.var_opt_spk_iso: self.change_spk_isotope(var_opt_iso))
            self.opt_02a["menu"].config(
                fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"],
                activeforeground=self.bg_colors["Dark Font"],
                activebackground=self.accent_color)
            self.opt_02a.config(
                bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"], activebackground=self.accent_color,
                activeforeground=self.bg_colors["Dark Font"], highlightthickness=0)

        ## INITIALIZATION
        if len(list_spk_isotopes) > 0:
            self.show_spike_data(mode=mode)

    def check_spikes_isotope(self, var_file=None):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        if var_file == None:
            var_file = self.current_file_spk
        else:
            var_file = var_file

        helper_list = []
        df_isotopes = self.container_lists["Measured Isotopes"][var_file]
        var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())

        for var_isotope in df_isotopes:
            updated_indices = []
            list_indices = self.container_spikes[var_file][var_isotope]["Indices"]
            if len(list_indices) > 0:
                for index in list_indices:
                    value_raw = self.container_spikes[var_file][var_isotope]["Data RAW"][index]
                    value_smoothed = self.container_spikes[var_file][var_isotope]["Data SMOOTHED"][index]
                    if value_raw >= var_threshold and value_smoothed != value_raw:
                        updated_indices.append(index)
                        if var_isotope not in helper_list:
                            helper_list.append(var_isotope)

            self.container_spikes[var_file][var_isotope]["Indices"] = updated_indices

        return helper_list

    def helper_spike_values(self, var_file_short, var_isotope, var_value_raw, var_value_smoothed, mode=None):
        if var_file_short not in self.container_spike_values:
            self.container_spike_values[var_file_short] = {}

        if var_isotope not in self.container_spike_values[var_file_short]:
            self.container_spike_values[var_file_short][var_isotope] = {
                "RAW": [], "SMOOTHED": [], "Current": [], "Save": {}}

        if var_value_raw not in self.container_spike_values[var_file_short][var_isotope]["RAW"]:
            self.container_spike_values[var_file_short][var_isotope]["RAW"].append(var_value_raw)

        if var_value_smoothed not in self.container_spike_values[var_file_short][var_isotope]["SMOOTHED"]:
            self.container_spike_values[var_file_short][var_isotope]["SMOOTHED"].append(var_value_smoothed)

        if var_value_smoothed not in self.container_spike_values[var_file_short][var_isotope]["Current"]:
            if len(self.container_spike_values[var_file_short][var_isotope]["Save"]) == 0 or self.file_loaded == False:
                self.container_spike_values[var_file_short][var_isotope]["Current"].append(var_value_smoothed)
            else:
                for var_id in self.container_spikes[var_file_short][var_isotope]["Indices"]:
                    if var_id in self.container_spike_values[var_file_short][var_isotope]["Save"]:
                        var_value_saved = self.container_spike_values[var_file_short][var_isotope]["Save"][var_id]
                        self.container_spike_values[var_file_short][var_isotope]["Current"].append(var_value_saved)
        data_improved = None
        if mode != None:
            for index_file, var_file_short in enumerate(self.container_lists[mode]["Short"]):
                file_long = self.container_lists[mode]["Long"][index_file]
                if self.container_var[mode][file_long]["Checkbox"].get() == 1:
                    if var_file_short not in self.container_spike_values:
                        self.container_spike_values[var_file_short] = {}
                    list_spk_isotopes = self.check_spikes_isotope(var_file=var_file_short)
                    for var_isotope in list_spk_isotopes:
                        if var_isotope not in self.container_spike_values[var_file_short]:
                            self.container_spike_values[var_file_short][var_isotope] = {
                                "RAW": [], "SMOOTHED": [], "Current": [], "Save": {}}
                        for var_id in self.container_spikes[var_file_short][var_isotope]["Indices"]:
                            val_id = self.container_spikes[var_file_short][var_isotope]["Data SMOOTHED"][var_id]
                            data_raw = self.container_spikes[var_file_short][var_isotope]["Data RAW"][var_id]
                            data_smoothed = self.container_spikes[var_file_short][var_isotope]["Data SMOOTHED"][var_id]
                            data_improved = self.container_spikes[var_file_short][var_isotope]["Data IMPROVED"][var_id]
                            self.container_spike_values[var_file_short][var_isotope]["Save"][var_id] = data_improved

                            if self.file_loaded == False:
                                self.container_spike_values[var_file_short][var_isotope]["Save"][var_id] = data_smoothed
                            else:
                                if var_id in self.container_spike_values[var_file_short][var_isotope]["Save"]:
                                    val_saved = self.container_spike_values[var_file_short][var_isotope]["Save"][var_id]
                                    self.container_spikes[var_file_short][var_isotope]["Data IMPROVED"][
                                        var_id] = val_saved

    def helper_fill_container_spike_values(self, mode="SMPL", file="all"):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode == "FI":
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        for index, var_file_short in enumerate(self.container_lists[mode]["Short"]):
            file_long = self.container_lists[mode]["Long"][index]
            if self.container_var[mode][file_long]["Checkbox"].get() == 1:
                if file == "all" or file == var_file_short:
                    df_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
                    for var_isotope in df_isotopes:
                        if var_isotope in self.container_spikes[var_file_short]:
                            list_indices = self.container_spikes[var_file_short][var_isotope]["Indices"]

                            if len(list_indices) > 0:
                                for var_index in list_indices:
                                    value_raw = self.container_spikes[var_file_short][var_isotope]["Data RAW"][
                                        var_index]
                                    value_smoothed = self.container_spikes[var_file_short][var_isotope][
                                        "Data SMOOTHED"][var_index]
                                    value_improved = self.container_spikes[var_file_short][var_isotope][
                                        "Data IMPROVED"][var_index]

                                    self.helper_spike_values(
                                        var_file_short=var_file_short, var_isotope=var_isotope, var_value_raw=value_raw,
                                        var_value_smoothed=value_smoothed, mode=mode)

    def show_spike_data(self, mode=None):
        var_isotope = self.var_opt_spk_iso.get()
        var_file = self.current_file_spk
        self.list_indices = self.container_spikes[var_file][var_isotope]["Indices"]
        if len(self.list_indices) < 16:
            n_ticks = 1
        else:
            if len(self.list_indices) < 31:
                n_ticks = 2
            elif len(self.list_indices) < 51:
                n_ticks = 5
            else:
                n_ticks = 8
        self.scl_01.configure(to=len(self.list_indices), tickinterval=n_ticks)
        self.current_nspikes = len(self.list_indices)
        self.lbl_04a2.configure(text=self.current_nspikes)

        value_0 = self.list_indices[0]
        current_id = self.scl_01.get()

        self.current_original_value = round(self.container_spikes[var_file][var_isotope]["Data RAW"][value_0], 2)
        self.current_suggested_value = round(self.container_spikes[var_file][var_isotope]["Data SMOOTHED"][value_0], 2)
        val_corrected = self.current_suggested_value
        val_improved = round(self.container_spikes[var_file][var_isotope]["Data IMPROVED"][value_0], 2)
        self.container_spike_values[var_file][var_isotope]["Save"][value_0] = val_improved
        
        if value_0 in self.container_spike_values[var_file][var_isotope]["Save"]:
            value_current = self.container_spike_values[var_file][var_isotope]["Save"][value_0]
            self.current_current_value = round(value_current, 2)
            if value_current == self.current_original_value:
                self.replace_spike_value(mode="RAW")
        else:
            if len(self.container_spike_values[var_file][var_isotope]["Current"]) < current_id:
                self.current_current_value = round(val_corrected, 2)
            else:
                self.current_current_value = round(self.container_spike_values[var_file][var_isotope]["Current"][
                    current_id - 1], 2)
        self.lbl_03a.configure(text=self.current_original_value)
        self.lbl_03b.configure(text=self.current_suggested_value)
        self.lbl_03c.configure(text=self.current_current_value)

        self.helper_spike_values(
            var_file_short=var_file, var_isotope=var_isotope, var_value_raw=self.current_original_value,
            var_value_smoothed=self.current_suggested_value, mode=mode)
        self.show_spike_diagram()

    def change_spk_isotope(self, var_opt_iso):
        var_isotope = var_opt_iso
        self.var_opt_spk_iso.set(var_isotope)
        self.current_isotope = var_isotope
        self.scl_01.set(1)

        self.show_spike_data()

    def change_spk_id(self, mode=None):
        current_id = self.scl_01.get()
        var_id_real = self.list_indices[current_id - 1]
        var_file = self.current_file_spk
        var_isotope = self.var_opt_spk_iso.get()
        val_original = round(self.container_spikes[var_file][var_isotope]["Data RAW"][var_id_real], 2)
        val_smoothed = round(self.container_spikes[var_file][var_isotope]["Data SMOOTHED"][var_id_real], 2)
        val_corrected = round(self.container_spikes[var_file][var_isotope]["Data IMPROVED"][var_id_real], 2)

        if len(self.container_spike_values[var_file][var_isotope]["Current"]) < current_id:
            val_current = round(val_corrected, 2)
        else:
            val_current = round(self.container_spike_values[var_file][var_isotope]["Current"][current_id - 1], 2)

        if var_file not in self.container_spike_values:
            self.container_spike_values[var_file] = {}
        if var_isotope not in self.container_spike_values[var_file]:
            self.container_spike_values[var_file][var_isotope] = {"RAW": [], "SMOOTHED": [], "Current": []}
        if val_original not in self.container_spike_values[var_file][var_isotope]["RAW"]:
            self.container_spike_values[var_file][var_isotope]["RAW"].append(val_original)
        if val_smoothed not in self.container_spike_values[var_file][var_isotope]["SMOOTHED"]:
            self.container_spike_values[var_file][var_isotope]["SMOOTHED"].append(val_smoothed)
        if val_corrected not in self.container_spike_values[var_file][var_isotope]["Current"]:
            self.container_spike_values[var_file][var_isotope]["Current"].append(val_corrected)

        self.lbl_03a.config(text=val_original)
        self.lbl_03b.config(text=val_smoothed)
        self.lbl_03c.configure(text=val_corrected)

        self.show_spike_diagram()

    def change_file_spk(self, mode):
        if mode == "Next":
            if self.current_file_spk in self.container_lists["STD"]["Short"]:
                var_filetype = "STD"
            else:
                var_filetype = "SMPL"

            if self.current_file_id < len(self.container_lists[var_filetype]["Short"]) - 1:
                self.current_file_id += 1
            elif self.current_file_id == len(self.container_lists[var_filetype]["Short"]) - 1:
                self.current_file_id = 0

            self.current_file_spk = self.container_lists[var_filetype]["Short"][self.current_file_id]
            self.lbl_01a.configure(text=self.current_file_spk)
        elif mode == "Before":
            if self.current_file_spk in self.container_lists["STD"]["Short"]:
                var_filetype = "STD"
            else:
                var_filetype = "SMPL"

            if self.current_file_id > 0:
                self.current_file_id -= 1
            elif self.current_file_id == 0:
                self.current_file_id = len(self.container_lists[var_filetype]["Short"]) - 1

            self.current_file_spk = self.container_lists[var_filetype]["Short"][self.current_file_id]
            self.lbl_01a.configure(text=self.current_file_spk)

        possible_spk_isotopes = self.check_spikes_isotope()
        if len(possible_spk_isotopes) > 0:
            self.var_opt_spk_iso.set(possible_spk_isotopes[0])
            self.current_isotope = possible_spk_isotopes[0]
        else:
            self.var_opt_spk_iso.set("No isotope")
            self.current_isotope = "No isotope"
        if len(possible_spk_isotopes) > 0:
            self.scl_01.set(1)

            for index, isotope in enumerate(possible_spk_isotopes):
                if index == 0:
                    self.opt_02a["menu"].delete(0, "end")
                #
                self.opt_02a["menu"].add_command(
                    label=isotope, command=lambda var_opt_iso=isotope: self.change_spk_isotope(var_opt_iso))

            self.show_spike_data()

    def replace_spike_value(self, mode):
        current_id = self.scl_01.get()
        var_id_real = self.list_indices[current_id - 1]
        var_file = self.current_file_spk
        var_isotope = self.current_isotope

        val_raw = round(self.container_spikes[var_file][var_isotope]["Data RAW"][var_id_real], 2)
        val_smoothed = round(self.container_spikes[var_file][var_isotope]["Data SMOOTHED"][var_id_real], 2)

        if mode == "RAW":
            val_updated = round(val_raw, 2)
        else:
            val_updated = round(val_smoothed, 2)

        self.container_spikes[var_file][var_isotope]["Data IMPROVED"][var_id_real] = val_updated
        self.container_spike_values[var_file][var_isotope]["Current"][current_id - 1] = val_updated
        self.lbl_03c.configure(text=val_updated)
        self.container_spike_values[var_file][var_isotope]["Save"][var_id_real] = val_updated

        self.show_spike_diagram()

    def show_spike_diagram(self):
        try:
            if self.canvas_spikes == None:
                self.canvas_spikes.get_tk_widget().grid_remove()
                self.toolbarFrame_spikes.grid_remove()
        except AttributeError:
            pass

        var_file = self.current_file_spk
        var_isotope = self.current_isotope
        current_id = self.scl_01.get()
        var_id_real = self.list_indices[current_id - 1]

        ## Diagram
        self.fig_spikes = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        self.ax_spikes = self.fig_spikes.add_subplot(label=np.random.uniform())

        self.canvas_spikes = FigureCanvasTkAgg(self.fig_spikes, master=self.subwindow_spike_check)
        self.canvas_spikes.get_tk_widget().grid(row=0, column=12, rowspan=22, columnspan=33, sticky="nesw")
        self.toolbarFrame_spikes = tk.Frame(master=self.subwindow_spike_check)
        self.toolbarFrame_spikes.grid(row=22, column=12, rowspan=2, columnspan=33, sticky="w")
        self.toolbar_spikes = NavigationToolbar2Tk(self.canvas_spikes, self.toolbarFrame_spikes)
        self.toolbar_spikes.config(background=self.bg_colors["Very Light"])
        self.toolbar_spikes._message_label.config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_spikes.winfo_children()[-2].config(background=self.bg_colors["Very Light"])

        data_x = self.container_spikes[var_file][var_isotope]["Times"]
        x_max = max(data_x)
        data_y_raw = self.container_spikes[var_file][var_isotope]["Data RAW"]
        data_y_smoothed = self.container_spikes[var_file][var_isotope]["Data SMOOTHED"]
        data_y_valid = self.container_spikes[var_file][var_isotope]["Data IMPROVED"]
        y_min = min(data_y_raw)
        y_max = max(data_y_raw)

        self.ax_spikes.scatter(
            data_x, data_y_raw, color=self.blue_dark, label="Original data")
        self.ax_spikes.plot(
            data_x, data_y_raw, color=self.blue_dark, linewidth=2, alpha=0.75)
        self.ax_spikes.scatter(data_x, data_y_smoothed, color=self.yellow_dark, label="Smoothed data")
        self.ax_spikes.plot(
            data_x, data_y_smoothed, color=self.yellow_dark, linewidth=2, alpha=0.75)
        self.ax_spikes.plot(
            data_x, data_y_valid, color=self.accent_color, label="Improved data", linewidth=2)

        # self.ax_spikes.plot(
        #     data_x, data_y_raw, color=self.bg_colors["Super Dark"], label="Original data", linewidth=2)
        # self.ax_spikes.plot(data_x, data_y_smoothed, color=self.accent_color, label="Smoothed data", linewidth=2)
        self.ax_spikes.axvline(
            x=data_x[var_id_real], color=self.bg_colors["Medium"], label="Current spike", linewidth=2,
            linestyle="dotted")

        self.ax_spikes.grid(True)
        self.ax_spikes.set_yscale("log")
        self.ax_spikes.set_xlim(left=0, right=x_max)
        self.ax_spikes.set_xticks(np.arange(0, x_max, 20))
        if abs(0.1*y_min) > 0:
            y_min_log = abs(0.1*y_min)
        else:
            y_min_log = 1*10**(1)
        self.ax_spikes.set_ylim(bottom=y_min_log, top=1.5*y_max)
        self.ax_spikes.grid(which="major", linestyle="-", linewidth=1)
        self.ax_spikes.minorticks_on()
        self.ax_spikes.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        self.ax_spikes.set_axisbelow(True)
        self.ax_spikes.set_title(var_file, fontsize=9)
        self.ax_spikes.set_xlabel("Experiment Time $t$ (s)", labelpad=0.5, fontsize=8)
        self.ax_spikes.set_ylabel("Signal Intensity Ratio $I$ (cps/cps)", labelpad=0.5, fontsize=8)
        self.ax_spikes.xaxis.set_tick_params(labelsize=8)
        self.ax_spikes.yaxis.set_tick_params(labelsize=8)

        self.leg_spikes = self.fig_spikes.legend(loc="upper left", fontsize="x-small", bbox_to_anchor=(0.075, 0.925))
        self.leg_spikes.set_in_layout(False)
        self.fig_spikes.tight_layout()

        self.canvas_spikes.draw()

    ####################################################################################################################
    # MELT INCLUSION ANALYSIS ##########################################################################################
    ####################################################################################################################
    #
    #
    ####################################################################################################################

    def create_popup_window_before_error(self, var_text):
        """Small window that occurs before a potential bug/error would occur."""
        ## Window Settings
        window_width = 400
        window_height = 300
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_popup = tk.Toplevel(self.parent)
        self.subwindow_popup.title("Attention")
        self.subwindow_popup.geometry(var_geometry)
        self.subwindow_popup.resizable(False, False)
        self.subwindow_popup["bg"] = self.bg_colors["Super Dark"]
        self.subwindow_popup.attributes("-topmost", "true")
        self.subwindow_popup.bell()

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_popup, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_popup, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_popup.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_popup.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 8
        int_category_n = 8

        # LABELS
        lbl_01 = SE(
            parent=self.subwindow_popup, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text="Did you miss something?", relief=tk.FLAT, fontsize="sans 10 bold")

        scrll = tk.Scrollbar(self.subwindow_popup)
        txt_01 = tk.Text(self.subwindow_popup, height=20, width=40)
        txt_01.insert(tk.END, "Attention!\n", "big")
        txt_01.insert(tk.END, var_text)
        scrll.grid(row=var_row_start + 1, column=var_column_start + 19, rowspan=8, columnspan=1, sticky="ns")
        txt_01.grid(row=var_row_start + 1, column=var_column_start, rowspan=8, columnspan=19, sticky="news")
        scrll.config(command=txt_01.yview)
        txt_01.configure(state="disabled", yscrollcommand=scrll.set)

        # BUTTONS
        SE(parent=self.subwindow_popup, row_id=var_row_start + 10, column_id=var_column_start + 1, n_rows=1,
           n_columns=var_header_n + 5, fg=self.bg_colors["Dark Font"], bg=self.accent_color).create_simple_button(
            text="Close window", bg_active=self.accent_color, fg_active=self.bg_colors["Light Font"],
            command=self.subwindow_popup.destroy)

    def run_datareduction_intensity(self, filetype):
        time_start = datetime.datetime.now()

        for var_file_short in self.container_lists[filetype]["Short"]:
            self.get_condensed_intervals_of_file(filetype=filetype, filename_short=var_file_short)

        var_file_short = "None"

        for var_datatype in ["RAW", "SMOOTHED"]:
            print(filetype, var_datatype)
            # Extract signal intensity values
            self.get_intensity(
                var_filetype=filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                var_focus=filetype, mode="All")

            if self.pysills_mode == "MA":
                if self.container_var["General Settings"]["Desired Average"].get() == 1:
                    str_averagetype = "arithmetic mean"
                else:
                    str_averagetype = "median"

                # Calculate corrected signal intensity values
                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_corrected[filetype][var_datatype]).get_averaged_intensities(
                    data_container=self.container_intensity_corrected[filetype][var_datatype],
                    average_type=str_averagetype)

                # Calculate signal intensity ratios
                self.ma_get_intensity_ratio(
                    var_filetype=filetype, var_datatype=var_datatype, var_file_short=var_file_short,
                    var_file_long="None", var_focus="None", mode="All")

        time_end = datetime.datetime.now()
        time_delta = (time_end - time_start)*1000
        print(f"Process time:", filetype, "-", time_delta.total_seconds(), "ms")

    def run_datareduction(self, filetype, focus_intensity=False, focus_sensitivity=False, focus_concentration=False):
        str_filetype = filetype
        if focus_intensity == True:
            self.run_datareduction_intensity(filetype=str_filetype)
            time.sleep(1)
            self.lbl_prg.configure(text=filetype + ": completed 'Intensity data reduction'")
        elif focus_sensitivity == True:
            # Extract signal intensity values
            # Calculate corrected signal intensity values
            # Calculate signal intensity ratios
            time.sleep(1)
            self.lbl_prg.configure(text=filetype + ": completed 'Sensitivity data reduction'")
        elif focus_concentration == True:
            # Calculate concentration values
            # Calculate concentration ratios
            # Calculate limit of detection values
            time.sleep(1)
            self.lbl_prg.configure(text=filetype + ": completed 'Composition data reduction'")

    def update_progress(self, parent, variable, value):
        variable["value"] = value
        parent.update()

    def create_progress_bar_spike_elimination(self):
        ## Window Settings
        window_width = 400
        window_height = 100
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        subwindow_progressbar_spike_elimination = tk.Toplevel(self.parent)
        subwindow_progressbar_spike_elimination.attributes("-topmost", "true")
        subwindow_progressbar_spike_elimination.title("Please wait ...")
        subwindow_progressbar_spike_elimination.geometry(var_geometry)
        subwindow_progressbar_spike_elimination.resizable(False, False)
        subwindow_progressbar_spike_elimination["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(subwindow_progressbar_spike_elimination, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(subwindow_progressbar_spike_elimination, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            subwindow_progressbar_spike_elimination.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            subwindow_progressbar_spike_elimination.grid_columnconfigure(i, minsize=column_min)

        ## Progress bar
        prgbar_spk = ttk.Progressbar(master=subwindow_progressbar_spike_elimination, maximum=100)
        prgbar_spk.grid(row=1, column=1, rowspan=1, columnspan=16, sticky="nesw")

        ## LABELS
        self.helper_lbl_progress_spk = tk.StringVar()
        self.helper_lbl_progress_spk.set("Process has started!")
        self.lbl_prg_spk = SE(
            parent=subwindow_progressbar_spike_elimination, row_id=2, column_id=1, n_rows=1, n_columns=16,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=self.helper_lbl_progress_spk.get(), relief=tk.FLAT, fontsize="sans 10 bold")

        return subwindow_progressbar_spike_elimination, prgbar_spk

    def create_progress_bar_window_datareduction(self, mode="complete"):
        ## Window Settings
        window_width = 400
        window_height = 400
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)

        self.subwindow_progressbar_datareduction = tk.Toplevel(self.parent)
        self.subwindow_progressbar_datareduction.title("Please wait ...")
        self.subwindow_progressbar_datareduction.geometry(var_geometry)
        self.subwindow_progressbar_datareduction.resizable(False, False)
        self.subwindow_progressbar_datareduction["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_progressbar_datareduction, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_progressbar_datareduction, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_progressbar_datareduction.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_progressbar_datareduction.grid_columnconfigure(i, minsize=column_min)

        ## Progress bar
        self.prgbar = ttk.Progressbar(master=self.subwindow_progressbar_datareduction, maximum=100)
        self.prgbar.grid(row=1, column=1, rowspan=1, columnspan=16, sticky="nesw")

        ## LABELS
        self.helper_lbl_progress = tk.StringVar()
        self.helper_lbl_progress.set("Process has started!")
        self.lbl_prg = SE(
            parent=self.subwindow_progressbar_datareduction, row_id=2, column_id=1, n_rows=1, n_columns=16,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=self.helper_lbl_progress.get(), relief=tk.FLAT, fontsize="sans 10 bold")


        if mode == "complete":
            self.update_progress(parent=self.subwindow_progressbar_datareduction, variable=self.prgbar, value=0)
            ## STD
            # Complete signal intensity data reduction
            self.run_datareduction(filetype="STD", focus_intensity=True)
            self.update_progress(parent=self.subwindow_progressbar_datareduction, variable=self.prgbar, value=20)
            # Complete sensitivity data reduction
            self.run_datareduction(filetype="STD", focus_sensitivity=True)
            self.update_progress(parent=self.subwindow_progressbar_datareduction, variable=self.prgbar, value=40)
            # Complete concentration data reduction
            self.run_datareduction(filetype="STD", focus_concentration=True)
            self.update_progress(parent=self.subwindow_progressbar_datareduction, variable=self.prgbar, value=50)
            ## SMPL
            # Complete signal intensity data reduction
            self.run_datareduction(filetype="SMPL", focus_intensity=True)
            self.update_progress(parent=self.subwindow_progressbar_datareduction, variable=self.prgbar, value=70)
            # Complete sensitivity data reduction
            self.run_datareduction(filetype="SMPL", focus_sensitivity=True)
            self.update_progress(parent=self.subwindow_progressbar_datareduction, variable=self.prgbar, value=90)
            # Complete concentration data reduction
            self.run_datareduction(filetype="SMPL", focus_concentration=True)
            self.update_progress(parent=self.subwindow_progressbar_datareduction, variable=self.prgbar, value=99.9)
        elif mode == "only intensity-related":
            ## STD
            # Extract signal intensity values
            # Calculate corrected signal intensity values
            # Calculate signal intensity ratios
            ## SMPL
            # Extract signal intensity values
            # Calculate corrected signal intensity values
            # Calculate signal intensity ratios
            pass
        elif mode == "only sensitivity-related":
            ## STD
            # Calculate analytical sensitivity values
            # Calculate normalized sensitivity values
            # Calculate relative sensitivity factor values
            ## SMPL
            # Calculate analytical sensitivity values
            # Calculate normalized sensitivity values
            # Calculate relative sensitivity factor values
            pass
        elif mode == "only concentration-related":
            ## STD
            # Calculate concentration values
            # Calculate concentration ratios
            # Calculate limit of detection values
            ## SMPL
            # Calculate concentration values
            # Calculate concentration ratios
            # Calculate limit of detection values
            pass

    def extract_filename_information(self, variable):
        """Extracts the long and short filename and also its file ending."""
        filename_long = variable
        filename_short = filename_long.split("/")[-1]
        filename_ending = filename_short.split(".")[-1]

        return filename_long, filename_short, filename_ending

    def add_file_manager(self, filetype):
        """Adds a file or multiple files to the related listbox and table within the PySILLS file manager."""

        output_filenames = filedialog.askopenfilenames(
            parent=self.parent,
            filetypes=(("LA-ICP-MS files", "*.csv *.FIN2 *.xl *.txt"), ("csv files", "*.csv"), ("FIN2 files", "*.FIN2"),
                       ("xl files", "*.xl"), ("txt files", "*.txt"), ("all files", "*.*")), initialdir=os.getcwd())

        for output_filename in output_filenames:
            filename_long, filename_short, filename_ending = self.extract_filename_information(variable=output_filename)

            if filename_short not in self.container_lists[filetype]["Short"]:
                self.container_lists[filetype]["Short"].append(filename_short)
                self.container_lists[filetype]["Long"].append(filename_long)
                self.container_listbox_files[filetype].insert(tk.END, filename_short)
                self.container_listbox_files[filetype + " Manager"].insert(tk.END, str(filename_short))

                str_filename_short = filename_short
                str_filename_long = filename_long
                str_filetype = filetype
                df_data, df_times, df_isotopes = self.load_data_as_dataframe(
                    filename_short=str_filename_short, filename_long=str_filename_long, with_isotopes=True)

                if "Dataframe" not in self.container_measurements:
                    self.container_measurements["Dataframe"] = {}
                if str_filename_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][filename_short] = df_data

                self.container_lists["Measured Isotopes"][filename_short] = df_isotopes
                self.add_needed_variables_for_later_added_files(
                    filename_long=str_filename_long, filename_short=str_filename_short, filetype=str_filetype,
                    file_isotopes=df_isotopes)

                if (self.container_icpms["name"] != None and
                        self.container_icpms["name"] not in ["PerkinElmer Syngistix"]):
                    var_skipheader = self.container_icpms["skipheader"]
                    var_skipfooter = self.container_icpms["skipfooter"]
                    var_timestamp = self.container_icpms["timestamp"]
                    var_icpms = self.container_icpms["name"]

                    dates, times = Data(filename=str_filename_long).import_as_list(
                        skip_header=var_skipheader, skip_footer=var_skipfooter, timestamp=var_timestamp,
                        icpms=var_icpms)
                elif self.container_icpms["name"] == "PerkinElmer Syngistix":
                    create_time = os.path.getctime(str_filename_long)
                    create_date = datetime.datetime.fromtimestamp(create_time)
                    times = [[str(create_date.hour), str(create_date.minute), str(create_date.second)]]
                    dates = [str(create_date.year), str(create_date.month), str(create_date.day)]
                else:
                    dates, times = Data(filename=str_filename_long).import_as_list(
                        skip_header=3, skip_footer=1, timestamp=2,
                        icpms="Agilent 7900s")

                if str_filename_short not in self.container_var["acquisition times"][filetype]:
                    self.container_var["acquisition times"][filetype][str_filename_short] = tk.StringVar()
                    self.container_var["acquisition times"][filetype][str_filename_short].set(
                        times[0][0] + ":" + times[0][1] + ":" + times[0][2])

        self.demo_mode = False

    def copy_file_manager(self, filetype):
        """Copies a file and adds it to the related listbox and table within the PySILLS file manager."""
        pass

    def rename_file_manager(self, filetype):
        """Renames a file and updates the result."""
        pass

    def remove_file_manager(self, filetype):
        """Removes a file and updates the result."""
        pass

    def project_manager(self, type="STD"):
        """Project manager that allows to check, copy and remove files and to check measured data."""
        ## Window Settings
        window_width = 1000
        window_height = 400
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)
        row_min = 25
        n_rows = int(window_height/row_min)
        column_min = 20
        n_columns = int(window_width/column_min)
        self.create_progress_bar_window_datareduction()
        self.subwindow_manager = tk.Toplevel(self.parent)
        self.subwindow_manager.title("PySILLS - Project manager")
        self.subwindow_manager.geometry(var_geometry)
        self.subwindow_manager.resizable(False, False)
        self.subwindow_manager["bg"] = self.bg_colors["Super Dark"]

        for x in range(n_columns):
            tk.Grid.columnconfigure(self.subwindow_manager, x, weight=1)
        for y in range(n_rows):
            tk.Grid.rowconfigure(self.subwindow_manager, y, weight=1)

        # Rows
        for i in range(0, n_rows):
            self.subwindow_manager.grid_rowconfigure(i, minsize=row_min)
        # Columns
        for i in range(0, n_columns):
            self.subwindow_manager.grid_columnconfigure(i, minsize=column_min)

        var_row_start = 0
        var_column_start = 0
        var_header_n = 15
        int_category_n = 5

        ## LABELS
        if type == "STD":
            str_lbl_01 = "Standard files"
        else:
            str_lbl_01 = "Sample files"

        lbl_01 = SE(
            parent=self.subwindow_manager, row_id=var_row_start, column_id=var_column_start, n_rows=1,
            n_columns=var_header_n, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Super Dark"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize="sans 10 bold")

        ## LISTBOXES
        if type == "STD":
            self.lb_std_manager = SE(
                parent=self.subwindow_manager, row_id=var_row_start + 4, column_id=var_column_start, n_rows=n_rows - 5,
                n_columns=3*int_category_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Very Light"]).create_simple_listbox()
            self.container_listbox_files["STD Manager"] = self.lb_std_manager
            self.lb_std_manager.bind(
                "<Double-1>", lambda event, var_filetype="STD Manager": self.quick_plot_file(var_filetype, event))
        else:
            self.lb_smpl_manager = SE(
                parent=self.subwindow_manager, row_id=var_row_start + 4, column_id=var_column_start, n_rows=n_rows - 5,
                n_columns=3*int_category_n, fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Very Light"]).create_simple_listbox()
            self.container_listbox_files["SMPL Manager"] = self.lb_smpl_manager
            self.lb_smpl_manager.bind(
                "<Double-1>", lambda event, var_filetype="SMPL": self.quick_plot_file(var_filetype, event))

        ## BUTTONS
        var_btn_01 = self.language_dict["Add"][self.var_language]
        var_btn_02 = self.language_dict["Copy"][self.var_language]
        var_btn_03 = self.language_dict["Delete"][self.var_language]
        var_btn_04 = self.language_dict["Rename"][self.var_language]

        btn_01 = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 1, column_id=var_column_start, n_rows=2,
            n_columns=int_category_n, fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
            text=var_btn_01, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype=type: self.add_file_manager(filetype))
        btn_02 = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 1, column_id=int_category_n, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
            text=var_btn_02, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype=type: self.copy_file_manager(filetype))
        btn_03 = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 1, column_id=2*int_category_n, n_rows=2,
            n_columns=int_category_n, fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
            text=var_btn_03, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype=type: self.remove_file_manager(filetype))
        btn_04 = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 2, column_id=int_category_n, n_rows=1,
            n_columns=int_category_n, fg=self.bg_colors["Very Dark"], bg=self.bg_colors["Light"]).create_simple_button(
            text=var_btn_04, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype=type: self.rename_file_manager(filetype))

        ## RADIOBUTTONS
        rb_01a = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 1, column_id=3*int_category_n + 1, n_rows=1,
            n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[type]["Project manager"], value_rb=0, color_bg=self.bg_colors["Light"],
            fg=self.bg_colors["Dark Font"], text="File manager", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_01b = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 2, column_id=3*int_category_n + 1, n_rows=1,
            n_columns=8, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var[type]["Project manager"], value_rb=1, color_bg=self.bg_colors["Light"],
            fg=self.bg_colors["Dark Font"], text="Data manager", sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        ## INITIALIZATION
        self.fill_lb_manager(type=type, init=True)

    def fill_lb_manager(self, type, init=False):
        if type == "STD":
            var_lb_manager = self.lb_std_manager
        else:
            var_lb_manager = self.lb_smpl_manager

        var_lb_manager.delete(0, tk.END)

        for filename_short in self.container_lists[type]["Short"]:
            if init == True:
                var_lb_manager.insert(tk.END, filename_short)

    def delete_file_manager(self, type):
        if type == "STD":
            print(type)
        else:
            print(type)

    def rename_file_manager(self, type):
        if type == "STD":
            print(type)
        else:
            print(type)

    def create_container_results(self, var_filetype, var_file_short, mode="MA"):
        ## Intensity
        if mode == "MA":
            self.container_intensity[var_filetype]["RAW"][var_file_short] = {
                "BG": {}, "BG SIGMA": {}, "N BG": {}, "N MAT": {}, "N INCL": {}, "MAT": {}, "MAT SIGMA": {},
                "1 SIGMA MAT": {}, "Parallelism BG": {}, "Parallelism MAT": {}, "Parallelism INCL": {}}
            self.container_intensity[var_filetype]["SMOOTHED"][var_file_short] = {
                "BG": {}, "BG SIGMA": {}, "N BG": {}, "N MAT": {}, "N INCL": {},"MAT": {}, "MAT SIGMA": {},
                "1 SIGMA MAT": {}, "Parallelism BG": {}, "Parallelism MAT": {}, "Parallelism INCL": {}}
        else:
            self.container_intensity[var_filetype]["RAW"][var_file_short] = {
                "BG": {}, "BG SIGMA": {}, "N BG": {}, "N MAT": {}, "N INCL": {},"MAT": {}, "MAT SIGMA": {}, "INCL": {},
                "1 SIGMA MAT": {}, "1 SIGMA INCL": {}, "INCL SIGMA": {}, "Parallelism BG": {}, "Parallelism MAT": {},
                "Parallelism INCL": {}}
            self.container_intensity[var_filetype]["SMOOTHED"][var_file_short] = {
                "BG": {}, "BG SIGMA": {}, "N BG": {}, "N MAT": {}, "N INCL": {},"MAT": {}, "MAT SIGMA": {}, "INCL": {},
                "1 SIGMA MAT": {}, "1 SIGMA INCL": {}, "INCL SIGMA": {}, "Parallelism BG": {}, "Parallelism MAT": {},
                "Parallelism INCL": {}}
        ## Intensity Ratio
        if mode == "MA":
            self.container_intensity_ratio[var_filetype]["RAW"][var_file_short] = {"BG": {}, "MAT": {}}
            self.container_intensity_ratio[var_filetype]["SMOOTHED"][var_file_short] = {"BG": {}, "MAT": {}}
        else:
            self.container_intensity_ratio[var_filetype]["RAW"][var_file_short] = {
                "BG": {}, "MAT": {}, "INCL": {}}
            self.container_intensity_ratio[var_filetype]["SMOOTHED"][var_file_short] = {
                "BG": {}, "MAT": {}, "INCL": {}}
        ## Intensity Corrected
        if mode == "MA":
            self.container_intensity_corrected[var_filetype]["RAW"][var_file_short] = {"BG": {}, "MAT": {}}
            self.container_intensity_corrected[var_filetype]["SMOOTHED"][var_file_short] = {"BG": {}, "MAT": {}}
        else:
            self.container_intensity_corrected[var_filetype]["RAW"][var_file_short] = {"BG": {}, "MAT": {}, "INCL": {}}
            self.container_intensity_corrected[var_filetype]["SMOOTHED"][var_file_short] = {"BG": {}, "MAT": {},
                                                                                            "INCL": {}}
        ## Intensity MIX
        if mode != "MA":
            self.container_intensity_mix[var_filetype]["RAW"][var_file_short] = {}
            self.container_intensity_mix[var_filetype]["SMOOTHED"][var_file_short] = {}
        ## Normalized Sensitivity
        if mode == "MA":
            self.container_normalized_sensitivity[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_normalized_sensitivity[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
        else:
            self.container_normalized_sensitivity[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_normalized_sensitivity[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "INCL": {}}
        ## Analytical Sensitivity
        if mode == "MA":
            self.container_analytical_sensitivity[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_analytical_sensitivity[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
        else:
            self.container_analytical_sensitivity[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_analytical_sensitivity[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "INCL": {}}
        ## Relative Sensitivity Factor
        if mode == "MA":
            self.container_rsf[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_rsf[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
        else:
            self.container_rsf[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}, "MIX": {}}
            self.container_rsf[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "INCL": {}, "MIX": {}}
        ## Concentration
        if mode == "MA":
            self.container_concentration[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "1 SIGMA MAT": {}}
            self.container_concentration[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "1 SIGMA MAT": {}}
        else:
            self.container_concentration[var_filetype]["RAW"][var_file_short] = {
                "MAT": {}, "INCL": {}, "MIX": {}, "Matrix-Only": {}, "Second-Internal": {}, "1 SIGMA MAT": {},
                "1 SIGMA INCL": {}, "Halter2002": {}, "Borisova2021": {}}
            self.container_concentration[var_filetype]["SMOOTHED"][var_file_short] = {
                "MAT": {}, "INCL": {}, "MIX": {}, "Matrix-Only": {}, "Second-Internal": {}, "1 SIGMA MAT": {},
                "1 SIGMA INCL": {}, "Halter2002": {}, "Borisova2021": {}}
            #
            if var_filetype == "SMPL":
                self.container_mixed_concentration[var_filetype]["RAW"][var_file_short] = {}
                self.container_mixed_concentration[var_filetype]["SMOOTHED"][var_file_short] = {}
                self.container_mixed_concentration_error[var_filetype]["RAW"][var_file_short] = {}
                self.container_mixed_concentration_error[var_filetype]["SMOOTHED"][var_file_short] = {}
        ## Concentration Ratio
        if mode == "MA":
            self.container_concentration_ratio[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_concentration_ratio[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
        else:
            self.container_concentration_ratio[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_concentration_ratio[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "INCL": {}}
            #
            if var_filetype == "SMPL":
                self.container_mixed_concentration_ratio[var_filetype]["RAW"][var_file_short] = {}
                self.container_mixed_concentration_ratio[var_filetype]["SMOOTHED"][var_file_short] = {}
                self.container_mixing_ratio[var_filetype]["RAW"][var_file_short] = {}
                self.container_mixing_ratio[var_filetype]["SMOOTHED"][var_file_short] = {}
        ## Limit of Detection
        if mode == "MA":
            self.container_lod[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_lod[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
        else:
            self.container_lod[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_lod[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "INCL": {}}
        #
        for isotope in self.container_lists["ISOTOPES"]:
            if var_file_short not in self.container_measurements["EDITED"]:
                self.container_measurements["EDITED"][var_file_short] = {}
                n_file = len(var_file_short)

            self.container_measurements["EDITED"][var_file_short][isotope] = {}
            self.container_measurements["EDITED"][var_file_short][isotope]["BG"] = []
            self.container_measurements["EDITED"][var_file_short][isotope]["MAT"] = []
            ## Intensity
            self.container_intensity[var_filetype]["RAW"][var_file_short]["BG"][isotope] = None
            self.container_intensity[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_intensity[var_filetype]["RAW"][var_file_short]["1 SIGMA MAT"][isotope] = None
            self.container_intensity[var_filetype]["SMOOTHED"][var_file_short]["BG"][isotope] = None
            self.container_intensity[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            self.container_intensity[var_filetype]["SMOOTHED"][var_file_short]["1 SIGMA MAT"][isotope] = None
            if mode != "MA":
                self.container_intensity[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_intensity[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
                self.container_intensity[var_filetype]["RAW"][var_file_short]["1 SIGMA INCL"][isotope] = None
                self.container_intensity[var_filetype]["SMOOTHED"][var_file_short]["1 SIGMA INCL"][isotope] = None
            ## Intensity Corrected
            self.container_intensity_corrected[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_intensity_corrected[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            if mode != "MA":
                self.container_intensity_corrected[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_intensity_corrected[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
            ## Intensity Ratio
            self.container_intensity_ratio[var_filetype]["RAW"][var_file_short]["BG"][isotope] = None
            self.container_intensity_ratio[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_intensity_ratio[var_filetype]["SMOOTHED"][var_file_short]["BG"][isotope] = None
            self.container_intensity_ratio[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            #
            if mode != "MA":
                self.container_intensity_ratio[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_intensity_ratio[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
            ## Intensity MIX
            if mode != "MA":
                self.container_intensity_mix[var_filetype]["RAW"][var_file_short][isotope] = None
                self.container_intensity_mix[var_filetype]["SMOOTHED"][var_file_short][isotope] = None
            ## Normalized Sensitivity
            self.container_normalized_sensitivity[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_normalized_sensitivity[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            #
            if mode != "MA":
                self.container_normalized_sensitivity[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_normalized_sensitivity[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
            ## Analytical Sensitivity
            self.container_analytical_sensitivity[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_analytical_sensitivity[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            #
            if mode != "MA":
                self.container_analytical_sensitivity[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_analytical_sensitivity[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
            ## Relative Sensitivity Factor
            self.container_rsf[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_rsf[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            #
            if mode != "MA":
                self.container_rsf[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_rsf[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
            ## Concentration
            self.container_concentration[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_concentration[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            #
            if mode != "MA":
                self.container_concentration[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_concentration[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
                self.container_concentration[var_filetype]["RAW"][var_file_short]["Matrix-Only"][isotope] = None
                self.container_concentration[var_filetype]["SMOOTHED"][var_file_short]["Matrix-Only"][isotope] = None
                self.container_concentration[var_filetype]["RAW"][var_file_short]["Second-Internal"][isotope] = None
                self.container_concentration[var_filetype]["SMOOTHED"][var_file_short]["Second-Internal"][
                    isotope] = None
                self.container_concentration[var_filetype]["RAW"][var_file_short]["Halter2002"][isotope] = None
                self.container_concentration[var_filetype]["SMOOTHED"][var_file_short]["Halter2002"][
                    isotope] = None
                self.container_concentration[var_filetype]["RAW"][var_file_short]["Borisova2021"][isotope] = None
                self.container_concentration[var_filetype]["SMOOTHED"][var_file_short]["Borisova2021"][
                    isotope] = None
            ## Concentration Ratio
            self.container_concentration_ratio[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_concentration_ratio[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            #
            if mode != "MA":
                self.container_concentration_ratio[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_concentration_ratio[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
            ## Limit of Detection
            self.container_lod[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_lod[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            #
            if mode != "MA":
                self.container_lod[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_lod[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None

if __name__ == "__main__":
    root = tk.Tk()
    root.title("PySILLS - LA-ICP-MS data reduction")

    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    PySILLS(parent=root, var_screen_width=screen_width, var_screen_height=screen_height)

    root.mainloop()

def pysills():
	root = tk.Tk()
	root.title("PySILLS - LA-ICP-MS data reduction")
	path = os.path.dirname(os.path.realpath(sys.argv[0]))
	screen_width = root.winfo_screenwidth()
	screen_height = root.winfo_screenheight()

	PySILLS(parent=root, var_screen_width=screen_width, var_screen_height=screen_height, var_path=path)

	root.mainloop()