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

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

# Name:		pysills_app.py
# Author:	Maximilian A. Beeskow
# Version:	v1.0.86
# Date:		28.11.2025

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

## MODULES
# external
import os, pathlib, sys, re, datetime, csv, string, math, webbrowser, time
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None
import scipy.io
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import colors
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, restart=False, last_used_directory=None,
            last_used_directory_input=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
        self.str_version_number = "1.0.86
        self.val_version = self.str_version_number + " - 28.11.2025"

        ## 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 = {
            "BG Window": "#2C2C2C", "Very Dark": "#3C3C3C", "Dark": "#676767", "Medium": "#909090", "Light": "#BABABA",
            "Very Light": "#E3E3E3", "Dark Font": "#292929", "Light Font": "#F7F7F7", "White": "#FFFFFF",
            "Black": "#000000", "Accent": "#E76F51"}

        self.standard_dark = {
            "BG Window": "#2C2C2C", "Very Dark": "#3C3C3C", "Dark": "#676767", "Medium": "#909090", "Button": "#BABABA",
            "Very Light": "#E3E3E3", "Dark Font": "#2C2C2C", "Light Font": "#E3E3E3", "White": "#FFFFFF",
            "Black": "#000000", "Accent": "#E76F51"}
        self.standard_light = {
            "BG Window": "#E3E3E3", "Very Dark": "#BABABA", "Dark": "#909090", "Medium": "#676767", "Light": "#BABABA",
            "Very Light": "#E3E3E3", "Dark Font": "#E3E3E3", "Light Font": "#E3E3E3", "White": "#FFFFFF",
            "Black": "#000000", "Accent": "#E76F51"}
        self.green_dark = {
            "BG Window": "#323A25", "Very Dark": "#505D3C", "Dark": "#606F49", "Medium": "#676767", "Light": "#CDD5BF",
            "Very Light": "#FAFBF9", "Dark Font": "#323A25", "Light Font": "#FAFBF9", "White": "#FFFFFF",
            "Black": "#000000", "Accent": "#E76F51"}
        self.boho_theme = {
            "BG Window": "#72574f", "Very Dark": "#a3573a", "Dark": "#e5af9e", "Medium": "#e7b7a7", "Light": "#f2d7ce",
            "Very Light": "#f9efeb", "Dark Font": "#2d231f", "Light Font": "#f9efeb", "White": "#FFFFFF",
            "Black": "#000000", "Accent": "#B15C4D"}

        self.accent_color = self.bg_colors["Accent"]
        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": "#D8CABD", "SIG LB": "#C6C8C1", "MAT LB": "#C6C8C1", "INCL LB": "#FBF1CE"}

        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": ["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(False, False)

        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.NORMAL)
            self.parent.option_add("*Font", default_font)
            mpl.use("TkAgg")
            self.fontsize_normal = 10
        elif var_os == "darwin":
            self.defaultFont = font.nametofont("TkDefaultFont")
            default_font = font.nametofont("TkDefaultFont")
            self.parent.option_add("*Font", default_font)
            mpl.use("MacOSX")
            self.fontsize_normal = 10
        else:
            self.defaultFont = font.nametofont("TkDefaultFont")
            default_font = font.nametofont("TkDefaultFont")
            self.parent.option_add("*Font", default_font)
            mpl.use("TkAgg")
            self.fontsize_normal = 10

        ## 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.container_var["a(TiO2,Rt)"] = tk.StringVar()
        self.container_var["a(TiO2,Rt)"].set("1.0")
        self.container_var["stepwise focus"] = tk.IntVar()
        self.container_var["stepwise focus"].set(1)
        self.container_var["stepwise parameter"] = tk.IntVar()
        self.container_var["stepwise parameter"].set(0)
        self.container_var["stepwise visualization"] = tk.IntVar()
        self.container_var["stepwise visualization"].set(0)
        self.container_var["check INCL"] = tk.BooleanVar()
        self.container_var["check INCL"].set(False)
        self.container_var["Python path"] = tk.StringVar()
        self.container_var["Python path"].set("Set python path")
        self.container_var["PySILLS path"] = tk.StringVar()
        self.container_var["PySILLS path"].set("Set PySILLS path")
        self.container_var["PySILLS script"] = tk.StringVar()
        self.container_var["PySILLS script"].set("Set PySILLS path")

        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(), "Color scheme": tk.StringVar(), "Screen resolution": tk.StringVar(),
            "Project type": tk.StringVar()}
        self.container_var["General Settings"]["Screen resolution"].set("1920x1080")
        self.container_var["General Settings"]["Language"].set("English")
        self.container_var["General Settings"]["Color scheme"].set("Dark scheme")
        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"]["Project type"].set("*.proj")
        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": {}},
                                          "INCL": {"Quickview": {}, "Time-Signal": {}, "Time-Ratio": {}}}
        self.container_var["Subwindows"] = {"MA": {}, "FI": {}, "MI": {}, "INCL": {}}

        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.var_calculation = False
        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}

        self.initial_spike_elimination_std = False
        self.initial_spike_elimination_smpl = False

        ## 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_lob = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_lod = {"STD": {"RAW": {}, "SMOOTHED": {}}, "SMPL": {"RAW": {}, "SMOOTHED": {}}}
        self.container_loq = {"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)

        self.helper_var_rb = {
            "File setup": {"QA section": tk.IntVar(), "Section": tk.IntVar(), "Analysis mode": tk.IntVar(),
                           "Interval limits": tk.IntVar()},
            "Mass/Charge balance": {"File selection": tk.IntVar()}}
        self.helper_var_rb["File setup"]["QA section"].set(1)
        self.helper_var_rb["File setup"]["Section"].set(0)
        self.helper_var_rb["File setup"]["Analysis mode"].set(0)
        self.helper_var_rb["File setup"]["Interval limits"].set(0)
        self.helper_var_rb["Mass/Charge balance"]["File selection"].set(0)

        self.helper_var_entr = {
            "File setup": {"Start": tk.StringVar(), "End": tk.StringVar()},
            "Mass/Charge balance": {"Salinity": tk.StringVar(), "Concentration": tk.StringVar()}}
        self.helper_var_entr["File setup"]["Start"].set("Set start value")
        self.helper_var_entr["File setup"]["End"].set("Set end value")
        self.helper_var_entr["Mass/Charge balance"]["Salinity"].set("0.0")
        self.helper_var_entr["Mass/Charge balance"]["Concentration"].set("0.0")

        self.helper_var_opt = {
            "File setup": {"Reference isotope 1": tk.StringVar(), "Reference isotope 2": tk.StringVar(),
                           "Parameter": tk.StringVar()},
            "Mass/Charge balance": {"Assemblage": tk.StringVar(), "File": tk.StringVar(), "IS": tk.StringVar()}}
        self.helper_var_opt["File setup"]["Reference isotope 1"].set("None")
        self.helper_var_opt["File setup"]["Reference isotope 2"].set("None")
        self.helper_var_opt["File setup"]["Parameter"].set("None")
        self.helper_var_opt["Mass/Charge balance"]["Assemblage"].set("Select assemblage")
        self.helper_var_opt["Mass/Charge balance"]["File"].set("Select file")
        self.helper_var_opt["Mass/Charge balance"]["IS"].set("Select isotope")

        self.helper_var_cb = {"Mass/Charge balance": {"Molality consideration": tk.IntVar()}}
        self.helper_var_cb["Mass/Charge balance"]["Molality consideration"].set(0)

        self.helper_lists = {"Considered chlorides": {}, "Salinity": {}, "Assemblages": {}}

        ## 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"},
            "Define ICP-MS": {"English": "Define ICP-MS", "German": "ICP-MS einstellen"},
            "Project": {"English": "Project", "German": "Projekt"},
            "Inclusions": {"English": "Inclusion Analysis", "German": "Einschlüsse"},
            "Add": {"English": "Add", "German": "Hinzufügen"},
            "Isotope": {"English": "Isotope", "German": "Isotop"},
            "Set salinity": {"English": "Set salinity", "German": "Salinität eingeben"},
            "Interval setup": {"English": "Interval setup", "German": "Zeintfenster Einstellungen"},
            "Remove interval": {"English": "Remove interval", "German": "Zeitfenster entfernen"},
            "Remove": {"English": "Remove", "German": "Entfernen"},
            "Remove sample intervals": {"English": "Remove sample intervals", "German": "Probenintervalle entfernen"},
            "Remove inclusion intervals": {
                "English": "Remove inclusion intervals", "German": "Einschlussintervalle entfernen"},
            "Remove matrix intervals": {"English": "Remove matrix intervals", "German": "Matrixintervalle entfernen"},
            "Update": {"English": "Update", "German": "Aktualisieren"},
            "Error course": {"English": "Error course", "German": "Fehlerverlauf"},
            "Chart analysis": {"English": "Chart analysis", "German": "Chartanalyse", "Chinese": "图表分析"},
            "Parallelism": {"English": "Parallelism", "German": "Parallelität"},
            "No selection": {"English": "No selection", "German": "Keine Auswahl"},
            "Background interval": {"English": "Background interval", "German": "Zeitfenster Untergrund"},
            "Sample interval": {"English": "Sample interval", "German": "Zeitfenster Probe"},
            "Matrix interval": {"English": "Matrix interval", "German": "Zeitfenster Matrix"},
            "Inclusion interval": {"English": "Inclusion interval", "German": "Zeitfenster Einschluss"},
            "Standard file": {"English": "Standard file", "German": "Standardmessung"},
            "Sample file": {"English": "Sample file", "German": "Probenmessung"},
            "Confirm all": {"English": "Confirm all", "German": "Alles bestätigen"},
            "Confirm": {"English": "Confirm", "German": "Bestätigen"},
            "Extend left": {"English": "Move left", "German": "Links verschieben"},
            "Extend right": {"English": "Move right", "German": "Rechts verschieben"},
            "Measured isotopes": {"English": "Measured isotopes", "German": "Gemessene Isotope"},
            "Display options": {"English": "Display options", "German": "Anzeigeoptionen"},
            "Analysis mode": {"English": "Analysis mode", "German": "Analysemodus"},
            "Show all": {"English": "Show all", "German": "Alles anzeigen"},
            "Hide all": {"English": "Hide all", "German": "Alles ausblenden"},
            "Show only RAW": {"English": "Show only RAW", "German": "RAW anzeigen"},
            "Hide only RAW": {"English": "Hide only RAW", "German": "RAW ausblenden"},
            "Time series view": {"English": "Time series view", "German": "Zeitreihe Messung"},
            "Time ratios view": {"English": "Time ratios view", "German": "Zeitreihe Verhältnisse"},
            "Time signal view": {"English": "Time signal view", "German": "Zeit-Signal Diagramm"},
            "Spectral data view": {"English": "Spectral data view", "German": "Datenspektrum"},
            "Box plot data view": {"English": "Box plot data view", "German": "Kastengrafik"},
            "Quick analysis": {"English": "Quick analysis", "German": "Schnellanalyse"},
            "Stepwise analysis": {"English": "Stepwise analysis", "German": "Schrittweise Analyse"},
            "Additional diagrams": {"English": "Additional diagrams", "German": "Weitere Diagramme"},
            "Copy": {"English": "Copy", "German": "Kopieren"},
            "Delete": {"English": "Delete", "German": "Löschen"},
            "Rename": {"English": "Rename", "German": "Umbenennen"},
            "Data analysis": {"English": "Data analysis", "German": "Datenanalyse"},
            "Interval options": {"English": "Interval options", "German": "Intervalleinstellungen"},
            "Reference isotope": {"English": "Reference isotope", "German": "Referenzisotop"},
            "Additional analysis": {"English": "Additional analysis", "German": "Weitere Analysen"},
            "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"},
            "Python path": {"English": "Python path", "German": "Python Pfad"},
            "PySILLS path": {"English": "PySILLS path", "German": "PySILLS Pfad"},
            "Before": {"English": "Previous", "German": "Zurück"},
            "Project file": {"English": "Project file", "German": "Projektdatei", "Chinese": "项目文件"},
            "Previous": {"English": "Previous", "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 auswählen"},
            "Mineral Analysis": {"English": "Mineral Analysis", "German": "Minerale"},
            "Settings": {"English": "Settings", "German": "Einstellungen"},
            "Results": {"English": "Results", "German": "Ergebnisse"},
            "Extras": {"English": "Extras", "German": "Extras"},
            "Mass balance": {"English": "Mass balance", "German": "Massenbilanz"},
            "Charge balance": {"English": "Charge balance", "German": "Ladungsbilanz"},
            "Fluid Inclusions": {"English": "Fluid Inclusions", "German": "Flüssigkeitseinschlüsse"},
            "Geometric approach": {"English": "Geometric approach", "German": "Geometrischer Ansatz"},
            "External quantification support": {
                "English": "External quantification", "German": "Externe Quantifizierung"},
            "Custom data": {"English": "Custom data", "German": "Manuelle Daten"},
            "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"},
            "Default ICP-MS": {"English": "Default ICP-MS", "German": "Voreinstellung ICP-MS"},
            "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"},
            "FLUID INCLUSION ANALYSIS - Setup": {
                "English": "Fluid inclusion analysis - Setup",
                "German": "Flüssigkeitseinschlussanalyse - Einstellungen"},
            "INCLUSION ANALYSIS - Setup": {
                "English": "Inclusion analysis - Setup", "German": "Einschlussanalyse - Einstellungen"},
            "MELT INCLUSION ANALYSIS - Setup": {
                "English": "Melt inclusion analysis - Setup",
                "German": "Schmelzeinschlussanalyse - Einstellungen"},
            "Author": {"English": "Author", "German": "Autor"},
            "Select last solid": {"English": "Select last solid", "German": "Letzten Festkörper auswählen"},
            "Source ID": {"English": "Source ID", "German": "Proben ID"},
            "Standard Reference Material (SRM)": {
                "English": "Standard Reference Material", "German": "Standard/Referenzmaterial"},
            "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"},
            "Category": {"English": "Category", "German": "Kategorie"},
            "Primary isotope": {"English": "Isotope Nr. 1", "German": "Isotop Nr. 1"},
            "Secondary isotope": {"English": "Isotope Nr. 2", "German": "Isotop Nr. 2"},
            "Intensity results": {"English": "Results - Intensity", "German": "Ergebnisse - Intensität"},
            "Sensitivity results": {"English": "Results - Sensitivity", "German": "Ergebnisse - Sensitivität"},
            "Composition results": {"English": "Results - Composition", "German": "Ergebnisse - Zusammensetzung"},
            "ID": {"English": "ID", "German": "ID"},
            "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"},
            "N(isotopes)": {"English": "N(isotopes)", "German": "N(Isotope)"},
            "t(start)": {"English": "t(start)", "German": "t(Start)"},
            "t(end)": {"English": "t(end)", "German": "t(Ende)"},
            "t(day)": {"English": "t(day)", "German": "t(Tag)"},
            "date": {"English": "date", "German": "Datum"},
            "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"},
            "Check inclusion": {"English": "Check only inclusion", "German": "Nur Inklusion überprüfen"},
            "Quantification Method": {"English": "Quantification Method", "German": "Quantifizierungsmethode"},
            "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"},
            "Acquisition Time": {"English": "Acquisition time", "German": "Messzeit"},
            "Imported Files": {"English": "Imported Files", "German": "Importierte Dateien"},
            "Line of time stamp": {"English": "Line of time stamp", "German": "Zeitstempel in Zeile"},
            "Skip header": {"English": "Skip header", "German": "Überspringe ... Kopfzeilen"},
            "Skip footer": {"English": "Skip footer", "German": "Überspringe ... Fußzeilen"},
            "Save ICP-MS setup": {"English": "Save ICP-MS setup", "German": "ICP-MS Daten speichern"},
            "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"},
            "Select file": {"English": "Select file", "German": "Datei auswählen"},
            "Select all": {"English": "Select all", "German": "Alles auswählen"},
            "Select": {"English": "Select", "German": "Auswählen"},
            "Alkali metals": {"English": "Alkali metals", "German": "Alkalimetalle"},
            "Alkaline earth metals": {"English": "Alkaline earth metals", "German": "Erdalkalimetalle"},
            "Transition metals": {"English": "Transition metals", "German": "Übergangsmetalle"},
            "Other metals": {"English": "Other metals", "German": "Andere Metalle"},
            "Metalloids": {"English": "Metalloids", "German": "Halbmetalle"},
            "Lanthanides": {"English": "Lanthanides", "German": "Lanthanoide"},
            "Actinides": {"English": "Actinides", "German": "Actinoide"},
            "Non-metals": {"English": "Non-metals", "German": "Nichtmetalle"},
            "Halogens": {"English": "Halogens", "German": "Halogene"},
            "Noble gases": {"English": "Noble gases", "German": "Edelgase"},
            "Select all oxides": {"English": "Select all oxides", "German": "Alle Oxide auswählen"},
            "Deselect all oxides": {"English": "Deselect all oxides", "German": "Alle Oxide abwählen"},
            "Rock-forming elements": {"English": "Rock-forming elements", "German": "Gesteinsbildende Elemente"},
            "Fix quantification": {"English": "Fix quantification", "German": "Quantifizierung reparieren"},
            "Calculate again": {"English": "Calculate again", "German": "Berechnung wiederholen"},
            "Molality-based quantification": {
                "English": "Molality-based quantification", "German": "Quantifizierung gemäß Molalität"},
            "Guess the composition": {"English": "Guess the composition", "German": "Zusammensetzung schätzen"},
            "Setup - Oxide ratios": {"English": "Setup - Oxide ratios", "German": "Einstellungen - Oxidverhältnisse"},
            "Setup - Reference element": {
                "English": "Setup - Reference element", "German": "Einstellungen - Referenzelement"},
            "Setup - Oxide selection": {"English": "Setup - Oxide selection", "German": "Einstellungen - Oxidauswahl"},
            "Run 100 wt.% oxides calculation for": {
                "English": "Run 100 wt.% oxides calculation for", "German": "Berechnung 100 Gew.% Oxide ausführen für"},
            "Setup - Files": {"English": "Setup - Files", "German": "Einstellungen - Dateien"},
            "Mineral quantification": {"English": "Mineral quantification", "German": "Mineralquantifizierung"},
            "Inclusion quantification": {"English": "Inclusion quantification", "German": "Einschlussquantifizierung"},
            "Assemblage Settings": {"English": "Assemblage settings", "German": "Einstellungen - Assemblage"},
            "Isotope Dwell Times": {"English": "Isotope Dwell Times", "German": "Haltezeiten je Isotop"},
            "Inclusion Settings": {"English": "Inclusion Settings", "German": "Einstellungen - Einschlüsse"},
            "Internal Standard Setup": {
                "English": "Internal Standard Setup", "German": "Einstellungen interner Standard"},
            "Oxide stoichiometry": {"English": "Oxide stoichiometry", "German": "Oxide Stöchiometrie"},
            "Default settings": {"English": "Default settings", "German": "Voreinstellungen"},
            "Composition": {"English": "Composition", "German": "Zusammensetzung"},
            "Cations": {"English": "Cations", "German": "Kationen"},
            "Anions": {"English": "Anions", "German": "Anionen"},
            "Melting temperature of the last solid": {
                "English": "Melting temperature of the last solid",
                "German": "Schmelztemperatur des letzten Festkörpers"},
            "Melting temperature": {"English": "Melting temperature", "German": "Schmelztemperatur"},
            "Last solid": {"English": "Last solid", "German": "Letzter Festkörper"},
            "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"},
            "Import external data": {"English": "Import external data", "German": "Externe Daten importieren"},
            "LA-ICP-MS data export": {"English": "LA-ICP-MS data export", "German": "LA-ICP-MS Daten exportieren"},
            "Oxide Setup": {"English": "Oxide Setup", "German": "Oxideinstellungen"},
            "Import data": {"English": "Import data", "German": "Daten importieren"},
            "Application launcher": {"English": "Application launcher", "German": "Startdatei"},
            "Dwell times": {"English": "Dwell times", "German": "Haltezeiten"},
            "Default author": {"English": "Default author", "German": "Voreinstellung (Name)"},
            "Default SRM": {"English": "Default SRM", "German": "Voreinstellung (SRM)"},
            "Median": {"English": "Median", "German": "Median"},
            "Standard deviation": {"English": "Standard deviation", "German": "Standardabweichung"},
            "Charge": {"English": "Charge", "German": "Ladung"},
            "charged": {"English": "charged", "German": "geladen"},
            "Screen resolution": {"English": "Screen resolution", "German": "Bildschirmauflösung"},
            "Arithmetic mean": {"English": "Arithmetic mean", "German": "Arithmetisches Mittel"},
            "Average of every interval": {
                "English": "Average of every interval", "German": "Durchschnitt pro Interval"},
            "Stack all intervals into one": {
                "English": "Stack all intervals into one", "German": "Alle Intervalle stappeln"},
            "File type": {"English": "File type", "German": "Dateiendung"},
            "Data type": {"English": "Data type", "German": "Datentyp"},
            "Data selection": {"English": "Data selection", "German": "Datenauswahl"},
            "Assemblage": {"English": "Assemblage", "German": "Assemblage"},
            "Value": {"English": "Value", "German": "Wert"},
            "Select standard file": {"English": "Select standard file", "German": "Standardmessung auswählen"},
            "Select sample file": {"English": "Select sample file", "German": "Probenmessung auswählen"},
            "Select parameter": {"English": "Select parameter", "German": "Parameter auswählen"},
            "Original data": {"English": "Original data", "German": "Originaldaten"},
            "Smoothed data": {"English": "Smoothed data", "German": "Korrigierte Daten"},
            "Current data": {"English": "Current data", "German": "Aktuelle Daten"},
            "Current outlier": {"English": "Current outlier", "German": "Aktueller Ausreißer"},
            "Scatter plot": {"English": "Scatter plot", "German": "Streudiagramm"},
            "Histogram plot": {"English": "Histogram plot", "German": "Häufigkeitsdiagramm"},
            "Diagram selection": {"English": "Diagram selection", "German": "Diagrammauswahl"},
            "Plotting setup": {"English": "Plotting setup", "German": "Ploteinstellungen"},
            "Section selection": {"English": "Phase selection", "German": "Phasenauswahl"},
            "Select section": {"English": "Select section", "German": "Abschnitt auswählen"},
            "Parameter selection": {"English": "Select parameter", "German": "Parameter auswählen"},
            "Color coding": {"English": "Color coding", "German": "Farbkodierung"},
            "Isotope selection": {"English": "Isotope selection", "German": "Isotopauswahl"},
            "Outlier selection": {"English": "Outlier selection", "German": "Ausreißerauswahl"},
            "Outlier correction": {"English": "Outlier correction", "German": "Ausreißerkorrektur"},
            "Number of outliers": {"English": "Number of outliers", "German": "Anzahl Ausreißer"},
            "File selection": {"English": "File selection", "German": "Dateiauswahl"},
            "Original value": {"English": "Original value", "German": "Originalwert"},
            "Smoothed value": {"English": "Smoothed value", "German": "Korrekturwert"},
            "Current value": {"English": "Current value", "German": "Aktueller Wert"},
            "Value selection": {"English": "Value selection", "German": "Wert auswählen"},
            "Outlier check": {"English": "Outlier check", "German": "Ausreißerüberprüfung"},
            "Signal intensity": {"English": "Signal intensity", "German": "Signalintensität"},
            "Experiment time": {"English": "Experiment time", "German": "Experimentzeit"},
            "Delimiter": {"English": "Delimiter", "German": "Trennzeichen"},
            "Sample": {"English": "Sample", "German": "Probe"},
            "of": {"English": "of", "German": "von"},
            "with": {"English": "with", "German": "mit"},
            "Up": {"English": "Up", "German": "Hoch"},
            "Down": {"English": "Down", "German": "Runter"},
            "without": {"English": "without", "German": "ohne"},
            "Densities": {"English": "Densities", "German": "Dichten"},
            "Dimensions": {"English": "Dimensions", "German": "Abmessungen"},
            "Inclusion intensity": {"English": "Inclusion intensity", "German": "Einschlussintensität"},
            "Inclusion dimensions": {"English": "Inclusion dimensions", "German": "Einschlussgröße"},
            "Inclusion concentration": {"English": "Inclusion concentration", "German": "Einschlusskonzentration"},
            "Length of": {"English": "Length of", "German": "Länge der"},
            "semi-axis": {"English": "semi-axis", "German": "Halbachse"},
            "Ablation radius": {"English": "Ablation radius", "German": "Ablationsradius"},
            "Inclusion radius": {"English": "Inclusion radius", "German": "Einschlussradius"},
            "Inclusion density": {"English": "Inclusion density", "German": "Einschlussdichte"},
            "Matrix density": {"English": "Matrix density", "German": "Matrixdichte"},
            "elements": {"English": "elements", "German": "Elemente"},
            "element ratios": {"English": "element ratios", "German": "Elementverhältnisse"},
            "oxides": {"English": "oxides", "German": "Oxide"},
            "oxide ratios": {"English": "oxide ratios", "German": "Oxidverhältnisse"},
            "with respect to": {"English": "with respect to", "German": "bezogen auf"},
            "x-y diagram": {"English": "X-Y diagram", "German": "X-Y-Diagramm"},
            "Ternary diagram": {"English": "Ternary diagram", "German": "Dreiecksdiagramm"},
            "Geothermometry": {"English": "Geothermometry", "German": "Geothermometrie"},
            "Matrix": {"English": "Matrix", "German": "Matrix"},
            "Inclusion": {"English": "Inclusion", "German": "Einschluss"},
            "Additional Settings": {"English": "Additional settings", "German": "Weitere Einstellungen"},
            "Select x": {"English": "Select x", "German": "x auswählen"},
            "Select y": {"English": "Select y", "German": "y auswählen"},
            "Select z": {"English": "Select z", "German": "z auswählen"},
            "Mixed signal": {"English": "Mixed signal", "German": "Gemischtes Signal"},
            "Concentration": {"English": "Concentration", "German": "Concentration"},
            "Concentration ratio": {"English": "Concentration ratio", "German": "Konzentrationsverhältnis"},
            "Limit of detection": {"English": "Limit of detection", "German": "Nachweisgrenze"},
            "Mixed intensity": {"English": "Mixed intensity", "German": "Gemischte Intensität"},
            "Mixed concentration": {"English": "Mixed concentration", "German": "Gemischte Konzentration"},
            "Mixing ratio": {"English": "Mixing ratio", "German": "Mischungsverhältnis"},
            "Intensity": {"English": "Intensity", "German": "Intensität"},
            "Intensity ratio": {"English": "Intensity ratio", "German": "Intensitätsverhältnis"},
            "Analytical sensitivity": {"English": "Analytical sensitivity", "German": "Analytische Sensitivität"},
            "Normalized sensitivity": {"English": "Normalized sensitivity", "German": "Normalisierte Sensitivität"},
            "Relative sensitivity factor": {
                "English": "Relative sensitivity factor", "German": "Relativer Sensitivitätsfaktor"},
            "Export results": {"English": "Export results", "German": "Ergebnisse exportieren"},
            "Further data analysis": {"English": "Further data analysis", "German": "Weitere Datenanalyse"},
            "Sensitivity drift": {"English": "Sensitivity drift", "German": "Sensitivitätsverschiebung"},
            "Internal standard": {"English": "Internal standard", "German": "Interner Standard"},
            "Sorting by": {"English": "Sorting by", "German": "Sortierung nach"},
            "All in one file": {"English": "All in one file", "German": "Alles in eine Datei"},
            "Background": {"English": "Background", "German": "Untergrund"},
            "Main signal": {"English": "Main signal", "German": "Hauptsignal"},
            "Line width": {"English": "Line width", "German": "Linienbreite"},
            "Save settings": {"English": "Save settings", "German": "Einstellungen speichern"},
            "Create launcher": {"English": "Create launcher", "German": "Startdatei erstellen"},
            "Calculation formula from ...": {
                "English": "Calculation formula from ...", "German": "Berechnung basierend auf ..."},
            "PySILLS color scheme": {"English": "PySILLS color scheme", "German": "PySILLS Farbschema"},
            "Default value": {"English": "Default value", "German": "Voreinstellung"},
            "Composition Setup": {"English": "Composition Setup", "German": "Zusammensetzung\n definieren"},
            "Mineral stoichiometry": {"English": "Mineral stoichiometry", "German": "Minerale Stöchiometrie"},
            "PySILLS subtitle": {
                "English": "Major, minor and trace element analysis of minerals, fluid and melt inclusions",
                "German":
                    "Haupt-, Neben- und Spurenelementanalysie von Mineralen, Flüssigkeits- und Schmelzeinschlüssen"},
            "File-specific Setup": {"English": "File-specific Setup", "German": "Datei-spezifische\n Einstellungen"}}

        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

        if restart == False:
            self.last_used_directory = os.getcwd()
            self.last_used_directory_input = os.getcwd()
        else:
            self.last_used_directory = last_used_directory
            self.last_used_directory_input = last_used_directory_input

        ## 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")

            self.helper_filesetup_lines = {}

            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)

            str_opt_01 = self.language_dict["Set salinity"][self.var_language]

            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(str_opt_01 + " (%)")
            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.projectname = None

        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_intervals = {}

        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["Radiobuttons"] = {"Quick Plot File": tk.IntVar()}
        self.container_var["Radiobuttons"]["Quick Plot File"].set(1)
        self.container_var["Checkboxes"] = {
            "Quick Plot File BG": tk.IntVar(), "Quick Plot File MAT": tk.IntVar(), "Quick Plot File INCL": tk.IntVar()}
        for key_cb in ["Quick Plot File BG", "Quick Plot File MAT", "Quick Plot File INCL"]:
            self.container_var["Checkboxes"][key_cb].set(1)
        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 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")

        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", "Whisker analysis", "Z-score 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["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"], ["OU-6 (GeoReM)"]])[:, 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", "")
        elif "Scripts" 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 = []

        if "pysills" in self.path_pysills_main:
            self.path_pysills_main = self.path_pysills_main.replace("pysills", "")

        if "\\" in self.path_pysills_main:
            self.path_pysills_main = self.path_pysills_main[:-1]

        folder_path = os.path.join(self.path_pysills_main, "pysills", "lib", "srm")
        folder_path_translations = os.path.join(self.path_pysills_main, "pysills", "lib", "translations", "")
        helper_srm_library = os.listdir(folder_path)

        for language in ["Chinese"]:
            if language == "Chinese":
                var_ending = ".txt"
            else:
                var_ending = ".csv"

            path_language = folder_path_translations + language + var_ending

            if language == "Chinese":
                var_encoding = "utf-8"
            else:
                var_encoding = "utf-8"
            with open(path_language, mode="r", newline="", encoding=var_encoding) as file:
                reader = csv.reader(file)
                for row in reader:
                    if language == "Chinese":
                        key = row[0].split("\t")[0]
                        translation = row[0].split("\t")[-1]
                        self.language_dict[key][language] = translation

        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:
            if ".csv" in var_srm:
                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")
                if "OU 6" in var_srm_new:
                    var_srm_new = var_srm_new.replace("OU 6", "OU-6")

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

        helper_icpms_library = []

        if "site-packages" in self.path_pysills_main:
            folder_path = os.path.join(self.path_pysills_main, "pysills", "lib", "icpms")
            helper_icpms_library = os.listdir(folder_path)
        else:
            try:
                folder_path = os.path.join(self.path_pysills_main, "lib", "icpms")
                helper_icpms_library = os.listdir(folder_path)
            except:
                folder_path = os.path.join(self.path_pysills_main, "pysills", "lib", "icpms")
                helper_icpms_library = os.listdir(folder_path)

        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:
            if ".csv" in var_icpms:
                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()

        ## USER SETTINGS
        project_path_prew = self.path_pysills[:]
        project_path = project_path_prew.strip("/pysills")

        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)

        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])

                if "Default ICP-MS" in file_data_splitted:
                    self.var_opt_icp.set(file_data_splitted[1])

                    str_icpms = file_data_splitted[1]
                    var_instrument = str_icpms.replace(" ", "_")
                    var_instrument_raw = str_icpms

                    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]
        except:
            print("There is no user_settings file!")

        # Screen resolution
        str_screen_resolution = self.container_var["General Settings"]["Screen resolution"].get()
        if str_screen_resolution == "1920x1080":
            self.row_height = 24
            self.column_width = 21

            if var_os == "linux":
                self.font_settings = {
                    "Header": "sans 12 bold", "Elements": "sans 10 bold", "Small": "sans 7 bold", "Options": "sans 10",
                    "Table": "sans 10", "Tiny": "sans 7 bold"}
            elif var_os == "darwin":
                self.font_settings = {
                    "Header": "sans 16 bold", "Elements": "sans 14 bold", "Small": "sans 10 bold", "Options": "sans 14",
                    "Table": "sans 14", "Tiny": "sans 10 bold"}
            else:
                self.font_settings = {
                    "Header": "sans 12 bold", "Elements": "sans 10 bold", "Small": "sans 8 bold", "Options": "sans 10",
                    "Table": "sans 10", "Tiny": "sans 8 bold"}
        elif str_screen_resolution == "1280x720":
            self.row_height = 16
            self.column_width = 14

            if var_os == "linux":
                self.font_settings = {
                    "Header": "sans 8 bold", "Elements": "sans 7 bold", "Small": "sans 5 bold", "Options": "sans 7",
                    "Table": "sans 7", "Tiny": "sans 5 bold"}
            elif var_os == "darwin":
                self.font_settings = {
                    "Header": "sans 11 bold", "Elements": "sans 9 bold", "Small": "sans 7 bold", "Options": "sans 9",
                    "Table": "sans 9", "Tiny": "sans 5 bold"}
            else:
                self.font_settings = {
                    "Header": "sans 8 bold", "Elements": "sans 7 bold", "Small": "sans 5 bold", "Options": "sans 7",
                    "Table": "sans 7", "Tiny": "sans 5 bold"}
        elif str_screen_resolution == "3840x2160":
            self.row_height = 32
            self.column_width = 28

            if var_os == "linux":
                self.font_settings = {
                    "Header": "sans 16 bold", "Elements": "sans 14 bold", "Small": "sans 14 bold", "Options": "sans 14",
                    "Table": "sans 12", "Tiny": "sans 12 bold"}
            elif var_os == "darwin":
                self.font_settings = {
                    "Header": "sans 18 bold", "Elements": "sans 16 bold", "Small": "sans 14 bold", "Options": "sans 16",
                    "Table": "sans 16", "Tiny": "sans 12 bold"}
            else:
                self.font_settings = {
                    "Header": "sans 16 bold", "Elements": "sans 14 bold", "Small": "sans 14 bold", "Options": "sans 14",
                    "Table": "sans 12", "Tiny": "sans 12 bold"}

        str_screen_resolution = self.container_var["General Settings"]["Screen resolution"].get()

        var_ncol_ma_settings = 65
        var_ncol_fi_settings = 67
        var_ncol_mi_settings = 63

        if str_screen_resolution == "1920x1080":    # Full HD
            if var_os == "linux":
                var_ncol_ma_settings = 66
                var_ncol_fi_settings = 68
                var_ncol_mi_settings = 64
            elif var_os == "darwin":
                var_ncol_ma_settings = 65
                var_ncol_fi_settings = 67
                var_ncol_mi_settings = 63
            else:
                var_ncol_ma_settings = 65
                var_ncol_fi_settings = 67
                var_ncol_mi_settings = 63
        elif str_screen_resolution == "1280x720":   # HD ready
            var_ncol_ma_settings = 70
            var_ncol_fi_settings = 72
            var_ncol_mi_settings = 68
        elif str_screen_resolution == "3840x2160":  # 4K
            var_ncol_ma_settings = 65
            var_ncol_fi_settings = 67
            var_ncol_mi_settings = 63

        self.window_dimensions = {
            "Main window": [33, 21], "MA main settings": [38, var_ncol_ma_settings],
            "FI main settings": [40, var_ncol_fi_settings], "MI main settings": [40, var_ncol_mi_settings],
            "ICP-MS setup": [8, 17], "Quick plot": [35, 70], "Spike elimination threshold": [24, 15],
            "Check-up oxides": [29, 83], "Check-up IS": [16, 42], "General settings": [23, 35],
            "Check-up SRM": [23, 32], "Check-up intervals": [32, 54], "Check-up acquisition times": [33, 26],
            "Check-up files": [32, 50], "MA Extras": [8, 25], "FI Extras": [9, 34], "MI Extras": [8, 34],
            "Geothermometry": [16, 40], "Diagram xy": [24, 50], "Diagram halogen ratios": [24, 40],
            "Matrix quantification": [5, 24], "Mineral quantification": [18, 40], "Stepwise analysis": [32, 55],
            "MA specific file": [34, 60], "MA datareduction files": [25, 63],
            "Detailed analysis": [32, 45], "About PySILLS": [22, 32], "Calculation report": [9, 13],
            "Sensitivity drift": [32, 70], "FI datareduction files": [29, 63], "Setup Halter": [24, 34],
            "Setup Borisova": [22, 34], "Setup matrix-only tracer": [15, 41], "Setup 2nd IS": [15, 36],
            "FI specific file": [34, 68], "Setup PyPitzer": [20, 60], "Setup mass balance": [24, 55],
            "Setup external calculation": [11, 33], "Custom spike check": [24, 45], "Popup window error": [12, 20],
            "Popup window progress": [4, 20], "Popup window progress datareduction": [16, 20],
            "Project manager": [16, 50], "Quick Plot Extra": [34, 46], "Specific file setup": [38, 75]}

        row_min = self.row_height
        self.n_rows = 33
        window_height = int(row_min*self.n_rows)
        column_min = self.column_width

        self.n_columns = 21
        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(self.n_columns):
            tk.Grid.columnconfigure(self.parent, x, weight=1)
        for y in range(self.n_rows):
            tk.Grid.rowconfigure(self.parent, y, weight=1)

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

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

        ## FRAMES

        frame_01 = tk.Frame(self.parent, bg=self.bg_colors["BG Window"], borderwidth=0, highlightthickness=0,
                            relief=tk.FLAT)
        frame_01.grid(row=3, 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
        str_color_scheme = self.container_var["General Settings"]["Color scheme"].get()
        if str_color_scheme == "Dark scheme":
            self.bg_colors = {
                "BG Window": "#2C2C2C", "Very Dark": "#3C3C3C", "Dark": "#676767", "Medium": "#909090",
                "Light": "#BABABA", "Very Light": "#E3E3E3", "Dark Font": "#292929", "Light Font": "#F7F7F7",
                "White": "#FFFFFF", "Black": "#000000", "Accent": "#E76F51",
                "BG Interval": 0, "MAT Interval": 0, "INCL Interval": 0,
                "BG Light": 0, "MAT Light": 0, "INCL Light": 0}
        elif str_color_scheme == "Light scheme":
            self.bg_colors = {
                "BG Window": "#cccccc", "Very Dark": "#91A1B1", "Dark": "#BAC4CE", "Medium": "#CFD6DD",
                "Light": "#e5e5e5", "Very Light": "#f2f2f2", "Dark Font": "#2C2C2C", "Light Font": "#2C2C2C",
                "White": "#FFFFFF", "Black": "#000000", "Accent": "#bd7966"}
        elif str_color_scheme == "Boho theme 1":
            self.bg_colors = {
                "BG Window": "#463F3A", "Very Dark": "#a3573a", "Dark": "#e5af9e", "Medium": "#e7b7a7",
                "Light": "#BCB8B1", "Very Light": "#F4F3EE", "Dark Font": "#463F3A", "Light Font": "#F4F3EE",
                "White": "#FFFFFF", "Black": "#000000", "Accent": "#E0AFA0"}
        elif str_color_scheme == "Synthwave theme":
            self.bg_colors = {
                "BG Window": "#1C1C3E", "Very Dark": "#3C3C3C", "Dark": "#676767", "Medium": "#909090",
                "Light": "#72419C", "Very Light": "#D3FCFF", "Dark Font": "#1C1C3E", "Light Font": "#F7F7F7",
                "White": "#FFFFFF", "Black": "#000000", "Accent": "#FF49DB"}
        elif str_color_scheme == "Gunmetal theme":
            self.bg_colors = {
                "BG Window": "#223843", "Light": "#B5BEC7", "Very Light": "#EFF1F3", "Dark Font": "#223843",
                "Light Font": "#EFF1F3", "White": "#FFFFFF", "Black": "#000000", "Accent": "#D77A61"}
        elif str_color_scheme == "Dark Jungle":
            self.bg_colors = {
                "BG Window": "#242C1D", "Light": "#C5D0B9", "Very Light": "#F0F3EE", "Dark Font": "#242C1D",
                "Light Font": "#F0F3EE", "White": "#FFFFFF", "Black": "#000000", "Accent": "#582F0E"}
        elif str_color_scheme == "Noble Room":
            self.bg_colors = {
                "BG Window": "#4B3F32", "Light": "#C3B5A5", "Very Light": "#E1DAD2", "Dark Font": "#4B3F32",
                "Light Font": "#E1DAD2", "White": "#FFFFFF", "Black": "#000000", "Accent": "#22333B"}

        ## 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["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_listbox = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]
        font_small = self.font_settings["Small"]
        font_tiny = self.font_settings["Tiny"]
        self.var_language = self.container_var["General Settings"]["Language"].get()
        self.update_variables_initial_values()
        self.parent["bg"] = self.bg_colors["BG Window"]

        ## 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="#2C2C2C")
            img.image = pysills_logo
            img.grid(
                row=start_row - 3, column=start_column, rowspan=n_rows_header, columnspan=common_n_columns + 11,
                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.")

        # FRAMES
        frm_00 = SE(
            parent=self.parent, row_id=start_row, column_id=start_column, n_rows=self.n_rows - 3,
            n_columns=common_n_columns + 11, fg=font_color_light, bg=background_color_header).create_frame(
            relief=tk.FLAT)
        frm_01 = SE(
            parent=self.parent, row_id=start_row + 2, column_id=start_column + 11, n_rows=n_rows_header + 4,
            n_columns=common_n_columns, fg=font_color_light, bg=background_color_elements).create_frame(relief=tk.FLAT)

        # LABELS
        var_lbl_00 = self.language_dict["Project"][self.var_language]
        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_04c = self.language_dict["Define ICP-MS"][self.var_language]
        var_lbl_dev = self.language_dict["PySILLS subtitle"][self.var_language]

        lbl_00 = 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=var_lbl_00, 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 + 13, 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 + 13, 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_04c = SE(
            parent=self.parent, row_id=start_row + 10, column_id=start_column, n_rows=common_n_rows,
            n_columns=common_n_columns, fg=font_color_light, bg=background_color_header).create_simple_label(
            text=var_lbl_04c, relief=tk.FLAT, fontsize=font_header)
        lbl_version = SE(
            parent=self.parent, row_id=start_row + 29, 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=font_tiny)
        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=var_lbl_dev, relief=tk.FLAT, fontsize=font_tiny, sticky="news")

        # LISTBOXES
        self.lb_std = SE(
            parent=self.parent, row_id=start_row + 17, column_id=start_column, n_rows=12,
            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 + 17, column_id=start_column + 11, n_rows=12,
            n_columns=common_n_columns, fg=font_color_dark, bg=background_color_listbox).create_simple_listbox()

        self.lb_std.configure(font=font_option)
        self.lb_smpl.configure(font=font_option)
        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", "Inclusion Analysis"]
            list_mode = ["Mineral Analysis", "Inclusion Analysis"]
        elif self.var_language == "German":
            #list_mode = ["Minerale", "Flüssigkeitseinschlüsse", "Schmelzeinschlüsse", "Einschlüsse"]
            list_mode = ["Minerale", "Einschlüsse"]
        elif self.var_language == "Chinese":
            str_01 = self.language_dict["Mineral Analysis"][self.var_language]
            str_02 = self.language_dict["Fluid Inclusions"][self.var_language]
            str_03 = self.language_dict["Melt Inclusions"][self.var_language]
            str_04 = "包含分析"
            #list_mode = [str_01, str_02, str_03, str_04]
            list_mode = [str_01, str_04]

        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_element, command=lambda var_rb=self.var_rb_mode:
                self.select_experiment(var_rb))
            if index == 0:
                self.rb_ma = rb_mode
            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]

        btn_01 = SE(
            parent=self.parent, row_id=start_row + 15, 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))
        btn_02 = SE(
            parent=self.parent, row_id=start_row + 16, 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))
        btn_03 = SE(
            parent=self.parent, row_id=start_row + 15, 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 + 16, 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_04 = SE(
            parent=self.parent, row_id=start_row + 15, 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))
        btn_05 = SE(
            parent=self.parent, row_id=start_row + 16, 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))
        btn_06 = SE(
            parent=self.parent, row_id=start_row + 15, 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 + 16, 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_07 = SE(
            parent=self.parent, row_id=start_row + 2, column_id=start_column, n_rows=common_n_rows,
            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)
        btn_08 = SE(
            parent=self.parent, row_id=start_row + 3, column_id=start_column, n_rows=common_n_rows,
            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 + 4, column_id=start_column, n_rows=common_n_rows,
            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")
        btn_09 = SE(
            parent=self.parent, row_id=start_row + 5, column_id=start_column, n_rows=common_n_rows,
            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 + 6, column_id=start_column, n_rows=common_n_rows,
            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)
        btn_10 = SE(
            parent=self.parent, row_id=start_row + 7, column_id=start_column, n_rows=common_n_rows,
            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 + 12, column_id=start_column, 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)

        btn_01.configure(font=font_element)
        btn_02.configure(font=font_element)
        btn_03.configure(font=font_element)
        btn_04.configure(font=font_element)
        btn_05.configure(font=font_element)
        btn_06.configure(font=font_element)
        btn_07.configure(font=font_element)
        btn_08.configure(font=font_element)
        btn_09.configure(font=font_element)
        btn_10.configure(font=font_element)
        btn_11_std.configure(font=font_element)
        btn_11_smpl.configure(font=font_element)
        self.btn_save_project.configure(font=font_element)
        btn_about.configure(font=font_element)
        btn_icp.configure(font=font_element)

        # OPTION MENUS
        opt_icp = SE(
            parent=self.parent, row_id=start_row + 11, 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_light, bg_active=accent_color,
            command=lambda var_opt=self.var_opt_icp: self.select_icp_ms(var_opt))
        opt_icp.configure(font=font_option)

    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."""
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_header = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_listbox = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        str_title = self.language_dict["ICP-MS file setup"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["ICP-MS setup"][0]
        n_columns = self.window_dimensions["ICP-MS setup"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_icpms_setup = tk.Toplevel(self.parent)
        self.subwindow_icpms_setup.title(str_title)
        self.subwindow_icpms_setup.geometry(var_geometry)
        self.subwindow_icpms_setup.resizable(False, False)
        self.subwindow_icpms_setup["bg"] = background_color_header

        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
        str_lbl_01 = self.language_dict["Name"][self.var_language]
        str_lbl_02 = self.language_dict["Line of time stamp"][self.var_language]
        str_lbl_03 = self.language_dict["Skip header"][self.var_language]
        str_lbl_04 = self.language_dict["Skip footer"][self.var_language]
        str_lbl_05 = self.language_dict["Save settings"][self.var_language]
        str_lbl_06 = self.language_dict["Save ICP-MS setup"][self.var_language]

        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=font_color_light, bg=background_color_header).create_simple_label(
            text=str_title, relief=tk.FLAT, fontsize=font_element)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_element)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize=font_element)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize=font_element)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize=font_element)

        # 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=font_color_dark,
            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=font_color_dark,
            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=font_color_dark,
            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=font_color_dark,
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["ICP-MS Info"]["skipfooter"], text_default=current_val_skipfooter)

        # BUTTONS
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent,
            bg=accent_color).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_accent,
            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=font_color_accent,
            bg=accent_color).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_accent,
            command=self.save_icpms_settings)

        btn_02.configure(font=font_element)
        btn_002.configure(font=font_element)

    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
        var_instrument_raw = "Select ICP-MS"

        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(" ", "_")
                if var_instrument != "Select_ICP-MS":
                    var_instrument_raw = var_opt
        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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
                    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 in ["FI", "INCL"]:
                    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 in ["FI", "INCL"]:
                    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 in ["FI", "INCL"]:
                    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 in ["FI", "INCL"]:
            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):
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_header = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_listbox = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_small = self.font_settings["Small"]

        start_row = 11
        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=font_color_light, bg=background_color_header).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

            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=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                command=self.ma_settings)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 3, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                command=self.ma_datareduction_files)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
                command=self.ma_extras)

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

        elif var_rb.get() == 3:  # Fluid Inclusions (1)
            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["BG Window"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

            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=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                command=self.fi_settings)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 3, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                command=self.fi_datareduction_files)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
                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["BG Window"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

            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=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                command=self.mi_settings)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 3, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                command=self.fi_datareduction_files)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
                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() == 1:  # Inclusion Analysis (3)
            self.pysills_mode = "INCL"
            ## 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["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["BG Window"]).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

            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=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                command=self.fi_settings)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 3, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                command=self.fi_datareduction_files)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
                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() == 4:  # 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["BG Window"]).create_simple_label(
                text="Report Analysis", relief=tk.FLAT, fontsize=font_header)

            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=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light)
            btn_02 = SE(
                parent=self.parent, row_id=start_row + 3, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light)
            btn_03 = SE(
                parent=self.parent, row_id=start_row + 4, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
                command=self.ma_datareduction_files)
            btn_03.configure(state="disabled")

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

        btn_01.configure(font=font_elements)
        btn_02.configure(font=font_elements)
        btn_03.configure(font=font_elements)

    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", "INCL"]:
                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", calculation=False):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        self.var_calculation = calculation

        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 in ["FI", "INCL"]:
                    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)

        if filetype == "STD":
            self.btn_09e2.configure(state="normal")
            self.initial_spike_elimination_std = True
        else:
            self.btn_09f2.configure(state="normal")
            self.initial_spike_elimination_smpl = True

    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]

        self.build_quick_plot_window(filetype=var_filetype, filename_long=file_long)

    def previous_quick_plot_file(self, filetype, filename_long, subwindow):
        index_filename = self.container_lists[filetype]["Long"].index(filename_long)

        if index_filename > 0:
            filename_long = self.container_lists[filetype]["Long"][index_filename - 1]
        else:
            filename_long = self.container_lists[filetype]["Long"][-1]

        subwindow.destroy()

        self.build_quick_plot_window(filetype=filetype, filename_long=filename_long)

    def next_quick_plot_file(self, filetype, filename_long, subwindow):
        index_filename = self.container_lists[filetype]["Long"].index(filename_long)

        if index_filename < len(self.container_lists[filetype]["Long"]) - 1:
            filename_long = self.container_lists[filetype]["Long"][index_filename + 1]
        else:
            filename_long = self.container_lists[filetype]["Long"][0]

        subwindow.destroy()

        self.build_quick_plot_window(filetype=filetype, filename_long=filename_long)

    def build_quick_plot_window(self, filetype, filename_long):
        var_filetype = filetype
        file_long = filename_long
        file_short = filename_long.split("/")[-1]
        file_isotopes = self.container_lists["Measured Isotopes"][file_short]

        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Quick plot"][0]
        n_columns = self.window_dimensions["Quick plot"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        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"]

        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
        n_rows_isotopes = n_rows - 15
        n_columns_isotopes = 8
        n_rows_diagram = n_rows_isotopes + 2
        n_columns_diagram = int(0.6*n_columns)
        n_columns_statistics = n_columns - n_columns_isotopes - n_columns_diagram
        row_display_opt = n_rows_isotopes + 1
        row_interval_opt = row_display_opt + 4
        n_columns_sections = int(n_columns_diagram/3)

        ## TRANSLATIONS
        str_var_01 = self.language_dict["Time-Signal Diagram"][self.var_language]
        str_var_02 = self.language_dict["Isotopes"][self.var_language]
        str_var_03 = self.language_dict["Data analysis"][self.var_language]
        str_var_04 = self.language_dict["Display options"][self.var_language]
        str_var_05 = self.language_dict["Interval options"][self.var_language]
        str_var_06 = self.language_dict["Background"][self.var_language]
        str_var_07 = self.language_dict["Matrix"][self.var_language]
        str_var_08 = self.language_dict["Inclusion"][self.var_language]
        str_var_09 = self.language_dict["Reference isotope"][self.var_language]
        str_var_10 = self.language_dict["Internal standard"][self.var_language]
        str_var_11 = self.language_dict["No selection"][self.var_language]
        str_var_12 = self.language_dict["Show all"][self.var_language]
        str_var_13 = self.language_dict["Hide all"][self.var_language]
        str_var_14 = self.language_dict["Remove interval"][self.var_language]
        str_var_15 = self.language_dict["Previous"][self.var_language]
        str_var_16 = self.language_dict["Next"][self.var_language]
        str_var_17 = self.language_dict["Additional analysis"][self.var_language]
        str_var_18 = self.language_dict["Sample"][self.var_language]

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_quickplotter, row_id=row_start, column_id=column_start + n_columns_isotopes, n_rows=1,
            n_columns=n_columns_diagram, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["BG Window"]).create_simple_label(
            text=str_var_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_02 = SE(
            parent=subwindow_quickplotter, row_id=row_start, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["BG Window"]).create_simple_label(
            text=str_var_02, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_03 = SE(
            parent=subwindow_quickplotter, row_id=row_start,
            column_id=column_start + n_columns_isotopes + n_columns_diagram, n_rows=1, n_columns=n_columns_statistics,
            fg=self.bg_colors["Light Font"], bg=self.bg_colors["BG Window"]).create_simple_label(
            text=str_var_03, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_04 = SE(
            parent=subwindow_quickplotter, row_id=row_display_opt, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["BG Window"]).create_simple_label(
            text=str_var_04, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_05 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["BG Window"]).create_simple_label(
            text=str_var_05, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_06 = SE(
            parent=subwindow_quickplotter, row_id=n_rows - 3, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["BG Window"]).create_simple_label(
            text="", relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_07 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt, column_id=column_start + n_columns_isotopes,
            n_rows=1, n_columns=n_columns_sections, fg=self.colors_intervals["BG LB"],
            bg=self.colors_intervals["BG"]).create_simple_label(
            text=str_var_06, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_08 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt,
            column_id=column_start + n_columns_isotopes + n_columns_sections, n_rows=1, n_columns=n_columns_sections,
            fg=self.colors_intervals["MAT LB"], bg=self.colors_intervals["MAT"]).create_simple_label(
            text=str_var_07, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_09 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt,
            column_id=column_start + n_columns_isotopes + 2*n_columns_sections, n_rows=1, n_columns=n_columns_sections,
            fg=self.colors_intervals["INCL LB"], bg=self.colors_intervals["INCL"]).create_simple_label(
            text=str_var_08, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)

        if var_filetype == "STD":
            lbl_10 = SE(
                parent=subwindow_quickplotter, row_id=row_start + 1,
                column_id=column_start + n_columns_isotopes + n_columns_diagram, n_rows=1,
                n_columns=int(n_columns_statistics/2), fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Very Light"]).create_simple_label(
                text=str_var_09, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        elif var_filetype == "SMPL":
            lbl_10 = SE(
                parent=subwindow_quickplotter, row_id=row_start + 1,
                column_id=column_start + n_columns_isotopes + n_columns_diagram, n_rows=1,
                n_columns=int(n_columns_statistics/2), fg=self.bg_colors["Dark Font"],
                bg=self.bg_colors["Very Light"]).create_simple_label(
                text=str_var_10, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)

        ## OPTION MENU
        self.qpl_opt_is = tk.StringVar()
        self.qpl_opt_is.set("Select isotope")

        opt_is = SE(
            parent=subwindow_quickplotter, row_id=row_start + 1,
            column_id=column_start + n_columns_isotopes + n_columns_diagram + int(n_columns_statistics/2), n_rows=1,
            n_columns=int(n_columns_statistics/2), fg=font_color_dark,
            bg=background_color_elements).create_option_isotope(
            var_iso=self.qpl_opt_is, option_list=file_isotopes, text_set=self.qpl_opt_is.get(),
            fg_active=font_color_light, bg_active=accent_color)

        ## RADIOBUTTONS
        rb_01 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 2, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["Radiobuttons"]["Quick Plot File"], value_rb=0, color_bg=self.bg_colors["Light"],
            fg=self.bg_colors["Dark Font"], text=str_var_06, sticky="nesw", relief=tk.FLAT,
            command=lambda var_type=var_filetype, var_file_short=file_short, list_isotopes=file_isotopes, section="BG":
            self.fill_tv_quick_plot_file(var_type, var_file_short, list_isotopes, section))
        rb_02 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 3, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["Radiobuttons"]["Quick Plot File"], value_rb=1, color_bg=self.bg_colors["Light"],
            fg=self.bg_colors["Dark Font"], text=str_var_07, sticky="nesw", relief=tk.FLAT,
            command=lambda var_type=var_filetype, var_file_short=file_short, list_isotopes=file_isotopes, section="MAT":
            self.fill_tv_quick_plot_file(var_type, var_file_short, list_isotopes, section))
        rb_03 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 4, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["Radiobuttons"]["Quick Plot File"], value_rb=2, color_bg=self.bg_colors["Light"],
            fg=self.bg_colors["Dark Font"], text=str_var_08, sticky="nesw", relief=tk.FLAT,
            command=lambda var_type=var_filetype, var_file_short=file_short, list_isotopes=file_isotopes,
                           section="INCL":
            self.fill_tv_quick_plot_file(var_type, var_file_short, list_isotopes, section))
        rb_04 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 1, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=self.container_var["Radiobuttons"]["Quick Plot File"], value_rb=3, color_bg=self.bg_colors["Light"],
            fg=self.bg_colors["Dark Font"], text=str_var_11, sticky="nesw", relief=tk.FLAT)

        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]

        if file_short not in self.container_measurements["Dataframe"]:
            self.container_measurements["Dataframe"][file_short] = df_data

        list_keys = list(df_data.columns.values)
        del list_keys[0]
        dataset_time = list(df_data.iloc[:, 0])
        self.dataset_time = dataset_time
        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, n_rows=n_rows_isotopes,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_frame(relief=tk.FLAT)
        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()
        text.configure(state="disabled")

        ## 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)
        self.var_ax = var_ax

        # Canvas
        self.var_canvas_qpl = FigureCanvasTkAgg(var_fig, master=subwindow_quickplotter)
        self.var_canvas_qpl.get_tk_widget().grid(
            row=row_start + 1, column=column_start + n_columns_isotopes, rowspan=n_rows_diagram,
            columnspan=n_columns_diagram, sticky="nesw")
        # Toolbar
        var_toolbarFrame = tk.Frame(master=subwindow_quickplotter)
        var_toolbarFrame.grid(
            row=n_rows_diagram + 1, column=column_start + n_columns_isotopes, rowspan=2, columnspan=n_columns_diagram,
            sticky="ew")
        var_toolbar = NavigationToolbar2Tk(self.var_canvas_qpl, 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": self.var_canvas_qpl, "Toolbar": var_toolbar, "Axes": var_ax}

        self.var_canvas_qpl.mpl_connect(
            "button_press_event", lambda event, var_type=filetype, var_file_short=file_short:
            self.add_interval_to_diagram_qpl(var_type, var_file_short, event))

        ## BUTTONS
        btn_01 = SE(
            parent=subwindow_quickplotter, row_id=row_display_opt + 1, column_id=column_start, n_rows=1,
            n_columns=n_columns_isotopes, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Light"]).create_simple_button(
            text=str_var_12, 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=row_display_opt + 2,
            column_id=column_start, n_rows=1, n_columns=n_columns_isotopes,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text=str_var_13, 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))
        btn_06 = SE(
            parent=subwindow_quickplotter, row_id=row_display_opt + 3,
            column_id=column_start, n_rows=1, n_columns=n_columns_isotopes,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text=str_var_17, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_type=var_filetype, var_file_short=file_short:
            self.qpl_additional_diagrams(var_type, var_file_short))
        btn_03 = SE(
            parent=subwindow_quickplotter, row_id=n_rows - 2,
            column_id=column_start, n_rows=2, n_columns=int(n_columns_isotopes/2),
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text=str_var_15, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype=var_filetype, filename_long=file_long, subwindow=subwindow_quickplotter:
            self.previous_quick_plot_file(filetype, filename_long, subwindow))
        btn_04 = SE(
            parent=subwindow_quickplotter, row_id=n_rows - 2,
            column_id=column_start + int(n_columns_isotopes/2), n_rows=2, n_columns=int(n_columns_isotopes/2),
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text=str_var_16, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype=var_filetype, filename_long=file_long, subwindow=subwindow_quickplotter:
            self.next_quick_plot_file(filetype, filename_long, subwindow))
        btn_05 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 5,
            column_id=column_start, n_rows=2, n_columns=n_columns_isotopes,
            fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_simple_button(
            text=str_var_14, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_type=var_filetype, var_file_short=file_short:
            self.remove_interval_qpl(var_type, var_file_short))

        btn_01.configure(font=font_elements)
        btn_02.configure(font=font_elements)
        btn_03.configure(font=font_elements)
        btn_04.configure(font=font_elements)
        btn_05.configure(font=font_elements)
        btn_06.configure(font=font_elements)

        ## CHECKBOXES
        self.qpl_cb_bg = tk.IntVar()
        self.qpl_cb_mat = tk.IntVar()
        self.qpl_cb_incl = tk.IntVar()
        self.qpl_cb_bg.set(1)
        self.qpl_cb_mat.set(1)
        self.qpl_cb_incl.set(1)

        cb_01 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt,
            column_id=column_start + n_columns_isotopes + (n_columns_sections - 1), n_rows=1, n_columns=1,
            fg=self.bg_colors["Dark Font"], bg=self.colors_intervals["BG"]).create_simple_checkbox(
            var_cb=self.qpl_cb_bg, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Background", var_type=var_filetype, var_file_short=file_short:
            self.show_or_hide_interval(key, var_type, var_file_short))
        cb_02 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt,
            column_id=column_start + n_columns_isotopes + n_columns_sections + (n_columns_sections - 1), n_rows=1,
            n_columns=1, fg=self.bg_colors["Dark Font"], bg=self.colors_intervals["MAT"]).create_simple_checkbox(
            var_cb=self.qpl_cb_mat, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Matrix", var_type=var_filetype, var_file_short=file_short:
            self.show_or_hide_interval(key, var_type, var_file_short))
        cb_03 = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt,
            column_id=column_start + n_columns_isotopes + 2*n_columns_sections + (n_columns_sections - 1), n_rows=1,
            n_columns=1, fg=self.bg_colors["Dark Font"], bg=self.colors_intervals["INCL"]).create_simple_checkbox(
            var_cb=self.qpl_cb_incl, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Inclusion", var_type=var_filetype, var_file_short=file_short:
            self.show_or_hide_interval(key, var_type, var_file_short))

        cb_01.configure(font=font_elements, onvalue=1, offvalue=0)
        cb_02.configure(font=font_elements, onvalue=1, offvalue=0)
        cb_03.configure(font=font_elements, onvalue=1, offvalue=0)

        ## TREEVIEW
        self.tv_quick_file_statistics = SE(
            parent=subwindow_quickplotter, row_id=row_start + 2,
            column_id=column_start + n_columns_isotopes + n_columns_diagram, n_rows=n_rows - 2,
            n_columns=n_columns_statistics, fg=font_color_dark, bg=self.bg_colors["White"]).create_treeview(
            n_categories=4, text_n=["Isotope", "\u03bc", "\u03c3", "I(i)/I(IS)"],
            width_n=["88", "110", "110", "110"], individual=True)

        style = ttk.Style()
        style.configure("Treeview", font=font_table)
        style.configure("Treeview.Heading", font=font_elements)

        ## LISTBOXES
        self.lb_quick_plot_file_bg = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 1, column_id=column_start + n_columns_isotopes,
            n_rows=n_rows - 26, n_columns=n_columns_sections, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["BG LB"]).create_simple_listbox()
        self.lb_quick_plot_file_mat = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 1,
            column_id=column_start + n_columns_isotopes + n_columns_sections, n_rows=n_rows - 26,
            n_columns=n_columns_sections, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["MAT LB"]).create_simple_listbox()
        self.lb_quick_plot_file_incl = SE(
            parent=subwindow_quickplotter, row_id=row_interval_opt + 1,
            column_id=column_start + n_columns_isotopes + 2*n_columns_sections, n_rows=n_rows - 26,
            n_columns=n_columns_sections, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["INCL LB"]).create_simple_listbox()

        ## INITIALIZATION
        self.helper_intervals = {"BG": [], "MAT": [], "INCL": []}

        if var_filetype not in self.container_helper:
            self.container_helper[var_filetype] = {}
            if file_short not in self.container_helper[var_filetype]:
                self.container_helper[var_filetype][file_short] = {}
                if "AXES" not in self.container_helper[var_filetype][file_short]:
                    self.container_helper[var_filetype][file_short]["AXES"] = {
                        "Quick Plot": var_ax, "Canvas QPL": self.var_canvas_qpl}
        else:
            if file_short not in self.container_helper[var_filetype]:
                self.build_container_helper(mode=var_filetype)

            for key in ["BG", "MAT", "INCL"]:
                if key not in self.container_helper[var_filetype][file_short]:
                    self.container_helper[var_filetype][file_short][key] = {"ID": 0, "Content": {}, "Indices": []}

            if "Quick Plot" not in self.container_helper[var_filetype][file_short]["AXES"]:
                self.container_helper[var_filetype][file_short]["AXES"] = {
                    "Quick Plot": var_ax, "Canvas QPL": self.var_canvas_qpl}

        if self.pysills_mode == "MA":
            lbl_08.configure(text=str_var_18)
            rb_02.configure(text=str_var_18)
            rb_03.configure(state="disabled")
            cb_03.configure(state="disabled")
            self.qpl_cb_incl.set(0)
            self.lb_quick_plot_file_incl.configure(state="disabled")

        self.fill_tv_quick_plot_file(
            var_type=var_filetype, var_file_short=file_short, list_isotopes=file_isotopes, init=True)
        self.check_for_intervals_qpl(filetype=var_filetype, filename_short=file_short)

    def qpl_additional_diagrams(self, var_type, var_file_short):
        list_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
        df_data = self.container_measurements["Dataframe"][var_file_short]
        list_keys = list_isotopes.copy()
        list_keys.insert(0, "None")
        list_keys.insert(1, "Time")

        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Quick Plot Extra"][0]
        n_columns = self.window_dimensions["Quick Plot Extra"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_qpl_extra = tk.Toplevel(self.parent)
        subwindow_qpl_extra.title("Quick Plotter")
        subwindow_qpl_extra.geometry(var_geometry)
        subwindow_qpl_extra.resizable(False, False)
        subwindow_qpl_extra["bg"] = background_color_light

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

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

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

        row_start = 0
        column_start = 0
        n_rows_navigation = n_rows
        n_colums_navigation = int(1/3*n_columns)
        n_columns_plot = n_columns - n_colums_navigation
        rows_tv = n_rows - 12
        n_rows_tv = 12

        ## TRANSLATIONS
        str_var_01 = self.language_dict["Plotting setup"][self.var_language]
        str_var_02 = self.language_dict["Isotope selection"][self.var_language]
        str_var_03 = self.language_dict["Section selection"][self.var_language]
        str_var_04 = self.language_dict["Color coding"][self.var_language]
        str_var_05 = self.language_dict["Diagram selection"][self.var_language]
        str_var_06 = self.language_dict["Data analysis"][self.var_language]
        str_var_07 = self.language_dict["Background"][self.var_language]
        str_var_08 = self.language_dict["Matrix"][self.var_language]
        str_var_09 = self.language_dict["Inclusion"][self.var_language]
        str_var_10 = self.language_dict["Scatter plot"][self.var_language]
        str_var_11 = self.language_dict["Histogram plot"][self.var_language]
        str_var_12 = self.language_dict["Sample"][self.var_language]

        ## FRAMES
        frm_01 = SE(
            parent=subwindow_qpl_extra, row_id=row_start, column_id=column_start, n_rows=n_rows_navigation,
            n_columns=n_colums_navigation, fg=font_color_dark, bg=background_color_dark).create_frame(relief=tk.FLAT)

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_qpl_extra, row_id=row_start, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_02 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 1, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_02, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_02a = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 2, column_id=column_start, n_rows=1,
            n_columns=2, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="x", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_02b = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 3, column_id=column_start, n_rows=1,
            n_columns=2, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="y", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_03 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 4, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_03, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_04 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 8, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_04, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_04a = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 9, column_id=column_start, n_rows=1,
            n_columns=2, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="z", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_05 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 10, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_05, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_06 = SE(
            parent=subwindow_qpl_extra, row_id=row_start, column_id=column_start + n_colums_navigation, n_rows=1,
            n_columns=n_columns_plot, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="", relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_07 = SE(
            parent=subwindow_qpl_extra, row_id=rows_tv - 1, column_id=column_start + n_colums_navigation, n_rows=1,
            n_columns=n_columns_plot, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_06, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)

        self.lbl_qpl_extra_06 = lbl_06

        ## RADIOBUTTONS
        self.var_rb_qpl_extra_01 = tk.IntVar()
        self.var_rb_qpl_extra_01.set(1)
        self.var_rb_qpl_extra_02 = tk.IntVar()
        self.var_rb_qpl_extra_02.set(0)

        var_filetype = var_type
        var_filename_short = var_file_short
        var_list_isotopes = list_isotopes
        var_row_start = row_start
        var_column_start = column_start
        var_df_data = df_data

        rb_01 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 5, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_dark,
            bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_qpl_extra_01, value_rb=0, color_bg=background_color_elements,
            fg=font_color_dark, text=str_var_07, sticky="nesw", relief=tk.FLAT,
            command=lambda var_type=var_filetype, var_file_short=var_filename_short, list_isotopes=var_list_isotopes,
                           section="BG":
            self.fill_tv_qpl_extra(var_type, var_file_short, list_isotopes, section))
        rb_02 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 6, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_dark,
            bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_qpl_extra_01, value_rb=1, color_bg=background_color_elements,
            fg=font_color_dark, text=str_var_08, sticky="nesw", relief=tk.FLAT,
            command=lambda var_type=var_filetype, var_file_short=var_filename_short, list_isotopes=var_list_isotopes,
                           section="MAT":
            self.fill_tv_qpl_extra(var_type, var_file_short, list_isotopes, section))
        rb_03 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 7, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_dark,
            bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_qpl_extra_01, value_rb=2, color_bg=background_color_elements,
            fg=font_color_dark, text=str_var_09, sticky="nesw", relief=tk.FLAT,
            command=lambda var_type=var_filetype, var_file_short=var_filename_short, list_isotopes=var_list_isotopes,
                           section="INCL":
            self.fill_tv_qpl_extra(var_type, var_file_short, list_isotopes, section))
        rb_04 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 11, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_dark,
            bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_qpl_extra_02, value_rb=0, color_bg=background_color_elements,
            fg=font_color_dark, text=str_var_10, sticky="nesw", relief=tk.FLAT,
            command=lambda filetype=var_filetype, filename_short=var_filename_short, df_data=var_df_data,
                           subwindow=subwindow_qpl_extra, row_start=var_row_start + 1,
                           column_start=var_column_start + n_colums_navigation, n_rows_diagram=n_rows - 14,
                           n_columns_diagram=n_columns_plot, init=False:
            self.create_qpl_extra_diagram(filetype, filename_short, df_data, subwindow, row_start, column_start,
                                          n_rows_diagram, n_columns_diagram, init))
        rb_05 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 12, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_dark,
            bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_qpl_extra_02, value_rb=1, color_bg=background_color_elements,
            fg=font_color_dark, text=str_var_11, sticky="nesw", relief=tk.FLAT,
            command=lambda filetype=var_filetype, filename_short=var_filename_short, df_data=var_df_data,
                           subwindow=subwindow_qpl_extra, row_start=var_row_start + 1,
                           column_start=var_column_start + n_colums_navigation, n_rows_diagram=n_rows - 14,
                           n_columns_diagram=n_columns_plot, init=False:
            self.create_qpl_extra_diagram(filetype, filename_short, df_data, subwindow, row_start, column_start,
                                          n_rows_diagram, n_columns_diagram, init))

        #rb_05.configure(state="disabled")

        if self.pysills_mode == "MA":
            rb_02.configure(text=str_var_12)
            rb_03.configure(state="disabled")

        ## OPTION MENUS
        self.var_opt_qpl_extra_01 = tk.StringVar()
        self.var_opt_qpl_extra_01.set("Select isotope")
        self.var_opt_qpl_extra_02 = tk.StringVar()
        self.var_opt_qpl_extra_02.set("Select isotope")
        self.var_opt_qpl_extra_03 = tk.StringVar()
        self.var_opt_qpl_extra_03.set(list_keys[0])

        opt_01 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 2, column_id=column_start + 2, n_rows=1,
            n_columns=n_colums_navigation - 2, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.var_opt_qpl_extra_01, option_list=list_isotopes, text_set=self.var_opt_qpl_extra_01.get(),
            fg_active=font_color_light, bg_active=accent_color,
            command=lambda filetype=var_filetype, filename_short=var_filename_short, df_data=var_df_data,
                           subwindow=subwindow_qpl_extra, row_start=var_row_start + 1,
                           column_start=var_column_start + n_colums_navigation, n_rows_diagram=n_rows - 14,
                           n_columns_diagram=n_columns_plot, init=False:
            self.create_qpl_extra_diagram(filetype, filename_short, df_data, subwindow, row_start, column_start,
                                          n_rows_diagram, n_columns_diagram, init))
        opt_02 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 3, column_id=column_start + 2, n_rows=1,
            n_columns=n_colums_navigation - 2, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.var_opt_qpl_extra_02, option_list=list_isotopes, text_set=self.var_opt_qpl_extra_02.get(),
            fg_active=font_color_light, bg_active=accent_color,
            command=lambda filetype=var_type, filename_short=var_file_short, df_data=var_df_data,
            subwindow=subwindow_qpl_extra, row_start=var_row_start + 1,
                           column_start=var_column_start + n_colums_navigation, n_rows_diagram=n_rows - 14,
                           n_columns_diagram=n_columns_plot:
            self.create_qpl_scatter_plot(filetype, filename_short, df_data, subwindow, row_start, column_start,
                                         n_rows_diagram, n_columns_diagram))
        opt_03 = SE(
            parent=subwindow_qpl_extra, row_id=row_start + 9, column_id=column_start + 2, n_rows=1,
            n_columns=n_colums_navigation - 2, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.var_opt_qpl_extra_03, option_list=list_keys, text_set=self.var_opt_qpl_extra_03.get(),
            fg_active=font_color_light, bg_active=accent_color,
            command=lambda filetype=var_type, filename_short=var_file_short, df_data=var_df_data,
            subwindow=subwindow_qpl_extra, row_start=var_row_start + 1,
                           column_start=var_column_start + n_colums_navigation, n_rows_diagram=n_rows - 14,
                           n_columns_diagram=n_columns_plot:
            self.create_qpl_scatter_plot(filetype, filename_short, df_data, subwindow, row_start, column_start,
                                         n_rows_diagram, n_columns_diagram))

        ## TREEVIEWS
        list_widths = 6*[112]
        list_widths[0] = 80

        self.tv_qpl_extra = SE(
            parent=subwindow_qpl_extra, row_id=rows_tv, column_id=column_start + n_colums_navigation, n_rows=n_rows_tv,
            n_columns=n_columns_plot, fg=font_color_dark, bg=self.bg_colors["White"]).create_treeview(
            n_categories=6, text_n=["Isotope", "Minimum", "Maximum", "\u03bc", "\u03c3", "I(i)/I(IS)"],
            width_n=list_widths, individual=True)

        style = ttk.Style()
        style.configure("Treeview", font=font_table)
        style.configure("Treeview.Heading", font=font_elements)

        ## INITIALIZATION
        self.fill_tv_qpl_extra(
            var_type=var_type, var_file_short=var_file_short, list_isotopes=list_isotopes, init=True)
        self.create_qpl_scatter_plot(
            filetype=var_type, filename_short=var_file_short, df_data=df_data, subwindow=subwindow_qpl_extra,
            row_start=row_start + 1, column_start=column_start + n_colums_navigation, n_rows_diagram=n_rows - 14,
            n_columns_diagram=n_columns_plot, init=True)

        n_intervals = 0
        for section in ["BG", "MAT", "INCL"]:
            n_intervals += len(self.container_helper[var_type][var_file_short][section]["Indices"])

        if n_intervals > 0:
            if len(self.container_helper[var_type][var_file_short]["BG"]["Indices"]) == 0:
                rb_01.configure(state="disabled")
            elif len(self.container_helper[var_type][var_file_short]["MAT"]["Indices"]) == 0:
                rb_02.configure(state="disabled")
            elif len(self.container_helper[var_type][var_file_short]["INCL"]["Indices"]) == 0:
                rb_03.configure(state="disabled")
        else:
            rb_01.configure(state="disabled")
            rb_02.configure(state="disabled")
            rb_03.configure(state="disabled")
            rb_04.configure(state="disabled")
            rb_05.configure(state="disabled")

            opt_01.configure(state="disabled")
            opt_02.configure(state="disabled")
            opt_03.configure(state="disabled")

    def create_qpl_extra_diagram(self, filetype, filename_short, df_data, subwindow, row_start, column_start,
                                  n_rows_diagram, n_columns_diagram, init=False):
        if self.var_rb_qpl_extra_02.get() == 0: # Scatter
            self.create_qpl_scatter_plot(
                filetype, filename_short, df_data, subwindow, row_start, column_start, n_rows_diagram,
                n_columns_diagram, init)
        elif self.var_rb_qpl_extra_02.get() == 1: # Histogram
            self.create_qpl_histogram_plot(
                filetype, filename_short, df_data, subwindow, row_start, column_start, n_rows_diagram,
                n_columns_diagram, init)

    def create_qpl_histogram_plot(self, filetype, filename_short, df_data, subwindow, row_start, column_start,
                                  n_rows_diagram, n_columns_diagram, init=False):
        # Data preparation
        list_isotopes = list(df_data.keys())[1:]
        if filename_short in self.container_lists["STD"]["Short"]:
            filetype = "STD"
        elif filename_short in self.container_lists["SMPL"]["Short"]:
            filetype = "SMPL"

        if init == False:
            var_x = self.var_opt_qpl_extra_01.get()
            var_y = self.var_opt_qpl_extra_02.get()
            var_z = self.var_opt_qpl_extra_03.get()
        else:
            var_x = list_isotopes[0]
            var_y = list_isotopes[1]
            var_z = list_isotopes[2]

        if self.var_rb_qpl_extra_01.get() == 0:
            section = "BG"
        elif self.var_rb_qpl_extra_01.get() == 1:
            section = "MAT"
        elif self.var_rb_qpl_extra_01.get() == 2:
            section = "INCL"

        var_section = section

        if (len(self.container_helper[filetype][filename_short][section]["Indices"]) > 0 and
                "Select isotope" not in [var_x, var_y]):
            condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                interval_set=self.container_helper[filetype][filename_short][section]["Content"])
            helper_data = {}

            helper_data[var_x] = []
            helper_data[var_y] = []
            for index, interval in condensed_intervals.items():
                start_index = interval[0]
                end_index = interval[1] + 1
                dataset_x = df_data[var_x][start_index:end_index]
                dataset_y = df_data[var_y][start_index:end_index]
                if var_z != "None" and var_z not in [var_x, var_y]:
                    if var_z not in helper_data:
                        helper_data[var_z] = []

                    dataset_z = df_data[var_z][start_index:end_index]
                    helper_data[var_z].extend(list(dataset_z))

                helper_data[var_x].extend(list(dataset_x))
                helper_data[var_y].extend(list(dataset_y))

            data_x = helper_data[var_x]
            data_y = helper_data[var_y]

            min_x = min(data_x)
            max_x = max(data_x)
            min_y = min(data_y)
            max_y = max(data_y)
            lim_x_min, lim_x_max = self.round_to_the_next_natural_limit(minimum=min_x, maximum=max_x)
            lim_y_min, lim_y_max = self.round_to_the_next_natural_limit(minimum=min_y, maximum=max_y)

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

            n_bins = 30
            var_ax.hist(data_x, bins=n_bins, color=self.accent_color, edgecolor="black")

            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(filename_short, fontsize=9)
            var_ax.set_xlabel("Signal " + var_x + " (cps)", labelpad=0.5, fontsize="x-small")
            var_ax.set_ylabel("Frequency", labelpad=0.5, fontsize="x-small")
            var_ax.xaxis.set_tick_params(labelsize="x-small")
            var_ax.yaxis.set_tick_params(labelsize="x-small")

            self.var_canvas_qpl_extra = FigureCanvasTkAgg(var_fig, master=subwindow)
            self.var_canvas_qpl_extra.get_tk_widget().grid(
                row=row_start, column=column_start, rowspan=n_rows_diagram, columnspan=n_columns_diagram, sticky="nesw")

            # TREEVIEW UPDATE
        self.fill_tv_qpl_extra(
            var_type=filetype, var_file_short=filename_short, list_isotopes=list_isotopes, section=var_section,
            isotope_is=var_x)

    def create_qpl_scatter_plot(
            self, filetype, filename_short, df_data, subwindow, row_start, column_start, n_rows_diagram,
            n_columns_diagram, init=False):
        # Data preparation
        list_isotopes = list(df_data.keys())[1:]
        if filename_short in self.container_lists["STD"]["Short"]:
            filetype = "STD"
        elif filename_short in self.container_lists["SMPL"]["Short"]:
            filetype = "SMPL"

        if init == False:
            var_x = self.var_opt_qpl_extra_01.get()
            var_y = self.var_opt_qpl_extra_02.get()
            var_z = self.var_opt_qpl_extra_03.get()
        else:
            var_x = list_isotopes[0]
            var_y = list_isotopes[1]
            var_z = list_isotopes[2]

        if self.var_rb_qpl_extra_01.get() == 0:
            section = "BG"
        elif self.var_rb_qpl_extra_01.get() == 1:
            section = "MAT"
        elif self.var_rb_qpl_extra_01.get() == 2:
            section = "INCL"

        var_section = section

        if (len(self.container_helper[filetype][filename_short][section]["Indices"]) > 0 and
                "Select isotope" not in [var_x, var_y]):
            condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                interval_set=self.container_helper[filetype][filename_short][section]["Content"])
            helper_data = {}

            helper_data[var_x] = []
            helper_data[var_y] = []
            for index, interval in condensed_intervals.items():
                start_index = interval[0]
                end_index = interval[1] + 1
                dataset_x = df_data[var_x][start_index:end_index]
                dataset_y = df_data[var_y][start_index:end_index]
                if var_z != "None" and var_z not in [var_x, var_y]:
                    if "Time" not in var_z:
                        pass
                    else:
                        if "Time" not in list(df_data.keys()):
                            if list(df_data.keys())[0] not in list_isotopes:
                                var_z = list(df_data.keys())[0]

                    if var_z not in helper_data:
                        helper_data[var_z] = []

                    dataset_z = df_data[var_z][start_index:end_index]
                    helper_data[var_z].extend(list(dataset_z))

                helper_data[var_x].extend(list(dataset_x))
                helper_data[var_y].extend(list(dataset_y))

            data_x = helper_data[var_x]
            data_y = helper_data[var_y]

            min_x = min(data_x)
            max_x = max(data_x)
            min_y = min(data_y)
            max_y = max(data_y)
            lim_x_min, lim_x_max = self.round_to_the_next_natural_limit(minimum=min_x, maximum=max_x)
            lim_y_min, lim_y_max = self.round_to_the_next_natural_limit(minimum=min_y, maximum=max_y)

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

            if var_z == "None":
                sct = var_ax.scatter(data_x, data_y, edgecolor="black")
            else:
                data_z = helper_data[var_z]

                min_z = min(data_z)
                max_z = max(data_z)
                sct = var_ax.scatter(data_x, data_y, c=data_z, edgecolor="black")
                cbar = var_fig.colorbar(sct, ax=var_ax)
                cbar.set_ticks(np.linspace(min_z, max_z, 6, endpoint=True))
                cbar.ax.tick_params(labelsize="x-small")
                if var_z != "Time" and "Time" not in var_z:
                    cbar.set_label("Signal " + var_z + " (cps)", fontsize=8)
                else:
                    cbar.set_label("Time (s)", fontsize="x-small")

            var_ax.grid(True)
            var_ax.set_xlim(left=lim_x_min, right=lim_x_max)
            var_ax.set_xticks(np.linspace(lim_x_min, lim_x_max, 6, endpoint=True))
            var_ax.set_ylim(bottom=lim_y_min, top=lim_y_max)
            var_ax.set_yticks(np.linspace(lim_y_min, lim_y_max, 6, endpoint=True))
            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(filename_short, fontsize=9)
            var_ax.set_xlabel("Signal " + var_x + " (cps)", labelpad=0.5, fontsize="x-small")
            var_ax.set_ylabel("Signal " + var_y + " (cps)", labelpad=0.5, fontsize="x-small")
            var_ax.xaxis.set_tick_params(labelsize="x-small")
            var_ax.yaxis.set_tick_params(labelsize="x-small")

            self.var_canvas_qpl_extra = FigureCanvasTkAgg(var_fig, master=subwindow)
            self.var_canvas_qpl_extra.get_tk_widget().grid(
                row=row_start, column=column_start, rowspan=n_rows_diagram, columnspan=n_columns_diagram, sticky="nesw")

        # TREEVIEW UPDATE
        self.fill_tv_qpl_extra(
            var_type=filetype, var_file_short=filename_short, list_isotopes=list_isotopes, section=var_section,
            isotope_is=var_x)

    def round_to_the_next_natural_limit(self, minimum, maximum):
        data_range = maximum - minimum
        scale_order = np.floor(np.log10(data_range))
        rounding_factor = 10**scale_order

        lim_min = np.floor(minimum/rounding_factor)*rounding_factor

        if lim_min == minimum:
            lim_min = lim_min
        else:
            lim_min = rounding_factor*np.floor(minimum/rounding_factor)

        lim_max = np.ceil(maximum/rounding_factor)*rounding_factor
        if lim_max == maximum:
            lim_max = lim_max
        else:
            lim_max = rounding_factor*np.ceil(maximum/rounding_factor)

        return lim_min, lim_max

    def fill_tv_qpl_extra(self, var_type, var_file_short, list_isotopes, section="MAT", init=False, isotope_is=None):
        if init == True:
            for isotope in list_isotopes:
                helper_values = [isotope, "---", "---", "---", "---", "---"]
                self.tv_qpl_extra.insert("", tk.END, values=helper_values)
        else:
            if len(self.tv_qpl_extra.get_children()) > 0:
                for item in self.tv_qpl_extra.get_children():
                    self.tv_qpl_extra.delete(item)

            if len(self.container_helper[var_type][var_file_short][section]["Indices"]) > 0:
                df_data  = self.container_measurements["Dataframe"][var_file_short]
                condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                    interval_set=self.container_helper[var_type][var_file_short][section]["Content"])

                if isotope_is == None:
                    reference_is = self.var_opt_qpl_extra_01.get()
                else:
                    reference_is = isotope_is
                if reference_is != "Select isotope":
                    isotope_is = reference_is
                    for isotope in list_isotopes:
                        helper = {"Min": [], "Max": [], "Mean": [], "Standard deviation": [], "Ratio": []}
                        for index, interval in condensed_intervals.items():
                            start_index = interval[0]
                            end_index = interval[1] + 1
                            dataset_i = df_data[isotope][start_index:end_index]
                            dataset_is = df_data[isotope_is][start_index:end_index]
                            helper["Min"].append(min(dataset_i))
                            helper["Max"].append(max(dataset_i))
                            helper["Mean"].append(np.mean(dataset_i))
                            helper["Standard deviation"].append(np.std(dataset_i, ddof=1))
                            helper["Ratio"].append(np.mean(dataset_i)/np.mean(dataset_is))
                        helper_values = [
                            isotope, round(np.mean(helper["Min"]), 2), round(np.mean(helper["Max"]), 2),
                            round(np.mean(helper["Mean"]), 2), round(np.mean(helper["Standard deviation"]), 2),
                            "{:0.2e}".format(np.mean(helper["Ratio"]))]
                        self.tv_qpl_extra.insert("", tk.END, values=helper_values)
                else:
                    for isotope in list_isotopes:
                        helper_values = [isotope, "---", "---", "---", "---", "---"]
                        self.tv_qpl_extra.insert("", tk.END, values=helper_values)

            else:
                for isotope in list_isotopes:
                    helper_values = [isotope, "---", "---", "---", "---", "---"]
                    self.tv_qpl_extra.insert("", tk.END, values=helper_values)

    def add_interval_to_diagram_qpl(self, var_type, var_file_short, event):
        filename_index = self.container_lists[var_type]["Short"].index(var_file_short)
        var_file_long = self.container_lists[var_type]["Long"][filename_index]

        if self.container_var["Radiobuttons"]["Quick Plot File"].get() == 0:    # BG
            var_key = "BG"
            var_color = self.colors_intervals[var_key]
        elif self.container_var["Radiobuttons"]["Quick Plot File"].get() == 1:  # MAT
            var_key = "MAT"
            var_color = self.colors_intervals[var_key]
        elif self.container_var["Radiobuttons"]["Quick Plot File"].get() == 2:  # INCL
            var_key = "INCL"
            var_color = self.colors_intervals[var_key]

        if self.container_var["Radiobuttons"]["Quick Plot File"].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.var_ax.axvspan(time_0, time_1, alpha=0.35, color=var_color)
                self.var_canvas_qpl.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}

                if var_key == "BG":
                    var_lb = self.lb_quick_plot_file_bg
                elif var_key == "MAT":
                    var_lb = self.lb_quick_plot_file_mat
                elif var_key == "INCL":
                    var_lb = self.lb_quick_plot_file_incl

                var_lb.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.var_canvas_qpl.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:
                if var_file_long in self.container_var[var_type]:
                    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:
                    if var_file_long in self.container_var[var_type]:
                        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:
                    if var_file_long in self.container_var[var_type]:
                        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:
                if var_file_long in self.container_var[var_type]:
                    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:
                    if var_file_long in self.container_var[var_type]:
                        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:
                    if var_file_long in self.container_var[var_type]:
                        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 remove_interval_qpl(self, var_type, var_file_short):
        if self.container_var["Radiobuttons"]["Quick Plot File"].get() == 0:  # BG
            var_key = "BG"
            var_lb = self.lb_quick_plot_file_bg
        elif self.container_var["Radiobuttons"]["Quick Plot File"].get() == 1:  # MAT
            var_key = "MAT"
            var_lb = self.lb_quick_plot_file_mat
        elif self.container_var["Radiobuttons"]["Quick Plot File"].get() == 2:  # INCL
            var_key = "INCL"
            var_lb = self.lb_quick_plot_file_incl

        item = var_lb.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.var_canvas_qpl.draw()

    def fill_tv_quick_plot_file(self, var_type, var_file_short, list_isotopes, section="MAT", init=False):
        if init == True:
            for isotope in list_isotopes:
                helper_values = [isotope, "---", "---", "---"]
                self.tv_quick_file_statistics.insert("", tk.END, values=helper_values)
        else:
            if len(self.tv_quick_file_statistics.get_children()) > 0:
                for item in self.tv_quick_file_statistics.get_children():
                    self.tv_quick_file_statistics.delete(item)

            if len(self.container_helper[var_type][var_file_short][section]["Indices"]) > 0:
                df_data  = self.container_measurements["Dataframe"][var_file_short]
                condensed_intervals = IQ(dataframe=None).combine_all_intervals(
                    interval_set=self.container_helper[var_type][var_file_short][section]["Content"])

                if self.qpl_opt_is.get() != "Select isotope":
                    isotope_is = self.qpl_opt_is.get()
                    for isotope in list_isotopes:
                        helper = {"Mean": [], "Standard deviation": [], "Ratio": []}
                        for index, interval in condensed_intervals.items():
                            start_index = interval[0]
                            end_index = interval[1] + 1
                            dataset_i = df_data[isotope][start_index:end_index]
                            dataset_is = df_data[isotope_is][start_index:end_index]
                            helper["Mean"].append(np.mean(dataset_i))
                            helper["Standard deviation"].append(np.std(dataset_i, ddof=1))
                            helper["Ratio"].append(np.mean(dataset_i)/np.mean(dataset_is))
                        helper_values = [
                            isotope, round(np.mean(helper["Mean"]), 2), round(np.mean(helper["Standard deviation"]), 2),
                            "{:0.2e}".format(np.mean(helper["Ratio"]))]
                        self.tv_quick_file_statistics.insert("", tk.END, values=helper_values)
                else:
                    for isotope in list_isotopes:
                        helper_values = [isotope, "---", "---", "---"]
                        self.tv_quick_file_statistics.insert("", tk.END, values=helper_values)

            else:
                for isotope in list_isotopes:
                    helper_values = [isotope, "---", "---", "---"]
                    self.tv_quick_file_statistics.insert("", tk.END, values=helper_values)

    def check_for_intervals_qpl(self, filetype, filename_short):
        if self.pysills_mode == "MA":
            list_sections = ["BG", "MAT"]
        else:
            list_sections = ["BG", "MAT", "INCL"]

        for section in list_sections:
            if len(self.container_helper[filetype][filename_short][section]["Indices"]) > 0:
                if section == "BG":
                    var_lb = self.lb_quick_plot_file_bg
                elif section == "MAT":
                    var_lb = self.lb_quick_plot_file_mat
                elif section == "INCL":
                    var_lb = self.lb_quick_plot_file_incl

                var_color = self.colors_intervals[section]

                for key_id, container in self.container_helper[filetype][filename_short][section]["Content"].items():
                    list_times = container["Times"]
                    time_0 = list_times[0]
                    time_1 = list_times[1]
                    var_lb.insert(tk.END, section + str(key_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    box = self.var_ax.axvspan(time_0, time_1, alpha=0.35, color=var_color)
                    container["Object"] = box

        self.var_canvas_qpl.draw()

    def show_or_hide_interval(self, key, var_type, var_file_short):
        if key == "Background":
            var_key = "BG"
            state_var = self.qpl_cb_bg.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False
        elif key in ["Matrix", "Sample"]:
            var_key = "MAT"
            state_var = self.qpl_cb_mat.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False
        elif key == "Inclusion":
            var_key = "INCL"
            state_var = self.qpl_cb_incl.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False

        for id, container in self.container_helper[var_type][var_file_short][var_key]["Content"].items():
            obj_interval = container["Object"]
            obj_interval.set_visible(state)

        self.var_canvas_qpl.draw()

    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 in ["FI", "INCL"]:
            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.container_var["Spike Elimination Method"].get() in ["Z-score analysis"]:
                var_method = 3
        elif self.pysills_mode in ["FI", "INCL"]:
            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.container_var["Spike Elimination Method"].get() in ["Z-score analysis"]:
                var_method = 3
        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
            elif self.container_var["Spike Elimination Method"].get() in ["Z-score analysis"]:
                var_method = 3

        if filetype == "STD":
            subwindow_progressbar_spike_elimination, prgbar_spk = self.create_progress_bar_spike_elimination()
            n_files = len(self.container_lists["STD"]["Short"])
            n_steps = 0

            for index, file_std in enumerate(self.container_lists["STD"]["Short"]):
                file_isotopes = self.container_lists["Measured Isotopes"][file_std]
                n_steps += len(file_isotopes)

            stepwidth = round(100/n_steps, 4)
            stepwidth_files = round(100/n_files, 4)
            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"]):
                current_step = index*stepwidth_files
                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 self.container_lists["Measured Isotopes"]["All"]:
                        if 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(float(
                                                    self.container_var["Spike Elimination"]["Threshold"][
                                                        isotope].get()))

                                                if var_threshold < 0:
                                                    var_threshold = abs(var_threshold)

                                                self.container_var["Spike Elimination"]["Threshold"][isotope].set(
                                                    var_threshold)

                                                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()
                                                    elif var_method == 3:
                                                        data_smoothed, indices_outl = GrubbsTestSILLS(
                                                            raw_data=dataset_raw, alpha=var_alpha,
                                                            threshold=var_threshold, start_index=interval[0],
                                                            dataset_complete=dataset_complete).outlier_elimination_zsore()

                                                    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, 2)) + " %", 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_steps = 0

            for index, file_smpl in enumerate(self.container_lists["SMPL"]["Short"]):
                file_isotopes = self.container_lists["Measured Isotopes"][file_smpl]
                n_steps += len(file_isotopes)

            stepwidth = round(100/n_steps, 4)
            stepwidth_files = round(100/n_files, 4)
            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"]):
                current_step = index*stepwidth_files
                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]

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

                    for isotope in self.container_lists["Measured Isotopes"]["All"]:
                        if 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(float(
                                                    self.container_var["Spike Elimination"]["Threshold"][
                                                        isotope].get()))

                                                if var_threshold < 0:
                                                    var_threshold = abs(var_threshold)

                                                self.container_var["Spike Elimination"]["Threshold"][isotope].set(
                                                    var_threshold)

                                                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()
                                                    elif var_method == 3:
                                                        data_smoothed, indices_outl = GrubbsTestSILLS(
                                                            raw_data=dataset_raw, alpha=var_alpha,
                                                            threshold=var_threshold, start_index=interval[0],
                                                            dataset_complete=dataset_complete).outlier_elimination_zsore()

                                                    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", "INCL"]:
                                                    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]

                                                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"]

                                                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, 2)) + " %", 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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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", "INCL"]:
                                        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 Blank
        report_lob = {}
        report_lob["Total STD"] = {}
        report_lob["Total SMPL"] = {}
        # Limit of Detection
        report_lod = {}
        report_lod["Total STD"] = {}
        report_lod["Total SMPL"] = {}
        # Limit of Quantification
        report_loq = {}
        report_loq["Total STD"] = {}
        report_loq["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_lob[var_filetype] = {}
            report_lob[var_key] = {}
            report_lob[var_key]["filename"] = "All Files"

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

            report_loq[var_filetype] = {}
            report_loq[var_key] = {}
            report_loq[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_lob[var_filetype][var_datatype] = {}
                report_lod[var_filetype][var_datatype] = {}
                report_loq[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_lob[var_filetype][var_datatype][file_short] = {}
                    report_lob[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
                    report_loq[var_filetype][var_datatype][file_short] = {}
                    report_loq[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_lob[var_filetype][var_datatype][file_short]["ID"] = "---"
                        report_lod[var_filetype][var_datatype][file_short]["ID"] = "---"
                        report_loq[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_lob[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()
                        report_loq[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_lod_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 Blank
                        value_i = self.container_lob[var_filetype][var_datatype][file_short]["MAT"][isotope]

                        if value_i != None:
                            report_lob[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_decimals_concentration)
                        else:
                            report_lob[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_lod[var_filetype][var_datatype][file_short][isotope] = "---"

                        # Limit of Quantification
                        value_i = self.container_loq[var_filetype][var_datatype][file_short]["MAT"][isotope]

                        if value_i != None:
                            report_loq[var_filetype][var_datatype][file_short][isotope] = round(
                                value_i, n_decimals_concentration)
                        else:
                            report_loq[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_lob, report_lod,
                report_loq,
                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_lob, report_lod,
                report_loq,
                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_lob, report_lod,
                report_loq,
                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_lob, report_lod,
            report_loq, 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 Blank\n")  # Limit of Blank
                        report_file.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lob[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("Limit of Quantification\n")  # Limit of Quantification
                        report_file.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_loq[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_lob, report_lod,
            report_loq, 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 Blank\n")  # Limit of Blank
                        report_file_std.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lob[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("Limit of Quantification\n")  # Limit of Quantification
                        report_file_std.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_loq[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 Blank\n")  # Limit of Blank
                        report_file_smpl.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lob[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("Limit of Quantification\n")  # Limit of Quantification
                        report_file_smpl.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_loq[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_lob, report_lod,
            report_loq, 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 Blank\n")  # Limit of Blank
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lob[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("Limit of Quantification\n")  # Limit of Quantification
                        report_file_raw.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_loq[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 Blank\n")  # Limit of Blank
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_lob[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("Limit of Quantification\n")  # Limit of Quantification
                        report_file_smoothed.write("(ppm)\n")
                        writer.writeheader()
                        for file_short in self.container_lists[var_filetype]["Short"]:
                            writer.writerow(report_loq[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 in ["FI", "INCL"]:
            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 Blank
        report_lob_incl = {}
        report_lob_incl["Total STD"] = {}
        report_lob_incl["Total SMPL"] = {}
        report_lob_mat = {}
        report_lob_mat["Total STD"] = {}
        report_lob_mat["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"] = {}
        # Limit of Quantification
        report_loq_incl = {}
        report_loq_incl["Total STD"] = {}
        report_loq_incl["Total SMPL"] = {}
        report_loq_mat = {}
        report_loq_mat["Total STD"] = {}
        report_loq_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_lob_incl[var_filetype] = {}
            report_lob_incl[var_key] = {}
            report_lob_incl[var_key]["filename"] = "All Files"

            report_lob_mat[var_filetype] = {}
            report_lob_mat[var_key] = {}
            report_lob_mat[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_loq_incl[var_filetype] = {}
            report_loq_incl[var_key] = {}
            report_loq_incl[var_key]["filename"] = "All Files"

            report_loq_mat[var_filetype] = {}
            report_loq_mat[var_key] = {}
            report_loq_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_lob_incl[var_filetype][var_datatype] = {}
                report_lob_mat[var_filetype][var_datatype] = {}
                report_lod_incl[var_filetype][var_datatype] = {}
                report_lod_mat[var_filetype][var_datatype] = {}
                report_loq_incl[var_filetype][var_datatype] = {}
                report_loq_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_lob_incl[var_filetype][var_datatype][file_short] = {}
                        report_lob_incl[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_lob_mat[var_filetype][var_datatype][file_short] = {}
                        report_lob_mat[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_loq_incl[var_filetype][var_datatype][file_short] = {}
                        report_loq_incl[var_filetype][var_datatype][file_short]["filename"] = file_short
                        report_loq_mat[var_filetype][var_datatype][file_short] = {}
                        report_loq_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_lob_incl[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_lob_mat[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_loq_incl[var_filetype][var_datatype][file_short]["ID"] = "---"
                            report_loq_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_lob_incl[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_lob_mat[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_loq_incl[var_filetype][var_datatype][file_short]["ID"] = self.container_var[
                                var_filetype][file_long]["ID"].get()
                            report_loq_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
                                value_i = -lod_i

                            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
                                value_i = -lod_i

                            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 Blank (Inclusion)
                            if var_filetype == "SMPL":
                                value_i = self.container_lob[var_filetype][var_datatype][file_short]["INCL"][isotope]
                            else:
                                value_i = 0.0

                            n_digits = 5
                            report_lob_incl[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 Quantification (Inclusion)
                            if var_filetype == "SMPL":
                                value_i = self.container_loq[var_filetype][var_datatype][file_short]["INCL"][isotope]
                            else:
                                value_i = 0.0

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

                            # Limit of Blank (Matrix)
                            value_i = self.container_lob[var_filetype][var_datatype][file_short]["MAT"][isotope]
                            n_digits = 5
                            report_lob_mat[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)

                            # Limit of Quantification (Matrix)
                            value_i = self.container_loq[var_filetype][var_datatype][file_short]["MAT"][isotope]
                            n_digits = 5
                            report_loq_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_lob_incl, report_lob_mat, report_lod_incl, report_lod_mat, report_loq_incl,
                report_loq_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_lob_incl, report_lob_mat, report_lod_incl, report_lod_mat, report_loq_incl,
                report_loq_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_lob_incl, report_lob_mat, report_lod_incl, report_lod_mat, report_loq_incl,
                report_loq_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_lob_incl, report_lob_mat, report_lod_incl, report_lod_mat, report_loq_incl,
            report_loq_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 Blank (Inclusion)\n")  # Limit of Blank (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_lob_incl[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("Limit of Quantification (Inclusion)\n")  # Limit of Quantification (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_loq_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 Blank (Matrix)\n")  # Limit of Blank (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_lob_mat[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")

                    report_file.write("Limit of Quantification (Matrix)\n")  # Limit of Quantification (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_loq_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_lob_incl, report_lob_mat, report_lod_incl, report_lod_mat, report_loq_incl,
            report_loq_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 Blank (Matrix)\n")  # Limit of Blank (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_lob_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("Limit of Quantification (Matrix)\n")  # Limit of Quantification (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_loq_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 Blank (Inclusion)\n")  # Limit of Blank (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_lob_incl[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("Limit of Quantification (Inclusion)\n")  # Limit of Quantification (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_loq_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 Blank (Matrix)\n")  # Limit of Blank (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_lob_mat[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")

                    report_file_smpl.write("Limit of Quantification (Matrix)\n")  # Limit of Quantification (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_loq_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_lob_incl, report_lob_mat, report_lod_incl, report_lod_mat, report_loq_incl,
            report_loq_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 Blank (Inclusion)\n")  # Limit of Blank (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_lob_incl[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("Limit of Quantification (Inclusion)\n")  # Limit of Quantification (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_loq_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 Blank (Matrix)\n")  # Limit of Blank (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_lob_mat[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")

                    report_file_raw.write("Limit of Quantification (Matrix)\n")  # Limit of Quantification (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_loq_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 Blank (Inclusion)\n")  # Limit of Blank (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_lob_incl[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("Limit of Quantification (Inclusion)\n")  # Limit of Quantification (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_loq_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 Blank (Matrix)\n")  # Limit of Blank (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_lob_mat[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")

                    report_file_smoothed.write("Limit of Quantification (Matrix)\n")  # Limit of Quantification (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_loq_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):
        file_ending_pre = self.container_var["General Settings"]["Project type"].get()
        file_ending = file_ending_pre[1:]

        if "csv" in file_ending:
            list_file_endings = [("CSV files *.csv", "*.csv"), ("Project files *.proj", "*.proj")]
        elif "proj" in file_ending:
            list_file_endings = [("Project files *.proj", "*.proj"), ("CSV files *.csv", "*.csv")]

        save_file = filedialog.asksaveasfile(
            mode="w", defaultextension=file_ending, title="Save as", filetypes=list_file_endings)

        # 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", "INCL"]:
            # Save information about 'Inclusion Setup'
            self.save_inclusion_information_in_file(save_file=save_file)
            if self.pysills_mode in ["FI", "INCL"]:
                # 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 in ["FI", "INCL"]:
                # 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 in "FI":
            info_mode = "Fluid Inclusion Analysis"
            info_key = "fi_setting"
        elif self.pysills_mode == "MI":
            info_mode = "Melt Inclusion Analysis"
            info_key = "mi_setting"
        elif self.pysills_mode == "INCL":
            info_mode = "Inclusion Analysis"
            info_key = "fi_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()

        if self.pysills_mode in ["FI", "INCL", "MI"]:
            info_used_quantification_method = self.container_var[info_key]["Quantification Method Option"].get()
            info_used_incl_method = self.container_var[info_key]["Inclusion Setup Option"].get()

            str_proj = (str(info_author) + ";" + str(info_source) + ";" + str(info_carrier_gas) + ";" + str(info_icpms) +
                        ";" + info_used_quantification_method + ";" + info_used_incl_method)
        else:
            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 in ["FI", "INCL"]:
            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]
            info_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
            info_concentration = self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].get()
            if filename_short in self.helper_lists["Salinity"]:
                info_salinity = self.helper_lists["Salinity"][filename_short]
            else:
                info_salinity = 0.0
            if filename_short in self.helper_lists["Considered chlorides"]:
                info_chlorides = self.helper_lists["Considered chlorides"][filename_short]
            else:
                info_chlorides = []

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

            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"

        if len(self.container_lists["Selected Anions"]) > 0:
            for index, anion in enumerate(self.container_lists["Selected Anions"]):
                if anion != "":
                    if anion in self.temp_checkbuttons_pypitzer:
                        if self.temp_checkbuttons_pypitzer[anion].get() == 1:
                            if index < len(self.container_lists["Selected Anions"]) - 1:
                                str_anions += anion + ";"
                            else:
                                str_anions += anion + "\n"
            if index == len(self.container_lists["Selected Anions"]) - 1 and "\n" not in str_anions:
                str_anions += "\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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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", "INCL"]:
                    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 in ["FI", "INCL"]:
            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 filetype in ["STD", "SMPL"]:
        #     for file_short in self.container_lists[filetype]["Short"]:
        #         df_isotopes = self.container_lists["Measured Isotopes"][file_short]
        #         if file_short in self.container_spike_values:
        #             for isotope in df_isotopes:
        #                 print(isotope)
        #                 print(len(self.container_spike_values[file_short][isotope]["Save"]),
        #                       self.container_spike_values[file_short][isotope]["Save"])

        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_lines = line_std.split(";")

            if len(splitted_lines[0]) != 0:
                if len(splitted_lines) == 1:
                    splitted_lines = line_std.split(",")

                self.container_var[key_setting]["Author"].set(splitted_lines[0])

                if len(splitted_lines) > 1:
                    self.container_var[key_setting]["Source ID"].set(splitted_lines[1])
                    self.container_var["LASER"].set(splitted_lines[2])

                    try:
                        self.var_opt_icp.set(splitted_lines[3])
                    except:
                        self.var_opt_icp.set("Select ICP-MS")

                    if self.pysills_mode != "MA":
                        try:
                            self.container_var[key_setting]["Quantification Method Option"].set(splitted_lines[4])
                            for index, key in enumerate(["Matrix-only Tracer (SILLS)", "Second Internal Standard (SILLS)",
                                               "Geometric Approach (Halter et al. 2002)",
                                               "Geometric Approach (Borisova et al. 2021)"]):
                                if key == splitted_lines[4]:
                                    self.container_var[key_setting]["Quantification Method"].set(int(index + 1))
                        except:
                            self.container_var[key_setting]["Quantification Method Option"].set(
                                "Matrix-only Tracer (SILLS)")
                            self.container_var[key_setting]["Quantification Method"].set(1)

                        try:
                            self.container_var[key_setting]["Inclusion Setup Option"].set(splitted_lines[5])
                            for index, key in enumerate(["Mass Balance", "Charge Balance", "PyPitzer (Liu et al. 2024)",
                                               "Custom Data", "External Calculation", "100 wt.% Oxides"]):
                                if key == splitted_lines[5]:
                                    self.container_var[key_setting]["Inclusion Setup Selection"].set(int(index + 1))
                        except:
                            self.container_var[key_setting]["Inclusion Setup Option"].set("Mass Balance")
                            self.container_var[key_setting]["Inclusion Setup Selection"].set(1)

    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_lines = line_std.split(";")

            if len(splitted_lines[0]) != 0:
                if len(splitted_lines) == 1:
                    splitted_lines = line_std.split(",")

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

                self.lbl_prg_spk.configure(text=str(20) +" % - " + var_file_short, anchor=tk.W)

                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_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()

                if self.old_file == True:
                    df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=var_file_long, filetype="STD",
                                                                       only_time_check=True)

                self.lb_std.insert(tk.END, str(var_file_short))
                self.container_var["STD"][var_file_long]["SRM"].set(splitted_lines[1])
                self.container_var["STD"][var_file_long]["Checkbox"].set(splitted_lines[2])

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

                if len(splitted_lines) > 4:
                    self.container_var["acquisition times"]["STD"][var_file_short].set(splitted_lines[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_lines = line_smpl.split(";")

            if len(splitted_lines[0]) != 0:
                if len(splitted_lines) == 1:
                    splitted_lines = line_smpl.split(",")

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

                self.lbl_prg_spk.configure(text=str(30) +" % - " + var_file_short, anchor=tk.W)

                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 self.old_file == True:
                    df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=var_file_long, filetype="SMPL",
                                                                       only_time_check=True)

                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_lines[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_lines[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_lines[2])
                self.container_var["SMPL"][var_file_long]["Checkbox"].set(splitted_lines[3])
                self.container_var["SMPL"][var_file_long]["Sign Color"].set(splitted_lines[4])

                if len(splitted_lines) > 5:
                    self.container_var["acquisition times"]["SMPL"][var_file_short].set(splitted_lines[5])

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

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

                    if len(splitted_lines) == 9:
                        if len(splitted_lines[8]) > 0:
                            self.container_var["Oxides Quantification INCL"]["Total Amounts"][var_file_short].set(
                                splitted_lines[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[0]) != 0:
                if len(splitted_lines) == 1:
                    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[0]) != 0:
            #if len(splitted_lines) > 1:
                if len(splitted_lines) == 1:
                    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)
                        self.helper_lists["Salinity"][info_file_short] = info_salinity

                        if len(splitted_lines) == 5:
                            clean_content = splitted_lines[4].replace("'", "").replace("[", "").replace("]", "").split(
                                ", ")
                            self.helper_lists["Considered chlorides"][info_file_short] = list(clean_content)

    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(";")

            if len(splitted_lines[0]) != 0:
            #if len(splitted_lines) > 1:
                if len(splitted_lines) == 1:
                    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 len(splitted_lines[0]) != 0:
            #if len(splitted_lines) > 1:
                if len(splitted_lines) == 1:
                    splitted_lines = [element for element in csv.reader(splitted_lines, delimiter=",")][0]

                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]
                        try:
                            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)
                        except:
                            print("File:", var_file_short)
                            print(
                                "There is a problem with the background interval data. It seems that they are damaged.")
                    elif splitted_lines[0] == "MAT":
                        var_id = int(splitted_lines[1])
                        var_times = splitted_lines[2]
                        try:
                            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)
                        except:
                            print("File:", var_file_short)
                            print("There is a problem with the matrix interval data. It seems that they are damaged.")
                    elif splitted_lines[0] == "INCL":
                        var_id = int(splitted_lines[1])
                        var_times = splitted_lines[2]
                        try:
                            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)
                        except:
                            print("File:", var_file_short)
                            print(
                                "There is a problem with the inclusion interval data. It seems that they are damaged.")
                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 len(splitted_lines[0]) != 0:
                if len(splitted_lines) == 1:
                    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"

                        if len(splitted_lines) == 8:
                            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]))
                        else:
                            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]))

                    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:
                    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

                if filename_short in self.container_lists["STD"]["Short"]:
                    str_filetype = "STD"
                    index_file = self.container_lists["STD"]["Short"].index(filename_short)
                    str_filename_long = self.container_lists["STD"]["Long"][index_file]
                elif filename_short in self.container_lists["SMPL"]["Short"]:
                    str_filetype = "SMPL"
                    index_file = self.container_lists["SMPL"]["Short"].index(filename_short)
                    str_filename_long = self.container_lists["SMPL"]["Long"][index_file]
                else:
                    str_filetype = "unknown"

                header_names = ["Time"]
                header_names.extend(self.container_lists["ISOTOPES"])

                try:
                    dataframe = pd.read_csv(
                        filename, sep=";", header=0, skiprows=data[0], nrows=data[1] - data[0],
                        usecols=header_names, engine="python")
                except:
                    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():
                                if index < len(data_improved):
                                    data_indices.append(index)
                                    data_improved[index] = value
                                else:
                                    print("ATTENTION - - -")
                                    print(filename_short, isotope, index, value)
                                    print(len(data_improved))
                                    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 build_file_data_09(self, key, df_isotopes, dataframe, times, dataframe_smoothed=None, with_smoothed=None):
        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
        self.container_measurements["EDITED"][key]["Time"] = times
        self.container_measurements["SELECTED"][key]["Time"] = times

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

            if with_smoothed != None:
                self.container_measurements["EDITED"][key][isotope] = dataframe_smoothed[isotope].tolist()
            else:
                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"][key][isotope]

            if with_smoothed != None:
                data_smoothed = self.container_measurements["EDITED"][key][isotope]
                data_improved = data_smoothed.copy()
            else:
                data_smoothed = data_raw.copy()
                data_improved = data_raw.copy()

            data_indices = []
            data_times = self.container_measurements["SELECTED"][key]["Time"]

            if key not in self.container_spike_values:
                self.container_spike_values[key] = {}
            if key not in self.container_spikes:
                self.container_spikes[key] = {}

            if key in self.container_spike_values:
                if isotope in self.container_spike_values[key]:
                    for index, value in self.container_spike_values[key][isotope]["Save"].items():
                        data_indices.append(index)
                        data_improved[index] = value
                else:
                    self.container_spike_values[key][isotope] = {"RAW": [], "SMOOTHED": [], "Current": [], "Save": {}}

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

    def build_intervals(self, filetype, filename, focus, list_time, start_i, end_i, id):
        index_start_i = list_time.index(start_i)
        index_end_i = list_time.index(end_i)
        int_id = id + 1

        if len(self.container_helper[filetype][filename][focus]["Indices"]) > 0:
            int_id = self.container_helper[filetype][filename][focus]["Indices"][-1] + 1

        helper_times = [float(start_i), float(end_i)]
        helper_indices = [int(index_start_i), int(index_end_i)]
        helper_times.sort()
        helper_indices.sort()

        self.container_helper[filetype][filename][focus]["ID"] = int_id
        self.container_helper[filetype][filename][focus]["Content"][int_id] = {}
        self.container_helper[filetype][filename][focus]["Content"][int_id][
            "Times"] = helper_times
        self.container_helper[filetype][filename][focus]["Content"][int_id][
            "Indices"] = helper_indices
        self.container_helper[filetype][filename][focus]["Indices"].append(int_id)

    def load_sills_file(self, filename):
        data_sills = scipy.io.loadmat(filename)
        list_srm = []

        if "SRM" in data_sills:
            helper_srm = {}
            for index, data_srm in enumerate(data_sills["SRM"]):
                str_srm = str(data_srm[0][4][0])
                list_srm.append(str_srm)
                helper_srm[str_srm] = {}
                container_values = data_srm[0][0]
                container_elements = data_srm[0][1]
                for index2, element_pre in enumerate(container_elements):
                    element = str(element_pre[0][0])
                    value = float(container_values[index2][0])
                    helper_srm[str_srm][element] = value

        # if "A" in data_sills:
        #     for index, data in enumerate(data_sills["A"]):
        #         print(index, data)

        if "STD" in data_sills:
            helper_std = {}
            helper_std_smoothed = {}
            for index, data_std in enumerate(data_sills["STD"]):
                for index2, data_file in enumerate(data_std):
                    str_std = str(data_file[3][0][0][0][0])
                    helper_std[str_std] = {}
                    helper_std_smoothed[str_std] = {}
                    list_isotopes = []
                    list_time = []

                    if "xl" in str_std:
                        str_acquisition_pre = str(data_file[3][0][0][1][0])
                    elif "csv" in str_std:
                        str_acquisition_pre = str(data_file[1][2][0][0])
                    else:
                        str_acquisition_pre = str(data_file[3][0][0][1][0])

                    self.container_spikes[str_std] = {}
                    self.container_helper["STD"][str_std] = {"BG": {"Content": {}, "Indices": []},
                                                             "MAT": {"Content": {}, "Indices": []},
                                                             "INCL": {"Content": {}, "Indices": []}}
                    self.container_files["STD"][str_std] = {"SRM": tk.StringVar()}
                    self.container_var["STD"][str_std] = {
                        "IS Data": {"IS": tk.StringVar(), "Concentration": tk.StringVar()},
                        "Checkbox": tk.IntVar(), "Sign Color": tk.StringVar(), "SRM": tk.StringVar()}

                    if "Acquired" in str_acquisition_pre:
                        key_start = re.search(
                            r"Acquired\s+\:\s+(\d+)\/(\d+)\/(\d+)\s+(\d+)\:(\d+)\:(\d+)( using Batch )(\w+)",
                            str_acquisition_pre)
                        if key_start:
                            str_acquisition = [
                                str(key_start.group(4)), str(key_start.group(5)), str(key_start.group(6))]
                            self.container_var["acquisition times"]["STD"][str_std] = tk.StringVar()
                            self.container_var["acquisition times"]["STD"][str_std].set(str_acquisition[0] + ":"
                                                                                        + str_acquisition[1] + ":"
                                                                                        + str_acquisition[2])
                    else:
                        if "xl" in str_std:
                            key_time = re.search(r"(\d+)\-(\w+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)",
                                                 str_acquisition_pre)
                            if key_time:
                                str_acquisition = [
                                    str(key_time.group(4)), str(key_time.group(5)), str(key_time.group(6))]

                                self.container_var["acquisition times"]["STD"][str_std] = tk.StringVar()
                                self.container_var["acquisition times"]["STD"][str_std].set(str_acquisition[0] + ":"
                                                                                            + str_acquisition[1] + ":"
                                                                                            + str_acquisition[2])

                    for i, item in enumerate(data_file[2][0]):
                        if i > 0:
                            isotope = str(item[0])
                            list_isotopes.append(isotope)
                            helper_std[str_std][isotope] = []
                            helper_std_smoothed[str_std][isotope] = []
                            if isotope not in self.container_var["dwell_times"]["Entry"]:
                                self.container_var["dwell_times"]["Entry"][isotope] = tk.StringVar()
                                self.container_var["dwell_times"]["Entry"][isotope].set("0.002")

                    for index3, data in enumerate(data_file):
                        if index3 == 0:
                            number_measurements = len(data)
                            list_indices_measurements = []
                        if len(data) == number_measurements:
                            list_indices_measurements.append(index3)
                        #print(index3, len(data), data)
                        if index3 == 0: # Corrected values
                            for line, values in enumerate(data):
                                value_time = float(values[0])
                                list_time.append(value_time)
                                for j, value in enumerate(values):
                                    if j > 0:
                                        isotope = list_isotopes[j - 1]
                                        helper_std_smoothed[str_std][isotope].append(float(value))
                        elif index3 == 26:   # Original values
                            for line, values in enumerate(data):
                                for j, value in enumerate(values):
                                    isotope = list_isotopes[j]
                                    helper_std[str_std][isotope].append(float(value))
                        elif index3 == 5:    # Standard Reference Material (SRM)
                            index_srm = data[0][0] - 1
                            self.container_files["STD"][str_std]["SRM"].set(list_srm[index_srm])
                            self.container_var["STD"][str_std]["SRM"].set(list_srm[index_srm])
                        elif index3 == 6:    # Background interval
                            for i, interval in enumerate(data):
                                start_i = interval[0]
                                end_i = interval[1]
                                self.build_intervals(filetype="STD", filename=str_std, focus="BG", list_time=list_time,
                                                     start_i=start_i, end_i=end_i, id=i)
                        elif index3 == 7:    # Matrix interval
                            for i, interval in enumerate(data):
                                start_i = interval[0]
                                end_i = interval[1]
                                self.build_intervals(filetype="STD", filename=str_std, focus="MAT", list_time=list_time,
                                                     start_i=start_i, end_i=end_i, id=i)
                        elif index3 == 38:    # SRM data
                            helper_srm_i = {}
                            unique_srm = []
                            self.srm_isotopes = {}

                            for i, srm_value in enumerate(data[0]):
                                isotope = list_isotopes[i]
                                helper_srm_i[isotope] = float(srm_value)

                            for isotope, value in helper_srm_i.items():
                                if value not in unique_srm:
                                    unique_srm.append(value)

                            for srm, srm_dataset in helper_srm.items():
                                data_srm_i = list(srm_dataset.values())
                                common_data_i = list(set(data_srm_i).intersection(unique_srm))

                                if unique_srm.sort() == common_data_i.sort():
                                    # self.container_files["STD"][str_std]["SRM"].set(srm)
                                    # self.container_var["STD"][str_std]["SRM"].set(srm)
                                    self.container_var["SRM"]["default"][0].set(srm)
                                    self.container_var["SRM"]["default"][1].set(srm)

                                    if srm not in self.srm_actual:
                                        self.srm_actual[srm] = {}

                                    for isotope, value in helper_srm_i.items():
                                        self.srm_isotopes[isotope] = {}
                                        key_element = re.search(r"(\D+)(\d+)", isotope)
                                        element = key_element.group(1)

                                        if element not in self.container_var["SRM"]:
                                            self.container_var["SRM"][element] = tk.StringVar()
                                        if isotope not in self.container_var["SRM"]:
                                            self.container_var["SRM"][isotope] = tk.StringVar()
                                        if element not in self.container_var["STD"]:
                                            self.container_var["STD"][element] = {"SRM": tk.StringVar()}

                                        self.container_var["STD"][element]["SRM"].set(srm)
                                        self.container_var["SRM"][isotope].set(srm)
                                        self.srm_isotopes[isotope]["SRM"] = srm

                                        if element in helper_srm[srm]:
                                            self.srm_actual[srm][element] = helper_srm[srm][element]
                                        else:
                                            self.srm_actual[srm][element] = 0.0

                                        if element in self.srm_actual[srm]:
                                            self.srm_isotopes[isotope]["Concentration"] = self.srm_actual[srm][element]
                                        else:
                                            self.srm_isotopes[isotope]["Concentration"] = 0.0

                    helper_std[str_std]["Time"] = list_time
                    helper_std_smoothed[str_std]["Time"] = list_time

                    self.container_var["STD"][str_std]["Checkbox"].set(1)
                    self.container_var["STD"][str_std]["Sign Color"].set(self.sign_yellow)
                    self.lb_std.insert(tk.END, str(str_std))
                    self.list_std.append(str_std)
                    self.container_lists["STD"]["Long"].append(str_std)
                    self.container_lists["STD"]["Short"].append(str_std)

                    # Build pandas dataframe
                    column_names = ["Time"]
                    column_names.extend(list_isotopes)
                    data_columns = [list_time]
                    data_columns_smoothed = [list_time]

                    for isotope in list_isotopes:
                        data_columns.append(helper_std[str_std][isotope])
                        data_columns_smoothed.append(helper_std_smoothed[str_std][isotope])

                    data_dict = {col: values for col, values in zip(column_names, data_columns)}
                    data_dict_smoothed = {col: values for col, values in zip(column_names, data_columns_smoothed)}

                    try:
                        df_std = pd.DataFrame(data_dict)
                        df_std_smoothed = pd.DataFrame(data_dict_smoothed)
                    except:
                        for index, data_std in enumerate(data_sills["STD"]):
                            for index2, data_file in enumerate(data_std):
                                if str_std == str(data_file[3][0][0][0][0]):
                                    helper_std[str_std] = {}
                                    helper_std_smoothed[str_std] = {}
                                    list_time = []
                                    for index3, data in enumerate(data_file):
                                        if index3 in list_indices_measurements:
                                            if index3 == 0:  # Corrected values
                                                for line, values in enumerate(data):
                                                    value_time = float(values[0])
                                                    list_time.append(value_time)
                                                    for j, value in enumerate(values):
                                                        if j > 0:
                                                            isotope = list_isotopes[j - 1]
                                                            if isotope not in helper_std_smoothed[str_std]:
                                                                helper_std_smoothed[str_std][isotope] = []
                                                            helper_std_smoothed[str_std][isotope].append(float(value))
                                            if index3 == list_indices_measurements[-1]:  # Original values
                                                if len(list_indices_measurements) > 1:
                                                    if len(data[0]) == len(list_isotopes):
                                                        for line, values in enumerate(data):
                                                            for j, value in enumerate(values):
                                                                isotope = list_isotopes[j]
                                                                if isotope not in helper_std[str_std]:
                                                                    helper_std[str_std][isotope] = []
                                                                helper_std[str_std][isotope].append(float(value))
                                                    else:
                                                        for index3, data in enumerate(data_file):
                                                            if index3 == list_indices_measurements[-2]:
                                                                if len(data[0]) == len(list_isotopes):
                                                                    for line, values in enumerate(data):
                                                                        for j, value in enumerate(values):
                                                                            isotope = list_isotopes[j]
                                                                            if isotope not in helper_std[str_std]:
                                                                                helper_std[str_std][isotope] = []
                                                                            helper_std[str_std][isotope].append(
                                                                                float(value))
                                                else:
                                                    for line, values in enumerate(data):
                                                        for j, value in enumerate(values):
                                                            if j > 0:
                                                                isotope = list_isotopes[j - 1]
                                                                if isotope not in helper_std[str_std]:
                                                                    helper_std[str_std][isotope] = []
                                                                helper_std[str_std][isotope].append(float(value))

                                    data_dict = {"Time": list_time}
                                    data_dict_smoothed = {"Time": list_time}
                                    for key, values in helper_std.items():
                                        for isotope, data in values.items():
                                            data_dict[isotope] = data
                                    for key, values in helper_std_smoothed.items():
                                        for isotope, data in values.items():
                                            data_dict_smoothed[isotope] = data

                                    df_std = pd.DataFrame(data_dict)
                                    df_std_smoothed = pd.DataFrame(data_dict_smoothed)

                    self.build_file_data_09(key=str_std, df_isotopes=list_isotopes, dataframe=df_std, times=list_time,
                                            dataframe_smoothed=df_std_smoothed, with_smoothed=False)
                    self.container_var["Spike Elimination"]["STD"]["State"] = True

            helper_srm_2 = {}

            if len(self.srm_actual) > 0:
                for srm, dataset in self.srm_actual.items():
                    helper_srm_2[srm] = 0
                    for isotope, value in dataset.items():
                        if value == 0:
                            helper_srm_2[srm] += 1
            else:
                helper_srm_i = {}
                unique_srm = []
                self.srm_isotopes = {}

                for srm, dataset in helper_srm.items():
                    for isotope in list_isotopes:
                        key_element = re.search(r"(\D+)(\d+)", isotope)
                        element = key_element.group(1)
                        if element in dataset:
                            helper_srm_i[isotope] = float(dataset[element])

                for isotope, value in helper_srm_i.items():
                    if value not in unique_srm:
                        unique_srm.append(value)

                for srm, srm_dataset in helper_srm.items():
                    data_srm_i = list(srm_dataset.values())
                    common_data_i = list(set(data_srm_i).intersection(unique_srm))

                    if unique_srm.sort() == common_data_i.sort():
                        self.container_var["SRM"]["default"][0].set(srm)
                        self.container_var["SRM"]["default"][1].set(srm)

                        if srm not in self.srm_actual:
                            self.srm_actual[srm] = {}

                        for isotope, value in helper_srm_i.items():
                            self.srm_isotopes[isotope] = {}
                            key_element = re.search(r"(\D+)(\d+)", isotope)
                            element = key_element.group(1)

                            if element not in self.container_var["SRM"]:
                                self.container_var["SRM"][element] = tk.StringVar()
                            if isotope not in self.container_var["SRM"]:
                                self.container_var["SRM"][isotope] = tk.StringVar()
                            if element not in self.container_var["STD"]:
                                self.container_var["STD"][element] = {"SRM": tk.StringVar()}

                            self.container_var["STD"][element]["SRM"].set(srm)
                            self.container_var["SRM"][isotope].set(srm)
                            self.srm_isotopes[isotope]["SRM"] = srm

                            if element in helper_srm[srm]:
                                self.srm_actual[srm][element] = helper_srm[srm][element]
                            else:
                                self.srm_actual[srm][element] = 0.0

                            if element in self.srm_actual[srm]:
                                self.srm_isotopes[isotope]["Concentration"] = self.srm_actual[srm][element]
                            else:
                                self.srm_isotopes[isotope]["Concentration"] = 0.0

                for srm, dataset in self.srm_actual.items():
                    helper_srm_2[srm] = 0
                    for isotope, value in dataset.items():
                        if value == 0:
                            helper_srm_2[srm] += 1

            if len(helper_srm_2) > 1:
                for isotope in list_isotopes:
                    srm = list_srm[1]
                    key_element = re.search(r"(\D+)(\d+)", isotope)
                    element = key_element.group(1)
                    self.container_var["STD"][element]["SRM"].set(srm)
                    self.container_var["SRM"][isotope].set(srm)
                    self.srm_isotopes[isotope]["SRM"] = srm

                    if element in self.srm_actual[srm]:
                        self.srm_isotopes[isotope]["Concentration"] = self.srm_actual[srm][element]
                    else:
                        self.srm_isotopes[isotope]["Concentration"] = 0.0

                    if element in ["Cl", "Br", "I"]:
                        for srm in list_srm:
                            if "Sca" in srm or "sca" in srm:
                                self.container_var["STD"][element]["SRM"].set(srm)
                                self.container_var["SRM"][isotope].set(srm)
                                self.srm_isotopes[isotope]["SRM"] = srm

                                if element in self.srm_actual[srm]:
                                    self.srm_isotopes[isotope]["Concentration"] = self.srm_actual[srm][element]
                                else:
                                    self.srm_isotopes[isotope]["Concentration"] = 0.0

        if "UNK" in data_sills:
            helper_smpl = {}
            helper_smpl_smoothed = {}
            self.mode_ma = True
            self.mode_2ndis = False
            for index, data_smpl in enumerate(data_sills["UNK"]):
                for index2, data_file in enumerate(data_smpl):
                    str_smpl = str(data_file[3][0][0][0][0])
                    helper_smpl[str_smpl] = {}
                    helper_smpl_smoothed[str_smpl] = {}
                    list_isotopes = []
                    list_time = []

                    if "xl" in str_std:
                        str_acquisition_pre = str(data_file[3][0][0][1][0])
                    elif "csv" in str_std:
                        str_acquisition_pre = str(data_file[1][2][0][0])
                    else:
                        str_acquisition_pre = str(data_file[3][0][0][1][0])

                    self.container_helper["SMPL"][str_smpl] = {"BG": {"Content": {}, "Indices": []},
                                                               "MAT": {"Content": {}, "Indices": []},
                                                               "INCL": {"Content": {}, "Indices": []}}
                    self.container_var["SMPL"][str_smpl] = {
                        "IS Data": {"IS": tk.StringVar(), "Concentration": tk.StringVar()},
                        "Checkbox": tk.IntVar(), "ID": tk.StringVar(), "Sign Color": tk.StringVar()}
                    self.container_var["SMPL"][str_smpl]["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"][str_smpl]["Host Only Tracer"] = {
                        "Name": tk.StringVar(), "Value": tk.StringVar(), "Matrix": tk.StringVar(),
                        "Amount": tk.StringVar()}
                    self.container_var["SMPL"][str_smpl]["Second Internal Standard"] = {
                        "Name": tk.StringVar(), "Value": tk.StringVar()}

                    if "Acquired" in str_acquisition_pre:
                        key_start = re.search(
                            r"Acquired\s+\:\s+(\d+)\/(\d+)\/(\d+)\s+(\d+)\:(\d+)\:(\d+)( using Batch )(\w+)",
                            str_acquisition_pre)
                        if key_start:
                            str_acquisition = [
                                str(key_start.group(4)), str(key_start.group(5)), str(key_start.group(6))]
                            self.container_var["acquisition times"]["SMPL"][str_smpl] = tk.StringVar()
                            self.container_var["acquisition times"]["SMPL"][str_smpl].set(str_acquisition[0] + ":"
                                                                                          + str_acquisition[1] + ":"
                                                                                          + str_acquisition[2])
                    else:
                        if "xl" in str_smpl:
                            key_time = re.search(r"(\d+)\-(\w+)\-(\d+)\s+(\d+)\:(\d+)\:(\d+)", str_acquisition_pre)
                            if key_time:
                                str_acquisition = [
                                    str(key_time.group(4)), str(key_time.group(5)), str(key_time.group(6))]

                                self.container_var["acquisition times"]["SMPL"][str_smpl] = tk.StringVar()
                                self.container_var["acquisition times"]["SMPL"][str_smpl].set(str_acquisition[0] + ":"
                                                                                            + str_acquisition[1] + ":"
                                                                                            + str_acquisition[2])

                    for i, item in enumerate(data_file[2][0]):
                        if i > 0:
                            isotope = str(item[0])
                            list_isotopes.append(isotope)
                            helper_smpl[str_smpl][isotope] = []
                            helper_smpl_smoothed[str_smpl][isotope] = []

                    for index3, data in enumerate(data_file):
                        if index3 == 0:
                            number_measurements = len(data)
                            list_indices_measurements = []
                        if len(data) == number_measurements:
                            list_indices_measurements.append(index3)
                        #print(index3, len(data), data)
                        if index3 == 0: # Corrected values
                            for line, values in enumerate(data):
                                value_time = float(values[0])
                                list_time.append(value_time)
                                for j, value in enumerate(values):
                                    if j > 0:
                                        isotope = list_isotopes[j - 1]
                                        helper_smpl_smoothed[str_smpl][isotope].append(float(value))
                        if index3 == 73: # Original values
                            for line, values in enumerate(data):
                                for j, value in enumerate(values):
                                    isotope = list_isotopes[j]
                                    helper_smpl[str_smpl][isotope].append(float(value))
                        elif index3 == 6:    # Background interval (MA/FI/MI)
                            for i, interval in enumerate(data):
                                start_i = interval[0]
                                end_i = interval[1]
                                self.build_intervals(filetype="SMPL", filename=str_smpl, focus="BG",
                                                     list_time=list_time, start_i=start_i, end_i=end_i, id=i)
                        elif index3 == 7 and len(data) > 0: # Matrix interval (FI/MI)
                            for i, interval in enumerate(data):
                                start_i = interval[0]
                                end_i = interval[1]
                                self.build_intervals(filetype="SMPL", filename=str_smpl, focus="MAT",
                                                     list_time=list_time, start_i=start_i, end_i=end_i, id=i)
                                self.mode_ma = False
                        elif index3 == 8 and len(data) > 0: # Matrix interval (FI/MI)
                            for i, interval in enumerate(data):
                                start_i = interval[0]
                                end_i = interval[1]
                                self.build_intervals(filetype="SMPL", filename=str_smpl, focus="MAT",
                                                     list_time=list_time, start_i=start_i, end_i=end_i, id=i)
                                self.mode_ma = False
                        elif index3 == 10:    # Matrix interval (MA) / Inclusion interval (FI/MI)
                            for i, interval in enumerate(data):
                                start_i = interval[0]
                                end_i = interval[1]

                                if self.mode_ma == True:
                                    self.build_intervals(filetype="SMPL", filename=str_smpl, focus="MAT",
                                                         list_time=list_time, start_i=start_i, end_i=end_i, id=i)
                                elif self.mode_ma == False:
                                    self.pysills_mode = "FIMI"
                                    self.build_intervals(filetype="SMPL", filename=str_smpl, focus="INCL",
                                                         list_time=list_time, start_i=start_i, end_i=end_i, id=i)
                        elif index3 == 26 and len(data) > 0:  # IS (Matrix)
                            index_isotope = data[0][0] - 1
                            if self.mode_ma == False:
                                self.container_var["SMPL"][str_smpl]["Matrix Setup"]["IS"]["Name"].set(
                                    list_isotopes[index_isotope])
                            else:
                                self.container_var["SMPL"][str_smpl]["IS Data"]["IS"].set(list_isotopes[index_isotope])
                        elif index3 == 29 and len(data) > 0 and self.mode_ma == False:    # Concentration (Matrix)
                            for i, value in enumerate(data[0]):
                                self.container_var["SMPL"][str_smpl]["Matrix Setup"]["IS"]["Concentration"].set(value)
                        elif index3 == 30 and len(data) > 0 and self.mode_ma == False:    # Amount oxide (Matrix)
                            try:
                                amount_oxide = float(data[0][0])
                            except:
                                amount_oxide = 0.0

                            self.container_var["SMPL"][str_smpl]["Matrix Setup"]["Oxide"]["Concentration"].set(
                                amount_oxide)
                        elif index3 == 31 and len(data) > 0:    # Oxide (Matrix)
                            index_oxide = data[0][0] - 1
                            list_oxides = ["SiO2", "TiO2", "Fe2O3", "FeO", "MnO", "MgO", "CaO", "Na2O", "K2O"]
                            self.container_var["SMPL"][str_smpl]["Matrix Setup"]["Oxide"]["Name"].set(
                                list_oxides[index_oxide])
                        elif index3 == 33 and len(data) > 0 and self.mode_ma == True:    # Amount oxide (Sample)
                            if len(data[0]) > 1:
                                amount_oxide = float(data[0][0])
                            else:
                                amount_oxide = 0.0
                            self.container_var["SMPL"][str_smpl]["Matrix Setup"]["Oxide"]["Concentration"].set(
                                amount_oxide)
                            key = re.search(r"(\D+)(\d*)(\D+)(\d*)", list_oxides[index_oxide])
                            element_cation = key.group(1)

                            if len(key.group(2)) > 0:
                                n_cation = int(key.group(2))
                            else:
                                n_cation = 1

                            value_is = round((n_cation*self.chemistry_data[element_cation]/self.chemistry_data_oxides[
                                list_oxides[index_oxide]])*10**6, 4)

                            if self.mode_ma == True:
                                self.container_var["SMPL"][str_smpl]["IS Data"]["Concentration"].set(value_is)
                        elif index3 == 37 and len(data) > 0 and self.mode_ma == False:    # IS (Sample/Inclusion)
                            index_isotope = data[0][0] - 1
                            self.container_var["SMPL"][str_smpl]["IS Data"]["IS"].set(list_isotopes[index_isotope])
                        elif index3 == 40 and len(data) > 0:    # Concentration (Sample/Inclusion)
                            for i, value in enumerate(data[0]):
                                self.container_var["SMPL"][str_smpl]["IS Data"]["Concentration"].set(value)
                        elif index3 == 44 and len(data) > 0 and self.mode_ma == False:  # 2nd IS
                            index_isotope = data[0][0] - 1
                            self.container_var["SMPL"][str_smpl]["Second Internal Standard"]["Name"].set(
                                list_isotopes[index_isotope])
                        elif index3 == 47 and len(data) > 0 and self.mode_ma == False:  # 2nd IS concentration
                            try:
                                value = data[0][0]
                            except:
                                value = 0.0

                            self.container_var["SMPL"][str_smpl]["Second Internal Standard"]["Value"].set(value)
                            self.mode_2ndis = True

                            for key_setting in ["fi_setting", "mi_setting"]:
                                self.container_var[key_setting]["Quantification Method Option"].set(
                                    "Second Internal Standard (SILLS)")
                        elif index3 == 60 and len(data) > 0 and self.mode_ma == False:  # Matrix-only tracer (MOT)
                            index_isotope = data[0][0] - 1
                            self.container_var["SMPL"][str_smpl]["Host Only Tracer"]["Name"].set(
                                list_isotopes[index_isotope])
                            self.container_var["SMPL"][str_smpl]["Host Only Tracer"]["Value"].set("0.0")

                            try:
                                self.container_var["SMPL"][str_smpl]["Host Only Tracer"]["Amount"].set(amount_oxide)
                                self.container_var["SMPL"][str_smpl]["Host Only Tracer"]["Matrix"].set(
                                    list_oxides[index_oxide])
                            except:
                                print("No oxide amount found.")

                            if self.mode_2ndis == False:
                                for key_setting in ["fi_setting", "mi_setting"]:
                                    self.container_var[key_setting]["Quantification Method Option"].set(
                                        "Matrix-only Tracer (SILLS)")

                    helper_smpl[str_smpl]["Time"] = list_time
                    helper_smpl_smoothed[str_smpl]["Time"] = list_time

                    self.container_var["SMPL"][str_smpl]["ID"].set("A")
                    self.container_var["SMPL"][str_smpl]["Checkbox"].set(1)
                    self.container_var["SMPL"][str_smpl]["Sign Color"].set(self.sign_yellow)
                    self.lb_smpl.insert(tk.END, str(str_smpl))
                    self.list_smpl.append(str_smpl)
                    self.container_lists["SMPL"]["Long"].append(str_smpl)
                    self.container_lists["SMPL"]["Short"].append(str_smpl)

                    # Build pandas dataframe
                    column_names = ["Time"]
                    column_names.extend(list_isotopes)
                    data_columns = [list_time]
                    data_columns_smoothed = [list_time]

                    for isotope in list_isotopes:
                        data_columns.append(helper_smpl[str_smpl][isotope])
                        data_columns_smoothed.append(helper_smpl_smoothed[str_smpl][isotope])

                    data_dict = {col: values for col, values in zip(column_names, data_columns)}
                    data_dict_smoothed = {col: values for col, values in zip(column_names, data_columns_smoothed)}

                    try:
                        df_smpl = pd.DataFrame(data_dict)
                        df_smpl_smoothed = pd.DataFrame(data_dict_smoothed)
                    except:
                        for index, data_smpl in enumerate(data_sills["UNK"]):
                            for index2, data_file in enumerate(data_smpl):
                                if str_smpl == str(data_file[3][0][0][0][0]):
                                    helper_smpl[str_smpl] = {}
                                    helper_smpl_smoothed[str_smpl] = {}
                                    list_time = []
                                    for index3, data in enumerate(data_file):
                                        if index3 in list_indices_measurements:
                                            if index3 == 0:  # Corrected values
                                                for line, values in enumerate(data):
                                                    value_time = float(values[0])
                                                    list_time.append(value_time)
                                                    for j, value in enumerate(values):
                                                        if j > 0:
                                                            isotope = list_isotopes[j - 1]
                                                            if isotope not in helper_smpl_smoothed[str_smpl]:
                                                                helper_smpl_smoothed[str_smpl][isotope] = []
                                                            helper_smpl_smoothed[str_smpl][isotope].append(float(value))
                                            if index3 == list_indices_measurements[-1]:  # Original values
                                                if len(list_indices_measurements) > 1:
                                                    if len(data[0]) == len(list_isotopes):
                                                        for line, values in enumerate(data):
                                                            for j, value in enumerate(values):
                                                                isotope = list_isotopes[j]
                                                                if isotope not in helper_smpl[str_smpl]:
                                                                    helper_smpl[str_smpl][isotope] = []
                                                                helper_smpl[str_smpl][isotope].append(float(value))
                                                    else:
                                                        for index3, data in enumerate(data_file):
                                                            if index3 == list_indices_measurements[-2]:
                                                                if len(data[0]) == len(list_isotopes):
                                                                    for line, values in enumerate(data):
                                                                        for j, value in enumerate(values):
                                                                            isotope = list_isotopes[j]
                                                                            if isotope not in helper_smpl[str_smpl]:
                                                                                helper_smpl[str_smpl][isotope] = []
                                                                            helper_smpl[str_smpl][isotope].append(
                                                                                float(value))
                                                else:
                                                    for line, values in enumerate(data):
                                                        for j, value in enumerate(values):
                                                            if j > 0:
                                                                isotope = list_isotopes[j - 1]
                                                                if isotope not in helper_smpl[str_smpl]:
                                                                    helper_smpl[str_smpl][isotope] = []
                                                                helper_smpl[str_smpl][isotope].append(float(value))

                                    data_dict = {"Time": list_time}
                                    data_dict_smoothed = {"Time": list_time}
                                    for key, values in helper_smpl.items():
                                        for isotope, data in values.items():
                                            data_dict[isotope] = data
                                    for key, values in helper_smpl_smoothed.items():
                                        for isotope, data in values.items():
                                            data_dict_smoothed[isotope] = data

                                    df_smpl = pd.DataFrame(data_dict)
                                    df_smpl_smoothed = pd.DataFrame(data_dict_smoothed)

                    self.build_file_data_09(key=str_smpl, df_isotopes=list_isotopes, dataframe=df_smpl, times=list_time,
                                            dataframe_smoothed=df_smpl_smoothed, with_smoothed=False)
                    self.container_var["Spike Elimination"]["SMPL"]["State"] = True

    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)

            file_ending_pre = self.container_var["General Settings"]["Project type"].get()
            file_ending = file_ending_pre[1:]

            if "csv" in file_ending:
                list_file_endings = [("CSV files *.csv", "*.csv"), ("Project files *.proj", "*.proj"),
                                     ("SILLS files *.mat", "*.mat"), ("Text files *.txt", "*.txt")]
            elif "proj" in file_ending:
                list_file_endings = [("Project files *.proj", "*.proj"), ("CSV files *.csv", "*.csv"),
                                     ("SILLS files *.mat", "*.mat"), ("Text files *.txt", "*.txt")]

            filename = filedialog.askopenfilename(
                title="Open as", defaultextension=file_ending,
                filetypes=list_file_endings,
                initialdir=self.last_used_directory)

            self.projectname = filename.split("/")[-1]
            split_filename = filename.split("/")
            self.last_used_directory = '/'.join(split_filename[:-1])
            self.parent.title("PySILLS - " + str(self.projectname))

            n_commas = 0
            n_semicolons = 0

            if ".mat" in filename:
                #print("Filename:", filename)
                self.load_sills_file(filename=filename)
                mat_data = scipy.io.loadmat(filename)
                #print(mat_data.keys())

                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
                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 == "FIMI":
                    self.rb_ma.configure(state="disabled")
                    print("Please select the correct analysis mode (Fluid/Melt inclusion analysis).")
            else:
                try:
                    file_loaded = open(str(filename), "r")
                    loaded_lines = file_loaded.readlines()
                    n_lines = len(loaded_lines)
                    for i in range(10):
                        if i == 2:
                            n_commas += loaded_lines[i].count(",")
                            n_semicolons += loaded_lines[i].count(";")
                            if n_commas > 0 and n_semicolons == 0:
                                delimiter = ","
                            elif n_commas == 0 and n_semicolons > 0:
                                delimiter = ";"
                            elif n_commas + n_semicolons == 0:
                                n_commas += loaded_lines[4].count(",")
                                n_semicolons += loaded_lines[4].count(";")
                                if n_commas > 0 and n_semicolons == 0:
                                    delimiter = ","
                                elif n_commas == 0 and n_semicolons > 0:
                                    delimiter = ";"

                    if delimiter == "," and loaded_lines[2].count(",") > 3:
                        if str("\n") in loaded_lines[0]:
                            cleaned_lines = [sub.replace(str("\n"), "") for sub in loaded_lines]
                            cleaned_lines_final = [sub.rstrip(",") for sub in cleaned_lines]
                            loaded_lines = cleaned_lines_final
                    else:
                        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 == "":
                            line_std = str(loaded_lines[2].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.pysills_mode = "INCL"
                            #self.var_rb_mode.set(1)
                            self.var_rb_mode.set(1)
                        elif var_mode == "Melt Inclusion Analysis":
                            key_setting = "mi_setting"
                            #self.pysills_mode = "MI"
                            self.pysills_mode = "INCL"
                            #self.var_rb_mode.set(2)
                            self.var_rb_mode.set(1)
                        elif var_mode == "Inclusion Analysis":
                            key_setting = "fi_setting"
                            self.pysills_mode = "INCL"
                            self.var_rb_mode.set(1)
                        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"]
                            elif ("PYPITZER SETTINGS" in loaded_lines and "QUANTIFICATION SETTINGS (HALTER2002)"
                                    in loaded_lines and "QUANTIFICATION SETTINGS (BORISOVA2021)" 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 in ["FI", "INCL"]:
                        ## 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 len(splitted_data) == 1:
                                    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"]:
                                    current_filename = splitted_data[0]
                                    var_last_compound = splitted_data[1]
                                    var_melting_temperature = splitted_data[2]

                                    self.container_var["SMPL"][current_filename]["Last compound"] = tk.StringVar()
                                    self.container_var["SMPL"][current_filename][
                                        "Melting temperature"] = tk.StringVar()
                                    self.container_var["SMPL"][current_filename]["Last compound"].set(
                                        var_last_compound)
                                    self.container_var["SMPL"][current_filename]["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 len(splitted_data) == 1:
                                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 len(splitted_data) == 1:
                                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 len(splitted_data) == 1:
                                    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 len(splitted_data) == 1:
                                    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(";")

                            if len(splitted_std) == 1:
                                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 len(splitted_data) == 1:
                                    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"]:
                                    current_filename = splitted_data[0]
                                    var_last_compound = splitted_data[1]
                                    var_melting_temperature = splitted_data[2]

                                    self.container_var["SMPL"][current_filename]["Last compound"] = tk.StringVar()
                                    self.container_var["SMPL"][current_filename][
                                        "Melting temperature"] = tk.StringVar()
                                    self.container_var["SMPL"][current_filename]["Last compound"].set(
                                        var_last_compound)
                                    self.container_var["SMPL"][current_filename]["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 len(splitted_data) == 1:
                                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 len(splitted_data) == 1:
                                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 len(splitted_data) == 1:
                                    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 len(splitted_data) == 1:
                                    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(";")

                            if len(splitted_data) == 1:
                                splitted_data = line_data.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 in ["FI", "INCL"]:
                        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, restart=True,
            last_used_directory=self.last_used_directory, last_used_directory_input=self.last_used_directory_input)
        root.mainloop()

    ####################
    ## DATA PROCESSING #
    ####################


    def find_icpms_data_in_file(self, filename_long, filetype=None, only_time_check=False):
        str_filename_long = filename_long
        str_filename_short = str_filename_long.split("/")[-1]
        potential_isotopes = ["Na23", "Al27", "Si29", "P31", "S32", "S33", "K39", "Ca43", "Ca44", "Fe57", "Pb208",
                              "U238"]
        list_indices = []
        var_timestamp = None

        if only_time_check == True:
            df = None
            file_info = None
            condition = False
            with open(str_filename_long, "r", encoding="utf-8", errors="ignore") as file:
                for lineno, line in enumerate(file, start=0):
                    if condition:
                        break
                    for isotope in potential_isotopes:
                        if condition:
                            break
                        if "Acquired" in line:
                            key_start = re.search(
                                r"Acquired\s+\:\s+(\d+)\/(\d+)\/(\d+)\s+(\d+)\:(\d+)\:(\d+)( using Batch )(\w+)", line)
                            if key_start:
                                str_acquisition = [
                                    str(key_start.group(4)), str(key_start.group(5)), str(key_start.group(6))]
                                if filetype != None:
                                    self.container_var["acquisition times"][filetype][str_filename_short] = tk.StringVar()
                                    self.container_var["acquisition times"][filetype][str_filename_short].set(
                                        str_acquisition[0] + ":" + str_acquisition[1] + ":" + str_acquisition[2])
                            var_timestamp = lineno
                            condition = True
                        if isotope in line:
                            list_indices.append(lineno)
                            condition = True
        else:
            with open(str_filename_long, "r", encoding="utf-8", errors="ignore") as file:
                for lineno, line in enumerate(file, start=0):
                    for isotope in potential_isotopes:
                        if isotope in line:
                            list_indices.append(lineno)
                        if "Acquired" in line:
                            key_start = re.search(
                                r"Acquired\s+\:\s+(\d+)\/(\d+)\/(\d+)\s+(\d+)\:(\d+)\:(\d+)( using Batch )(\w+)", line)
                            if key_start:
                                str_acquisition = [
                                    str(key_start.group(4)), str(key_start.group(5)), str(key_start.group(6))]
                                if filetype != None:
                                    self.container_var["acquisition times"][filetype][str_filename_short] = tk.StringVar()
                                    self.container_var["acquisition times"][filetype][str_filename_short].set(
                                        str_acquisition[0] + ":" + str_acquisition[1] + ":" + str_acquisition[2])
                            var_timestamp = lineno

        # list_indices = []
        #
        # try:
        #     file = pd.read_csv(str_filename_long, sep=",", engine="python")
        # except:
        #     file = pd.read_csv(str_filename_long, sep=";", engine="python")
        #
        # for isotope in potential_isotopes:
        #     a = file[file.columns[file.dtypes == "object"]].apply(lambda x: " ".join(x), axis=1).str.contains(isotope)
        #     matches = file.index[a]
        #     if len(matches) > 0:
        #         list_indices.append(matches[0])
        #
        # var_skipheader = int(list_indices[0] + 1)
        if only_time_check == False:
            var_skipheader = int(list_indices[0])
            var_skipfooter = 0

            for skip_footer in range(10):
                try:
                    df = DE(filename_long=str_filename_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=skip_footer)
                except:
                    var_skipfooter += 1

            df = DE(filename_long=str_filename_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
            file_info = {"skipheader": var_skipheader, "skipfooter": var_skipfooter, "delimiter": ",",
                         "timestamp": var_timestamp}

        return df, file_info

    def get_delimiter(self, var_line):
        n_commas = 0
        n_semicolons = 0

        n_commas += var_line.count(",")
        n_semicolons += var_line.count(";")

        if n_commas > 0 and n_semicolons == 0:
            delimiter = ","
        elif n_commas == 0 and n_semicolons > 0:
            delimiter = ";"

        return delimiter

    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=self.last_used_directory_input)

        split_filename = filename[0].split("/")

        self.last_used_directory_input = '/'.join(split_filename[:-1])

        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, file_info = self.find_icpms_data_in_file(filename_long=str_filename_long)
                    var_skipheader = file_info["skipheader"]
                    var_skipfooter = file_info["skipfooter"]
                    self.container_icpms["skipheader"] = file_info["skipheader"]
                    self.container_icpms["skipfooter"] = file_info["skipfooter"]

                    if var_skipheader == 3 and var_skipfooter == 1:
                        try:
                            dates, times = Data(filename=str_filename_long).import_as_list(
                                skip_header=3, skip_footer=1, timestamp=2, icpms="Agilent 7900s")
                            var_timestamp = 2
                            self.container_icpms["timestamp"] = var_timestamp
                            self.container_icpms["name"] = "Agilent 7900s"
                        except:
                            self.container_icpms["name"] = "Undefined ICP-MS"
                    elif var_skipheader == 3 and var_skipfooter == 0:
                        try:
                            dates, times = Data(filename=str_filename_long).import_as_list(
                                skip_header=3, skip_footer=1, timestamp=2, icpms="Agilent 7900s")
                            var_timestamp = 2
                            self.container_icpms["timestamp"] = var_timestamp
                            self.container_icpms["name"] = "Agilent 7900s"
                        except:
                            self.container_icpms["name"] = "Undefined ICP-MS"
                    else:
                        self.container_icpms["name"] = "Undefined ICP-MS"

                    self.var_opt_icp.set(self.container_icpms["name"])

                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):
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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"] = background_color_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=font_color_light, bg=background_color_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=font_color_dark,
            bg=background_color_elements).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=font_color_dark, 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=font_color_dark,
            bg=background_color_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=background_color_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=background_color_light, fg=font_color_dark)
            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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0,
                highlightbackground=background_color_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."""
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Spike elimination threshold"][0]
        n_columns = self.window_dimensions["Spike elimination threshold"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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"] = background_color_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 in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_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=font_color_dark, bg=background_color_elements).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=font_color_light,
            bg=self.bg_colors["BG Window"]).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=font_color_dark,
            bg=self.bg_colors["White"]).create_simple_entry(var=var_threshold, text_default=var_threshold.get())
        entr_01.bind( "<Return>", lambda event, variable=var_threshold: self.update_threshold_value(variable, event))

        ## BUTTONS
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent, bg=accent_color).create_simple_button(
            text="Update values", bg_active=accent_color, fg_active=font_color_accent,
            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=font_color_dark, bg=background_color_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=background_color_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=background_color_light, fg=font_color_dark)
                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=background_color_light, fg=font_color_dark)
                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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=background_color_light, width=8)
                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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=background_color_light, width=8)
                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=background_color_light, fg=font_color_dark)
                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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=background_color_light, width=8)
                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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=background_color_light, width=8)
                text_se_threshold.window_create("insert", window=entr_i)
                text_se_threshold.insert("end", "\n")

    def update_threshold_value(self, variable, event):
        val_threshold_default = int(variable.get())

        if val_threshold_default < 0:
            val_threshold_default = abs(val_threshold_default)

        variable.set(val_threshold_default)

        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            self.container_var["Spike Elimination"]["Threshold"][isotope].set(val_threshold_default)
            val_dwell_time = 10/val_threshold_default
            self.container_var["dwell_times"]["Entry"][isotope].set(val_dwell_time)

    def detect_signal_interval(self, mode="BG"):
        if self.pysills_mode == "MA":
            key_setting = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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
            isotope_is = "Select IS"
            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 in ["FI", "INCL"]:
                    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 in ["FI", "INCL"]:
                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 in ["FI", "INCL"]:
                    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."""
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Check-up oxides"][0]
        n_columns = self.window_dimensions["Check-up oxides"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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"] = background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).create_frame(relief=tk.FLAT)

        ## LABELS
        str_lbl_01 = self.language_dict["Select isotope"][self.var_language]
        str_lbl_02 = self.language_dict["Sample"][self.var_language]
        str_lbl_03 = self.language_dict["Matrix"][self.var_language]
        str_lbl_04 = self.language_dict["Inclusion"][self.var_language]
        str_lbl_05 = self.language_dict["Select all"][self.var_language]
        str_lbl_06 = self.language_dict["Run"][self.var_language]
        str_lbl_07 = self.language_dict["Select"][self.var_language]
        str_lbl_08 = self.language_dict["Setup - Oxide ratios"][self.var_language]
        str_lbl_09 = self.language_dict["Setup - Reference element"][self.var_language]
        str_lbl_10 = self.language_dict["Setup - Oxide selection"][self.var_language]
        str_lbl_11 = self.language_dict["Run 100 wt.% oxides calculation for"][self.var_language]
        str_lbl_12 = self.language_dict["Mineral quantification"][self.var_language]
        str_lbl_13 = self.language_dict["Inclusion quantification"][self.var_language]
        str_lbl_14 = self.language_dict["Select all oxides"][self.var_language]
        str_lbl_15 = self.language_dict["Deselect all oxides"][self.var_language]
        str_lbl_16 = self.language_dict["Rock-forming elements"][self.var_language]
        str_lbl_17 = self.language_dict["Guess the composition"][self.var_language]
        str_lbl_18 = self.language_dict["Setup - Files"][self.var_language]
        str_lbl_19 = self.language_dict["Alkali metals"][self.var_language]
        str_lbl_20 = self.language_dict["Alkaline earth metals"][self.var_language]
        str_lbl_21 = self.language_dict["Transition metals"][self.var_language]
        str_lbl_22 = self.language_dict["Other metals"][self.var_language]
        str_lbl_23 = self.language_dict["Metalloids"][self.var_language]
        str_lbl_24 = self.language_dict["Lanthanides"][self.var_language]
        str_lbl_25 = self.language_dict["Actinides"][self.var_language]
        str_lbl_26 = self.language_dict["Non-metals"][self.var_language]
        str_lbl_27 = self.language_dict["Halogens"][self.var_language]
        str_lbl_28 = self.language_dict["Noble gases"][self.var_language]

        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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_19, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_20, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_21, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_22, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_23, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_24, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_25, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_26, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_27, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_28, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_08, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_02 + "/"+ str_lbl_03, 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=font_color_dark,
            bg=background_color_elements).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=font_color_dark,
            bg=background_color_elements).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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_dark,
            bg=background_color_elements).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=font_color_dark,
            bg=background_color_elements).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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_09, 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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_12, 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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_13, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_10, 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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_14, 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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_15, 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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_16, 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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_17, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_18, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_02 + "/"+ str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_11, 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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light)
        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=font_color_dark,
            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=font_color_dark,
            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=font_color_dark,
            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=font_color_dark,
            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=background_color_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=background_color_light,
                             fg=font_color_dark)
            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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0,
                highlightbackground=background_color_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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_ref_i.config(
                bg=background_color_elements, fg=font_color_dark,
                activeforeground=font_color_light, activebackground=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=background_color_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 in ["MI", "INCL"]:
            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=background_color_light,
                                 fg=font_color_dark)
                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=font_color_dark, bg=self.bg_colors["White"],
                    highlightthickness=0, highlightbackground=background_color_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=font_color_dark, bg=background_color_elements,
                    activeforeground=font_color_light, activebackground=accent_color)
                opt_ref_i.config(
                    bg=background_color_elements, fg=font_color_dark,
                    activeforeground=font_color_light, activebackground=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=background_color_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=font_color_dark,
                        bg=background_color_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=background_color_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=font_color_dark,
                        bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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=background_color_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=font_color_dark,
                            bg=background_color_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(str_lbl_01)
        var_opt_incl_isotope = tk.StringVar()
        var_opt_incl_isotope.set(str_lbl_01)

        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=font_color_dark,
            bg=background_color_elements).create_option_isotope(
            var_iso=var_opt_mat_isotope, option_list=list_mat_isotopes, text_set=var_opt_mat_isotope.get(),
            fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=accent_color)
        opt_mat_isotope.config(
            fg=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=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=font_color_dark,
            bg=background_color_elements).create_option_isotope(
            var_iso=var_opt_incl_isotope, option_list=list_incl_isotopes, text_set=var_opt_incl_isotope.get(),
            fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=accent_color)
        opt_incl_isotope.config(
            fg=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=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=font_color_dark, n_rows=1, n_columns=int(1.5*var_header_n),
            bg=background_color_elements).create_simple_checkbox(
            var_cb=self.oxide_calculation_mat, text=str_lbl_02 + "/"+ str_lbl_03, 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=font_color_dark, n_rows=1, n_columns=int(1.5*var_header_n),
            bg=background_color_elements).create_simple_checkbox(
            var_cb=self.oxide_calculation_incl, text=str_lbl_04, 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."""
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_lbl_01 = self.language_dict["Check-Up"][self.var_language]
        str_lbl_02 = self.language_dict["Internal standard"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Check-up IS"][0]
        n_columns = self.window_dimensions["Check-up IS"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_checkup_is = tk.Toplevel(self.parent)
        subwindow_checkup_is.title(str_lbl_01 + " - " + str_lbl_02)
        subwindow_checkup_is.geometry(var_geometry)
        subwindow_checkup_is.resizable(False, False)
        subwindow_checkup_is["bg"] = background_color_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
        str_lbl_03 = self.language_dict["Sample"][self.var_language]
        str_lbl_04 = self.language_dict["Matrix"][self.var_language]
        str_lbl_05 = self.language_dict["Inclusion"][self.var_language]
        str_lbl_06 = self.language_dict["Select isotope"][self.var_language]

        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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_02 + " (" + str_lbl_03 + "/" + str_lbl_04 + ")", 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_02 + " (" + str_lbl_05 + ")", 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=font_color_dark, bg=background_color_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=background_color_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=background_color_light, fg=font_color_dark)
            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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_is_i.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, 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=font_color_dark, bg=self.bg_colors["White"],
                highlightthickness=0, highlightbackground=background_color_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=font_color_dark, bg=background_color_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=background_color_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=background_color_light, fg=font_color_dark)
                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(str_lbl_06)
                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=font_color_dark, bg=background_color_elements,
                    activeforeground=font_color_light, activebackground=accent_color)
                opt_is_i.config(
                    bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                    activeforeground=font_color_light, 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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0,
                    highlightbackground=background_color_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(str_lbl_06)
        self.var_opt_is_incl_default.set(str_lbl_06)

        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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=accent_color,
            command=lambda var_opt=self.var_opt_is_mat_default: self.change_default_is(var_opt))
        opt_is_mat["menu"].config(
            fg=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=accent_color)
        opt_is_mat.config(
            fg=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=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=font_color_dark,
                bg=background_color_elements).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=font_color_light,
                bg_active=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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            opt_is_incl.config(
                fg=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=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=font_color_dark,
            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=font_color_dark,
                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)

    # 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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        var_title = self.language_dict["General Settings"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["General settings"][0]
        n_columns = self.window_dimensions["General settings"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_generalsettings = tk.Toplevel(self.parent)
        subwindow_generalsettings.title(var_title)
        subwindow_generalsettings.geometry(var_geometry)
        subwindow_generalsettings.resizable(False, False)
        subwindow_generalsettings["bg"] = background_color_dark

        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 = self.language_dict["Dwell times"][self.var_language]
        str_lbl_12 = self.language_dict["Default value"][self.var_language]
        str_lbl_13 = self.language_dict["Application launcher"][self.var_language]
        str_lbl_14 = self.language_dict["PySILLS color scheme"][self.var_language]
        str_lbl_15 = self.language_dict["Default author"][self.var_language]
        str_lbl_16 = self.language_dict["Default SRM"][self.var_language]
        str_lbl_17 = self.language_dict["Calculation formula from ..."][self.var_language]
        str_lbl_18 = self.language_dict["Background"][self.var_language]
        str_lbl_19 = self.language_dict["Main signal"][self.var_language]
        str_lbl_20 = self.language_dict["File type"][self.var_language]
        str_lbl_21 = self.language_dict["Delimiter"][self.var_language]
        str_lbl_22 = self.language_dict["Line width"][self.var_language]
        str_lbl_23 = self.language_dict["Save settings"][self.var_language]
        str_lbl_24 = self.language_dict["Create launcher"][self.var_language]
        str_lbl_25 = self.language_dict["Arithmetic mean"][self.var_language]
        str_lbl_26 = self.language_dict["Average of every interval"][self.var_language]
        str_lbl_27 = self.language_dict["Stack all intervals into one"][self.var_language]
        str_lbl_28 = self.language_dict["Median"][self.var_language]
        str_lbl_29 = self.language_dict["Screen resolution"][self.var_language]
        str_lbl_30 = self.language_dict["Python path"][self.var_language]
        str_lbl_31 = self.language_dict["PySILLS path"][self.var_language]
        str_lbl_32 = self.language_dict["Default ICP-MS"][self.var_language]
        str_lbl_33 = self.language_dict["Project file"][self.var_language]

        lbl_01 = SE(
            parent=subwindow_generalsettings, row_id=2, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_element)
        lbl_02 = SE(
            parent=subwindow_generalsettings, row_id=5, column_id=start_column, n_rows=2, n_columns=10,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="Standard Reference\n Material (SRM)", relief=tk.FLAT, fontsize=font_element)
        lbl_13 = SE(
            parent=subwindow_generalsettings, row_id=0, column_id=25, n_rows=1, n_columns=9,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_13, relief=tk.FLAT, fontsize=font_element)
        lbl_14 = SE(
            parent=subwindow_generalsettings, row_id=2, column_id=25, n_rows=1, n_columns=9,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_14, relief=tk.FLAT, fontsize=font_element)
        lbl_06 = SE(
            parent=subwindow_generalsettings, row_id=0, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize=font_element)
        lbl_07 = SE(
            parent=subwindow_generalsettings, row_id=5, column_id=11, n_rows=2, n_columns=13,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, relief=tk.FLAT, fontsize=font_element)
        lbl_08 = SE(
            parent=subwindow_generalsettings, row_id=9, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_06, relief=tk.FLAT, fontsize=font_element)
        lbl_09 = SE(
            parent=subwindow_generalsettings, row_id=18, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_07, relief=tk.FLAT, fontsize=font_element)
        lbl_10 = SE(
            parent=subwindow_generalsettings, row_id=11, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_08, relief=tk.FLAT, fontsize=font_element)
        lbl_11 = SE(
            parent=subwindow_generalsettings, row_id=0, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_09, relief=tk.FLAT, fontsize=font_element)
        lbl_11 = SE(
            parent=subwindow_generalsettings, row_id=13, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_10, relief=tk.FLAT, fontsize=font_element)
        lbl_11 = SE(
            parent=subwindow_generalsettings, row_id=9, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_11, relief=tk.FLAT, fontsize=font_element)
        lbl_15 = SE(
            parent=subwindow_generalsettings, row_id=4, column_id=25, n_rows=1, n_columns=9,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_29, relief=tk.FLAT, fontsize=font_element)
        lbl_30 = SE(
            parent=subwindow_generalsettings, row_id=11, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_30, relief=tk.FLAT, fontsize=font_element)
        lbl_31 = SE(
            parent=subwindow_generalsettings, row_id=13, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_31, relief=tk.FLAT, fontsize=font_element)
        lbl_09 = SE(
            parent=subwindow_generalsettings, row_id=18, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_32, relief=tk.FLAT, fontsize=font_element)
        lbl_33 = SE(
            parent=subwindow_generalsettings, row_id=21, column_id=start_column, n_rows=1, n_columns=5,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_33, relief=tk.FLAT, fontsize=font_element)

        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_12, relief=tk.FLAT, fontsize=font_element)
        lbl_01a = SE(
            parent=subwindow_generalsettings, row_id=3, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_15, relief=tk.FLAT, fontsize=font_element)
        lbl_02a = SE(
            parent=subwindow_generalsettings, row_id=7, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_16, relief=tk.FLAT, fontsize=font_element)
        lbl_06a = SE(
            parent=subwindow_generalsettings, row_id=1, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_17, relief=tk.FLAT, fontsize=font_element, anchor=tk.W)
        lbl_07a = SE(
            parent=subwindow_generalsettings, row_id=7, column_id=11, n_rows=1, n_columns=7,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_18, relief=tk.FLAT, fontsize=font_element)
        lbl_07b = SE(
            parent=subwindow_generalsettings, row_id=8, column_id=11, n_rows=1, n_columns=7,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_19, relief=tk.FLAT, fontsize=font_element)
        lbl_09a = SE(
            parent=subwindow_generalsettings, row_id=19, column_id=start_column, n_rows=1, n_columns=5,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_20, relief=tk.FLAT, fontsize=font_element)
        lbl_09b = SE(
            parent=subwindow_generalsettings, row_id=20, column_id=start_column, n_rows=1, n_columns=5,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_21, relief=tk.FLAT, fontsize=font_element)
        lbl_10a = SE(
            parent=subwindow_generalsettings, row_id=12, column_id=start_column, n_rows=1, n_columns=5,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_22, relief=tk.FLAT, fontsize=font_element)

        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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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))
        entr_30 = SE(
            parent=subwindow_generalsettings, row_id=12, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["Python path"], text_default=self.container_var["Python path"].get(), command=None)
        entr_31 = SE(
            parent=subwindow_generalsettings, row_id=14, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["PySILLS path"], text_default=self.container_var["PySILLS path"].get(), command=None)
        entr_32 = SE(
            parent=subwindow_generalsettings, row_id=15, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["PySILLS script"], text_default=self.container_var["PySILLS script"].get(),
            command=None)

        entr_11a.configure(font=font_element)
        entr_01a.configure(font=font_element)
        entr_07a.configure(font=font_element)
        entr_07b.configure(font=font_element)
        entr_07c.configure(font=font_element)
        entr_07d.configure(font=font_element)
        entr_10a.configure(font=font_element)
        entr_30.configure(font=font_element)
        entr_31.configure(font=font_element)
        entr_32.configure(font=font_element)

        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_colorschemes = [
            "Dark scheme", "Light scheme", "Boho theme 1", "Synthwave theme", "Gunmetal theme",
            "Dark Jungle", "Noble Room"]
        list_screenresolutions = ["3840x2160", "1920x1080", "1280x720"]
        list_colormaps.sort()
        list_filetypes = ["*.csv", "*.txt"]
        list_filetypes.sort()
        list_delimiter = ["comma", "semicolon"]
        list_delimiter.sort()
        list_languages.sort()
        list_projecttypes = ["*.proj", "*.csv"]
        list_projecttypes.sort()

        opt_srm = SE(
            parent=subwindow_generalsettings, row_id=8, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=accent_color)
        opt_colormaps = SE(
            parent=subwindow_generalsettings, row_id=10, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=accent_color)
        opt_icpms_default = SE(
            parent=subwindow_generalsettings, row_id=19, column_id=11, n_rows=1, n_columns=13,
            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_light, bg_active=accent_color)
        opt_projecttype = SE(
            parent=subwindow_generalsettings, row_id=21, column_id=5, n_rows=1, n_columns=5,
            fg=font_color_dark, bg=background_color_elements).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["Project type"],
            var_default=self.container_var["General Settings"]["Project type"].get(), var_list=list_projecttypes,
            fg_active=font_color_light, bg_active=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")

        opt_srm.configure(font=font_option)
        opt_colormaps.configure(font=font_option)
        opt_filetype.configure(font=font_option)
        opt_delimiter.configure(font=font_option)
        opt_language.configure(font=font_option)

        opt_colorscheme = SE(
            parent=subwindow_generalsettings, row_id=3, column_id=25, n_rows=1, n_columns=9,
            fg=font_color_dark, bg=background_color_elements).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["Color scheme"],
            var_default=self.container_var["General Settings"]["Color scheme"].get(), var_list=list_colorschemes,
            fg_active=font_color_light, bg_active=accent_color)
        opt_screenresolution = SE(
            parent=subwindow_generalsettings, row_id=5, column_id=25, n_rows=1, n_columns=9,
            fg=font_color_dark, bg=background_color_elements).create_simple_optionmenu(
            var_opt=self.container_var["General Settings"]["Screen resolution"],
            var_default=self.container_var["General Settings"]["Screen resolution"].get(),
            var_list=list_screenresolutions, fg_active=font_color_light, bg_active=accent_color)

        opt_colorscheme.configure(font=font_option)
        opt_screenresolution.configure(font=font_option)

        self.gui_elements["general_settings"]["Option Menu"]["General"].extend(
            [opt_srm, opt_colormaps, opt_filetype, opt_delimiter, opt_language])

        ## Radiobuttons
        rb_06a = SE(
            parent=subwindow_generalsettings, row_id=2, column_id=11, n_rows=1, n_columns=13,
            fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["General Settings"]["LOD Selection"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["General Settings"]["LOD Selection"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text="Longerich et al. (1996)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")

        rb_06c = SE(
            parent=subwindow_generalsettings, row_id=14, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Desired Average"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_25,
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold")
        rb_06d = SE(
            parent=subwindow_generalsettings, row_id=15, column_id=start_column, n_rows=1, n_columns=10,
            fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Desired Average"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_28,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Interval Processing"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_26,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["General Settings"]["Interval Processing"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_27,
            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])

        rb_06a.configure(font=font_element)
        rb_06b.configure(font=font_element)
        rb_06c.configure(font=font_element)
        rb_06d.configure(font=font_element)
        rb_07a.configure(font=font_element)
        rb_07b.configure(font=font_element)

        ## Buttons
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        btn_01 = SE(
            parent=subwindow_generalsettings, row_id=19, column_id=25, n_rows=2, n_columns=9,
            fg=font_color_accent, bg=accent_color).create_simple_button(
            text=str_lbl_23, bg_active=accent_color, fg_active=font_color_accent,
            command=self.confirm_general_settings)
        btn_13 = SE(
            parent=subwindow_generalsettings, row_id=1, column_id=25, n_rows=1, n_columns=9,
            fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_24, bg_active=accent_color, fg_active=font_color_accent,
            command=self.create_starter_file)

        btn_01.configure(font=font_element)
        btn_13.configure(font=font_element)

        self.gui_elements["general_settings"]["Button"]["General"].extend([btn_01])

        self.check_lw_value(var_entr=self.container_var["General Settings"]["Line width"], event="")

        # INITIALIZATION
        self.get_current_path_python()
        self.get_current_path_pysills_folder()
        self.get_current_path_pysills_script()

    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)
            str_key = str("Default ICP-MS") + ";" + str(self.var_opt_icp.get()) + ";\n"
            file_settings.write(str_key)

    def check_srm_settings(self):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Check-up SRM"][0]
        n_columns = self.window_dimensions["Check-up SRM"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        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"] = background_color_dark

        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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_light).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=font_color_dark, bg=background_color_light).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=font_color_dark, bg=background_color_elements).create_simple_optionmenu(
            var_opt=var_opt_srm, var_default=var_opt_srm.get(), var_list=list_srm,
            fg_active=font_color_light, bg_active=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":
            if var_opt in self.srm_actual:
                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)
            else:
                for str_srm in np.sort(list(self.srm_actual.keys())):
                    for element in np.sort(list(self.srm_actual[str_srm].keys())):
                        entry_isotope = [element, self.srm_actual[var_opt][element]]
                        var_tv.insert("", tk.END, values=entry_isotope)

    def check_interval_settings(self):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_lbl_01 = self.language_dict["Check-Up"][self.var_language]
        str_lbl_02 = self.language_dict["Calculation Intervals"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Check-up intervals"][0]
        n_columns = self.window_dimensions["Check-up intervals"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_intervals = tk.Toplevel(self.parent)
        subwindow_intervals.title(str_lbl_01 + " - " + str_lbl_02)
        subwindow_intervals.geometry(var_geometry)
        subwindow_intervals.resizable(False, False)
        subwindow_intervals["bg"] = background_color_dark

        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)

        str_lbl_03 = self.language_dict["Name"][self.var_language]
        str_lbl_04 = self.language_dict["Category"][self.var_language]
        str_lbl_05 = self.language_dict["ID"][self.var_language]
        str_lbl_06 = self.language_dict["Start"][self.var_language]
        str_lbl_07 = self.language_dict["End"][self.var_language]

        if self.pysills_mode == "MA":
            var_categories = [str_lbl_03, str_lbl_04, str_lbl_05, str_lbl_06, str_lbl_07]
            var_widths = ["160", "90", "90", "90", "90"]
        elif self.pysills_mode in ["FI", "INCL"]:
            var_categories = [str_lbl_03, str_lbl_04, str_lbl_05, str_lbl_06, str_lbl_07]
            var_widths = ["160", "90", "90", "90", "90"]
        elif self.pysills_mode == "MI":
            var_categories = [str_lbl_03, str_lbl_04, str_lbl_05, str_lbl_06, str_lbl_07]
            var_widths = ["160", "90", "90", "90", "90"]

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

        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=font_color_dark,
            bg=background_color_light).create_frame(relief=tk.FLAT)

        ## FIGURES
        fig_checkup_std = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_light)
        fig_checkup_smpl = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_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
        str_lbl_03 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_04 = self.language_dict["Sample Files"][self.var_language]
        str_lbl_05 = self.language_dict["Before"][self.var_language]
        str_lbl_06 = self.language_dict["Next"][self.var_language]
        str_lbl_07 = self.language_dict["Setup"][self.var_language]

        lbl_std = SE(
            parent=subwindow_intervals, row_id=start_row, column_id=start_column, n_rows=1, n_columns=26,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
                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 in ["FI", "INCL"]:
            btn_std_03 = SE(
                parent=subwindow_intervals, row_id=start_row, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
                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 in ["FI", "INCL"]:
            btn_smpl_03 = SE(
                parent=subwindow_intervals, row_id=start_row + 16, column_id=start_column + 38, n_rows=1, n_columns=6,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, 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=font_color_dark, 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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_lbl_01 = self.language_dict["Check-Up"][self.var_language]
        str_lbl_02 = self.language_dict["Acquisition Times"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Check-up acquisition times"][0]
        n_columns = self.window_dimensions["Check-up acquisition times"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_aquisition_times = tk.Toplevel(self.parent)
        subwindow_aquisition_times.title(str_lbl_01 + " - " + str_lbl_02)
        subwindow_aquisition_times.geometry(var_geometry)
        subwindow_aquisition_times.resizable(False, False)
        subwindow_aquisition_times["bg"] = background_color_dark

        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
        str_lbl_03 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_04 = self.language_dict["Sample Files"][self.var_language]

        lbl_std = SE(
            parent=subwindow_aquisition_times, row_id=start_row, column_id=start_column, n_rows=1, n_columns=16,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_dark, 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=font_color_dark, 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
        str_lbl_05 = self.language_dict["Name"][self.var_language]
        str_lbl_06 = self.language_dict["Acquisition Time"][self.var_language]

        self.tv_std = SE(
            parent=subwindow_aquisition_times, row_id=start_row + 1, column_id=start_column, n_rows=14, n_columns=15,
            fg=font_color_dark, bg=background_color_light).create_treeview(
            n_categories=2, text_n=[str_lbl_05, str_lbl_06],
            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=font_color_dark, bg=background_color_light).create_treeview(
            n_categories=2, text_n=[str_lbl_05, str_lbl_06],
            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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_lbl_01 = self.language_dict["Check-Up"][self.var_language]
        str_lbl_02 = self.language_dict["Imported Files"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Check-up files"][0]
        n_columns = self.window_dimensions["Check-up files"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_imported_files = tk.Toplevel(self.parent)
        subwindow_imported_files.title(str_lbl_01 + " - " + str_lbl_02)
        subwindow_imported_files.geometry(var_geometry)
        subwindow_imported_files.resizable(False, False)
        subwindow_imported_files["bg"] = background_color_dark

        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)

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

        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=font_color_dark,
            bg=background_color_light).create_frame(relief=tk.FLAT)

        ## LABELS
        str_lbl_03 = self.language_dict["Standard Files"][self.var_language]
        str_lbl_04 = self.language_dict["Sample Files"][self.var_language]

        lbl_std = SE(
            parent=subwindow_imported_files, row_id=start_row, column_id=start_column, n_rows=1, n_columns=26,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize="sans 10 bold")

        ## FIGURES
        fig_checkup_std = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_light)
        fig_checkup_smpl = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_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
        str_lbl_05 = self.language_dict["Before"][self.var_language]
        str_lbl_06 = self.language_dict["Next"][self.var_language]

        btn_std_01 = SE(
            parent=subwindow_imported_files, row_id=start_row, column_id=start_column + 26, n_rows=1, n_columns=6,
            fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_05, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light,
            command=lambda filetype="SMPL", var_fig=fig_checkup_smpl: self.change_graph_checkup(filetype, var_fig))

        ## TREEVIEW
        str_lbl_07 = self.language_dict["Name"][self.var_language]
        str_lbl_08 = self.language_dict["N(isotopes)"][self.var_language]
        str_lbl_09 = self.language_dict["t(start)"][self.var_language]
        str_lbl_10 = self.language_dict["t(end)"][self.var_language]
        str_lbl_11 = self.language_dict["t(day)"][self.var_language]
        str_lbl_12 = self.language_dict["date"][self.var_language]

        tv_std = SE(
            parent=subwindow_imported_files, row_id=start_row + 1, column_id=start_column, n_rows=15, n_columns=26,
            fg=font_color_dark, bg=self.bg_colors["White"]).create_treeview(
            n_categories=6, text_n=[str_lbl_07, str_lbl_08, str_lbl_09, str_lbl_10, str_lbl_11, str_lbl_12],
            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]

            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=font_color_dark, bg=self.bg_colors["White"]).create_treeview(
            n_categories=6, text_n=[str_lbl_07, str_lbl_08, str_lbl_09, str_lbl_10, str_lbl_11, str_lbl_12],
            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", "INCL"]:
                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", "INCL"]:
                    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."""
        str_title_01 = self.language_dict["Mineral Analysis"][self.var_language]
        str_title_02 = self.language_dict["Extras"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["MA Extras"][0]
        n_columns = self.window_dimensions["MA Extras"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_ma_extras = tk.Toplevel(self.parent)
        self.subwindow_ma_extras.title(str_title_01 + " - " + str_title_02)
        self.subwindow_ma_extras.geometry(var_geometry)
        self.subwindow_ma_extras.resizable(False, False)
        self.subwindow_ma_extras["bg"] = self.bg_colors["BG Window"]

        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
        str_lbl_01 = self.language_dict["Mineral Analysis"][self.var_language]
        str_lbl_02 = self.language_dict["Further data analysis"][self.var_language]
        str_lbl_03 = self.language_dict["x-y diagram"][self.var_language]
        str_lbl_04 = self.language_dict["Ternary diagram"][self.var_language]
        str_lbl_05 = self.language_dict["Geothermometry"][self.var_language]
        str_lbl_06 = self.language_dict["elements"][self.var_language]
        str_lbl_07 = self.language_dict["element ratios"][self.var_language]
        str_lbl_08 = self.language_dict["oxides"][self.var_language]
        str_lbl_09 = self.language_dict["oxide ratios"][self.var_language]

        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["BG Window"]).create_simple_label(
            text=str_lbl_01 + " - " + str_lbl_02, 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=str_lbl_03 + " (" + str_lbl_06 + ")", 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=str_lbl_03 + " (" + str_lbl_07 + ")", 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=str_lbl_03 + " (" + str_lbl_08 + ")", 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=str_lbl_03 + " (" + str_lbl_09 + ")", 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=str_lbl_04 + " (" + str_lbl_06 + ")", 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=str_lbl_04 + " (" + str_lbl_08 + ")", 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["BG Window"]).create_simple_label(
            text=str_lbl_05, 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
        str_btn_01 = self.language_dict["Setup"][self.var_language]

        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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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."""
        str_title_01 = self.language_dict["Geothermometry"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Geothermometry"][0]
        n_columns = self.window_dimensions["Geothermometry"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_geothermometry_ti_in_qz = tk.Toplevel(self.parent)
        self.subwindow_geothermometry_ti_in_qz.title(str_title_01 + " - 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["BG Window"]

        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
        str_lbl_01 = self.language_dict["Geothermometry"][self.var_language]
        str_lbl_02 = self.language_dict["Additional Settings"][self.var_language]
        str_lbl_03 = self.language_dict["Results"][self.var_language]

        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["BG Window"]).create_simple_label(
            text="Titanium-in-Quartz " + str_lbl_01, 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["BG Window"]).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02a = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start + 7, column_id=var_column_start,
            n_rows=1, n_columns=9, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["BG Window"]).create_simple_label(
            text="Activity of TiO2 in Rt", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        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["BG Window"]).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold")

        # BUTTONS
        str_btn_01 = self.language_dict["Run"][self.var_language]
        str_btn_02 = self.language_dict["Export results"][self.var_language]

        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=str_btn_01, 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=str_btn_02, 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")

        ## ENTRIES
        entr_02a = SE(
            parent=self.subwindow_geothermometry_ti_in_qz, row_id=var_row_start + 7, column_id=var_column_start + 9,
            n_rows=1, n_columns=3, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["White"]).create_simple_entry(
            var=self.container_var["a(TiO2,Rt)"], text_default=self.container_var["a(TiO2,Rt)"].get())

        ## TREEVIEW
        str_tv_01 = self.language_dict["Name"][self.var_language]
        str_tv_02 = self.language_dict["Category"][self.var_language]

        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=[str_tv_01, str_tv_02, "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)

        a_TiO2_Rt = float(self.container_var["a(TiO2,Rt)"].get())

        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/a_TiO2_Rt) - 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."""
        str_title_02 = self.language_dict["Extras"][self.var_language]

        if self.pysills_mode in ["FI", "INCL"]:
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["FI Extras"][0]
        n_columns = self.window_dimensions["FI Extras"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_fi_extras = tk.Toplevel(self.parent)
        self.subwindow_fi_extras.title(str_title_01 + " - " + str_title_02)
        self.subwindow_fi_extras.geometry(var_geometry)
        self.subwindow_fi_extras.resizable(False, False)
        self.subwindow_fi_extras["bg"] = self.bg_colors["BG Window"]

        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
        str_lbl_01 = self.language_dict["Matrix"][self.var_language]
        str_lbl_01b = self.language_dict["Inclusion"][self.var_language]
        str_lbl_02 = self.language_dict["Further data analysis"][self.var_language]
        str_lbl_03 = self.language_dict["x-y diagram"][self.var_language]
        str_lbl_04 = self.language_dict["Ternary diagram"][self.var_language]
        str_lbl_06 = self.language_dict["elements"][self.var_language]
        str_lbl_07 = self.language_dict["element ratios"][self.var_language]
        str_lbl_08 = self.language_dict["oxides"][self.var_language]
        str_lbl_09 = self.language_dict["oxide ratios"][self.var_language]

        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["BG Window"]).create_simple_label(
            text=str_lbl_01 + " - " + str_lbl_02, 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["BG Window"]).create_simple_label(
            text=str_lbl_01b + " - " + str_lbl_02, 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=str_lbl_03 + " (" + str_lbl_06 + ")", 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=str_lbl_03 + " (" + str_lbl_07 + ")", 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=str_lbl_03 + " (" + str_lbl_08 + ")", 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=str_lbl_03 + " (" + str_lbl_09 + ")", 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=str_lbl_04 + " (" + str_lbl_06 + ")", 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=str_lbl_04 + " (" + str_lbl_08 + ")", 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=str_lbl_03 + " (" + str_lbl_06 + ")", 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=str_lbl_03 + " (" + str_lbl_07 + ")", 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=str_lbl_03 + " (" + str_lbl_08 + ")", 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=str_lbl_03 + " (" + str_lbl_09 + ")", 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=str_lbl_04 + " (" + str_lbl_06 + ")", 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=str_lbl_04 + " (" + str_lbl_08 + ")", 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
        str_btn_01 = self.language_dict["Setup"][self.var_language]

        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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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=str_btn_01, 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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["MI Extras"][0]
        n_columns = self.window_dimensions["MI Extras"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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["BG Window"]

        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["BG Window"]).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["BG Window"]).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):
        str_title_02 = self.language_dict["Extras"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Diagram xy"][0]
        n_columns = self.window_dimensions["Diagram xy"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_diagram_xy = tk.Toplevel(self.parent)

        if self.pysills_mode == "MA":
            str_title_01 = self.language_dict["Mineral Analysis"][self.var_language]
            subwindow_diagram_xy.title(str_title_01 + " - " + str_title_02)
        elif self.pysills_mode in ["FI", "INCL"]:
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
            subwindow_diagram_xy.title(str_title_01 + " - " + str_title_02)
        elif self.pysills_mode == "MI":
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]
            subwindow_diagram_xy.title(str_title_01 + " - " + str_title_02)

        subwindow_diagram_xy.geometry(var_geometry)
        subwindow_diagram_xy.resizable(False, False)
        subwindow_diagram_xy["bg"] = self.bg_colors["BG Window"]

        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":
            str_lbl_01a = self.language_dict["Sample"][self.var_language]
            str_lbl_01b = self.language_dict["Matrix"][self.var_language]

            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=str_lbl_01a + "/" + str_lbl_01b, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        elif focus == "INCL":
            str_lbl_01a = self.language_dict["Inclusion"][self.var_language]

            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=str_lbl_01a, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        self.oxides_xy = False

        if mode == "Elements":
            str_lbl_02 = self.language_dict["elements"][self.var_language].capitalize()

            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["BG Window"]).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        elif mode == "Element ratios":
            str_lbl_02 = self.language_dict["element ratios"][self.var_language].capitalize()

            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["BG Window"]).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        elif mode == "Oxides":
            str_lbl_02 = self.language_dict["oxides"][self.var_language].capitalize()

            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["BG Window"]).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
            self.oxides_xy = True
        elif mode == "Oxide ratios":
            str_lbl_02 = self.language_dict["oxide ratios"][self.var_language].capitalize()

            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["BG Window"]).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
            self.oxides_xy = True

        str_lbl_03 = self.language_dict["Results"][self.var_language]

        if "ratios" in mode:
            str_lbl_04 = self.language_dict["with respect to"][self.var_language]

            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["BG Window"]).create_simple_label(
                text=str_lbl_04, 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["BG Window"]).create_simple_label(
                text=str_lbl_03, 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["BG Window"]).create_simple_label(
                text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        ## OPTION MENUS
        str_opt_01 = self.language_dict["Select x"][self.var_language]
        str_opt_02 = self.language_dict["Select y"][self.var_language]
        str_opt_03 = self.language_dict["Select z"][self.var_language]

        self.container_var["x-y diagram"]["x"].set(str_opt_01)
        self.container_var["x-y diagram"]["y"].set(str_opt_02)
        self.container_var["x-y diagram"]["z"].set(str_opt_03)

        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()

        str_opt_01 = self.language_dict["Select x"][self.var_language]
        str_opt_02 = self.language_dict["Select y"][self.var_language]
        str_opt_03 = self.language_dict["Select z"][self.var_language]

        if var_opt_x != str_opt_01 and var_opt_y != str_opt_02:
            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() != str_opt_03:
                    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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Diagram halogen ratios"][0]
        n_columns = self.window_dimensions["Diagram halogen ratios"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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["BG Window"]

        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["BG Window"]).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 - 1, columnspan=n_columns - var_header_n,
            sticky="nesw")

        self.toolbarFrame_halogen_ratios = tk.Frame(master=parent)
        self.toolbarFrame_halogen_ratios.grid(
            row=n_rows - 1, 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("/")
                var_file_short = file_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"]
                        try:
                            df_exmpl = DE(filename_long=file_std).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        except:
                            print("ERROR - Data import failed.")
                            print("Possible problem: imported files were created by different ICP-MS instruments.")
                            df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_std)
                            self.container_icpms["name"] = "Undefined ICP-MS"
                            self.container_icpms["skipheader"] = file_info["skipheader"]
                            self.container_icpms["skipfooter"] = file_info["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("/")
                        if self.old_file == True:
                            df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_std)
                            self.container_icpms["name"] = "Undefined ICP-MS"
                            self.container_icpms["skipheader"] = file_info["skipheader"]
                            self.container_icpms["skipfooter"] = file_info["skipfooter"]
                        else:
                            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:
                            if self.old_file == True:
                                df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_std)
                                self.container_icpms["name"] = "Undefined ICP-MS"
                                self.container_icpms["skipheader"] = file_info["skipheader"]
                                self.container_icpms["skipfooter"] = file_info["skipfooter"]
                            else:
                                df_exmpl = DE(filename_long=file_std).get_measurements(
                                    delimiter=",", skip_header=3, skip_footer=1)

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

                if var_file_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][var_file_short] = 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"][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("/")
                var_file_short = file_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"]
                        try:
                            df_exmpl = DE(filename_long=file_smpl).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        except:
                            print("ERROR - Data import failed.")
                            print("Possible problem: imported files were created by different ICP-MS instruments.")
                            df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_smpl)
                            self.container_icpms["name"] = "Undefined ICP-MS"
                            self.container_icpms["skipheader"] = file_info["skipheader"]
                            self.container_icpms["skipfooter"] = file_info["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("/")
                        if self.old_file == True:
                            df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_smpl)
                            self.container_icpms["name"] = "Undefined ICP-MS"
                            self.container_icpms["skipheader"] = file_info["skipheader"]
                            self.container_icpms["skipfooter"] = file_info["skipfooter"]
                        else:
                            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)

                if var_file_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][var_file_short] = 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"][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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["MA main settings"][0]
        n_columns = self.window_dimensions["MA main settings"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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["BG Window"]

        if self.projectname != None:
            self.subwindow_ma_settings.title(self.projectname + " - " + str_title_window)

        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 in ["FI", "INCL"]:
            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
        str_screen_resolution = self.container_var["General Settings"]["Screen resolution"].get()
        if str_screen_resolution == "1920x1080":
            var_n_last_column = 18
            var_n_last_column = n_columns - 47
        elif str_screen_resolution == "1280x720":
            var_n_last_column = 23
        elif str_screen_resolution == "3840x2160":
            var_n_last_column = 18

        # 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": var_n_last_column}
        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": var_n_last_column}
        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": var_n_last_column}
        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 in ["FI", "INCL"]:
            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

        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        # 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["BG Window"]).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        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=font_element, anchor=tk.W)
        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=font_element, anchor=tk.W)

        # 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)
        entr_01a.configure(font=font_option)
        entr_01b.configure(font=font_option)

    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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
        elif self.pysills_mode in ["FI", "INCL"]:
            var_parent = self.subwindow_fi_settings
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings

        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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize=font_element, anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize=font_element, anchor=tk.W)

        # 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=font_color_dark,
            bg=background_color_elements).create_option_srm(
            var_srm=self.container_var["SRM"]["default"][0], text_set=var_text_std,
            fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_02a.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0, font=font_option)

        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=font_color_dark,
            bg=background_color_elements).create_option_srm(
            var_srm=self.container_var["SRM"]["default"][1], text_set=var_text_iso,
            fg_active=font_color_light, option_list=self.container_lists["SRM Library"],
            bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_02b.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0, font=font_option)

    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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            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 in ["FI", "INCL"]:
            var_parent = self.subwindow_fi_settings
            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
            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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)

        # 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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
            command=self.mineral_matrix_quantification)
        btn_03a.configure(font=font_element)

        # 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=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.container_var["Quantification Mineral"]["Method"], option_list=list_methods,
            text_set=str_default_method, fg_active=font_color_light, bg_active=accent_color)
        opt_03a["menu"].config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_03a.config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color, highlightthickness=0, font=font_option)

    def mineral_matrix_quantification(self, focus="MAT"):
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        # Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Matrix quantification"][0]
        n_columns = self.window_dimensions["Matrix quantification"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        if self.pysills_mode == "MA":
            str_title_window = self.language_dict["Sample Settings"][self.var_language]
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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 = self.language_dict["Matrix Settings"][self.var_language]
            else:
                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"] = background_color_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 stoichiometry"][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 stoichiometry"][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=font_color_light,
                bg=background_color_dark).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

            # 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=font_color_dark,
                bg=background_color_elements).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=1,
                color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_02,
                sticky="nesw", relief=tk.FLAT, font=font_element)
            rb_01d = 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=font_color_dark,
                bg=background_color_elements).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=4,
                color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_05,
                sticky="nesw", relief=tk.FLAT, font=font_element)
            rb_01e = 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=font_color_dark,
                bg=background_color_elements).create_radiobutton(
                var_rb=self.container_var[var_setting_key]["Host Setup Selection"], value_rb=5,
                color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_06,
                sticky="nesw", relief=tk.FLAT, font=font_element)

            # 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=font_color_dark,
                bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                command=self.ma_matrix_concentration_setup)
            btn_02a.configure(font=font_element)
        elif str_method == "100 wt.% Oxides":
            self.subwindow_mineral_matrix_quantification.destroy()
            self.checkup_oxides()

    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 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
        """
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
                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=font_color_light,
                bg=background_color_dark).create_simple_label(
                text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
            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=font_color_light, bg=background_color_dark).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)

            # Option Menu
            str_default_inclusion_setup = self.container_var[key_setting]["Inclusion Setup Option"].get()
            if self.pysills_mode in ["FI", "INCL"]:
                list_opt_incl_is_quantification = ["Mass Balance", "Charge Balance", "PyPitzer (Liu et al. 2024)",
                                                   "Custom Data", "External Calculation", "100 wt.% Oxides"]
            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=font_color_dark, bg=background_color_elements).create_option_srm(
                var_srm=self.container_var[key_setting]["Inclusion Setup Option"], text_set=str_default_inclusion_setup,
                fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            opt_02a.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0, font=font_option)

            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=font_color_dark, bg=background_color_elements).create_option_srm(
                var_srm=self.container_var[key_setting]["Quantification Method Option"],
                text_set=str_default_quantification_setup, fg_active=font_color_light,
                bg_active=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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            opt_03a.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0, font=font_option)

    def select_opt_inclusion_is_quantification(self, var_opt, dict_geometry_info):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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 in ["FI", "INCL"]:
            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=font_color_dark,
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                    bg=self.bg_colors["Light"]).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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 in ["FI", "INCL"]:
            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=font_color_dark,
                    bg=background_color_elements).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                        bg=background_color_elements).create_simple_button(
                        text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                        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=font_color_dark,
                    bg=background_color_elements).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                    bg=background_color_elements).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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=font_color_dark,
                    bg=background_color_elements).create_simple_button(
                    text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                    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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
        elif self.pysills_mode in ["FI", "INCL"]:
            var_parent = self.subwindow_fi_settings
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings

        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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize=font_element, anchor=tk.W)

        # 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=font_color_dark,
            bg=background_color_elements).create_option_isotope(
            var_iso=self.container_var["ID"]["Default SMPL"], option_list=self.list_alphabet, text_set=var_text,
            fg_active=font_color_light, bg_active=accent_color,
            command=lambda var_opt=self.container_var["ID"]["Default SMPL"]: self.fi_select_id_default(var_opt))
        opt_05a["menu"].config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_05a.config(
            fg=font_color_dark, bg=background_color_elements, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0, font=font_option)

    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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize=font_element, anchor=tk.W)

        # 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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light, command=self.create_dwell_time_window)

        btn_06a.configure(font=font_element)

    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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize=font_element, anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_03, relief=var_relief, fontsize=font_element, anchor=tk.W)
        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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_04, relief=var_relief, fontsize=font_element, anchor=tk.W)

        # 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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
            command=lambda mode="BG": self.clear_all_calculation_intervals(mode))

        btn_07c.configure(font=font_element)
        btn_07cd.configure(font=font_element)

        # 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=font_color_dark,
            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[var_setting_key]["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=font_color_dark,
            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[var_setting_key]["Time BG End"], var_key="End",
                           mode="default", var_interval="BG":
            self.ma_set_bg_interval(var_entr, var_key, mode, var_interval, event))
        entr_07a.configure(font=font_option)
        entr_07b.configure(font=font_option)

    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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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 in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize=font_element, anchor=tk.W)
        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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_03, relief=var_relief, fontsize=font_element, anchor=tk.W)
        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=font_color_dark,
            bg=background_color_elements).create_simple_label(
            text=str_lbl_04, relief=var_relief, fontsize=font_element, anchor=tk.W)

        # 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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
            command=lambda mode="MAT": self.clear_all_calculation_intervals(mode))

        btn_08c.configure(font=font_element)
        btn_08cd.configure(font=font_element)

        # 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=font_color_dark,
            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=font_color_dark,
            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))
        entr_08a.configure(font=font_option)
        entr_08b.configure(font=font_option)

    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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"] # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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]
        str_lbl_04 = self.language_dict["Check 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize=font_element, 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=font_color_dark,
            bg=background_color_elements).create_option_isotope(
            var_iso=self.container_var["Spike Elimination Method"], option_list=self.list_se_methods, text_set=var_text,
            fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_09b.config(
            fg=font_color_dark, bg=background_color_elements, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0, font=font_option)

        if self.pysills_mode != "MA":
            # Checkboxes
            cb_09b = SE(
                parent=var_parent, row_id=var_row_start + 2, column_id=0, fg=font_color_dark, n_rows=1,
                n_columns=int(var_header_n/2), bg=background_color_elements).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)
            cb_09c = SE(
                parent=var_parent, row_id=var_row_start + 2, column_id=int(var_header_n/2),
                fg=font_color_dark, n_rows=1, n_columns=int(var_header_n/2),
                bg=background_color_elements).create_simple_checkbox(
                var_cb=self.container_var["check INCL"], text=str_lbl_04, set_sticky="nesw", own_color=True)
            cb_09b.configure(font=font_option)
            cb_09c.configure(font=font_option)

    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
        """
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
        elif self.pysills_mode in ["FI", "INCL"]:
            var_parent = self.subwindow_fi_settings
        elif self.pysills_mode == "MI":
            var_parent = self.subwindow_mi_settings

        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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, relief=var_relief, fontsize=font_element, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_03, relief=var_relief, fontsize=font_element, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_04, relief=var_relief, fontsize=font_element, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_05, relief=var_relief, fontsize=font_element, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_06, relief=var_relief, fontsize=font_element, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_07, relief=var_relief, fontsize=font_element, 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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light, command=self.check_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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light, command=self.checkup_internal_standard)
        btn_10f = 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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light, command=self.checkup_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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light, command=self.check_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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light, command=self.check_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=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light, command=self.check_imported_files)

        btn_10a.configure(font=font_element)
        btn_10b.configure(font=font_element)
        btn_10c.configure(font=font_element)
        btn_10d.configure(font=font_element)
        btn_10e.configure(font=font_element)
        btn_10f.configure(font=font_element)

    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
        """
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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]

        str_screen_resolution = self.container_var["General Settings"]["Screen resolution"].get()
        if str_screen_resolution == "1920x1080":
            var_width = 30
            var_height = 25
        elif str_screen_resolution == "1280x720":
            var_width = 12 #16
            var_height = 10 #12
        elif str_screen_resolution == "3840x2160":
            var_width = 30
            var_height = 25

        # 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)
        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=font_color_dark, bg=background_color_light).create_frame()
        vsb_iso = ttk.Scrollbar(frm_iso, orient="vertical")
        text_iso = tk.Text(
            master=frm_iso, width=var_width, height=var_height, yscrollcommand=vsb_iso.set, fg=font_color_dark,
            bg=background_color_light, padx=10, pady=10, state="disabled")
        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", "\t\t")

                lbl_i = tk.Label(frm_iso, text=isotope, bg=background_color_light, fg=font_color_dark, font=font_table,
                                 width=5, anchor="w")
                text_iso.window_create("end", window=lbl_i)
                text_iso.insert("end", "\t")

                if self.var_os == "darwin":
                    width_opt = 16
                else:
                    width_opt = 22

                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=font_color_dark, bg=background_color_elements,
                    activeforeground=font_color_light, activebackground=accent_color)
                opt_srm_i.config(
                    bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                    activeforeground=font_color_light, highlightthickness=0, font=font_table, width=width_opt,
                    anchor=tk.W)

                text_iso.window_create("end", window=opt_srm_i)
                text_iso.insert("end", "\t")
                opt_srm_i.configure(justify="left", compound="right")

                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 = accent_color
                else:
                    self.container_var["charge"][isotope]["textvar"].set("1+ charged")
                    charge_fg = font_color_dark

                lbl_i = tk.Label(
                    frm_iso, text=self.container_var["charge"][isotope]["textvar"].get(),
                    textvariable=self.container_var["charge"][isotope]["textvar"], bg=background_color_light,
                    fg=charge_fg, font=font_table)
                text_iso.window_create("end", window=lbl_i)
                text_iso.insert("end", "\n")

                self.container_var["charge"][isotope]["labelvar"] = lbl_i

        # 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=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.container_var["LASER"], option_list=list_opt_gas, text_set="Argon",
            fg_active=font_color_light, bg_active=accent_color,
            command=lambda var_opt=self.container_var["LASER"]: self.change_carrier_gas(var_opt))
        opt_laser["menu"].config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_laser.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0, font=font_option)

    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
        """
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]
        font_small = self.font_settings["Small"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

        # 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=font_color_dark,
            bg=background_color_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=background_color_light, padx=10, pady=10)
        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=background_color_light, fg=font_color_dark, font=font_element)
        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=background_color_light, fg=font_color_dark, font=font_table,
                width=len(var_file_short), anchor=tk.W)
            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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0, width=12, font=font_table)
            text_02.window_create("insert", window=entr_i)
            text_02.insert("end", "\n")

        text_02.insert("end", "\n")

        lbl_i = tk.Label(
            frm_02, text=str_lbl_03, bg=background_color_light, fg=font_color_dark, font=font_element)
        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=background_color_light, fg=font_color_dark, font=font_table,
                width=len(var_file_short), anchor=tk.W)
            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=font_color_dark, bg=self.bg_colors["White"], highlightthickness=0, width=12, font=font_table)
            text_02.window_create("insert", window=entr_i)
            text_02.insert("end", "\n")

        text_02.configure(state="disabled")

    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
        """
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_mode_setting = "ma_setting"
            row_correction = 0
        elif self.pysills_mode in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

        # 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=font_color_dark,
            bg=background_color_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=int(var_header_n/2), fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[var_mode_setting]["Time-Signal Checker"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_02, sticky="nesw",
            relief=tk.FLAT, font=font_element, 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 + int(var_header_n/2),
            n_rows=var_row_n, n_columns=int(var_header_n/2), fg=font_color_dark,
            bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[var_mode_setting]["Time-Signal Checker"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text=str_lbl_03, sticky="nesw",
            relief=tk.FLAT, font=font_element, 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 + 2, column_id=var_column_start,
            n_rows=var_row_n, n_columns=int(var_header_n/2), fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
            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 + 2, column_id=var_column_start + int(var_header_n/2),
            n_rows=var_row_n, n_columns=int(var_header_n/2), fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
            command=lambda var_mode="Next", var_setting_key=var_mode_setting:
            self.change_file_time_signal_diagram_checker(var_mode, var_setting_key))
        btn_01.configure(font=font_element)
        btn_02.configure(font=font_element)

        ## Initialization
        self.current_file_id_checker = 0

        self.fig_time_signal_checker = Figure(
            figsize=(10, 5), tight_layout=True, facecolor=background_color_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 + 3, column=var_column_start, rowspan=9 + 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()

        if len(self.container_lists[var_filetype]["Long"]) > 0:
            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]

            if var_file_short not in self.container_intervals:
                self.container_intervals[var_file_short] = {
                    "Setup": {"BG": [], "MAT": [], "INCL": []}, "Checker": {"BG": [], "MAT": [], "INCL": []}}

            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"]
                        try:
                            df_data = DE(filename_long=var_file_long).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        except:
                            df_data, file_info = self.find_icpms_data_in_file(filename_long=var_file_long)
                    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 = float(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 = float(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", "INCL"]:
                            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"])
                                self.container_intervals[var_file_short]["Checker"]["BG"].append(box_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", "INCL"]:
                            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)
                                self.container_intervals[var_file_short]["Checker"]["MAT"].append(box_mat)
                        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)
                                self.container_intervals[var_file_short]["Checker"]["MAT"].append(box_mat)
                        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)
                                self.container_intervals[var_file_short]["Checker"]["MAT"].append(box_mat)

                # 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 in ["FI", "INCL"]:
                                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"])
                                    self.container_intervals[var_file_short]["Checker"]["INCL"].append(box_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"])
                                    self.container_intervals[var_file_short]["Checker"]["INCL"].append(box_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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_header = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_listbox = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_header).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

        # Buttons
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent, bg=accent_color).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_accent,
            command=lambda var_filetype="STD": self.confirm_all_files_2(var_filetype))
        btn_confirm.configure(font=font_element)

        # 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=font_color_dark, bg=background_color_listbox).create_frame()
        vsb_files = ttk.Scrollbar(master=frm_files, orient="vertical")
        text_files = tk.Text(
            master=frm_files, width=50, height=25, yscrollcommand=vsb_files.set, fg=font_color_dark,
            bg=background_color_listbox, padx=10, pady=10)
        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", "FIGURE SPECTRUM", "CANVAS SPECTRUM", "TOOLBARFRAME SPECTRUM"]
            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=font_color_dark,
                    bg=background_color_listbox, variable=self.container_var["STD"][file_std]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=background_color_listbox, activeforeground=font_color_dark,
                    anchor=tk.W, highlightthickness=0, bd=0, width=len(file_std_short))
            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=font_color_dark,
                    bg=background_color_listbox, variable=self.container_var["STD"][file_std]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=background_color_listbox, activeforeground=font_color_dark,
                    anchor=tk.W, highlightthickness=0, bd=0, width=len(file_std_short))

            cb_i.configure(font=font_table)
            text_files.window_create("end", window=cb_i)
            text_files.insert("end", "\t\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)

            if self.var_os == "darwin":
                width_opt = 16
            else:
                width_opt = 22

            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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
                activebackground=accent_color)
            opt_srm_i.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0, font=font_table, width=width_opt, anchor=tk.W)
            text_files.window_create("end", window=opt_srm_i)
            text_files.insert("end", "\t")

            lbl_i = tk.Label(
                frm_files, text="", bg=background_color_listbox, fg=font_color_dark, font=font_table, anchor=tk.W)
            text_files.window_create("end", window=lbl_i)
            text_files.insert("end", " ")

            if self.pysills_mode == "MA":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=background_color_elements, fg=font_color_dark,
                    activebackground=accent_color, activeforeground=font_color_light,
                    highlightthickness=0, highlightbackground=background_color_listbox,
                    command=lambda var_filename_long=file_std, var_filetype="STD":
                    self.ma_check_specific_file(var_filename_long, var_filetype))
            elif self.pysills_mode in ["FI", "INCL"]:
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=background_color_elements, fg=font_color_dark,
                    activebackground=accent_color, activeforeground=font_color_light,
                    highlightthickness=0, highlightbackground=background_color_listbox,
                    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=background_color_elements, fg=font_color_dark,
                    activebackground=accent_color, activeforeground=font_color_light,
                    highlightthickness=0, highlightbackground=background_color_listbox,
                    command=lambda var_file=file_std, var_type="STD": self.fi_check_specific_file(var_file, var_type))

            btn_i.configure(font=font_table, anchor=tk.CENTER)
            text_files.window_create("end", window=btn_i)
            text_files.insert("end", "\t")

            lbl_i = tk.Label(
                frm_files, text="", bg=background_color_listbox, fg=font_color_dark, font=font_table, anchor=tk.W)
            text_files.window_create("end", window=lbl_i)
            text_files.insert("end", " ")

            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

        text_files.configure(state="disabled")

    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"]
                try:
                    df_i = DE(filename_long=filename_long).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                except:
                    df_i, file_info = self.find_icpms_data_in_file(filename_long=filename_long)
            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"]
                    
                    if "Dataframe" in self.container_measurements:
                        if filename_short in self.container_measurements["Dataframe"]:
                            df_i = self.container_measurements["Dataframe"][filename_short]
                    else:
                        try:
                            df_i = DE(filename_long=filename_long).get_measurements(
                                delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                        except:
                            df_i, file_info = self.find_icpms_data_in_file(filename_long=filename_long)
                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 in ["FI", "INCL"]:
            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_04)
                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(str_var_04)
                    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)
                    self.container_var["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)
                    self.container_var["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
                str_opt_01 = self.language_dict["Select last solid"][self.var_language]
                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(str_opt_01)
                # Salinity
                str_opt_01 = self.language_dict["Set salinity"][self.var_language]
                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(str_opt_01)

        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", "ERROR FRAME", "FIGURE RATIO",
                         "CANVAS RATIO", "TOOLBARFRAME RATIO", "FIGURE SPECTRUM", "CANVAS SPECTRUM",
                         "TOOLBARFRAME SPECTRUM"]:
            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
        """
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode == "MA":
            var_parent = self.subwindow_ma_settings
            var_setting_key = "ma_setting"
        elif self.pysills_mode in ["FI", "INCL"]:
            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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header)

        # Buttons
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent, bg=accent_color).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_accent,
            command=lambda var_filetype="SMPL": self.confirm_all_files_2(var_filetype))
        btn_confirm.configure(font=font_element)

        # 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=font_color_dark, bg=background_color_light).create_frame()
        vsb_files = ttk.Scrollbar(master=frm_files, orient="vertical")
        text_files = tk.Text(
            master=frm_files, width=50, height=25, yscrollcommand=vsb_files.set, fg=font_color_dark,
            bg=background_color_light, padx=10, pady=10)
        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", "INCL"]:
                    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", "FIGURE SPECTRUM", "CANVAS SPECTRUM", "TOOLBARFRAME SPECTRUM"]
            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=font_color_dark,
                    bg=background_color_light, variable=self.container_var["SMPL"][file_smpl]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=background_color_light, activeforeground=font_color_dark,
                    anchor=tk.W, highlightthickness=0, bd=0, width=len(file_smpl_short))
            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=font_color_dark,
                    bg=background_color_light, variable=self.container_var["SMPL"][file_smpl]["Checkbox"],
                    onvalue=1, offvalue=0, selectcolor=self.bg_colors["White"],
                    activebackground=background_color_light, activeforeground=font_color_dark,
                    anchor=tk.W, highlightthickness=0, bd=0, width=len(file_smpl_short))

            cb_i.configure(font=font_table)
            text_files.window_create("end", window=cb_i)
            text_files.insert("end", "\t\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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_is_i.config(
                bg=self.bg_colors["Light"], fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0, font=font_table, width=8, anchor=tk.W)
            text_files.window_create("end", window=opt_is_i)
            text_files.insert("end", "\t")

            lbl_i = tk.Label(
                frm_files, text="", bg=background_color_light, fg=font_color_dark, font=font_table, anchor=tk.W)
            text_files.window_create("end", window=lbl_i)
            text_files.insert("end", " ")

            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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_id_i.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0, font=font_table, width=5, anchor=tk.W)

            text_files.window_create("end", window=opt_id_i)
            text_files.insert("end", "\t")

            lbl_i = tk.Label(
                frm_files, text="", bg=background_color_light, fg=font_color_dark, font=font_table, anchor=tk.W)
            text_files.window_create("end", window=lbl_i)
            text_files.insert("end", " ")

            if self.pysills_mode == "MA":
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=background_color_elements, fg=font_color_dark,
                    activebackground=accent_color, activeforeground=font_color_light,
                    highlightthickness=0, highlightbackground=background_color_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 in ["FI", "INCL"]:
                btn_i = tk.Button(
                    master=frm_files, text=str_lbl_02, bg=background_color_elements, fg=font_color_dark,
                    activebackground=accent_color, activeforeground=font_color_light,
                    highlightthickness=0, highlightbackground=background_color_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=background_color_elements, fg=font_color_dark,
                    activebackground=accent_color, activeforeground=font_color_light,
                    highlightthickness=0, highlightbackground=background_color_light,
                    command=lambda var_file=file_smpl, var_type="SMPL": self.fi_check_specific_file(var_file, var_type))

            btn_i.configure(font=font_table, anchor=tk.CENTER)
            text_files.window_create("end", window=btn_i)
            text_files.insert("end", "\t")

            lbl_i = tk.Label(
                frm_files, text="", bg=background_color_light, fg=font_color_dark, font=font_table, anchor=tk.W)
            text_files.window_create("end", window=lbl_i)
            text_files.insert("end", " ")

            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

        text_files.configure(state="disabled")

    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]["ERROR 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"] = {}
                self.container_helper[mode][var_file_short]["FIGURE SPECTRUM"] = None
                self.container_helper[mode][var_file_short]["CANVAS SPECTRUM"] = None
                self.container_helper[mode][var_file_short]["TOOLBARFRAME SPECTRUM"] = None
                self.container_helper[mode][var_file_short]["AXES SPECTRUM"] = {}

    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):
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
            var_window_header = self.language_dict["Sample Settings"][self.var_language]
        elif self.pysills_mode in ["FI", "INCL"]:
            var_setting_key = "fi_setting"
            var_window_header = self.language_dict["Matrix Settings"][self.var_language]
        elif self.pysills_mode == "MI":
            var_setting_key = "mi_setting"
            var_window_header = self.language_dict["Matrix Settings"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Mineral quantification"][0]
        n_columns = self.window_dimensions["Mineral quantification"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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"] = background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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
            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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_option_isotope(
                var_iso=var_opt_is_default, option_list=var_opt_is_list, text_set=var_opt_is_default_text,
                fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            self.opt_02b.config(
                bg=background_color_elements, fg=font_color_dark,
                activeforeground=font_color_light,
                activebackground=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=font_color_dark, 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=font_color_dark,
                    bg=background_color_elements).create_option_isotope(
                    var_iso=var_opt_default, option_list=list_compound, text_set=var_opt_default_text,
                    fg_active=font_color_light, bg_active=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=font_color_dark,
                    bg=background_color_elements).create_option_isotope(
                    var_iso=var_opt_default, option_list=list_compound, text_set=var_opt_default_text,
                    fg_active=font_color_light, bg_active=accent_color)

            opt_02a["menu"].config(
                fg=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            opt_02a.config(
                bg=background_color_elements, fg=font_color_dark,
                activeforeground=font_color_light,
                activebackground=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=font_color_dark,
                    bg=background_color_elements).create_option_isotope(
                    var_iso=var_opt_is_default, option_list=var_opt_is_list, text_set=var_opt_is_default_text,
                    fg_active=font_color_light, bg_active=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=font_color_dark,
                    bg=background_color_elements).create_option_isotope(
                    var_iso=var_opt_is_default, option_list=var_opt_is_list, text_set=var_opt_is_default_text,
                    fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            self.opt_02b.config(
                bg=background_color_elements, fg=font_color_dark,
                activeforeground=font_color_light,
                activebackground=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=font_color_dark,
                    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=font_color_dark,
                    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=font_color_dark, bg=background_color_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=background_color_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=background_color_light,
                             fg=font_color_dark)
            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=font_color_dark, bg=background_color_elements,
                                          activeforeground=font_color_light,
                                          activebackground=accent_color)
                opt_comp_i.config(bg=background_color_elements, fg=font_color_dark,
                                  activeforeground=font_color_light, activebackground=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=font_color_dark,
                    bg=self.bg_colors["White"], highlightthickness=0, highlightbackground=background_color_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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_is_i.config(
                bg=background_color_elements, fg=font_color_dark,
                activeforeground=font_color_light, activebackground=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=font_color_dark,
                bg=self.bg_colors["White"], highlightthickness=0, highlightbackground=background_color_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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 show_boxplot_data_view(self, filetype, filename_long):
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        index_file = self.container_lists[filetype]["Long"].index(filename_long)
        filename_short = self.container_lists[filetype]["Short"][index_file]

        ## Cleaning
        try:
            canvas = self.container_helper[filetype][filename_short]["CANVAS"]
            toolbarframe = self.container_helper[filetype][filename_short]["TOOLBARFRAME"]

            if canvas == None:
                canvas.get_tk_widget().grid_remove()
                toolbarframe.grid_remove()
        except AttributeError:
            pass

        try:
            canvas_ratio = self.container_helper[filetype][filename_short]["CANVAS RATIO"]
            toolbarframe_ratio = self.container_helper[filetype][filename_short]["TOOLBARFRAME RATIO"]

            if canvas_ratio == None:
                canvas_ratio.get_tk_widget().grid_remove()
                toolbarframe_ratio.grid_remove()
        except AttributeError:
            pass

        try:
            canvas_spectrum = self.container_helper[filetype][filename_short]["CANVAS SPECTRUM"]
            toolbarframe_spectrum = self.container_helper[filetype][filename_short]["TOOLBARFRAME SPECTRUM"]

            if canvas_spectrum == None:
                canvas_spectrum.get_tk_widget().grid_remove()
                toolbarframe_spectrum.grid_remove()
        except AttributeError:
            pass

        try:
            resultsframe = self.container_helper[filetype][filename_short]["RESULTS FRAME"]

            if resultsframe != None:
                resultsframe.destroy()
        except AttributeError:
            pass

        try:
            errorframe = self.container_helper[filetype][filename_short]["ERROR FRAME"]

            if errorframe == None:
                errorframe.destroy()
        except AttributeError:
            pass

        self.fig_specific_spectrum = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        ax_spectrum = self.fig_specific_spectrum.add_subplot(label=np.random.uniform())
        self.container_helper[filetype][filename_short]["AXES"] = {"Time-Ratio": ax_spectrum}

        # if self.pysills_mode == "MA":
        #     parent = self.subwindow_ma_checkfile
        #     val_row_start = 0
        #     val_column_start = 16
        #     val_row_span = 22
        #     val_column_span = 44
        # if self.pysills_mode in ["FI", "MI", "INCL"]:
        #     parent = self.subwindow_fi_checkfile
        #     val_row_start = 0
        #     val_column_start = 14
        #     val_row_span = 22
        #     val_column_span = 54
        # else:
        parent = self.var_geometry[0]
        val_row_start = self.var_geometry[1]
        val_column_start = self.var_geometry[2]
        val_row_span = self.var_geometry[3] - 1
        val_column_span = self.var_geometry[4]

        frm_00 = SE(
            parent=parent, row_id=val_row_start, column_id=val_column_start, n_rows=val_row_span + 2,
            n_columns=val_column_span, fg=font_color_dark, bg=background_color_light).create_frame(relief=tk.FLAT)

        self.canvas_specific_spectrum = FigureCanvasTkAgg(
            self.fig_specific_spectrum, master=parent)
        self.canvas_specific_spectrum.get_tk_widget().grid(
            row=val_row_start, column=val_column_start, rowspan=val_row_span, columnspan=val_column_span, sticky="nesw")
        self.toolbarFrame_specific_spectrum = tk.Frame(master=parent)
        self.toolbarFrame_specific_spectrum.grid(
            row=val_row_span, column=val_column_start, rowspan=2, columnspan=val_column_span, sticky="w")
        self.toolbar_specific_spectrum = NavigationToolbar2Tk(
            self.canvas_specific_spectrum, self.toolbarFrame_specific_spectrum)
        self.toolbar_specific_spectrum.config(background=self.bg_colors["Very Light"])
        self.toolbar_specific_spectrum._message_label.config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_specific_spectrum.winfo_children()[-2].config(background=self.bg_colors["Very Light"])

        self.container_helper[filetype][filename_short]["FIGURE SPECTRUM"] = self.fig_specific_spectrum
        self.container_helper[filetype][filename_short]["CANVAS SPECTRUM"] = self.canvas_specific_spectrum
        self.container_helper[filetype][filename_short]["TOOLBARFRAME SPECTRUM"] = self.toolbarFrame_specific_spectrum

        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:
            if filename_short not in self.container_measurements["Dataframe"] and "_copy" in filename_short:
                str_filename_short_original = filename_short.replace("_copy", "")
                df_data = self.container_measurements["Dataframe"][str_filename_short_original]
            else:
                df_data = self.container_measurements["Dataframe"][filename_short]

        self.dataset_time = list(DE().get_times(dataframe=df_data))
        file_isotopes = self.container_lists["Measured Isotopes"][filename_short]

        if "Time [Sec]" in df_data:
            df_isotopes = df_data.loc[:, df_data.columns != "Time [Sec]"]
        elif "Time" in df_data:
            df_isotopes = df_data.loc[:, df_data.columns != "Time"]
        else:
            df_isotopes = df_data.loc[:, df_data.columns != list(df_data.keys())[0]]

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

        x_index = []
        x_ticks = []

        if "Time [Sec]" in df_data:
            list_times = df_data["Time [Sec]"].tolist()
        else:
            list_times = self.dataset_time.copy()

        for index, value in enumerate(np.linspace(0, len(list_times) - 1, 10, endpoint=True)):
            x_index.append(int(value))
        for index in x_index:
            x_ticks.append(round(list_times[index], 2))

        y_ticks = file_isotopes

        ax_spectrum.boxplot(
            df_isotopes, showmeans=True, meanline=True, patch_artist=True,
            boxprops=dict(facecolor=self.bg_colors["Light"]),
            medianprops=dict(color=self.bg_colors["Very Dark"], linewidth=1.5),
            meanprops=dict(color=self.bg_colors["Very Dark"], linewidth=1.5, linestyle="dotted"),
            flierprops=dict(marker="o", markerfacecolor=self.accent_color, alpha=0.5))

        ax_spectrum.set_yscale("log")

        ax_spectrum.set_xticks(np.arange(1, len(y_ticks) + 1), labels=y_ticks, rotation=45, ha="right")
        ax_spectrum.set_xlim(0.25, len(y_ticks) + 0.75)
        ax_spectrum.set_ylim(1, 1.67*y_max)

        str_ax_01 = self.language_dict["Measured isotopes"][self.var_language]
        str_ax_02 = self.language_dict["Signal intensity"][self.var_language]

        ax_spectrum.set_xlabel(str_ax_01, labelpad=0.5, fontsize=8)
        ax_spectrum.set_ylabel(str_ax_02 + " $I$ (cps)", labelpad=0.5, fontsize=8)

        ax_spectrum.grid(which="major", axis="both", linestyle="-")
        ax_spectrum.grid(which="minor", axis="both", linestyle=":", alpha=0.5)
        ax_spectrum.set_axisbelow(True)

        self.canvas_specific_spectrum.draw()

    def show_spectral_data_view(self, filetype, filename_long):
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        index_file = self.container_lists[filetype]["Long"].index(filename_long)
        filename_short = self.container_lists[filetype]["Short"][index_file]

        ## Cleaning
        try:
            canvas = self.container_helper[filetype][filename_short]["CANVAS"]
            toolbarframe = self.container_helper[filetype][filename_short]["TOOLBARFRAME"]

            if canvas == None:
                canvas.get_tk_widget().grid_remove()
                toolbarframe.grid_remove()
        except AttributeError:
            pass

        try:
            canvas_ratio = self.container_helper[filetype][filename_short]["CANVAS RATIO"]
            toolbarframe_ratio = self.container_helper[filetype][filename_short]["TOOLBARFRAME RATIO"]

            if canvas_ratio == None:
                canvas_ratio.get_tk_widget().grid_remove()
                toolbarframe_ratio.grid_remove()
        except AttributeError:
            pass

        try:
            canvas_spectrum = self.container_helper[filetype][filename_short]["CANVAS SPECTRUM"]
            toolbarframe_spectrum = self.container_helper[filetype][filename_short]["TOOLBARFRAME SPECTRUM"]

            if canvas_spectrum == None:
                canvas_spectrum.get_tk_widget().grid_remove()
                toolbarframe_spectrum.grid_remove()
        except AttributeError:
            pass

        try:
            resultsframe = self.container_helper[filetype][filename_short]["RESULTS FRAME"]

            if resultsframe != None:
                resultsframe.destroy()
        except AttributeError:
            pass

        try:
            errorframe = self.container_helper[filetype][filename_short]["ERROR FRAME"]

            if errorframe == None:
                errorframe.destroy()
        except AttributeError:
            pass

        self.fig_specific_spectrum = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        ax_spectrum = self.fig_specific_spectrum.add_subplot(label=np.random.uniform())
        self.container_helper[filetype][filename_short]["AXES"] = {"Time-Ratio": ax_spectrum}

        # if self.pysills_mode == "MA":
        #     parent = self.subwindow_ma_checkfile
        #     val_row_start = 0
        #     val_column_start = 16
        #     val_row_span = 22
        #     val_column_span = 44
        # if self.pysills_mode in ["FI", "MI", "INCL"]:
        #     parent = self.subwindow_fi_checkfile
        #     val_row_start = 0
        #     val_column_start = 14
        #     val_row_span = 22
        #     val_column_span = 54
        # else:
        parent = self.var_geometry[0]
        val_row_start = self.var_geometry[1]
        val_column_start = self.var_geometry[2]
        val_row_span = self.var_geometry[3] - 1
        val_column_span = self.var_geometry[4]

        frm_00 = SE(
            parent=parent, row_id=val_row_start, column_id=val_column_start, n_rows=val_row_span + 2,
            n_columns=val_column_span, fg=font_color_dark, bg=background_color_light).create_frame(relief=tk.FLAT)

        self.canvas_specific_spectrum = FigureCanvasTkAgg(
            self.fig_specific_spectrum, master=parent)
        self.canvas_specific_spectrum.get_tk_widget().grid(
            row=val_row_start, column=val_column_start, rowspan=val_row_span, columnspan=val_column_span, sticky="nesw")
        self.toolbarFrame_specific_spectrum = tk.Frame(master=parent)
        self.toolbarFrame_specific_spectrum.grid(
            row=val_row_span, column=val_column_start, rowspan=2, columnspan=val_column_span, sticky="w")
        self.toolbar_specific_spectrum = NavigationToolbar2Tk(
            self.canvas_specific_spectrum, self.toolbarFrame_specific_spectrum)
        self.toolbar_specific_spectrum.config(background=self.bg_colors["Very Light"])
        self.toolbar_specific_spectrum._message_label.config(
            bg=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.toolbar_specific_spectrum.winfo_children()[-2].config(background=self.bg_colors["Very Light"])

        self.container_helper[filetype][filename_short]["FIGURE SPECTRUM"] = self.fig_specific_spectrum
        self.container_helper[filetype][filename_short]["CANVAS SPECTRUM"] = self.canvas_specific_spectrum
        self.container_helper[filetype][filename_short]["TOOLBARFRAME SPECTRUM"] = self.toolbarFrame_specific_spectrum

        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:
            if filename_short not in self.container_measurements["Dataframe"] and "_copy" in filename_short:
                str_filename_short_original = filename_short.replace("_copy", "")
                df_data = self.container_measurements["Dataframe"][str_filename_short_original]
            else:
                df_data = self.container_measurements["Dataframe"][filename_short]

        self.dataset_time = list(DE().get_times(dataframe=df_data))
        file_isotopes = self.container_lists["Measured Isotopes"][filename_short]

        if "Time [Sec]" in df_data:
            df_isotopes = df_data.loc[:, df_data.columns != "Time [Sec]"]
        elif "Time" in df_data:
            df_isotopes = df_data.loc[:, df_data.columns != "Time"]
        else:
            df_isotopes = df_data.loc[:, df_data.columns != list(df_data.keys())[0]]

        if self.container_var["Spike Elimination"][filetype]["State"] == True:
            for isotope in file_isotopes:
                df_isotopes[isotope] = self.container_spikes[filename_short][isotope]["Data IMPROVED"]

        x_index = []
        x_ticks = []

        if "Time [Sec]" in df_data:
            list_times = df_data["Time [Sec]"].tolist()
        else:
            list_times = self.dataset_time.copy()

        for index, value in enumerate(np.linspace(0, len(list_times) - 1, 10, endpoint=True)):
            x_index.append(int(value))
        for index in x_index:
            x_ticks.append(round(list_times[index], 2))

        y_ticks = file_isotopes

        if self.pysills_mode == "MA":
            df_isotopes_edited = df_isotopes.copy()
            normalized_df = np.log(df_isotopes_edited.replace(0, 1))
            normalized_df = (normalized_df - normalized_df.min())/(normalized_df.max() - normalized_df.min())
        else:
            df_isotopes_edited = df_isotopes.copy()
            normalized_df = np.log(df_isotopes_edited.replace(0, 1))
            normalized_df = (normalized_df - normalized_df.min())/(normalized_df.max() - normalized_df.min())

        im = ax_spectrum.imshow(normalized_df.transpose(), aspect="auto", interpolation="None", cmap="viridis")

        ax_spectrum.set_xticks(np.linspace(0, len(list_times), 10, endpoint=True), labels=x_ticks)
        ax_spectrum.set_yticks(np.arange(len(y_ticks)), labels=y_ticks)

        str_ax_01 = self.language_dict["Experiment time"][self.var_language]
        str_ax_02 = self.language_dict["Measured isotopes"][self.var_language]

        ax_spectrum.set_xlabel(str_ax_01 + " $t$ (s)", labelpad=0.5, fontsize=8)
        ax_spectrum.set_ylabel(str_ax_02, labelpad=0.5, fontsize=8)

        cbar = self.fig_specific_spectrum.colorbar(im)
        cbar.ax.get_yaxis().labelpad = 12
        cbar.set_label("Normalized range of signal intensity", rotation=90)

        self.canvas_specific_spectrum.draw()

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

        var_rb_02 = self.container_var["stepwise focus"]
        var_rb_03 = self.container_var["stepwise parameter"]
        var_rb_04 = self.container_var["stepwise visualization"]

        if self.pysills_mode == "MA":
            str_title = "MINERAL ANALYSIS - " + str(filename_short)
            str_matrix = "Sample"
        elif self.pysills_mode in ["FI", "INCL"]:
            str_title = "FLUID INCLUSION ANALYSIS - " + str(filename_short)
            str_matrix = "Matrix"
        elif self.pysills_mode == "MELT":
            str_title = "MELT INCLUSION ANALYSIS - " + str(filename_short)
            str_matrix = "Matrix"

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Stepwise analysis"][0]
        n_columns = self.window_dimensions["Stepwise analysis"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_stepwise_analysis = tk.Toplevel(self.parent)
        subwindow_stepwise_analysis.title(str_title)
        subwindow_stepwise_analysis.geometry(var_geometry)
        subwindow_stepwise_analysis.resizable(False, False)
        subwindow_stepwise_analysis["bg"] = self.bg_colors["BG Window"]

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

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

        start_row = 0
        start_column = 0
        n_navigation = 12

        ## FRAMES
        frm_00 = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row, column_id=start_column, n_rows=n_rows,
            n_columns=n_navigation, fg=self.bg_colors["Light Font"], bg=self.bg_colors["Very Dark"]).create_frame(
            relief=tk.FLAT)

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"],
            bg=self.accent_color).create_simple_label(
            text="Stepwise analysis", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_02 = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Focus selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Parameter selection", relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04 = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 9, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Light Font"],
            bg=self.bg_colors["Very Dark"]).create_simple_label(
            text="Visualization ", relief=tk.FLAT, fontsize="sans 10 bold")

        ## RADIOBUTTONS
        rb_02a = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_02, value_rb=0, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Background", sticky="nesw", relief=tk.FLAT)
        rb_02b = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_02, value_rb=1, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text=str_matrix, sticky="nesw", relief=tk.FLAT)
        rb_02c = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 4, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_02, value_rb=2, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Inclusion", sticky="nesw", relief=tk.FLAT)
        rb_03a = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 6, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_03, value_rb=0, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Intensity (corrected)", sticky="nesw", relief=tk.FLAT)
        rb_03b = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 7, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_03, value_rb=1, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Analytical sensitivity", sticky="nesw", relief=tk.FLAT)
        rb_03c = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 8, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_03, value_rb=2, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Concentration", sticky="nesw", relief=tk.FLAT)
        rb_04a = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 10, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_04, value_rb=0, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Table", sticky="nesw", relief=tk.FLAT)
        rb_04b = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 11, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_04, value_rb=1, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Histogram", sticky="nesw", relief=tk.FLAT)
        rb_04c = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 12, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_04, value_rb=2, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Time series", sticky="nesw", relief=tk.FLAT)
        rb_04d = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 13, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_04, value_rb=3, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Box plot", sticky="nesw", relief=tk.FLAT)
        rb_04e = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 14, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_04, value_rb=4, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Scatter plot", sticky="nesw", relief=tk.FLAT)
        rb_04f = SE(
            parent=subwindow_stepwise_analysis, row_id=start_row + 15, column_id=start_column, n_rows=1,
            n_columns=n_navigation, fg=self.bg_colors["Dark Font"], bg=self.bg_colors["Light"]).create_radiobutton(
            var_rb=var_rb_04, value_rb=5, color_bg=self.bg_colors["Light"], fg=self.bg_colors["Dark Font"],
            text="Correlation heatmap", sticky="nesw", relief=tk.FLAT)

        ## INITIALIZATION
        if self.pysills_mode == "MA":
            rb_02c.configure(state="disabled")

    def specific_file_setup(self, filetype, filename_long):
        """ File-specific setup window where further settings like intervals can be defined.
        -------
        Parameters
        filetype : str, the file category, e.g. STD
        filename_long : str, the complete filename, including its whole path
        -------
        Returns
        -------
        """
        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        # Initial parameters and variables
        str_filetype = filetype
        str_filename_long = filename_long
        str_filename_short = str_filename_long.split("/")[-1]
        file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]
        self.ca_filetype = str_filetype
        self.ca_filename_short = str_filename_short
        self.ca_filename_long = str_filename_long
        str_title = self.language_dict["Setup"][self.var_language]

        if str_filename_short not in self.helper_filesetup_lines:
            self.helper_filesetup_lines[str_filename_short] = {}
        self.helper_filesetup_lines[str_filename_short] = {}

        self.helper_var_rb["File setup"]["QA section"].set(1)
        self.helper_var_rb["File setup"]["Section"].set(0)
        self.helper_var_rb["File setup"]["Analysis mode"].set(0)
        self.helper_var_rb["File setup"]["Interval limits"].set(0)
        self.helper_var_entr["File setup"]["Start"].set("Set start value")
        self.helper_var_entr["File setup"]["End"].set("Set end value")
        self.helper_var_opt["File setup"]["Reference isotope 1"].set("None")
        self.helper_var_opt["File setup"]["Reference isotope 2"].set("None")
        self.helper_var_opt["File setup"]["Parameter"].set("None")
        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Window settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Specific file setup"][0]
        n_columns = self.window_dimensions["Specific file setup"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_file_setup = tk.Toplevel(self.parent)
        self.subwindow_file_setup.title(str_title + " - " + str(str_filename_short))
        self.subwindow_file_setup.geometry(var_geometry)
        self.subwindow_file_setup.resizable(False, False)
        self.subwindow_file_setup["bg"] = background_color_dark

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

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

        n_1st_column = int(0.24*n_columns)
        n_3rd_column = int(0.12*n_columns)
        n_2nd_column = n_columns - n_1st_column - n_3rd_column
        n_1st_column_half = int(n_1st_column/2)
        n_1st_column_third = int(n_1st_column/3)
        n_2nd_column_third = int(n_2nd_column/3)
        start_2nd_column = n_1st_column
        start_3rd_column = n_1st_column + n_2nd_column

        var_geometry = [self.subwindow_file_setup, 0, start_2nd_column, n_rows - 11, n_2nd_column]
        self.var_geometry = var_geometry

        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Frames
        frm_00 = SE(
            parent=self.subwindow_file_setup, row_id=0, column_id=n_1st_column, n_rows=n_rows, n_columns=n_2nd_column,
            fg=font_color_dark, bg=background_color_light).create_frame(relief=tk.FLAT)

        # Labels
        str_lbl_01 = self.language_dict["Measured isotopes"][self.var_language]
        str_lbl_02 = self.language_dict["Quick analysis"][self.var_language]
        str_lbl_03 = self.language_dict["Select section"][self.var_language]
        str_lbl_04 = self.language_dict["Parameter selection"][self.var_language]
        str_lbl_05 = self.language_dict["Results"][self.var_language]
        str_lbl_06 = self.language_dict["Analysis mode"][self.var_language]
        str_lbl_07 = self.language_dict["Start"][self.var_language]
        str_lbl_08 = self.language_dict["End"][self.var_language]
        str_lbl_09 = self.language_dict["Interval setup"][self.var_language]
        str_lbl_10 = self.language_dict["Reference isotope"][self.var_language]
        str_lbl_13 = self.language_dict["Background"][self.var_language]
        str_lbl_15 = self.language_dict["Inclusion"][self.var_language]

        if self.pysills_mode == "MA":
            str_lbl_14 = self.language_dict["Sample"][self.var_language]
        else:
            str_lbl_14 = self.language_dict["Matrix"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_file_setup, row_id=0, column_id=0, n_rows=1, n_columns=n_1st_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_02 = SE(
            parent=self.subwindow_file_setup, row_id=0, column_id=start_3rd_column, n_rows=1, n_columns=n_3rd_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_02, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_03 = SE(
            parent=self.subwindow_file_setup, row_id=1, column_id=start_3rd_column, n_rows=1, n_columns=n_3rd_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_04 = SE(
            parent=self.subwindow_file_setup, row_id=5, column_id=start_3rd_column, n_rows=1, n_columns=n_3rd_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_05 = SE(
            parent=self.subwindow_file_setup, row_id=8, column_id=start_3rd_column, n_rows=1, n_columns=n_3rd_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_06 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 16, column_id=0, n_rows=1, n_columns=n_1st_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_06, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_07 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 7, column_id=0, n_rows=1, n_columns=n_1st_column_third,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_07, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_08 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 6, column_id=0, n_rows=1, n_columns=n_1st_column_third,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_08, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_09 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 11, column_id=0, n_rows=1, n_columns=n_1st_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_09, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_10 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 19, column_id=0, n_rows=1, n_columns=n_1st_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_10, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_11 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 18, column_id=0, n_rows=1, n_columns=2,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="#1", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_12 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 17, column_id=0, n_rows=1, n_columns=2,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="#2", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_13 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 10, column_id=n_1st_column, n_rows=1,
            n_columns=n_2nd_column_third, fg=self.colors_intervals["BG LB"],
            bg=self.colors_intervals["BG"]).create_simple_label(
            text=str_lbl_13, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_14 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 10, column_id=n_1st_column + n_2nd_column_third, n_rows=1,
            n_columns=n_2nd_column_third, fg=self.colors_intervals["MAT LB"],
            bg=self.colors_intervals["MAT"]).create_simple_label(
            text=str_lbl_14, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_14 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 10, column_id=n_1st_column + 2*n_2nd_column_third,
            n_rows=1, n_columns=n_2nd_column_third, fg=self.colors_intervals["INCL LB"],
            bg=self.colors_intervals["INCL"]).create_simple_label(
            text=str_lbl_15, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)

        # Buttons
        str_btn_01 = self.language_dict["Confirm all"][self.var_language]
        str_btn_02 = self.language_dict["Previous"][self.var_language]
        str_btn_03 = self.language_dict["Next"][self.var_language]
        str_btn_04 = self.language_dict["Confirm"][self.var_language]
        str_btn_05 = self.language_dict["Extend left"][self.var_language]
        str_btn_06 = self.language_dict["Extend right"][self.var_language]
        str_btn_07 = self.language_dict["Copy"][self.var_language]
        str_btn_08 = self.language_dict["Remove"][self.var_language]
        str_btn_09 = self.language_dict["Additional diagrams"][self.var_language]
        str_btn_10 = self.language_dict["Stepwise analysis"][self.var_language]
        str_btn_11 = self.language_dict["Show only RAW"][self.var_language]
        str_btn_12 = self.language_dict["Hide only RAW"][self.var_language]
        str_btn_13 = self.language_dict["Show all"][self.var_language]
        str_btn_14 = self.language_dict["Hide all"][self.var_language]
        str_btn_15 = self.language_dict["Update"][self.var_language]
        str_btn_16 = self.language_dict["Remove all"][self.var_language]

        btn_01 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 2, column_id=2*n_1st_column_third, n_rows=2,
            n_columns=n_1st_column_third, fg=font_color_light, bg=accent_color).create_simple_button(
            text=str_btn_01, bg_active=background_color_elements, fg_active=font_color_dark,
            command=lambda filetype=str_filetype, filename_long=str_filename_long:
            self.confirm_and_close_filesetup(filetype, filename_long))
        btn_02 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 2, column_id=0, n_rows=2,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
            command=lambda filetype=str_filetype, filename_long=str_filename_long, direction="previous":
            self.switch_to_another_filesetup(filetype, filename_long, direction))
        btn_03 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 2, column_id=n_1st_column_third, n_rows=2,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
            command=lambda filetype=str_filetype, filename_long=str_filename_long, direction="next":
            self.switch_to_another_filesetup(filetype, filename_long, direction))
        btn_16 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 5, column_id=2*n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_16, bg_active=accent_color, fg_active=font_color_light, command=self.remove_all_interval_ca)
        self.btn_04 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 4, column_id=2*n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_04, bg_active=accent_color, fg_active=font_color_light,
            command=self.filesetup_confirm_new_interval)
        self.btn_05 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 4, column_id=0, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_05, bg_active=accent_color, fg_active=font_color_light,
            command=lambda mode="move left": self.filesetup_move_interval(mode))
        self.btn_06 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 4, column_id=n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_06, bg_active=accent_color, fg_active=font_color_light,
            command=lambda mode="move right": self.filesetup_move_interval(mode))
        btn_07 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 5, column_id=0, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_07, bg_active=accent_color, fg_active=font_color_light, command=self.filesetup_copy_interval)
        btn_08 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 5, column_id=n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_08, bg_active=accent_color, fg_active=font_color_light, command=self.remove_interval_ca)
        btn_09 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 12, column_id=0, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_09, bg_active=accent_color, fg_active=font_color_light,
            command=lambda var_type=str_filetype, var_file_short=str_filename_short:
            self.qpl_additional_diagrams(var_type, var_file_short))
        btn_10 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 12, column_id=n_1st_column_half, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_10, bg_active=accent_color, fg_active=font_color_light)
        btn_11 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 20, column_id=0, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_11, bg_active=accent_color, fg_active=font_color_light,
            command=lambda filename_short=str_filename_short:
            self.filesetup_visibility_all_raw_lines(filename_short))
        btn_12 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 20, column_id=n_1st_column_half, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_12, bg_active=accent_color, fg_active=font_color_light,
            command=lambda filename_short=str_filename_short, hide=True:
            self.filesetup_visibility_all_raw_lines(filename_short, hide))
        btn_13 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 21, column_id=0, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_13, bg_active=accent_color, fg_active=font_color_light,
            command=lambda filename_short=str_filename_short:
            self.filesetup_visibility_all_lines(filename_short))
        btn_14 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 21, column_id=n_1st_column_half, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_14, bg_active=accent_color, fg_active=font_color_light,
            command=lambda filename_short=str_filename_short, hide=True:
            self.filesetup_visibility_all_lines(filename_short, hide))
        btn_15 = SE(
            parent=self.subwindow_file_setup, row_id=7, column_id=start_3rd_column, n_rows=1,
            n_columns=n_3rd_column, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_15, bg_active=accent_color, fg_active=font_color_light,
            command=lambda opt=self.helper_var_opt["File setup"]["Parameter"], filetype=str_filetype,
                           filename_long=str_filename_long:
            self.fill_table_filesetup(opt, filetype, filename_long))

        # Radiobuttons
        str_rb_01 = self.language_dict["Background"][self.var_language]
        str_rb_03 = self.language_dict["Inclusion"][self.var_language]
        str_rb_04 = self.language_dict["No selection"][self.var_language]
        str_rb_05 = str_rb_01
        str_rb_07 = str_rb_03
        str_rb_08 = str_lbl_05
        str_rb_09 = self.language_dict["Error course"][self.var_language]
        str_rb_10 = self.language_dict["Spectral data view"][self.var_language]
        str_rb_11 = self.language_dict["Box plot data view"][self.var_language]
        str_rb_12 = self.language_dict["Time signal view"][self.var_language]
        str_rb_13 = "left limit"
        str_rb_14 = "right limit"
        str_rb_15 = "both limits"

        if self.pysills_mode == "MA":
            str_rb_02 = self.language_dict["Sample"][self.var_language]
        else:
            str_rb_02 = self.language_dict["Matrix"][self.var_language]

        str_rb_06 = str_rb_02
        var_rb_qa = self.helper_var_rb["File setup"]["QA section"]
        var_rb_section = self.helper_var_rb["File setup"]["Section"]
        var_rb_limits = self.helper_var_rb["File setup"]["Interval limits"]
        self.helper_rb_ca_bg = var_rb_section

        rb_01 = SE(
            parent=self.subwindow_file_setup, row_id=2, column_id=start_3rd_column, n_rows=1, n_columns=n_3rd_column,
            fg=font_color_light, bg=background_color_dark).create_radiobutton(
            var_rb=var_rb_qa, value_rb=0, color_bg=background_color_dark, fg=font_color_light, text=str_rb_01,
            sticky="nesw", relief=tk.FLAT)
        rb_02 = SE(
            parent=self.subwindow_file_setup, row_id=3, column_id=start_3rd_column, n_rows=1, n_columns=n_3rd_column,
            fg=font_color_light, bg=background_color_dark).create_radiobutton(
            var_rb=var_rb_qa, value_rb=1, color_bg=background_color_dark, fg=font_color_light, text=str_rb_02,
            sticky="nesw", relief=tk.FLAT)
        rb_03 = SE(
            parent=self.subwindow_file_setup, row_id=4, column_id=start_3rd_column, n_rows=1, n_columns=n_3rd_column,
            fg=font_color_light, bg=background_color_dark).create_radiobutton(
            var_rb=var_rb_qa, value_rb=2, color_bg=background_color_dark, fg=font_color_light, text=str_rb_03,
            sticky="nesw", relief=tk.FLAT)
        rb_04 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 10, column_id=0, n_rows=1, n_columns=n_1st_column,
            fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=var_rb_section, value_rb=0, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_04, sticky="nesw", relief=tk.FLAT)
        rb_05 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 9, column_id=0, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=var_rb_section, value_rb=1, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_05, sticky="nesw", relief=tk.FLAT)
        rb_06 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 9, column_id=n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=var_rb_section, value_rb=2, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_06, sticky="nesw", relief=tk.FLAT)
        rb_07 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 9, column_id=2*n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=var_rb_section, value_rb=3, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_07, sticky="nesw", relief=tk.FLAT)
        if self.pysills_mode == "MA":
            rb_08 = SE(
                parent=self.subwindow_file_setup, row_id=n_rows - 13, column_id=0, n_rows=1,
                n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
                var_rb=self.helper_var_rb["File setup"]["Analysis mode"], value_rb=3, color_bg=background_color_elements,
                fg=font_color_dark, text=str_rb_08, sticky="nesw", relief=tk.FLAT,
                command=lambda var_file=str_filename_long, var_type=str_filetype, filesetup=True:
                self.ma_show_quick_results(var_file, var_type, filesetup))
        else:
            rb_09 = SE(
                parent=self.subwindow_file_setup, row_id=n_rows - 13, column_id=0, n_rows=1,
                n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
                var_rb=self.helper_var_rb["File setup"]["Analysis mode"], value_rb=3,
                color_bg=background_color_elements,
                fg=font_color_dark, text=str_rb_08, sticky="nesw", relief=tk.FLAT,
                command=lambda var_file=str_filename_long, var_type=str_filetype, filesetup=True:
                self.fi_show_quick_results(var_file, var_type, filesetup))

        rb_09 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 13, column_id=n_1st_column_half, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["File setup"]["Analysis mode"], value_rb=4, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_09, sticky="nesw", relief=tk.FLAT,
            command=lambda var_file=str_filename_long, var_type=str_filetype, filesetup=True:
            self.error_course(var_file, var_type, filesetup))
        rb_10 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 14, column_id=0, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["File setup"]["Analysis mode"], value_rb=1, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_10, sticky="nesw", relief=tk.FLAT,
            command=lambda filetype=str_filetype, filename_long=str_filename_long:
            self.show_spectral_data_view(filetype, filename_long))  # Spectral data view
        rb_11 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 14, column_id=n_1st_column_half, n_rows=1,
            n_columns=n_1st_column_half, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["File setup"]["Analysis mode"], value_rb=2, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_11, sticky="nesw", relief=tk.FLAT,
            command=lambda filetype=str_filetype, filename_long=str_filename_long:
            self.show_boxplot_data_view(filetype, filename_long))   # Box plot data view
        rb_12 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 15, column_id=0, n_rows=1,
            n_columns=n_1st_column, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["File setup"]["Analysis mode"], value_rb=0, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_12, sticky="nesw", relief=tk.FLAT,
            command=lambda geometry=var_geometry, filetype=str_filetype, filename_long=str_filename_long:
            self.create_time_signal_diagram(geometry, filetype, filename_long))
        rb_13 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 8, column_id=0, n_rows=1, n_columns=n_1st_column_third,
            fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["File setup"]["Interval limits"], value_rb=0, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_13, sticky="nesw", relief=tk.FLAT)
        rb_14 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 8, column_id=n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["File setup"]["Interval limits"], value_rb=1, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_14, sticky="nesw", relief=tk.FLAT)
        rb_15 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 8, column_id=2*n_1st_column_third, n_rows=1,
            n_columns=n_1st_column_third, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["File setup"]["Interval limits"], value_rb=2, color_bg=background_color_elements,
            fg=font_color_dark, text=str_rb_15, sticky="nesw", relief=tk.FLAT)

        #rb_01.configure(state="disabled")
        #rb_02.configure(state="disabled")
        #rb_03.configure(state="disabled")

        # Option Menues
        list_parameters = [
            "Concentration", "Concentration ratio", "1-sigma concentration", "Limit of detection", "Intensity",
            "Intensity ratio", "Sensitivity"]
        list_parameters.insert(0, "None")
        list_isotopes_opt = file_isotopes.copy()
        list_isotopes_opt.insert(0, "None")

        opt_qa_param = SE(
            parent=self.subwindow_file_setup, row_id=6, column_id=start_3rd_column, n_rows=1,
            n_columns=n_3rd_column, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_var_opt["File setup"]["Parameter"], option_list=list_parameters,
            text_set=self.helper_var_opt["File setup"]["Parameter"].get(), fg_active=font_color_light,
            bg_active=accent_color,
            command=lambda opt=self.helper_var_opt["File setup"]["Parameter"], filetype=str_filetype,
                           filename_long=str_filename_long:
            self.fill_table_filesetup(opt, filetype, filename_long))
        opt_ref1 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 18, column_id=2, n_rows=1,
            n_columns=n_1st_column - 2, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_var_opt["File setup"]["Reference isotope 1"], option_list=list_isotopes_opt,
            text_set=self.helper_var_opt["File setup"]["Reference isotope 1"].get(), fg_active=font_color_light,
            bg_active=accent_color,
            command=lambda geometry=var_geometry, filetype=str_filetype, filename_long=str_filename_long:
            self.create_time_signal_diagram(geometry, filetype, filename_long))
        opt_ref2 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 17, column_id=2, n_rows=1,
            n_columns=n_1st_column - 2, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_var_opt["File setup"]["Reference isotope 2"], option_list=list_isotopes_opt,
            text_set=self.helper_var_opt["File setup"]["Reference isotope 2"].get(), fg_active=font_color_light,
            bg_active=accent_color,
            command=lambda geometry=var_geometry, filetype=str_filetype, filename_long=str_filename_long:
            self.create_time_signal_diagram(geometry, filetype, filename_long))

        #opt_qa_param.configure(state="disabled")

        # Checkboxes
        self.helper_cb_ca_bg = tk.IntVar()
        self.helper_cb_ca_mat = tk.IntVar()
        self.helper_cb_ca_incl = tk.IntVar()
        self.helper_cb_ca_bg.set(1)
        self.helper_cb_ca_mat.set(1)
        self.helper_cb_ca_incl.set(1)

        cb_01 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 10, column_id=n_1st_column + n_2nd_column_third - 1,
            n_rows=1, n_columns=1, fg=font_color_dark, bg=self.colors_intervals["BG"]).create_simple_checkbox(
            var_cb=self.helper_cb_ca_bg, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Background": self.show_or_hide_intervals_ca(key))
        cb_02 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 10, column_id=n_1st_column + 2*n_2nd_column_third - 1,
            n_rows=1, n_columns=1, fg=font_color_dark, bg=self.colors_intervals["MAT"]).create_simple_checkbox(
            var_cb=self.helper_cb_ca_mat, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Matrix": self.show_or_hide_intervals_ca(key))
        cb_03 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 10, column_id=n_1st_column + 3*n_2nd_column_third - 1,
            n_rows=1, n_columns=1, fg=font_color_dark, bg=self.colors_intervals["INCL"]).create_simple_checkbox(
            var_cb=self.helper_cb_ca_incl, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Inclusion": self.show_or_hide_intervals_ca(key))

        # Entries
        entr_01 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 7, column_id=n_1st_column_third, n_rows=1,
            n_columns=2*n_1st_column_third, fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
            var=self.helper_var_entr["File setup"]["Start"],
            text_default=self.helper_var_entr["File setup"]["Start"].get(),
            command=lambda event, var_entr=self.helper_var_entr["File setup"]["Start"], var_key="Start",
                           mode=str_filename_long:
            self.filesetup_set_interval(var_entr, var_key, mode, event))
        entr_02 = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 6, column_id=n_1st_column_third, n_rows=1,
            n_columns=2*n_1st_column_third, fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
            var=self.helper_var_entr["File setup"]["End"],
            text_default=self.helper_var_entr["File setup"]["End"].get(),
            command=lambda event, var_entr=self.helper_var_entr["File setup"]["End"], var_key="End",
                           mode=str_filename_long:
            self.filesetup_set_interval(var_entr, var_key, mode, event))

        entr_01.configure(font=font_option)
        entr_02.configure(font=font_option)

        # Listboxes
        self.lb_filesetup_bg = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 9, column_id=n_1st_column, n_rows=n_rows - 9,
            n_columns=n_2nd_column_third, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["BG LB"]).create_simple_listbox()
        self.lb_filesetup_mat = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 9, column_id=n_1st_column + n_2nd_column_third,
            n_rows=n_rows - 9, n_columns=n_2nd_column_third, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["MAT LB"]).create_simple_listbox()
        self.lb_filesetup_incl = SE(
            parent=self.subwindow_file_setup, row_id=n_rows - 9, column_id=n_1st_column + 2*n_2nd_column_third,
            n_rows=n_rows - 9, n_columns=n_2nd_column_third, fg=self.bg_colors["Dark Font"],
            bg=self.colors_intervals["INCL LB"]).create_simple_listbox()

        self.lb_ca_bg = self.lb_filesetup_bg
        self.lb_ca_mat = self.lb_filesetup_mat
        self.lb_ca_incl = self.lb_filesetup_incl

        frm_iso = SE(
            parent=self.subwindow_file_setup, row_id=1, column_id=0, n_rows=16, n_columns=n_1st_column,
            fg=font_color_dark, bg=background_color_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=background_color_light, padx=10,
            pady=10)
        vsb_iso.config(command=text_iso.yview)
        vsb_iso.pack(side="right", fill="y")
        text_iso.pack(side="left", fill="both", expand=True)

        self.temp_cb_i = {"RAW": {}, "SMOOTHED": {}}
        for index, isotope in enumerate(file_isotopes):
            str_isotope = isotope
            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=background_color_light, fg=font_color_dark, font=font_option,
                                 width=5, anchor="w")
                text_iso.window_create("end", window=lbl_i)
                text_iso.insert("end", "\t")

                self.temp_cb_i["RAW"][isotope] = tk.IntVar()
                self.temp_cb_i["RAW"][isotope].set(1)

                cb_raw_i = tk.Checkbutton(
                    frm_iso,
                    variable=self.temp_cb_i["RAW"][isotope], text="RAW", onvalue=1, offvalue=0,
                    bg=background_color_light, fg=font_color_dark, font=font_option,
                    command=lambda filename_short=str_filename_short, isotope=str_isotope,
                                   datatype="RAW":
                    self.filesetup_visibility_isotope(filename_short, isotope, datatype))
                text_iso.window_create("end", window=cb_raw_i)
                text_iso.insert("end", "\t")

                self.temp_cb_i["SMOOTHED"][isotope] = tk.IntVar()
                if self.container_var["Spike Elimination"][str_filetype]["State"] == False:
                    self.temp_cb_i["SMOOTHED"][isotope].set(0)
                else:
                    self.temp_cb_i["SMOOTHED"][isotope].set(1)

                cb_smoothed_i = tk.Checkbutton(
                    frm_iso,
                    variable=self.temp_cb_i["SMOOTHED"][isotope], text="SMOOTHED", onvalue=1, offvalue=0,
                    bg=background_color_light, fg=font_color_dark, font=font_option,
                    command=lambda filename_short=str_filename_short, isotope=str_isotope,
                                   datatype="SMOOTHED":
                    self.filesetup_visibility_isotope(filename_short, isotope, datatype))

                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")

        text_iso.configure(state="disabled")

        # Treeviews
        self.tv_filesetup_qa = SE(
            parent=self.subwindow_file_setup, row_id=9, column_id=start_3rd_column, n_rows=n_rows - 9,
            n_columns=n_3rd_column, fg=font_color_dark, bg=self.bg_colors["White"]).create_treeview(
            n_categories=2, text_n=["Isotope", "Parameter"],
            width_n=["75", "112"], individual=True)

        style = ttk.Style()
        style.configure("Treeview", font=font_table)
        style.configure("Treeview.Heading", font=font_elements)

        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Initialization
        #self.btn_04.configure(state="disabled")
        #self.btn_05.configure(state="disabled")
        #self.btn_06.configure(state="disabled")
        btn_10.configure(state="disabled")

        self.copy_button_pressed = False
        self.still_not_confirmed = False

        if self.pysills_mode == "MA":
            rb_03.configure(state="disabled")
            rb_07.configure(state="disabled")
            cb_03.configure(state="disabled")
            self.lb_ca_incl.configure(state="disabled")

        self.create_time_signal_diagram(
            geometry=var_geometry, filetype=str_filetype, filename_long=str_filename_long, init=True)
        self.check_for_intervals_ca(filesetup=True)

        for isotope in file_isotopes:
            entries = [isotope, "---"]
            self.tv_filesetup_qa.insert("", tk.END, values=entries)

    def check_if_quantification_possible(self, filetype, filename_long):
        str_filetype = filetype
        str_filename_long = filename_long
        str_filename_short = str_filename_long.split("/")[-1]

        if str_filetype == "STD":
            var_srm_file = self.container_var["STD"][str_filename_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"][str_filename_short]:
                    var_is = self.container_lists["Measured Elements"][str_filename_short][element][0]
                    self.container_var[str_filetype][str_filename_long]["IS Data"]["IS"].set(var_is)
                break

            list_considered_isotopes = []
            file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]

            for isotope in file_isotopes:
                if isotope in self.container_var["SRM"]:
                    var_srm_i = self.container_var["SRM"][isotope].get()
                    if var_srm_i == var_srm_file:
                        list_considered_isotopes.append(isotope)

            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[str_filetype][str_filename_long]["IS Data"]["IS"].get()
            list_considered_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]
            stop_calculation = False

        return stop_calculation, list_considered_isotopes

    def fill_table_filesetup(self, opt, filetype, filename_long):
        str_filetype = filetype
        str_filename_long = filename_long
        str_filename_short = str_filename_long.split("/")[-1]
        var_opt = self.helper_var_opt["File setup"]["Parameter"].get()
        stop_calculation, list_considered_isotopes = self.check_if_quantification_possible(filetype, filename_long)

        if self.helper_var_rb["File setup"]["QA section"].get() == 0:
            focus = "BG"
        elif self.helper_var_rb["File setup"]["QA section"].get() == 1:
            focus = "MAT"
        elif self.helper_var_rb["File setup"]["QA section"].get() == 2:
            focus = "INCL"

        if self.container_var["Spike Elimination"][str_filetype]["State"] == True:
            str_datatype = "SMOOTHED"
        else:
            str_datatype = "RAW"

        if len(list_considered_isotopes) > 0 and stop_calculation == False:
            if len(self.tv_filesetup_qa.get_children()) > 0:
                for item in self.tv_filesetup_qa.get_children():
                    self.tv_filesetup_qa.delete(item)

            if self.pysills_mode == "MA":
                self.do_quantification_ma(filetype=str_filetype, datatype=str_datatype, filename_long=str_filename_long)
            else:
                self.do_quantification_incl(
                    filetype=str_filetype, datatype=str_datatype, filename_long=str_filename_long)

            value_i = None
            for isotope in list_considered_isotopes:
                if var_opt == "Concentration":
                    if focus in self.container_concentration[str_filetype][str_datatype][str_filename_short]:
                        value_i = self.container_concentration[str_filetype][str_datatype][str_filename_short][focus][
                            isotope]
                elif var_opt == "Concentration ratio":
                    if focus in self.container_concentration_ratio[str_filetype][str_datatype][str_filename_short]:
                        value_i = self.container_concentration_ratio[str_filetype][str_datatype][str_filename_short][
                            focus][isotope]
                elif var_opt == "1-sigma concentration":
                    key_focus = "1 SIGMA " + focus
                    if key_focus in self.container_concentration[str_filetype][str_datatype][str_filename_short]:
                        value_i = self.container_concentration[str_filetype][str_datatype][str_filename_short][
                            key_focus][isotope]
                elif var_opt == "Limit of detection":
                    if focus in self.container_lod[str_filetype][str_datatype][str_filename_short]:
                        value_i = self.container_lod[str_filetype][str_datatype][str_filename_short][focus][isotope]
                elif var_opt == "Intensity":
                    if focus in ["MAT", "INCL"]:
                        value_i = self.container_intensity_corrected[str_filetype][str_datatype][str_filename_short][
                            focus][isotope]
                    else:
                        value_i = self.container_intensity[str_filetype][str_datatype][str_filename_short][focus][
                            isotope]
                elif var_opt == "Intensity ratio":
                    if focus in self.container_intensity_ratio[str_filetype][str_datatype][str_filename_short]:
                        value_i = self.container_intensity_ratio[str_filetype][str_datatype][str_filename_short][focus][
                            isotope]
                elif var_opt == "Sensitivity":
                    if 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][
                            focus][isotope]

                if var_opt != "None" and value_i != None:
                    if var_opt in ["Concentration ratio", "Intensity ratio"]:
                        entries = [isotope, "{:0.4e}".format(value_i)]
                    else:
                        entries = [isotope, "{:0.4f}".format(value_i)]
                    self.tv_filesetup_qa.insert("", tk.END, values=entries)
                else:
                    entries = [isotope, "---"]
                    self.tv_filesetup_qa.insert("", tk.END, values=entries)

        if var_opt == "None":
            if len(self.tv_filesetup_qa.get_children()) > 0:
                for item in self.tv_filesetup_qa.get_children():
                    self.tv_filesetup_qa.delete(item)

            file_isotopes = self.container_lists["Measured Isotopes"][str_filename_short]
            for isotope in file_isotopes:
                entries = [isotope, "---"]
                self.tv_filesetup_qa.insert("", tk.END, values=entries)

    def do_quantification_incl(self, filetype, datatype, filename_long):
        str_filetype = filetype
        str_filename_long = filename_long
        var_file_short = str_filename_long.split("/")[-1]
        var_is_host = self.container_var[str_filetype][str_filename_long]["Matrix Setup"]["IS"]["Name"].get()
        var_is_smpl = self.container_var[str_filetype][str_filename_long]["IS Data"]["IS"].get()
        n_intervals_bg = len(self.container_helper[str_filetype][var_file_short]["BG"]["Content"])
        n_intervals_mat = len(self.container_helper[str_filetype][var_file_short]["MAT"]["Content"])
        n_intervals_incl = len(self.container_helper[str_filetype][var_file_short]["INCL"]["Content"])
        str_keyword = datatype

        if (var_is_smpl != "Select IS" and var_is_host != "Select IS" and n_intervals_bg > 0 and n_intervals_mat > 0 and
                n_intervals_incl > 0):
            ## INITIALIZATION
            if str_filetype == "STD":
                # Intensity analysis
                self.get_intensity(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short, mode="Specific")
                self.fi_get_intensity_corrected(
                    var_filetype=str_filetype, var_datatype=str_keyword, 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=str_keyword, var_file_short=file_std_short, mode="Specific")

                self.fi_get_intensity_corrected(
                    var_filetype="STD", var_datatype=str_keyword, var_file_short=None, var_focus="MAT", mode="only STD")

                self.get_intensity(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short, mode="Specific")
                self.fi_get_intensity_corrected(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short, var_focus="MAT",
                    mode="Specific")
                self.fi_get_intensity_corrected(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_focus="INCL", mode="Specific")
                self.fi_get_intensity_ratio(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long, var_focus="INCL")
                self.fi_get_intensity_mix(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short, mode="Specific")
                self.get_analytical_sensitivity_std(
                    var_datatype=str_keyword, mode="all", var_is_host=var_is_host, var_is_smpl=var_is_smpl)

            self.fi_get_intensity_ratio(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long, var_focus="MAT")

            # Sensitivity analysis
            self.get_analytical_sensitivity(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long)
            results_is = self.determine_possible_is(filetype="ALL", consider_matrix=True)

            IQ(dataframe=None, project_type=self.pysills_mode,
               results_container=self.container_intensity_ratio[str_filetype][str_keyword]).get_intensity_ratio(
                data_container=self.container_intensity_corrected[str_filetype][str_keyword], dict_is=results_is,
                filename_short=var_file_short)
            self.fi_get_rsf(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long, var_focus="MAT")
            # Concentration analysis
            self.fi_get_concentration2(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long)
            # Normalized Sensitivity
            self.fi_get_normalized_sensitivity(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long, var_focus="MAT")
            self.fi_get_concentration_ratio(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long, var_focus="MAT")
            self.get_lod(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long, var_focus="MAT")

            if str_filetype == "SMPL":
                if self.molality_based_quantification.get() == False:
                    self.fi_get_concentration2(
                        var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                        var_file_long=str_filename_long, var_focus="INCL")
                self.fi_get_normalized_sensitivity(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long, var_focus="INCL")
                self.fi_get_concentration_ratio(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long, var_focus="INCL")
                self.get_lod(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long, var_focus="INCL")
                self.fi_get_mixed_concentration_ratio(
                    var_datatype=str_keyword, var_file_short=var_file_short, var_file_long=str_filename_long)
                self.fi_get_mixing_ratio(
                    var_datatype=str_keyword, var_file_short=var_file_short, var_file_long=str_filename_long)
                self.fi_get_concentration_mixed(var_datatype=str_keyword, var_file_short=var_file_short)

    def do_quantification_ma(self, filetype, datatype, filename_long):
        str_filetype = filetype
        str_filename_long = filename_long
        var_file_short = str_filename_long.split("/")[-1]
        var_is = self.container_var[filetype][filename_long]["IS Data"]["IS"].get()
        n_intervals_bg = len(self.container_helper[str_filetype][var_file_short]["BG"]["Content"])
        n_intervals_mat = len(self.container_helper[str_filetype][var_file_short]["MAT"]["Content"])
        str_keyword = datatype

        if var_is != "Select IS" and n_intervals_bg > 0 and n_intervals_mat > 0:
            ## INITIALIZATION
            # Intensity-related parameters
            if str_filetype == "STD":
                self.get_condensed_intervals_of_file(filetype=str_filetype, filename_short=var_file_short)
                self.get_intensity(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short, mode="Specific")
                self.ma_get_concentration(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long)
            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=str_keyword, 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"][str_keyword]).get_averaged_intensities(
                    data_container=self.container_intensity_corrected["STD"][str_keyword], average_type=str_averagetype)

                self.get_intensity(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short, mode="Specific")

                self.ma_get_intensity_ratio(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long, var_focus="MAT")
                # Sensitivity-related parameters
                self.get_analytical_sensitivity_std(var_datatype=str_keyword, mode="all")
                # self.get_analytical_sensitivity_std_alternative(var_datatype=str_keyword, mode="all")

            self.get_analytical_sensitivity(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long)
            results_is = self.determine_possible_is(filetype="ALL")
            # Intensity Ratio
            IQ(dataframe=None, project_type=self.pysills_mode,
               results_container=self.container_intensity_ratio[str_filetype][str_keyword]).get_intensity_ratio(
                data_container=self.container_intensity_corrected[str_filetype][str_keyword], dict_is=results_is,
                filename_short=var_file_short)
            # Concentration-related parameters
            self.ma_get_concentration(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long)
            # Normalized Sensitivity
            SQ(dataframe_01=self.container_intensity_corrected[str_filetype][str_keyword][var_file_short],
               dataframe_02=self.container_concentration[str_filetype][str_keyword][var_file_short],
               results_container=self.container_normalized_sensitivity[str_filetype][
                   str_keyword]).get_normalized_sensitivity(
                filename_short=var_file_short, filetype=str_filetype,
                data_sensitivity=self.container_analytical_sensitivity[str_filetype][str_keyword][var_file_short],
                dict_is=results_is)

            if str_filetype == "SMPL":
                self.ma_get_rsf(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long)

            if str_filetype == "SMPL":
                self.ma_get_concentration_ratio(
                    var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                    var_file_long=str_filename_long)

            self.ma_get_lod(
                var_filetype=str_filetype, var_datatype=str_keyword, var_file_short=var_file_short,
                var_file_long=str_filename_long)

    def filesetup_copy_interval(self):
        self.copy_button_pressed = True
        self.btn_05.configure(state="normal")
        self.btn_06.configure(state="normal")

        self.copy_index_start_new = None
        self.copy_index_end_new = None

        if self.helper_rb_ca_bg.get() == 1:  # BG
            var_key = "BG"
            var_lb = self.lb_ca_bg
        elif self.helper_rb_ca_bg.get() == 2:  # MAT
            var_key = "MAT"
            var_lb = self.lb_ca_mat
        elif self.helper_rb_ca_bg.get() == 3:  # INCL
            var_key = "INCL"
            var_lb = self.lb_ca_incl

        if self.helper_rb_ca_bg.get() != 0:
            item = var_lb.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))

            condition = False
            new_id = self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["ID"]
            while condition == False:
                new_id += 1
                if new_id not in self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"]:
                    condition = True

            self.new_copy_id = new_id
            dict_content = self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][var_id]
            time_start = dict_content["Times"][0]
            time_end = dict_content["Times"][1]
            self.helper_var_entr["File setup"]["Start"].set(time_start)
            self.helper_var_entr["File setup"]["End"].set(time_end)
            self.copy_index_start = dict_content["Indices"][0]
            self.copy_index_end = dict_content["Indices"][1]

    def filesetup_move_interval(self, mode):
        self.btn_04.configure(state="normal")

        if self.copy_button_pressed == True:
            if self.copy_index_start_new == None:
                copy_index_start = self.copy_index_start
            else:
                copy_index_start = self.copy_index_start_new

            if self.copy_index_end_new == None:
                copy_index_end = self.copy_index_end
            else:
                copy_index_end = self.copy_index_end_new
        else:
            if self.helper_rb_ca_bg.get() == 1:  # BG
                var_key = "BG"
                var_lb = self.lb_ca_bg
            elif self.helper_rb_ca_bg.get() == 2:  # MAT
                var_key = "MAT"
                var_lb = self.lb_ca_mat
            elif self.helper_rb_ca_bg.get() == 3:  # INCL
                var_key = "INCL"
                var_lb = self.lb_ca_incl

            if self.helper_rb_ca_bg.get() != 0:
                item = var_lb.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.var_id = var_id
            if self.still_not_confirmed == False:
                dict_content = self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][
                    var_id]
                copy_index_start = dict_content["Indices"][0]
                copy_index_end = dict_content["Indices"][1]
                self.still_not_confirmed = True
            else:
                copy_index_start = self.copy_index_start_new
                copy_index_end = self.copy_index_end_new

        if mode == "move left":
            if self.helper_var_rb["File setup"]["Interval limits"].get() == 0:      # left limit
                if copy_index_start > 0:
                    new_index_start = copy_index_start - 1
                else:
                    new_index_start = 0

                new_index_end = copy_index_end
            elif self.helper_var_rb["File setup"]["Interval limits"].get() == 1:    # right limit
                new_index_start = copy_index_start

                if copy_index_end > copy_index_start + 1:
                    new_index_end = copy_index_end - 1
                else:
                    new_index_end = copy_index_start + 1
            elif self.helper_var_rb["File setup"]["Interval limits"].get() == 2:    # both limits
                if copy_index_start > 0:
                    new_index_start = copy_index_start - 1
                else:
                    new_index_start = 0

                if copy_index_end > copy_index_start + 1:
                    new_index_end = copy_index_end - 1
                else:
                    new_index_end = copy_index_start + 1
        elif mode == "move right":
            if self.helper_var_rb["File setup"]["Interval limits"].get() == 0:  # left limit
                if copy_index_start < copy_index_end - 1:
                    new_index_start = copy_index_start + 1
                else:
                    new_index_start = copy_index_end - 1

                new_index_end = copy_index_end
            elif self.helper_var_rb["File setup"]["Interval limits"].get() == 1:  # right limit
                new_index_start = copy_index_start

                if copy_index_end < len(self.dataset_time) - 1:
                    new_index_end = copy_index_end + 1
                else:
                    new_index_end = len(self.dataset_time) - 1
            elif self.helper_var_rb["File setup"]["Interval limits"].get() == 2:  # both limits
                if copy_index_start < copy_index_end - 1:
                    new_index_start = copy_index_start + 1
                else:
                    new_index_start = copy_index_end - 1

                if copy_index_end < len(self.dataset_time) - 1:
                    new_index_end = copy_index_end + 1
                else:
                    new_index_end = len(self.dataset_time) - 1

        time_0 = self.dataset_time[new_index_start]
        time_1 = self.dataset_time[new_index_end]

        self.helper_var_entr["File setup"]["Start"].set(time_0)
        self.helper_var_entr["File setup"]["End"].set(time_1)
        self.copy_index_start_new = new_index_start
        self.copy_index_end_new = new_index_end

    def filesetup_confirm_new_interval(self):
        self.still_not_confirmed = False
        self.btn_04.configure(state="disabled")
        self.helper_var_entr["File setup"]["Start"].set("Set start value")
        self.helper_var_entr["File setup"]["End"].set("Set end value")

        if self.helper_rb_ca_bg.get() == 1:  # BG
            var_key = "BG"
            var_lb = self.lb_ca_bg
        elif self.helper_rb_ca_bg.get() == 2:  # MAT
            var_key = "MAT"
            var_lb = self.lb_ca_mat
        elif self.helper_rb_ca_bg.get() == 3:  # INCL
            var_key = "INCL"
            var_lb = self.lb_ca_incl

        var_color = self.colors_intervals[var_key]

        if self.copy_button_pressed == True:
            self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["ID"] = self.new_copy_id
            self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Indices"].append(self.new_copy_id)
            var_id = self.new_copy_id
        else:
            #self.container_helper[var_type][var_file_short][var_key]["Indices"].remove(var_id)
            var_lb.delete(tk.ANCHOR)
            self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][self.var_id][
                "Object"].set_visible(False)
            del self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][self.var_id]
            var_id = self.var_id

        time_0 = self.dataset_time[self.copy_index_start_new]
        time_1 = self.dataset_time[self.copy_index_end_new]

        box_key = self.var_ax_ca.axvspan(time_0, time_1, alpha=0.35, color=var_color)

        self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][var_id] = {
            "Times": [time_0, time_1], "Indices": [self.copy_index_start_new, self.copy_index_end_new],
            "Object": box_key}

        var_lb.insert(tk.END, var_key + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")
        self.var_canvas_ca.draw()

        self.fill_table_filesetup(
            opt=self.helper_var_opt["File setup"]["Parameter"], filetype=self.ca_filetype,
            filename_long=self.ca_filename_long)

    def filesetup_set_interval(self, var_entr, var_key, mode, event):
        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.helper_rb_ca_bg.get() == 1:
                var_category = "BG"
            elif self.helper_rb_ca_bg.get() == 2:
                var_category = "MAT"
            elif self.helper_rb_ca_bg.get() == 3:
                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.var_ax_ca.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

                    if var_category == "BG":
                        var_lb = self.lb_ca_bg
                    elif var_category == "MAT":
                        var_lb = self.lb_ca_mat
                    elif var_category == "INCL":
                        var_lb = self.lb_ca_mat

                    var_lb.insert(tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.var_canvas_ca.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.var_ax_ca.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

                    if var_category == "BG":
                        var_lb = self.lb_ca_bg
                    elif var_category == "MAT":
                        var_lb = self.lb_ca_mat
                    elif var_category == "INCL":
                        var_lb = self.lb_ca_mat

                    var_lb.insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.var_canvas_ca.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.helper_rb_ca_bg.get() == 1:
                var_category = "BG"
            elif self.helper_rb_ca_bg.get() == 2:
                var_category = "MAT"
            elif self.helper_rb_ca_bg.get() == 3:
                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.var_ax_ca.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

                    if var_category == "BG":
                        var_lb = self.lb_ca_bg
                    elif var_category == "MAT":
                        var_lb = self.lb_ca_mat
                    elif var_category == "INCL":
                        var_lb = self.lb_ca_mat

                    var_lb.insert(tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.var_canvas_ca.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.var_ax_ca.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

                    if var_category == "BG":
                        var_lb = self.lb_ca_bg
                    elif var_category == "MAT":
                        var_lb = self.lb_ca_mat
                    elif var_category == "INCL":
                        var_lb = self.lb_ca_mat

                    var_lb.insert(
                        tk.END, var_category + str(var_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    self.var_canvas_ca.draw()

                    for key, item in self.helper_var_entr["File setup"].items():
                        if key == "Start":
                            item.set("Set start value")
                        elif key == "End":
                            item.set("Set end value")

    def confirm_and_close_filesetup(self, filetype, filename_long):
        self.container_var[filetype][filename_long]["Frame"].config(background=self.sign_green, bd=1)
        self.container_var[filetype][filename_long]["Sign Color"].set(self.sign_green)
        self.subwindow_file_setup.destroy()

    def switch_to_another_filesetup(self, filetype, filename_long, direction):
        index_file = self.container_lists[filetype]["Long"].index(filename_long)

        if direction == "previous":
            if index_file == 0:
                index_new = len(self.container_lists[filetype]["Long"]) - 1
            else:
                index_new = index_file - 1
        elif direction == "next":
            if index_file == len(self.container_lists[filetype]["Long"]) - 1:
                index_new = 0
            else:
                index_new = index_file + 1

        filename_long_new = self.container_lists[filetype]["Long"][index_new]
        self.subwindow_file_setup.destroy()
        self.specific_file_setup(filetype=filetype, filename_long=filename_long_new)

    def create_time_signal_diagram(self, geometry, filetype, filename_long, init=False):
        if init == False:
            self.var_canvas_ca.get_tk_widget().destroy()
            self.var_toolbarFrame_ca.destroy()
            self.var_toolbar_ca.destroy()
            plt.close(self.var_canvas_ca.figure)

        str_filename_short = filename_long.split("/")[-1]
        str_filetype = filetype
        df_data = self.container_measurements["Dataframe"][str_filename_short]

        data_x = list(df_data.iloc[:, 0])
        self.dataset_time = data_x
        x_max = max(data_x)

        ref_iso_1 = self.helper_var_opt["File setup"]["Reference isotope 1"].get()
        ref_iso_2 = self.helper_var_opt["File setup"]["Reference isotope 2"].get()
        list_isotopes = []

        for datatype in ["RAW", "SMOOTHED"]:
            for isotope, variable in self.temp_cb_i[datatype].items():
                if variable.get() == 1 and isotope not in [ref_iso_1, ref_iso_2]:
                    if isotope not in list_isotopes:
                        list_isotopes.append(isotope)

        # Diagram
        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_fig = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        var_ax = var_fig.add_subplot(label=np.random.uniform())

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            # Time-Signal diagram
            for isotope in list_isotopes:
                if isotope not in self.helper_filesetup_lines[str_filename_short]:
                    self.helper_filesetup_lines[str_filename_short][isotope] = {"RAW": None, "SMOOTHED": None}

                data_y = df_data[isotope]
                ln_raw_i = var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=var_lw)
                self.helper_filesetup_lines[str_filename_short][isotope]["RAW"] = ln_raw_i

                if self.temp_cb_i["RAW"][isotope].get() == 0:
                    ln_raw_i[0].set_visible(False)

                if self.container_var["Spike Elimination"][str_filetype]["State"] == True:
                    if isotope in self.container_spikes[str_filename_short]:
                        data_y = self.container_spikes[str_filename_short][isotope]["Data IMPROVED"]
                        ln_smoothed_i = var_ax.plot(
                            data_x, data_y, label=isotope, color=self.isotope_colors[isotope], linewidth=var_lw,
                            visible=True)
                        self.helper_filesetup_lines[str_filename_short][isotope]["SMOOTHED"] = ln_smoothed_i

                        if self.temp_cb_i["SMOOTHED"][isotope].get() == 0:
                            ln_smoothed_i[0].set_visible(False)
        else:
            # Time-Ratio diagram
            if ref_iso_1 != "None":
                for index, isotope in enumerate(list_isotopes):
                    if "RAW 1" not in self.helper_filesetup_lines[str_filename_short][isotope]:
                        self.helper_filesetup_lines[str_filename_short][isotope]["RAW 1"] = None

                    data_ref_iso_1 = df_data[ref_iso_1]
                    data_i = df_data[isotope]
                    data_y = data_i/data_ref_iso_1

                    if index > 0:
                        ln_raw_1_i = var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=1)
                    else:
                        ln_raw_1_i = var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=1,
                                                 label="i/" + ref_iso_1)

                    self.helper_filesetup_lines[str_filename_short][isotope]["RAW 1"] = ln_raw_1_i
            if ref_iso_2 != "None":
                for index, isotope in enumerate(list_isotopes):
                    if "RAW 2" not in self.helper_filesetup_lines[str_filename_short][isotope]:
                        self.helper_filesetup_lines[str_filename_short][isotope]["RAW 2"] = None

                    data_ref_iso_2 = df_data[ref_iso_2]
                    data_i = df_data[isotope]
                    data_y = data_i/data_ref_iso_2

                    if index > 0:
                        ln_raw_2_i = var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=2)
                    else:
                        ln_raw_2_i = var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=2,
                                                 label="i/" + ref_iso_2)

                    self.helper_filesetup_lines[str_filename_short][isotope]["RAW 2"] = ln_raw_2_i

        var_ax.grid(True)
        var_ax.set_yscale("log")
        var_ax.set_xlim(left=0, right=x_max)
        var_ax.set_xticks(np.linspace(0, x_max, 11, endpoint=True))

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            var_ax.set_ylim(bottom=5e1, top=1e10)
            var_ax.set_yticks([5e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e6, 1e7, 1e8, 1e9, 1e10])
        else:
            var_ax.set_ylim(bottom=1e-4, top=1e5)
            var_ax.set_yticks([1e-4, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5])

        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(str_filename_short, fontsize=9)
        var_ax.set_xlabel("Time (s)", labelpad=0.5, fontsize="x-small")

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            var_ax.set_ylabel("Signal intensity (cps)", labelpad=0.5, fontsize="x-small")
        else:
            var_ax.set_ylabel("Signal intensity ratio (cps/cps)", labelpad=0.5, fontsize="x-small")

        var_ax.xaxis.set_tick_params(labelsize="x-small")
        var_ax.yaxis.set_tick_params(labelsize="x-small")

        self.var_ax_ca = var_ax
        self.var_fig_ca = var_fig

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            pass
        else:
            var_ax.legend(loc="upper left", framealpha=1.0, fontsize="x-small")

        if type(geometry) != list:
            geometry = self.var_geometry

        subwindow = geometry[0]
        row_start = geometry[1]
        column_start = geometry[2]
        n_rows_diagram = geometry[3]
        n_columns_diagram = geometry[4]

        self.var_canvas_ca = FigureCanvasTkAgg(var_fig, master=subwindow)
        self.var_canvas_ca.get_tk_widget().grid(
            row=row_start, column=column_start, rowspan=n_rows_diagram, columnspan=n_columns_diagram,
            sticky="nesw")

        self.var_toolbarFrame_ca = tk.Frame(master=subwindow)
        self.var_toolbarFrame_ca.grid(
            row=n_rows_diagram, column=column_start, rowspan=1, columnspan=n_columns_diagram, sticky="ew")
        self.var_toolbar_ca = NavigationToolbar2Tk(self.var_canvas_ca, self.var_toolbarFrame_ca)
        self.var_toolbar_ca.config(
            bg=self.bg_colors["Very Light"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
            highlightcolor=self.bg_colors["Dark Font"], bd=0)
        self.var_toolbar_ca._message_label.config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.var_toolbar_ca.winfo_children()[-2].config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])

        self.var_canvas_ca.mpl_connect(
            "button_press_event", lambda event, var_type=filetype, var_file_short=str_filename_short:
            self.add_interval_to_diagram_ca(var_type, var_file_short, event))

        self.helper_filesetup_lines[str_filename_short]["AXIS"] = var_ax
        self.helper_filesetup_lines[str_filename_short]["CANVAS"] = self.var_canvas_ca

        if init == True:
            if "AXIS" not in self.helper_filesetup_lines[str_filename_short]:
                self.helper_filesetup_lines[str_filename_short]["AXIS"] = var_ax
                self.helper_filesetup_lines[str_filename_short]["CANVAS"] = self.var_canvas_ca

            self.helper_intervals = {"BG": [], "MAT": [], "INCL": []}

            if filetype not in self.container_helper:
                self.container_helper[filetype] = {}
                if str_filename_short not in self.container_helper[filetype]:
                    self.container_helper[filetype][str_filename_short] = {}
                    if "AXES" not in self.container_helper[filetype][str_filename_short]:
                        self.container_helper[filetype][str_filename_short]["AXES"] = {
                            "Chart analysis": var_ax, "Canvas CA": self.var_canvas_ca}
            else:
                if str_filename_short not in self.container_helper[filetype]:
                    self.build_container_helper(mode=filetype)

                for key in ["BG", "MAT", "INCL"]:
                    if key not in self.container_helper[filetype][str_filename_short]:
                        self.container_helper[filetype][str_filename_short][key] = {
                            "ID": 0, "Content": {}, "Indices": []}

                if "Chart analysis" not in self.container_helper[filetype][str_filename_short]["AXES"]:
                    self.container_helper[filetype][str_filename_short]["AXES"]["Chart analysis"] = var_ax
                    self.container_helper[filetype][str_filename_short]["AXES"][
                        "Canvas CA"] = self.var_canvas_ca

        if init == False:
            self.check_for_intervals_ca(only_boxes=True, filesetup=True)

    def filesetup_visibility_all_raw_lines(self, filename_short, hide=False):
        ref_iso_1 = self.helper_var_opt["File setup"]["Reference isotope 1"].get()
        ref_iso_2 = self.helper_var_opt["File setup"]["Reference isotope 2"].get()

        file_isotopes = self.container_lists["Measured Isotopes"][filename_short]
        for isotope in file_isotopes:
            dict_lines = self.helper_filesetup_lines[filename_short][isotope]

            if hide == False:  # show only RAW
                if dict_lines["SMOOTHED"] != None:
                    dict_lines["SMOOTHED"][0].set_visible(False)
                    self.temp_cb_i["SMOOTHED"][isotope].set(0)
            else:               # hide only RAW
                if ref_iso_1 == "None" and ref_iso_2 == "None":
                    dict_lines["RAW"][0].set_visible(False)
                else:
                    if ref_iso_1 != "None":
                        if "RAW 1" in dict_lines:
                            dict_lines["RAW 1"][0].set_visible(False)
                    if ref_iso_2 != "None":
                        if "RAW 2" in dict_lines:
                            dict_lines["RAW 2"][0].set_visible(False)

                self.temp_cb_i["RAW"][isotope].set(0)

        self.helper_filesetup_lines[filename_short]["CANVAS"].draw()

    def filesetup_visibility_all_lines(self, filename_short, hide=False):
        if hide == False:
            visibility = True
        else:
            visibility = False

        ref_iso_1 = self.helper_var_opt["File setup"]["Reference isotope 1"].get()
        ref_iso_2 = self.helper_var_opt["File setup"]["Reference isotope 2"].get()
        file_isotopes = self.container_lists["Measured Isotopes"][filename_short]

        for isotope in file_isotopes:
            dict_lines = self.helper_filesetup_lines[filename_short][isotope]
            if ref_iso_1 == "None" and ref_iso_2 == "None":
                dict_lines["RAW"][0].set_visible(visibility)
            else:
                if ref_iso_1 != "None":
                    if "RAW 1" in dict_lines:
                        dict_lines["RAW 1"][0].set_visible(visibility)
                if ref_iso_2 != "None":
                    if "RAW 2" in dict_lines:
                        dict_lines["RAW 2"][0].set_visible(visibility)

            if dict_lines["SMOOTHED"] != None:
                dict_lines["SMOOTHED"][0].set_visible(visibility)

            if hide == True:
                self.temp_cb_i["RAW"][isotope].set(0)
                self.temp_cb_i["SMOOTHED"][isotope].set(0)
            else:
                self.temp_cb_i["RAW"][isotope].set(1)
                self.temp_cb_i["SMOOTHED"][isotope].set(1)

        self.var_canvas_ca.draw()
        self.helper_filesetup_lines[filename_short]["CANVAS"].draw()

    def filesetup_visibility_isotope(self, filename_short, isotope, datatype):
        ref_iso_1 = self.helper_var_opt["File setup"]["Reference isotope 1"].get()
        ref_iso_2 = self.helper_var_opt["File setup"]["Reference isotope 2"].get()
        dict_lines = self.helper_filesetup_lines[filename_short][isotope]

        if self.temp_cb_i[datatype][isotope].get() == 0:
            if ref_iso_1 == "None" and ref_iso_2 == "None":
                dict_lines[datatype][0].set_visible(False)
            else:
                if ref_iso_1 != "None":
                    if "RAW 1" in dict_lines:
                        dict_lines["RAW 1"][0].set_visible(False)
                if ref_iso_2 != "None":
                    if "RAW 2" in dict_lines:
                        dict_lines["RAW 2"][0].set_visible(False)
        else:
            if ref_iso_1 == "None" and ref_iso_2 == "None":
                dict_lines[datatype][0].set_visible(True)
            else:
                if ref_iso_1 != "None":
                    if "RAW 1" in dict_lines:
                        dict_lines["RAW 1"][0].set_visible(True)
                if ref_iso_2 != "None":
                    if "RAW 2" in dict_lines:
                        dict_lines["RAW 2"][0].set_visible(True)

        self.helper_filesetup_lines[filename_short]["CANVAS"].draw()

    def check_for_internal_standard(self, filetype, filename_long):
        var_filename_short = filename_long.split("/")[-1]

        if filetype == "STD":
            var_srm_file = self.container_var[filetype][filename_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_filename_short]:
                    var_is_i = self.container_lists["Measured Elements"][var_filename_short][element][0]
                    self.container_var[filetype][filename_long]["IS Data"]["IS"].set(var_is_i)
                break
        else:
            if self.pysills_mode == "MA":
                var_mat_is = self.container_var[filetype][filename_long]["IS Data"]["IS"].get()
                var_is_i = var_mat_is
            else:
                var_mat_is = self.container_var[filetype][filename_long]["Matrix Setup"]["IS"]["Name"].get()
                var_incl_is = self.container_var[filetype][filename_long]["IS Data"]["IS"].get()
                var_is_i = var_incl_is

        return var_is_i

    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
        parts = str_filename_long.split("/")
        var_filename_short = parts[-1]

        if var_filetype == "STD":
            var_srm_file = self.container_var["STD"][var_filename_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_filename_short]:
                    var_is_i = self.container_lists["Measured Elements"][var_filename_short][element][0]
                    self.container_var[var_filetype][var_filename_long]["IS Data"]["IS"].set(var_is_i)
                break
        else:
            if self.pysills_mode == "MA":
                var_mat_is = self.container_var[var_filetype][var_filename_long]["IS Data"]["IS"].get()
                var_is_i = var_mat_is
            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()
                var_is_i = var_incl_is

        self.specific_file_setup(filetype=str_filetype, filename_long=str_filename_long)

    def error_course(self, var_file, var_type, filesetup=False):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        var_file_long = var_file
        parts = var_file_long.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]

        if filesetup == False:
            if self.pysills_mode == "MA":
                parent = self.subwindow_ma_checkfile
                start_row = 0
                start_column = 16
                n_rows = 34
                n_columns = 44
                fix = 2
                frm_n_rows = n_rows
                hb_start_row = 18
                vb_start_column = n_columns + 13 + fix
                vb_n_rows = 18
            else:
                parent = self.subwindow_fi_checkfile
                start_row = 0
                start_column = 14
                n_rows = 36
                n_columns = 54
                fix = 0
                frm_n_rows = n_rows
                hb_start_row = 18
                vb_start_column = n_columns + 13 + fix
                vb_n_rows = 18
        else:
            parent = self.var_geometry[0]
            start_row = self.var_geometry[1]
            start_column = self.var_geometry[2]
            n_rows = self.var_geometry[3]
            n_columns = self.var_geometry[4]
            frm_n_rows = n_rows + 1
            hb_start_row = n_rows
            vb_start_column = n_columns + 17
            vb_n_rows = n_rows
            fix = 0

        ## FRAMES
        frm_quick = SE(
            parent=parent, row_id=start_row, column_id=start_column, n_rows=frm_n_rows, n_columns=n_columns,
            fg=font_color_dark, bg=background_color_light).create_frame(relief=tk.FLAT)

        self.container_helper[var_type][var_file_short]["ERROR FRAME"] = frm_quick

        ## TREEVIEWS
        list_categories = ["Section"]
        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]
                    self.container_var[var_type][var_file]["IS Data"]["IS"].set(var_is)
                break

            list_considered_isotopes = []
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

            for isotope in file_isotopes:
                if isotope in self.container_var["SRM"]:
                    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(95*np.ones(len(list_categories)))
        list_width = [int(item) for item in list_width]
        list_width[0] = 150

        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":
            if var_type == "SMPL":
                n_intervals_incl = len(self.container_helper[var_type][var_file_short]["INCL"]["Content"])

        if self.container_var["Spike Elimination"][var_type]["State"] == False:
            str_keyword = "RAW"
        else:
            str_keyword = "SMOOTHED"

        if len(list_categories) > 1 and stop_calculation == False:
            self.tv_error_course = SE(
                parent=parent, row_id=start_row, column_id=start_column, n_rows=vb_n_rows, n_columns=n_columns - 1,
                fg=font_color_dark, 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(parent, orient="vertical")
            scb_h = ttk.Scrollbar(parent, orient="horizontal")
            self.tv_error_course.configure(xscrollcommand=scb_h.set, yscrollcommand=scb_v.set)
            scb_v.config(command=self.tv_error_course.yview)
            scb_h.config(command=self.tv_error_course.xview)
            scb_v.grid(row=start_row, column=vb_start_column, rowspan=vb_n_rows, columnspan=1, sticky="ns")
            scb_h.grid(row=hb_start_row, column=start_column, rowspan=1, columnspan=n_columns - 1, sticky="ew")

            if n_intervals_bg > 0 and n_intervals_mat > 0 and n_intervals_incl > 0:
                ## INITIALIZATION
                self.get_condensed_intervals_of_file(filetype=var_type, filename_short=var_file_short)

                df_data = self.load_input_data(var_file=var_file_long)
                df_isotopes = list(df_data.columns[1:])

                helper_mean = {}
                for focus in ["BG", "MAT", "INCL"]:
                    if focus in self.container_var[var_type][var_file_short]["Intervals"]:
                        helper_mean[focus] = {}
                        intervals = self.container_var[var_type][var_file_short]["Intervals"][focus]
                        for key, interval in intervals.items():
                            for mode in ["min", "max", "mean", "standard deviation", "slope", "intercept",
                                         "coefficient of determination"]:
                                if mode == "mean":
                                    symbol = "\u03bc"
                                    ending = ""
                                elif mode == "standard deviation":
                                    symbol = "\u03c3"
                                    ending = " %"
                                elif mode == "min":
                                    symbol = "min"
                                    ending = ""
                                elif mode == "max":
                                    symbol = "max"
                                    ending = ""
                                elif mode == "slope":
                                    symbol = "a"
                                    ending = ""
                                elif mode == "intercept":
                                    symbol = "b"
                                    ending = ""
                                elif mode == "coefficient of determination":
                                    symbol = "R\u00B2"
                                    ending = ""

                                if focus == "BG":
                                    entries_data = [symbol + "(Background " + str(key) + ")" + ending]
                                elif focus == "MAT":
                                    if self.pysills_mode != "MA":
                                        entries_data = [symbol + "(Matrix " + str(key) + ")" + ending]
                                    else:
                                        entries_data = [symbol + "(Sample " + str(key) + ")" + ending]
                                elif focus == "INCL":
                                    entries_data = [symbol + "(Inclusion " + str(key) + ")" + ending]

                                for isotope in df_isotopes:
                                    try:
                                        x_data = df_data["Time"][interval[0]:interval[1] + 1]
                                    except:
                                        x_data = df_data["Time [Sec]"][interval[0]:interval[1] + 1]
                                    y_data = df_data[isotope][interval[0]:interval[1] + 1]
                                    slope, intercept = np.polyfit(x_data, y_data, 1)

                                    if mode == "mean":
                                        if focus == "BG":
                                            value_mean = np.mean(df_data[isotope][interval[0]:interval[1] + 1])
                                        elif focus == "MAT":
                                            value_bg = helper_mean["BG"][isotope]
                                            value_mean = (np.mean(df_data[isotope][interval[0]:interval[1] + 1]) -
                                                          value_bg)
                                        elif focus == "INCL":
                                            value_bg = helper_mean["BG"][isotope]
                                            value_mat = helper_mean["MAT"][isotope]
                                            value_mean = (np.mean(df_data[isotope][interval[0]:interval[1] + 1]) -
                                                          value_bg - value_mat)
                                    elif mode == "standard deviation":
                                        value_avg = helper_mean[focus][isotope]
                                        if value_avg != 0:
                                            if focus == "BG":
                                                value_mean = (np.std(df_data[isotope][interval[0]:interval[1] + 1],
                                                                     ddof=1)/value_avg)*100
                                            elif focus == "MAT":
                                                value_mean = (np.std(df_data[isotope][interval[0]:interval[1] + 1],
                                                                     ddof=1)/value_avg)*100
                                            elif focus == "INCL":
                                                value_mean = (np.std(df_data[isotope][interval[0]:interval[1] + 1],
                                                                     ddof=1)/value_avg)*100
                                        else:
                                            value_mean = np.nan
                                    elif mode == "min":
                                        value_mean = np.min(df_data[isotope][interval[0]:interval[1] + 1])
                                    elif mode == "max":
                                        value_mean = np.max(df_data[isotope][interval[0]:interval[1] + 1])
                                    elif mode == "slope":
                                        value_mean = slope
                                    elif mode == "intercept":
                                        value_mean = intercept
                                    elif mode == "coefficient of determination":
                                        polynomial = np.poly1d([slope, intercept])
                                        y_pred = polynomial(x_data)
                                        ss_total = np.sum((y_data - np.mean(y_data))**2)
                                        ss_residual = np.sum((y_data - y_pred)**2)
                                        if ss_total != 0:
                                            value_mean = 1 - (ss_residual/ss_total)
                                        else:
                                            value_mean = np.nan
                                    if mode == "mean":
                                        entries_data.append(f"{value_mean:.{1}f}")
                                        helper_mean[focus][isotope] = value_mean
                                    elif mode == "standard deviation":
                                        entries_data.append("+/- " + f"{value_mean:.{1}f}")
                                    elif mode == "coefficient of determination":
                                        entries_data.append(f"{value_mean:.{3}f}")
                                    else:
                                        entries_data.append(f"{value_mean:.{1}f}")

                                self.tv_error_course.insert("", tk.END, values=entries_data)

                            entries_sep = [""]

                            for isotope in df_isotopes:
                                entries_sep.append("---")

                            self.tv_error_course.insert("", tk.END, values=entries_sep)

    def load_input_data(self, var_file):
        str_filename_short = var_file.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"]
                try:
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                except:
                    df_data, file_info = self.find_icpms_data_in_file(filename_long=var_file)
            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)

        return df_data

    def remove_intervals(self, filetype, filename_short, focus):
        if self.pysills_mode == "MA":
            var_setting_key = "ma_setting"
            self.temp_lines_checkup2[filetype][filename_short] = 0
            self.show_time_signal_diagram_checker(var_setting_key=var_setting_key)
        elif self.pysills_mode in ["FI", "INCL"]:
            var_setting_key = "fi_setting"
            self.temp_lines_checkup2[filetype][filename_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[filetype][filename_short] = 0
            self.show_time_signal_diagram_checker(var_setting_key=var_setting_key)

        var_lb = self.container_helper[filetype][filename_short][focus]["Listbox"]
        var_lb.delete(0, tk.END)

        for var_id in list(self.container_helper[filetype][filename_short][focus]["Content"].keys()):
            self.container_helper[filetype][filename_short][focus]["Content"][var_id]["Object"].set_visible(False)
            del self.container_helper[filetype][filename_short][focus]["Content"][var_id]

        self.container_helper[filetype][filename_short][focus]["Indices"].clear()
        self.container_helper[filetype][filename_short][focus]["ID"] = 0

        self.canvas_specific.draw()

        if filename_short in self.container_intervals:
            for var_object in self.container_intervals[filename_short]["Checker"][focus]:
                var_object.set_visible(False)

            self.canvas_time_signal_checker.draw()

    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", "INCL"]:
                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", "INCL"]:
                    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", "INCL"]:
                    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 in ["FI", "INCL"]:
            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, custom_parent=None):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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:
            canvas_spectrum = self.container_helper[str_filetype][str_filename_short]["CANVAS SPECTRUM"]
            toolbarframe_spectrum = self.container_helper[str_filetype][str_filename_short]["TOOLBARFRAME SPECTRUM"]

            if canvas_spectrum == None:
                canvas_spectrum.get_tk_widget().grid_remove()
                toolbarframe_spectrum.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

        try:
            errorframe = self.container_helper[str_filetype][str_filename_short]["ERROR FRAME"]

            if errorframe != None:
                errorframe.destroy()
        except AttributeError:
            pass

        self.fig_specific = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_light)
        self.canvas_specific = FigureCanvasTkAgg(self.fig_specific, master=self.subwindow_ma_checkfile)
        self.canvas_specific.get_tk_widget().grid(row=0, column=16, rowspan=22, columnspan=44, sticky="nesw")
        self.toolbarFrame_specific = tk.Frame(master=self.subwindow_ma_checkfile)
        self.toolbarFrame_specific.grid(row=22, column=16, rowspan=2, columnspan=44, sticky="ew")
        self.toolbar_specific = NavigationToolbar2Tk(self.canvas_specific, self.toolbarFrame_specific)
        self.toolbar_specific.config(
            bg=background_color_light, highlightthickness=0, highlightbackground=background_color_light,
            highlightcolor=font_color_dark, bd=0)
        self.toolbar_specific._message_label.config(
            bg=background_color_light, fg=font_color_dark, font="sans 12")
        self.toolbar_specific.winfo_children()[-2].config(
            bg=background_color_light, fg=font_color_dark)

        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"]
                try:
                    df_data = DE(filename_long=var_file).get_measurements(
                        delimiter=",", skip_header=var_skipheader, skip_footer=var_skipfooter)
                except:
                    df_data, file_info = self.find_icpms_data_in_file(filename_long=var_file)
            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:
                if self.container_var["ma_setting"]["Display RAW"][str_filetype][str_filename_short][
                    isotope].get() == 1:
                    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
                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["ma_setting"]["Time-Signal Lines"][str_filetype][str_filename_short][isotope][
                        "RAW"] = ln_raw
                    ln_raw[0].set_visible(False)

                if (self.container_var["Spike Elimination"][str_filetype]["State"] == True and
                        isotope in self.container_spikes[str_filename_short]):
                    if self.container_var["ma_setting"]["Display SMOOTHED"][str_filetype][str_filename_short][
                        isotope].get() == 1:
                        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
                    else:
                        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
                        ln_smoothed[0].set_visible(False)

        if self.pysills_mode in ["FI", "MI", "INCL"]:
            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)

        str_lbl_01 = self.language_dict["Experiment time"][self.var_language]
        str_lbl_02 = self.language_dict["Signal intensity"][self.var_language]

        ax.set_xlabel(str_lbl_01 + " $t$ (s)", labelpad=0.5, fontsize=8)
        ax.set_ylabel(str_lbl_02 + " $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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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_spectrum = self.container_helper[var_type][var_file_short]["CANVAS SPECTRUM"]
            toolbarframe_spectrum = self.container_helper[var_type][var_file_short]["TOOLBARFRAME SPECTRUM"]

            if canvas_spectrum == None:
                canvas_spectrum.get_tk_widget().grid_remove()
                toolbarframe_spectrum.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

        try:
            errorframe = self.container_helper[var_type][var_file_short]["ERROR FRAME"]

            if errorframe == None:
                errorframe.destroy()
        except AttributeError:
            pass

        if self.helper_opt_ri.get() == "Select isotope":
            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]
                        self.container_var[var_type][var_file]["IS Data"]["IS"].set(var_is)
                    break
            else:
                var_is = self.container_var[var_type][var_file]["IS Data"]["IS"].get()
        else:
            var_is = self.helper_opt_ri.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=background_color_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=16, rowspan=22, columnspan=44, sticky="nesw")
        self.toolbarFrame_specific_ratio = tk.Frame(master=self.subwindow_ma_checkfile)
        self.toolbarFrame_specific_ratio.grid(row=22, column=16, rowspan=2, columnspan=44, sticky="w")
        self.toolbar_specific_ratio = NavigationToolbar2Tk(self.canvas_specific_ratio, self.toolbarFrame_specific_ratio)
        self.toolbar_specific_ratio.config(background=background_color_light)
        self.toolbar_specific_ratio._message_label.config(
            bg=background_color_light, fg=font_color_dark, font="sans 12")
        self.toolbar_specific_ratio.winfo_children()[-2].config(background=background_color_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, filesetup=False):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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

        try:
            errorframe = self.container_helper[var_type][var_file_short]["ERROR FRAME"]

            if errorframe == None:
                errorframe.destroy()
        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]

        if filesetup == False:
            parent = self.subwindow_ma_checkfile
            val_row_start = 0
            val_column_start = 16
            val_row_span = 34
            val_column_span = 44
            frm_n_rows = val_row_span
            hb_start_row = val_column_start + 2
            vb_start_column = val_column_span + 15
            vb_n_rows = val_column_start + 2
        else:
            parent = self.var_geometry[0]
            val_row_start = self.var_geometry[1]
            val_column_start = self.var_geometry[2]
            val_row_span = self.var_geometry[3]
            val_column_span = self.var_geometry[4]
            frm_n_rows = val_row_span + 1
            hb_start_row = val_row_span
            vb_start_column = val_column_span + 17
            vb_n_rows = val_row_span

        ## FRAMES
        frm_quick = SE(
            parent=parent, row_id=val_row_start, column_id=val_column_start, n_rows=frm_n_rows,
            n_columns=val_column_span, fg=font_color_dark, bg=background_color_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]
                    self.container_var[var_type][var_file]["IS Data"]["IS"].set(var_is)
                break

            list_considered_isotopes = []
            file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]

            for isotope in file_isotopes:
                if isotope in self.container_var["SRM"]:
                    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] = 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"])
        n_intervals_incl = 1

        if self.pysills_mode != "MA":
            n_intervals_incl = len(self.container_helper[var_type][var_file_short]["INCL"]["Content"])

        if self.container_var["Spike Elimination"][var_type]["State"] == False:
            str_keyword = "RAW"
        else:
            str_keyword = "SMOOTHED"

        if len(list_categories) > 1 and stop_calculation == False:
            self.tv_results_quick = SE(
                parent=parent, row_id=val_row_start, column_id=val_column_start, n_rows=vb_n_rows,
                n_columns=val_column_span - 1, fg=font_color_dark, 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(parent, orient="vertical")
            scb_h = ttk.Scrollbar(parent, 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=val_row_start, column=vb_start_column, rowspan=vb_n_rows, columnspan=1,
                       sticky="ns")
            scb_h.grid(row=hb_start_row, column=val_column_start, rowspan=1, columnspan=val_column_span - 1,
                       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=str_keyword, var_file_short=var_file_short, mode="Specific")
                    self.ma_get_concentration(
                        var_filetype=var_type, var_datatype=str_keyword, 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=str_keyword, 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"][str_keyword]).get_averaged_intensities(
                        data_container=self.container_intensity_corrected["STD"][str_keyword], average_type=str_averagetype)

                    self.get_intensity(
                        var_filetype=var_type, var_datatype=str_keyword, var_file_short=var_file_short, mode="Specific")

                    self.ma_get_intensity_ratio(
                        var_filetype=var_type, var_datatype=str_keyword, var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="MAT")
                    # Sensitivity-related parameters
                    self.get_analytical_sensitivity_std(var_datatype=str_keyword, mode="all")
                    #self.get_analytical_sensitivity_std_alternative(var_datatype=str_keyword, mode="all")

                self.get_analytical_sensitivity(
                    var_filetype=var_type, var_datatype=str_keyword, 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][str_keyword]).get_intensity_ratio(
                    data_container=self.container_intensity_corrected[var_type][str_keyword], 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=str_keyword, 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][str_keyword][var_file_short],
                   dataframe_02=self.container_concentration[var_type][str_keyword][var_file_short],
                   results_container=self.container_normalized_sensitivity[var_type][str_keyword]).get_normalized_sensitivity(
                    filename_short=var_file_short, filetype=var_type,
                    data_sensitivity=self.container_analytical_sensitivity[var_type][str_keyword][var_file_short],
                    dict_is=results_is)

                if var_type == "SMPL":
                    self.ma_get_rsf(
                        var_filetype=var_type, var_datatype=str_keyword, 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=str_keyword, var_file_short=var_file_short,
                        var_file_long=var_file)

                self.ma_get_lod(
                    var_filetype=var_type, var_datatype=str_keyword, 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_lob_i = ["Limit of Blank"]
                entries_lod_i = ["Limit of Detection"]
                entries_loq_i = ["Limit of Quantification"]
                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][str_keyword][var_file_short]["BG"][isotope]
                    intensity_mat_i = self.container_intensity_corrected[var_type][str_keyword][var_file_short]["MAT"][
                        isotope]
                    intensity_mat_sigma_i = self.container_intensity[var_type][str_keyword][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][str_keyword][var_file_short][
                        "MAT"][isotope]
                    normalized_sensitivity_i = self.container_normalized_sensitivity[var_type][str_keyword][var_file_short][
                        "MAT"][isotope]
                    # Concentration Results
                    concentration_i = self.container_concentration[var_type][str_keyword][var_file_short]["MAT"][isotope]
                    concentration_sigma_i = self.container_concentration[var_type][str_keyword][var_file_short][
                        "1 SIGMA MAT"][isotope]
                    lob_i = self.container_lob[var_type][str_keyword][var_file_short]["MAT"][isotope]
                    lod_i = self.container_lod[var_type][str_keyword][var_file_short]["MAT"][isotope]
                    loq_i = self.container_loq[var_type][str_keyword][var_file_short]["MAT"][isotope]

                    if var_type == "SMPL":
                        intensity_ratio_i = self.container_intensity_ratio[var_type][str_keyword][var_file_short][
                            "MAT"][isotope]
                        rsf_i = self.container_rsf[var_type][str_keyword][var_file_short]["MAT"][isotope]
                        concentration_ratio_i = self.container_concentration_ratio[var_type][str_keyword][
                            var_file_short]["MAT"][isotope]
                    else:
                        intensity_ratio_i = self.container_intensity_ratio[var_type][str_keyword][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:.{1}f}")
                        entries_intensity_mat_i.append(f"{intensity_mat_i:.{1}f}")
                        entries_intensity_mat_sigma_i.append(f"{intensity_mat_sigma_i:.{1}f}")
                        entries_intensity_ratio_i.append(f"{intensity_ratio_i:.{2}E}")
                        entries_analytical_sensitivity_i.append(f"{analytical_sensitivity_i:.{2}f}")
                        entries_normalized_sensitivity_i.append(f"{normalized_sensitivity_i:.{2}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_lob_i.append(f"{lob_i:.{4}f}")
                        entries_lod_i.append(f"{lod_i:.{4}f}")
                        entries_loq_i.append(f"{loq_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_lob_i.append("---")
                        entries_lod_i.append("---")
                        entries_loq_i.append("---")

                    if var_type == "SMPL":
                        entries_concentration_ratio_i.append(f"{concentration_ratio_i:.{2}E}")
                        entries_rsf_i.append(f"{rsf_i:.{2}f}")

                # Filling treeview
                self.tv_results_quick.insert("", tk.END, values=entries_concentration_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_concentration_sigma_i)
                self.tv_results_quick.insert("", tk.END, values=entries_lod_i)
                self.tv_results_quick.insert("", tk.END, values=entries_lob_i)
                self.tv_results_quick.insert("", tk.END, values=entries_loq_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_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)

    def ma_show_all_lines(self, var_type, var_file_short, key="ALL"):
        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)
                if key == "ALL":
                    try:
                        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)
                    except:
                        print(var_file_short, isotope, "- There are no smoothed line curves.")

        self.canvas_specific.draw()

    def ma_hide_all_lines(self, var_type, var_file_short, key="ALL"):
        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)
                if key == "ALL":
                    try:
                        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)
                    except:
                        print(var_file_short, isotope, "- There are no smoothed line curves.")

        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", "INCL"]:
                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"]:
                    parts = var_file.split("/")
                    str_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_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]

                    dataset_time = list(DE().get_times(dataframe=df_data))
                    var_file_short = var_file.split("/")[-1]

                    list_indices = list(self.container_helper[var_type][var_file_short][var_interval]["Content"].keys())
                    if var_key == "Start":
                        if len(list_indices) == 0:
                            val_index = 1
                        elif len(list_indices) == 1:
                            val_index = list_indices[0] + 1
                        else:
                            val_index = list_indices[-1] + 1
                    else:
                        val_index = list_indices[-1]

                    if val_index not in self.container_helper[var_type][var_file_short][var_interval]["Content"]:
                        self.container_helper[var_type][var_file_short][var_interval]["Content"][val_index] = {
                            "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(val_index)

                    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"][val_index]["Times"][
                            0] = var_time
                        self.container_helper[var_type][var_file_short][var_interval]["Content"][val_index]["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"][val_index]["Times"][
                            1] = var_time
                        self.container_helper[var_type][var_file_short][var_interval]["Content"][val_index]["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 in ["FI", "INCL"]:
                            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 run_quantification_ma_tables(self):
        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")

    def ma_datareduction_tables(self, init=False):  # MA - data reduction tables #######################
        ## Initialization
        if len(self.helper_lists["Assemblages"]["All"]) > 1 and init == True:
            for var_file_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][var_file_long]["ID"].set("A")
            self.run_quantification_ma_tables()
            for index, var_file_short in enumerate(self.container_lists["SMPL"]["Short"]):
                var_file_long = self.container_lists["SMPL"]["Long"][index]
                self.container_var["SMPL"][var_file_long]["ID"].set(self.helper_lists["Assemblages"]["True"][
                                                                        var_file_short])

        if init:
            self.run_quantification_ma_tables()
            # 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]
                                    if value_is != None:
                                        if value_is > 0:
                                            value = value/value_is
                                        else:
                                            value = np.nan
                                    else:
                                        value = np.nan

                                if var_filetype == "STD" and value != 1.0:
                                    if var_srm_i != var_srm_file and value != 0.0:
                                        value = 0.0

                                n_digits = self.ma_determine_ndigits(var_value=value)
                                entries_category.append(f"{value:.{n_digits}f}")

                                if var_srm_i == var_srm_file or value != 0.0:
                                        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]

                                    if var_filetype == "STD" and value != 1.0:
                                        if var_srm_i != var_srm_file and value != 0.0:
                                            value = 0.0

                                    n_digits = self.ma_determine_ndigits(var_value=value)
                                    entries_category.append(f"{value:.{n_digits}f}")

                                    if var_srm_i == var_srm_file or value != 0.0:
                                        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", consider_matrix=False):
        """ 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]
                if consider_matrix == True:
                    isotope_incl_is = self.container_var[filetype][filename_long]["IS Data"]["IS"].get()
                    isotope_mat_is = self.container_var[filetype][filename_long]["Matrix Setup"]["IS"]["Name"].get()
                    helper_is[filetype][filename_short] = {"MAT": isotope_mat_is, "INCL": isotope_incl_is}
                else:
                    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]
                    if filetype_key == "STD":
                        isotope_is = self.container_var[filetype_key][filename_long]["IS Data"]["IS"].get()
                        helper_is[filetype_key][filename_short] = isotope_is
                    else:
                        if consider_matrix == True:
                            isotope_incl_is = self.container_var[filetype_key][filename_long]["IS Data"]["IS"].get()
                            isotope_mat_is = self.container_var[filetype_key][filename_long]["Matrix Setup"]["IS"][
                                "Name"].get()
                            helper_is[filetype_key][filename_short] = {"MAT": isotope_mat_is, "INCL": isotope_incl_is}
                        else:
                            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):
        str_tv_01 = self.language_dict["Arithmetic mean"][self.var_language]
        str_tv_02 = self.language_dict["Standard deviation"][self.var_language]
        str_tv_03 = self.language_dict["Charge"][self.var_language]

        entries_mean = [str_tv_01]
        entries_std = [str_tv_02]
        entries_chrg = [str_tv_03]

        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 in ["FI", "INCL"]:
            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", "INCL"]:
                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)

            str_var_01 = self.language_dict["Select isotope"][self.var_language]

            if self.pysills_mode in ["FI", "INCL"]:
                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 == str_var_01:
                            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 != str_var_01:
                        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 == str_var_01:
                            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 != str_var_01:
                        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", "INCL"]:
                                        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", "INCL"]:
                                    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 in ["FI", "INCL"] 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":
                try:
                    var_is = self.container_var[var_filetype][var_file_long]["IS Data"]["IS"].get()
                except:
                    var_is = self.check_for_internal_standard(filetype=var_filetype, filename_long=var_file_long)
            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]

                if var_intensity_is > 0:
                    var_result = var_intensity_i/var_intensity_is
                else:
                    var_result = np.nan

                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]
                            if var_intensity_is > 0 and var_concentration_i > 0:
                                var_result_i = (var_intensity_i/var_intensity_is)*(
                                        var_concentration_is/var_concentration_i)
                            else:
                                var_result_i = np.nan
                        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]

                            if var_intensity_is > 0 and var_concentration_i > 0:
                                var_result_i = (var_intensity_i/var_intensity_is)*(
                                        var_concentration_is/var_concentration_i)
                            else:
                                var_result_i = np.nan
                        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]
                            if var_intensity_is > 0 and var_concentration_i > 0:
                                var_result_i = (var_intensity_i/var_intensity_is)*(
                                        var_concentration_is/var_concentration_i)
                            else:
                                var_result_i = np.nan
                        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]
                                if var_intensity_is > 0 and var_concentration_i > 0:
                                    var_result_i = (var_intensity_i/var_intensity_is)*(
                                            var_concentration_is/var_concentration_i)
                                else:
                                    var_result_i = np.nan
                            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_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:
                    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)

                    helper_results = [x for x in helper_results if x is not None]

                    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 in ["FI", "INCL"]:
            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]
                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:
                    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 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)

                    helper_results = [x for x in helper_results if x is not None]

                    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 != None:
                    if var_concentration_is > 0:
                        var_result_i = var_concentration_i/var_concentration_is
                    else:
                        var_result_i = np.nan
                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

                        a = 3.29/3.3
                        b = 1/3.29

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*b*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)

                        a = 3/3.3
                        b = 1/3.0

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*b*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

                        a = 3.29/3.3
                        b = 1/3.29

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*b*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)

                        a = 3/3.3
                        b = 1/3.0

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*b*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

                        a = 3.29/3.3
                        b = 1/3.29

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*b*var_result_i
                        #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)

                        a = 3.0/3.3
                        b = 1/3.0

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*b*var_result_i
                        #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 != None:
                            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
                        else:
                            var_sensitivity_i = np.nan

                        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

                        a = 3.29/3.3
                        b = 1/3.29

                        self.container_lob[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 10*a*b*var_result_i
                        # 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)

                        a = 3.0/3.3
                        b = 1/3.0

                        self.container_lob[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 1.65*a*b*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 10*a*b*var_result_i
                        # 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 in ["FI", "INCL"]:
                        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 ######################################################
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_title_01 = self.language_dict["Mineral Analysis"][self.var_language]
        str_title_02 = self.language_dict["Results"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["MA datareduction files"][0]
        n_columns = self.window_dimensions["MA datareduction files"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_ma_datareduction_files = tk.Toplevel(self.parent)
        self.subwindow_ma_datareduction_files.title(str_title_01 + " - " + str_title_02)
        self.subwindow_ma_datareduction_files.geometry(var_geometry)
        self.subwindow_ma_datareduction_files.resizable(False, False)
        self.subwindow_ma_datareduction_files["bg"] = background_color_dark

        if self.projectname != None:
            self.subwindow_ma_datareduction_files.title(self.projectname + " - " + str_title_01 + " - " + str_title_02)

        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
        str_lbl_01 = self.language_dict["File selection"][self.var_language]
        str_lbl_02 = self.language_dict["Data selection"][self.var_language]
        str_lbl_03 = self.language_dict["Assemblage"][self.var_language]
        str_lbl_04 = self.language_dict["Category"][self.var_language]
        str_lbl_05 = self.language_dict["Results"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_ma_datareduction_files, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_02, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, relief=tk.FLAT, fontsize="sans 10 bold")

        ## RADIOBUTTONS
        str_rb_01 = self.language_dict["Standard Files"][self.var_language]
        str_rb_02 = self.language_dict["Sample Files"][self.var_language]
        str_rb_03 = self.language_dict["Original data"][self.var_language]
        str_rb_04 = self.language_dict["Smoothed data"][self.var_language]
        str_rb_05 = self.language_dict["Sample"][self.var_language]
        str_rb_06 = self.language_dict["Concentration"][self.var_language]
        str_rb_07 = self.language_dict["Concentration ratio"][self.var_language]
        str_rb_08 = self.language_dict["Limit of detection"][self.var_language]
        str_rb_09 = self.language_dict["Intensity"][self.var_language]
        str_rb_10 = self.language_dict["Intensity ratio"][self.var_language]
        str_rb_11 = self.language_dict["Analytical sensitivity"][self.var_language]
        str_rb_12 = self.language_dict["Normalized sensitivity"][self.var_language]
        str_rb_13 = self.language_dict["Relative sensitivity factor"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["File Type"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_01, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["File Type"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_02, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Data Type"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_03, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Data Type"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_04, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Focus"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_05, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_06, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_07, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_08, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=3,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_09, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=4,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_10, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=5,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_11,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=6,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_12,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["ma_datareduction_files"]["Result Category"], value_rb=7,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_13,
            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 = []
        self.helper_lists["Assemblages"]["True"] = {}
        for index, var_file_long in enumerate(self.container_lists["SMPL"]["Long"]):
            var_filename_short = self.container_lists["SMPL"]["Short"][index]
            var_id_i = self.container_var["SMPL"][var_file_long]["ID"].get()
            self.helper_lists["Assemblages"][var_filename_short] = var_id_i
            self.helper_lists["Assemblages"]["True"][var_filename_short] = var_id_i
            if var_id_i not in list_id_found:
                list_id_found.append(var_id_i)

        self.helper_lists["Assemblages"]["All"] = list_id_found

        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=font_color_dark, bg=background_color_elements).create_option_isotope(
                var_iso=self.container_var["ID"]["Results Files"], option_list=list_id_found,
                text_set=var_text, fg_active=font_color_light, bg_active=accent_color,
                command=lambda var_opt=self.container_var["ID"]["Results Files"]: self.change_id_results(var_opt))
            opt_03a["menu"].config(
                fg=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            opt_03a.config(
                fg=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color, highlightthickness=0)
            self.container_var["ID"]["Results Files"].set(list_id_found[0])

        ## BUTTONS
        str_btn_01 = self.language_dict["Export results"][self.var_language]
        str_btn_02 = self.language_dict["Further data analysis"][self.var_language]
        str_btn_03 = self.language_dict["Sensitivity drift"][self.var_language]

        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent, bg=accent_color).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_accent, 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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
            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=background_color_light,
            bg=background_color_light).create_frame(relief=tk.FLAT)

        ## TREEVIEWS
        str_tv_01 = self.language_dict["Name"][self.var_language]

        list_categories = [str_tv_01]
        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=font_color_dark, 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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_title_02 = self.language_dict["Further data analysis"][self.var_language]

        if self.pysills_mode == "MA":
            str_title_01 = self.language_dict["Mineral Analysis"][self.var_language]
            str_title_window = str_title_01 + " - " + str_title_02
        elif self.pysills_mode in ["FI", "INCL"]:
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
            str_title_window = str_title_01 + " - " + str_title_02
        elif self.pysills_mode == "MI":
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]
            str_title_window = str_title_01 + " - " + str_title_02

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Detailed analysis"][0]
        n_columns = self.window_dimensions["Detailed analysis"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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"] = background_color_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
        str_lbl_01 = self.language_dict["File selection"][self.var_language]
        str_lbl_02 = self.language_dict["Data selection"][self.var_language]
        str_lbl_03 = self.language_dict["Category"][self.var_language]
        str_lbl_04 = self.language_dict["Intensity results"][self.var_language]
        str_lbl_05 = self.language_dict["Sensitivity results"][self.var_language]
        str_lbl_06 = self.language_dict["Composition results"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_detailed_data_analysis, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_02, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_06, relief=tk.FLAT, fontsize="sans 10 bold")

        # RADIOBUTTONS
        str_rb_01 = self.language_dict["Original data"][self.var_language]
        str_rb_02 = self.language_dict["Smoothed data"][self.var_language]
        str_rb_03 = self.language_dict["Background"][self.var_language]
        str_rb_04 = self.language_dict["Sample"][self.var_language]
        str_rb_05 = self.language_dict["Matrix"][self.var_language]
        str_rb_06 = self.language_dict["Inclusion"][self.var_language]
        str_rb_07 = self.language_dict["Mixed signal"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Datatype"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_01, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Datatype"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_02, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_03, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_04 + "/" + str_rb_05, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_06, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["Detailed Data Analysis"]["Focus"], value_rb=3,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_07, 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
        str_opt_01 = self.language_dict["Select standard file"][self.var_language]
        str_opt_02 = self.language_dict["Select sample file"][self.var_language]
        str_opt_03 = self.language_dict["Select parameter"][self.var_language]

        list_files_std = self.container_lists["STD"]["Short"]
        str_default_std = str_opt_01

        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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_01a.config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color, highlightthickness=0)

        list_files_smpl = self.container_lists["SMPL"]["Short"]
        str_default_smpl = str_opt_02
        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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_01b.config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color, highlightthickness=0)

        list_intensity_parameter = ["Measured Intensity", "Intensity", "Intensity Ratio", "Intensity Noise",
                                    "\u03C3 Intensity"]
        str_default_intensity = str_opt_03
        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=font_color_dark, bg=background_color_elements).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=font_color_light,
            bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_04a.config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color, highlightthickness=0)

        list_sensitivity_parameter = ["Analytical Sensitivity", "Normalized Sensitivity", "Relative Sensitivity Factor"]
        str_default_sensitivity = str_opt_03
        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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_05a.config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color, highlightthickness=0)

        list_concentration_parameter = ["Concentration", "Concentration Ratio", "Concentration Noise",
                                        "Limit of Detection", "\u03C3 Concentration"]
        str_default_concentration = str_opt_03
        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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_05a.config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=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=background_color_light,
            bg=background_color_light).create_frame(relief=tk.FLAT)

        # TREEVIEW
        str_tv_01 = self.language_dict["Name"][self.var_language]
        str_tv_02 = self.language_dict["Value"][self.var_language]

        list_categories = [str_tv_01, str_tv_02]
        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=font_color_dark,
                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)

        self.fig_detailed_analysis = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_light)
        self.ax_detailed_analysis = self.fig_detailed_analysis.add_subplot(label=np.random.uniform())

        self.canvas_detailed_analysis = FigureCanvasTkAgg(
            self.fig_detailed_analysis, master=self.subwindow_detailed_data_analysis)
        self.canvas_detailed_analysis.get_tk_widget().grid(
            row=0, column=23, rowspan=n_rows - 2, columnspan=n_columns - 23, sticky="nesw")
        self.toolbarFrame_detailed_analysis = tk.Frame(master=self.subwindow_detailed_data_analysis)
        self.toolbarFrame_detailed_analysis.grid(
            row=n_rows - 2, column=23, rowspan=2, columnspan=n_columns - 23, sticky="w")
        self.toolbar_detailed_analysis = NavigationToolbar2Tk(
            self.canvas_detailed_analysis, self.toolbarFrame_detailed_analysis)
        self.toolbar_detailed_analysis.config(background=background_color_light)
        self.toolbar_detailed_analysis._message_label.config(
            bg=background_color_light, fg=font_color_dark, font="sans 12")
        self.toolbar_detailed_analysis.winfo_children()[-2].config(background=background_color_light)

    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()

        helper_values = {}
        # 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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_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)
                    if isotope not in helper_values:
                        helper_values[isotope] = value_i
            elif var_opt == "Concentration Noise":
                pass
            elif var_opt == "Limit of Detection":
                for isotope in file_isotopes:
                    if str_focus in self.container_lod[str_filetype][str_datatype][str_filename_short]:
                        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)
                        if isotope not in helper_values:
                            helper_values[isotope] = value_i
            elif var_opt == "\u03C3 Concentration":
                pass

        self.create_detailed_analysis_diagram(values=helper_values)

    def create_detailed_analysis_diagram(self, values):
        self.ax_detailed_analysis.cla()

        for index, (isotope, value) in enumerate(values.items()):
            value_i = value
            # self.ax_detailed_analysis.scatter(
            #     value_i, index, marker="o", color=self.accent_color, edgecolor="black", s=75, alpha=0.75)
            self.ax_detailed_analysis.scatter(
                value_i, index, marker="o", color=self.isotope_colors[isotope], edgecolor="black", s=75, alpha=0.75)

        self.ax_detailed_analysis.invert_yaxis()
        self.ax_detailed_analysis.set_xscale("log")
        self.ax_detailed_analysis.grid(which="major", linestyle="-", linewidth=1)
        self.ax_detailed_analysis.minorticks_on()
        self.ax_detailed_analysis.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.75)
        self.ax_detailed_analysis.set_axisbelow(True)

        self.ax_detailed_analysis.set_yticks(np.arange(len(list(values.keys()))), labels=list(values.keys()))

        self.canvas_detailed_analysis.draw()

    def about_pysills(self):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        var_title = self.language_dict["About"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["About PySILLS"][0]
        n_columns = self.window_dimensions["About PySILLS"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_about_pysills = tk.Toplevel(self.parent)
        self.subwindow_about_pysills.title(var_title)
        self.subwindow_about_pysills.geometry(var_geometry)
        self.subwindow_about_pysills.resizable(False, False)
        self.subwindow_about_pysills["bg"] = background_color_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=font_color_dark, bg=background_color_elements).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 + 11, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="Maximilian A. Beeskow", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_01b = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 2, column_id=start_column + 11, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="Thomas Wagner", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_01c = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 3, column_id=start_column + 11, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="Tobias Fusswinkel", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_001a = SE(
            parent=self.subwindow_about_pysills, row_id=start_row, column_id=start_column + 20, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="RWTH Aachen University", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_light, bg=background_color_dark).create_simple_label(
            text="RWTH Aachen University", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_light, bg=background_color_dark).create_simple_label(
            text="RWTH Aachen University", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        lbl_02 = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 5, column_id=start_column, n_rows=1,
            n_columns=10, fg=font_color_dark, bg=background_color_elements).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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_dark).create_simple_label(
            text="PySILLS on Blogger", relief=tk.FLAT, fontsize="sans 10 bold underline", link=True, anchor=tk.W)
        lbl_02e = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 5, column_id=start_column + 20, n_rows=1,
            n_columns=11, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="PySILLS manual (installation)", relief=tk.FLAT, fontsize="sans 10 bold underline", link=True,
            anchor=tk.W)
        lbl_02f = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 6, column_id=start_column + 20, n_rows=1,
            n_columns=11, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="PySILLS manual (mineral analysis)", relief=tk.FLAT, fontsize="sans 10 bold underline", link=True,
            anchor=tk.W)
        lbl_02g = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 7, column_id=start_column + 20, n_rows=1,
            n_columns=11, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="PySILLS manual (fluid inclusion analysis)", relief=tk.FLAT, fontsize="sans 10 bold underline",
            link=True, anchor=tk.W)
        lbl_02h = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 8, column_id=start_column + 20, n_rows=1,
            n_columns=11, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="PySILLS manual (melt inclusion analysis)", 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_blogger)
        lbl_02e.bind("<Button-1>", self.callback_installation)
        lbl_02f.bind("<Button-1>", self.callback_manual_ma)
        lbl_02g.bind("<Button-1>", self.callback_manual_fi)
        lbl_02h.bind("<Button-1>", self.callback_manual_mi)

        lbl_03 = SE(
            parent=self.subwindow_about_pysills, row_id=start_row + 10, column_id=start_column, n_rows=1,
            n_columns=10, fg=font_color_dark, bg=background_color_elements).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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_dark, bg=background_color_elements).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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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=font_color_light, bg=background_color_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_installation(self, event):
        webbrowser.open_new(r"https://docs.google.com/document/d/18nw22PvVRpJvcUNXSThIvXpVhTG6ePhRhZph0nDWVaY/")

    def callback_manual_ma(self, event):
        webbrowser.open_new(r"https://docs.google.com/document/d/1u5CkBJiXBnhqsdh7ooiEncuexeBWgP6WDg5X2Am6bOA/")

    def callback_manual_fi(self, event):
        webbrowser.open_new(r"https://docs.google.com/document/d/1GeK4aQaiP3D1Na_-7ZUZiBLfzr0wK2mq2888VtTlZIY/")

    def callback_manual_mi(self, event):
        webbrowser.open_new(r"https://docs.google.com/document/d/15PcfBwTK-dGnMUEiuOhYsKcNpWurOAWnUiKUSeNjtN8/")

    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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_title_01 = self.language_dict["Setup"][self.var_language]
        str_title_02 = self.language_dict["Export results"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Calculation report"][0]
        n_columns = self.window_dimensions["Calculation report"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_report_setup = tk.Toplevel(self.parent)
        subwindow_report_setup.title(str_title_01 + " - " + str_title_02)
        subwindow_report_setup.geometry(var_geometry)
        subwindow_report_setup.resizable(False, False)
        subwindow_report_setup["bg"] = background_color_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
        str_lbl_01 = self.language_dict["Sorting by"][self.var_language]
        str_lbl_02 = self.language_dict["All in one file"][self.var_language]

        lbl_01 = SE(
            parent=subwindow_report_setup, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=12, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_title_01 + " - " + str_title_02, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_01, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.rb_report, value_rb=0, color_bg=background_color_elements, fg=font_color_dark,
            text=str_lbl_02, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.rb_report, value_rb=1, color_bg=background_color_elements, fg=font_color_dark,
            text="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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.rb_report, value_rb=2, color_bg=background_color_elements, fg=font_color_dark,
            text="RAW / SMOOTHED", sticky="nesw", relief=tk.FLAT)

        ## BUTTONS
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent, bg=accent_color).create_simple_button(
                text=str_title_02, bg_active=accent_color, fg_active=font_color_accent,
                command=self.ma_export_calculation_report)
        elif self.pysills_mode in ["FI", "INCL"]:
            btn_06a = SE(
                parent=subwindow_report_setup, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=12,
                fg=font_color_accent, bg=accent_color).create_simple_button(
                text=str_title_02, bg_active=accent_color, fg_active=font_color_accent,
                command=self.fi_export_calculation_report)
        elif self.pysills_mode == "MI":
            btn_06a = SE(
                parent=subwindow_report_setup, row_id=start_row + 6, column_id=start_column, n_rows=2, n_columns=12,
                fg=font_color_accent, bg=accent_color).create_simple_button(
                text=str_title_02, bg_active=accent_color, fg_active=font_color_accent,
                command=self.fi_export_calculation_report)
        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"):
                        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()))

                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("/")
                var_file_short = file_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_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:
                        if self.old_file == True:
                            df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_std)
                            self.container_icpms["name"] = "Undefined ICP-MS"
                            self.container_icpms["skipheader"] = file_info["skipheader"]
                            self.container_icpms["skipfooter"] = file_info["skipfooter"]
                        else:
                            df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]
                    except:
                        print("File (" + str(file_std) + str(")"), "cannot be read.")

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

                if var_file_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][var_file_short] = 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"][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("/")
                var_file_short = file_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_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:
                        if self.old_file == True:
                            df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_std)
                            self.container_icpms["name"] = "Undefined ICP-MS"
                            self.container_icpms["skipheader"] = file_info["skipheader"]
                            self.container_icpms["skipfooter"] = file_info["skipfooter"]
                        else:
                            df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]
                    except:
                        print("File (" + str(file_smpl) + str(")"), "cannot be read.")

                if var_file_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][var_file_short] = 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"][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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["FI main settings"][0]
        n_columns = self.window_dimensions["FI main settings"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_fi_settings = tk.Toplevel(self.parent)

        if self.pysills_mode == "FI":
            str_title_window = self.language_dict["FLUID INCLUSION ANALYSIS - Setup"][self.var_language] #"FLUID INCLUSION ANALYSIS - Setup"
            self.subwindow_fi_settings.title(str_title_window)
        elif self.pysills_mode == "INCL":
            str_title_window = self.language_dict["INCLUSION ANALYSIS - Setup"][self.var_language] #"INCLUSION ANALYSIS - Setup"
            self.subwindow_fi_settings.title(str_title_window)

        if self.projectname != None:
            self.subwindow_fi_settings.title(self.projectname + " - " + str_title_window)

        self.subwindow_fi_settings.geometry(var_geometry)
        self.subwindow_fi_settings.resizable(False, False)
        self.subwindow_fi_settings["bg"] = self.bg_colors["BG Window"]

        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 in ["FI", "INCL"]:
            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
        str_screen_resolution = self.container_var["General Settings"]["Screen resolution"].get()
        if str_screen_resolution == "1920x1080":
            var_n_last_column = 18
            var_n_last_column = n_columns - 49
        elif str_screen_resolution == "1280x720":
            var_n_last_column = 23
        elif str_screen_resolution == "3840x2160":
            var_n_last_column = 18
        # 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": var_n_last_column}
        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": var_n_last_column}
        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": var_n_last_column}
        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

        str_opt_incl = self.container_var[var_setting_key]["Inclusion Setup Option"].get()
        str_opt_quant = self.container_var[var_setting_key]["Quantification Method Option"].get()

        self.select_opt_inclusion_is_quantification(
            var_opt=str_opt_incl, dict_geometry_info=var_quantification_method)
        self.select_opt_inclusion_quantification(
            var_opt=str_opt_quant, 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"):
                        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()))

                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("/")
                var_file_short = file_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_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("/")
                    if self.old_file == True:
                        df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_std)
                        self.container_icpms["name"] = "Undefined ICP-MS"
                        self.container_icpms["skipheader"] = file_info["skipheader"]
                        self.container_icpms["skipfooter"] = file_info["skipfooter"]
                    else:
                        df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]

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

                if var_file_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][var_file_short] = 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"][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("/")
                var_file_short = file_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_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("/")
                    if self.old_file == True:
                        df_exmpl, file_info = self.find_icpms_data_in_file(filename_long=file_std)
                        self.container_icpms["name"] = "Undefined ICP-MS"
                        self.container_icpms["skipheader"] = file_info["skipheader"]
                        self.container_icpms["skipfooter"] = file_info["skipfooter"]
                    else:
                        df_exmpl = self.container_measurements["Dataframe"][file_parts[-1]]

                if var_file_short not in self.container_measurements["Dataframe"]:
                    self.container_measurements["Dataframe"][var_file_short] = 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"][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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["MI main settings"][0]
        n_columns = self.window_dimensions["MI main settings"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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["BG Window"]

        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 in ["FI", "INCL"]:
            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
        str_screen_resolution = self.container_var["General Settings"]["Screen resolution"].get()
        if str_screen_resolution == "1920x1080":
            var_n_last_column = 18
            var_n_last_column = n_columns - 45
        elif str_screen_resolution == "1280x720":
            var_n_last_column = 23
        elif str_screen_resolution == "3840x2160":
            var_n_last_column = 18
        # 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": var_n_last_column}
        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": var_n_last_column}
        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": var_n_last_column}
        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()

    #########################
    ## 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 in ["FI", "INCL"]:
            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:
                if var_focus == "INCL":
                    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()

            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)

                    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[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)

                        if element in self.srm_actual[var_srm_i]:
                            var_concentration_i = self.srm_actual[var_srm_i][element]
                        else:
                            var_concentration_i = 0

                        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_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 in ["FI", "INCL"]:
            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)

                    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

                    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 in ["FI", "INCL"] 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_t = self.container_var["Borisova2021"]["Name"].get()
                            var_rho_host = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                       "rho(host)"].get())
                            var_rho_incl = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                       "rho(incl)"].get())
                            var_radius_host = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                          "R(host)"].get())
                            var_radius_incl = float(self.container_var["SMPL"][var_file_long]["Borisova2021"][
                                                          "R(incl)"].get())

                            var_concentration_host_t = self.container_concentration["SMPL"][var_datatype][
                                var_file_short]["MAT"][var_t]
                            var_ratio_rho = var_rho_host/var_rho_host
                            var_ratio_radius = 1.5*(var_radius_host**2)/(var_radius_incl**2) - 1

                            var_srm_t = self.container_lists["SRM Isotopes"][var_t]
                            var_srm_is = self.container_lists["SRM Isotopes"][var_is]
                            list_srm_t = []
                            list_srm_is = []
                            for key, value in self.container_lists["SRM Files"].items():
                                if value == var_srm_t:
                                    list_srm_t.append(key)
                                if value == var_srm_is:
                                    list_srm_is.append(key)

                            print("Matrix-only tracer:", var_t, self.container_lists["SRM Isotopes"][var_t])
                            print(list_srm_t)
                            print("Internal standard:", var_is, self.container_lists["SRM Isotopes"][var_is])
                            print(list_srm_is)

                            list_intensity_srm_t = []
                            list_intensity_srm_is = []
                            for filename_short in list_srm_t:
                                var_intensity_t = self.container_intensity_corrected["STD"][var_datatype][
                                    filename_short]["MAT"][var_t]
                                list_intensity_srm_t.append(var_intensity_t)
                            for filename_short in list_srm_is:
                                var_intensity_is = self.container_intensity_corrected["STD"][var_datatype][
                                    filename_short]["MAT"][var_is]
                                list_intensity_srm_is.append(var_intensity_is)
#
                            var_mean_intensity_srm_t = np.mean(list_intensity_srm_t)
                            var_mean_intensity_srm_is = np.mean(list_intensity_srm_is)

                            var_intensity_t = self.container_intensity_corrected["SMPL"][var_datatype][var_file_short][
                                "MAT"][var_t]
                            var_intensity_is = self.container_intensity_corrected["SMPL"][var_datatype][var_file_short][
                                "INCL"][var_is]

                            key_element = re.search(r"(\D+)(\d+)", var_t)
                            element = key_element.group(1)

                            var_concentration_srm_t = self.container_concentration["STD"][var_datatype][
                                list_srm_t[0]]["MAT"][var_t]
                            var_concentration_srm_is = self.container_concentration["STD"][var_datatype][
                                list_srm_is[0]]["MAT"][var_is]

                            if None in [var_concentration_srm_t, var_concentration_srm_is]:
                                if element in self.srm_actual[var_srm_t]:
                                    var_concentration_srm_t = self.srm_actual[var_srm_t][element]
                                else:
                                    var_concentration_srm_t = 0.0

                                key_element = re.search(r"(\D+)(\d+)", var_is)
                                element = key_element.group(1)

                                if element in self.srm_actual[var_srm_is]:
                                    var_concentration_srm_is = self.srm_actual[var_srm_is][element]
                                else:
                                    var_concentration_srm_is = 0.0

                            var_s = (var_mean_intensity_srm_t*var_concentration_srm_is)/(
                                    var_mean_intensity_srm_is*var_concentration_srm_t)
                            var_k = var_intensity_is/var_intensity_t

                            var_concentration_incl_is = (var_concentration_host_t*var_ratio_rho*var_ratio_radius*var_s*
                                                         var_k)

                            for index, isotope in enumerate(file_isotopes):
                                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

                                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
                    else:
                        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.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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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

                        a = 3.29/3.3

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 3.3*a*var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*var_result_i
                        # 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)

                        a = 3.0/3.3

                        self.container_lob[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 1.65*a*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 3.3*a*var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short]["MAT"][
                            isotope] = 10*a*var_result_i
                        # 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

                        a = 3.29/3.3

                        self.container_lob[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 1.65*a*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 3.3*a*var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 10*a*var_result_i
                        # 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

                        a = 3.29/3.3

                        self.container_lob[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 1.65*a*var_result_i
                        self.container_lod[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 3.3*a*var_result_i
                        self.container_loq[var_filetype][var_datatype][var_file_short][var_focus][
                            isotope] = 10*a*var_result_i
                        # 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 run_quantification_incl_tables(self):
        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")
            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")

    def fi_datareduction_tables(self, init=False):
        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        ## Initialization
        if len(self.helper_lists["Assemblages"]["All"]) > 1 and init == True:
            for var_file_long in self.container_lists["SMPL"]["Long"]:
                self.container_var["SMPL"][var_file_long]["ID"].set("A")
            self.run_quantification_incl_tables()
            for index, var_file_short in enumerate(self.container_lists["SMPL"]["Short"]):
                var_file_long = self.container_lists["SMPL"]["Long"][index]
                self.container_var["SMPL"][var_file_long]["ID"].set(self.helper_lists["Assemblages"]["True"][
                                                                        var_file_short])

        if init:
            self.run_quantification_incl_tables()

        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:
                            var_srm_i = self.container_var["SRM"][isotope].get()
                            value = self.container_analytical_sensitivity[var_filetype][var_datatype][var_file][
                                var_focus][isotope]

                            if var_filetype == "STD" and value != 1.0:
                                if var_srm_i != var_srm_file and value != 0.0:
                                    value = 0.0

                            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

                                if var_filetype == "STD" and value != 1.0:
                                    if var_srm_i != var_srm_file and value != 0.0:
                                        value = 0.0

                                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}")

                            if var_srm_i == var_srm_file or value != 0.0:
                                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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_title_02 = self.language_dict["Sensitivity drift"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Sensitivity drift"][0]
        n_columns = self.window_dimensions["Sensitivity drift"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_fi_graphical_sensitivity = tk.Toplevel(self.parent)
        if self.pysills_mode == "MA":
            str_title_01 = self.language_dict["Mineral Analysis"][self.var_language]
            self.subwindow_fi_graphical_sensitivity.title(str_title_01 + " - " + str_title_02)
        elif self.pysills_mode in ["FI", "INCL"]:
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
            self.subwindow_fi_graphical_sensitivity.title(str_title_01 + " - " + str_title_02)
        elif self.pysills_mode == "MI":
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]
            self.subwindow_fi_graphical_sensitivity.title(str_title_01 + " - " + str_title_02)

        self.subwindow_fi_graphical_sensitivity.geometry(var_geometry)
        self.subwindow_fi_graphical_sensitivity.resizable(False, False)
        self.subwindow_fi_graphical_sensitivity["bg"] = background_color_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=background_color_light,
            bg=background_color_dark).create_frame(relief=tk.FLAT)

        ## LABELS
        str_lbl_01 = self.language_dict["File selection"][self.var_language]
        str_lbl_02 = self.language_dict["Data selection"][self.var_language]
        str_lbl_03 = self.language_dict["Category"][self.var_language]
        str_lbl_04 = self.language_dict["Primary isotope"][self.var_language]
        str_lbl_05 = self.language_dict["Secondary isotope"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_fi_graphical_sensitivity, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_02, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, relief=tk.FLAT, fontsize="sans 10 bold")

        ## RADIOBUTTONS
        str_rb_01 = self.language_dict["Standard Files"][self.var_language]
        str_rb_02 = self.language_dict["Sample Files"][self.var_language]
        str_rb_03 = self.language_dict["Original data"][self.var_language]
        str_rb_04 = self.language_dict["Smoothed data"][self.var_language]
        str_rb_05 = self.language_dict["Sample"][self.var_language]
        str_rb_06 = self.language_dict["Matrix"][self.var_language]
        str_rb_07 = self.language_dict["Inclusion"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_01, value_rb=0, color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_01, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_01, value_rb=1, color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_02, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_02, value_rb=0, color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_03, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_02, value_rb=1, color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_04, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_03, value_rb=0, color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_05 + "/" + str_rb_06, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.var_rb_03, value_rb=1, color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_07, 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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=accent_color,
            command=self.fi_change_sensitivity_drift_diagram)
        opt_04a["menu"].config(
            fg=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=accent_color)
        opt_04a.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, 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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=accent_color,
            command=self.change_normalized_sensitivity_scatter)
        opt_05a["menu"].config(
            fg=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=accent_color)
        opt_05a.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, 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)

        str_ax_01 = self.language_dict["Sensitivity drift"][self.var_language]
        str_ax_02 = self.language_dict["Experiment time"][self.var_language]
        str_ax_03 = self.language_dict["Analytical sensitivity"][self.var_language]
        str_ax_04 = self.language_dict["of"][self.var_language]

        self.ax_sensitivity_03a.set_title(str_ax_01, fontsize=9)
        self.ax_sensitivity_03a.set_xlabel(str_ax_02 + " $t$ (s)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a.set_ylabel(
            str_ax_03 + " $\\xi$ " + str_ax_04 + " " + 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)

        str_ax_01 = self.language_dict["Sensitivity drift"][self.var_language]
        str_ax_02 = self.language_dict["Experiment time"][self.var_language]
        str_ax_03 = self.language_dict["Analytical sensitivity"][self.var_language]
        str_ax_04 = self.language_dict["of"][self.var_language]

        self.ax_sensitivity_03a.set_title(str_ax_01, fontsize=9)
        self.ax_sensitivity_03a.set_xlabel(str_ax_02 + " $t$ (s)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a.set_ylabel(
            str_ax_03 + " $\\xi$ " + str_ax_04 + " " + 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)

        str_ax_01 = self.language_dict["Analytical sensitivity"][self.var_language]
        str_ax_02 = self.language_dict["Normalized sensitivity"][self.var_language]
        str_ax_03 = self.language_dict["of"][self.var_language]

        self.ax_sensitivity_03a2.set_title(str_ax_01, fontsize=9)
        self.ax_sensitivity_03a2.set_xlabel(
            str_ax_02 + " $S$ " + str_ax_03 + " " + str(var_iso_01) + " (cps/ppm)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a2.set_ylabel(
            str_ax_02 + " $S$ " + str_ax_03 + " " + 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)

        str_ax_01 = self.language_dict["Analytical sensitivity"][self.var_language]
        str_ax_02 = self.language_dict["Normalized sensitivity"][self.var_language]
        str_ax_03 = self.language_dict["of"][self.var_language]

        self.ax_sensitivity_03a2.set_title(str_ax_01, fontsize=9)
        self.ax_sensitivity_03a2.set_xlabel(
            str_ax_02 + " $S$ " + str_ax_03 + " " + str(var_iso_01) + " (cps/ppm)", labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a2.set_ylabel(
            str_ax_02 + " $S$ " + str_ax_03 + " " + 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)

        str_ax_01 = self.language_dict["Sensitivity drift"][self.var_language]
        str_ax_02 = self.language_dict["Isotope"][self.var_language]

        self.ax_sensitivity_03a3.set_title(str_ax_01 + " (%)", fontsize=9)
        self.ax_sensitivity_03a3.set_xlabel(
            str_ax_02, labelpad=0.5, fontsize=8)
        self.ax_sensitivity_03a3.set_ylabel(
            str_ax_01 + " (%)", 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 #####################################################
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]

        str_title_02 = self.language_dict["Results"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["FI datareduction files"][0]
        n_columns = self.window_dimensions["FI datareduction files"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_fi_datareduction_files = tk.Toplevel(self.parent)
        self.subwindow_fi_datareduction_files.title(str_title_01 + " - " + str_title_02)
        self.subwindow_fi_datareduction_files.geometry(var_geometry)
        self.subwindow_fi_datareduction_files.resizable(False, False)
        self.subwindow_fi_datareduction_files["bg"] = background_color_dark

        if self.projectname != None:
            self.subwindow_fi_datareduction_files.title(self.projectname + " - " + str_title_01 + " - " + str_title_02)

        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
        str_lbl_01 = self.language_dict["File selection"][self.var_language]
        str_lbl_02 = self.language_dict["Data selection"][self.var_language]
        str_lbl_03 = self.language_dict["Assemblage"][self.var_language]
        str_lbl_04 = self.language_dict["Category"][self.var_language]
        str_lbl_05 = self.language_dict["Results"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_fi_datareduction_files, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_02, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, relief=tk.FLAT, fontsize="sans 10 bold")

        ## RADIOBUTTONS
        str_rb_01 = self.language_dict["Standard Files"][self.var_language]
        str_rb_02 = self.language_dict["Sample Files"][self.var_language]
        str_rb_03 = self.language_dict["Original data"][self.var_language]
        str_rb_04 = self.language_dict["Smoothed data"][self.var_language]
        str_rb_05 = self.language_dict["Matrix"][self.var_language]
        str_rb_14 = self.language_dict["Inclusion"][self.var_language]
        str_rb_06 = self.language_dict["Concentration"][self.var_language]
        str_rb_07 = self.language_dict["Concentration ratio"][self.var_language]
        str_rb_08 = self.language_dict["Limit of detection"][self.var_language]
        str_rb_09 = self.language_dict["Intensity"][self.var_language]
        str_rb_10 = self.language_dict["Mixed intensity"][self.var_language]
        str_rb_11 = self.language_dict["Analytical sensitivity"][self.var_language]
        str_rb_12 = self.language_dict["Normalized sensitivity"][self.var_language]
        str_rb_13 = self.language_dict["Relative sensitivity factor"][self.var_language]
        str_rb_15 = self.language_dict["Mixing ratio"][self.var_language]
        str_rb_16 = self.language_dict["Mixed concentration"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["File Type"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_01, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["File Type"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_02, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Data Type"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_03, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Data Type"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_04, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Focus"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_05, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Focus"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_14, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_06,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_07,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_08, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=3,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_15 + " 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=4,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_15 + " 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=5,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_16,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=6,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_09, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=7,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_10, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=8,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_11,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=9,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_12,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var["fi_datareduction_files"]["Result Category"], value_rb=10,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_13,
            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 = []
        self.helper_lists["Assemblages"]["True"] = {}
        for index, var_file_long in enumerate(self.container_lists["SMPL"]["Long"]):
            var_filename_short = self.container_lists["SMPL"]["Short"][index]
            var_id_i = self.container_var["SMPL"][var_file_long]["ID"].get()
            self.helper_lists["Assemblages"][var_filename_short] = var_id_i
            self.helper_lists["Assemblages"]["True"][var_filename_short] = var_id_i
            if var_id_i not in list_id_found:
                list_id_found.append(var_id_i)

        self.helper_lists["Assemblages"]["All"] = list_id_found

        if len(list_id_found) > 0:
            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=font_color_dark, bg=background_color_elements).create_option_isotope(
                var_iso=self.container_var["ID"]["Results Files"], option_list=list_id_found, text_set=var_text,
                fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
                activebackground=accent_color)
            opt_03a.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0)
            self.container_var["ID"]["Results Files"].set(list_id_found[0])

        ## BUTTONS
        str_btn_01 = self.language_dict["Export results"][self.var_language]
        str_btn_02 = self.language_dict["Further data analysis"][self.var_language]
        str_btn_03 = self.language_dict["Sensitivity drift"][self.var_language]

        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent, bg=accent_color).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_accent,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
            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=background_color_light,
            bg=background_color_light).create_frame(relief=tk.FLAT)

        ## TREEVIEW
        str_tv_01 = self.language_dict["Name"][self.var_language]

        list_categories = [str_tv_01]
        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=font_color_dark, 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 != "Select SRM":
                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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]

        str_title_02 = self.language_dict["Geometric approach"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Setup Halter"][0]
        n_columns = self.window_dimensions["Setup Halter"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_quantification_setup_halter2002 = tk.Toplevel(self.parent)
        self.subwindow_quantification_setup_halter2002.title(
            str_title_01 + " - " + str_title_02 + " (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"] = background_color_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
        str_lbl_01 = self.language_dict["Default settings"][self.var_language]
        str_lbl_02 = self.language_dict["Sample Files"][self.var_language]
        str_lbl_03 = self.language_dict["Setup"][self.var_language]
        str_lbl_04 = self.language_dict["Inclusion intensity"][self.var_language]
        str_lbl_05 = self.language_dict["Inclusion dimensions"][self.var_language]
        str_lbl_06 = self.language_dict["Densities"][self.var_language]
        str_lbl_07 = self.language_dict["Matrix density"][self.var_language]
        str_lbl_08 = self.language_dict["Inclusion density"][self.var_language]
        str_lbl_09 = self.language_dict["Ablation radius"][self.var_language]
        str_lbl_10 = self.language_dict["Length of"][self.var_language]
        str_lbl_11 = self.language_dict["semi-axis"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_quantification_setup_halter2002, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=18, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_05 + " (\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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_10 + " " + str_lbl_11 + " 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_10 + " " + str_lbl_11 + " 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_06 + " (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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_07, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_08, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text="Laser (\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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_09, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_02, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03 + " - " + str_lbl_04, 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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_light,
            bg_active=accent_color)
        opt_03a["menu"].config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_03a.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0)

        ## BUTTONS
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        str_btn_01 = self.language_dict["Confirm all"][self.var_language]

        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=font_color_accent, bg=accent_color).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_accent,
            command=self.change_values_halter2002_all)

        # RADIOBUTTONS
        str_rb_01 = self.language_dict["without"][self.var_language]
        str_rb_02 = self.language_dict["with"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text="SILLS (" + str_rb_01 + " 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text="SILLS (" + str_rb_02 + " 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=background_color_elements, fg=font_color_dark,
            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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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
        str_tv_01 = self.language_dict["Name"][self.var_language]
        str_tv_02 = self.language_dict["semi-axis"][self.var_language].capitalize()
        str_tv_03 = self.language_dict["Matrix density"][self.var_language]
        str_tv_04 = self.language_dict["Inclusion density"][self.var_language]
        str_tv_05 = self.language_dict["Ablation radius"][self.var_language]

        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=font_color_dark,
            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=background_color_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=str_tv_01, bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_file)
        text_smpl.insert("end", "\t")
        lbl_a = tk.Label(frm_smpl, text=str_tv_02 + " a", bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_a)
        text_smpl.insert("end", "\t")
        lbl_b = tk.Label(frm_smpl, text=str_tv_02 + " b", bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_b)
        text_smpl.insert("end", "\t")
        lbl_rhohost = tk.Label(
            frm_smpl, text=str_tv_03, bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_rhohost)
        text_smpl.insert("end", "\t")
        lbl_rhoincl = tk.Label(
            frm_smpl, text=str_tv_04, bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_rhoincl)
        text_smpl.insert("end", "\t")
        lbl_ablationradius = tk.Label(
            frm_smpl, text=str_tv_05, bg=background_color_light, fg=font_color_dark)
        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=background_color_light, fg=font_color_dark)
            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=font_color_dark)
            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=font_color_dark)
            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=font_color_dark)
            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=font_color_dark)
            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=font_color_dark)
            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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]

        str_title_02 = self.language_dict["Geometric approach"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Setup Borisova"][0]
        n_columns = self.window_dimensions["Setup Borisova"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_quantification_setup_borisova2021 = tk.Toplevel(self.parent)
        self.subwindow_quantification_setup_borisova2021.title(
            str_title_01 + " - " + str_title_02 + " (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"] = background_color_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
        str_lbl_01 = self.language_dict["Default settings"][self.var_language]
        str_lbl_02 = self.language_dict["Sample Files"][self.var_language]
        str_lbl_03 = self.language_dict["Setup"][self.var_language]
        str_lbl_04 = self.language_dict["Inclusion intensity"][self.var_language]
        str_lbl_05 = self.language_dict["Dimensions"][self.var_language]
        str_lbl_06 = self.language_dict["Densities"][self.var_language]
        str_lbl_07 = self.language_dict["Matrix density"][self.var_language]
        str_lbl_08 = self.language_dict["Inclusion density"][self.var_language]
        str_lbl_09 = self.language_dict["Ablation radius"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_quantification_setup_borisova2021, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=18, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_05 + " (\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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_09, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_06 + " (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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_07, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_08, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_02, 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=font_color_light,
            bg=background_color_dark).create_simple_label(
            text=str_lbl_03 + " - " + str_lbl_04, 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=font_color_dark, bg=background_color_elements).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=font_color_dark, bg=background_color_elements).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=font_color_light,
            bg_active=accent_color)
        opt_03a["menu"].config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_03a.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0)

        ## BUTTONS
        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        str_btn_01 = self.language_dict["Confirm all"][self.var_language]

        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=font_color_accent, bg=accent_color).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_accent,
            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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, 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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=background_color_elements, fg=font_color_dark,
            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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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=font_color_dark, 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
        str_tv_01 = self.language_dict["Name"][self.var_language]
        str_tv_02 = self.language_dict["Inclusion radius"][self.var_language].capitalize()
        str_tv_03 = self.language_dict["Matrix density"][self.var_language]
        str_tv_04 = self.language_dict["Inclusion density"][self.var_language]
        str_tv_05 = self.language_dict["Ablation radius"][self.var_language]

        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=font_color_dark,
            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=background_color_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=str_tv_01, bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_file)
        text_smpl.insert("end", "\t")
        lbl_a = tk.Label(
            frm_smpl, text=str_tv_02, bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_a)
        text_smpl.insert("end", "\t")
        lbl_b = tk.Label(
            frm_smpl, text=str_tv_05, bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_b)
        text_smpl.insert("end", "\t")
        lbl_rhohost = tk.Label(
            frm_smpl, text=str_tv_03, bg=background_color_light, fg=font_color_dark)
        text_smpl.window_create("end", window=lbl_rhohost)
        text_smpl.insert("end", "\t")
        lbl_rhoincl = tk.Label(
            frm_smpl, text=str_tv_04, bg=background_color_light, fg=font_color_dark)
        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=background_color_light, fg=font_color_dark)
            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=font_color_dark)
            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=font_color_dark)
            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=font_color_dark)
            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=font_color_dark)
            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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Setup matrix-only tracer"][0]
        n_columns = self.window_dimensions["Setup matrix-only tracer"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_fi_setup_matrixonlytracer = tk.Toplevel(self.parent)
        self.subwindow_fi_setup_matrixonlytracer.title(str_title_01 + " - Matrix-only tracer")
        self.subwindow_fi_setup_matrixonlytracer.geometry(var_geometry)
        self.subwindow_fi_setup_matrixonlytracer.resizable(False, False)
        self.subwindow_fi_setup_matrixonlytracer["bg"] = background_color_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
        str_lbl_01 = self.language_dict["Default settings"][self.var_language]
        str_lbl_02 = self.language_dict["Concentration"][self.var_language]
        str_lbl_03 = self.language_dict["Sample Files"][self.var_language]
        str_lbl_04 = self.language_dict["Setup"][self.var_language]
        str_lbl_05 = self.language_dict["Inclusion intensity"][self.var_language]
        str_lbl_06 = self.language_dict["Inclusion concentration"][self.var_language]
        str_lbl_07 = self.language_dict["Matrix"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=25, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01 + " - Matrix-only tracer", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_01c = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 1, column_id=start_column, n_rows=1,
            n_columns=13, fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text="Matrix-only tracer", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_01d = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 2, column_id=start_column, n_rows=1,
            n_columns=13, fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02 + " (" + str_lbl_07 + ")" + " (ppm)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 3, column_id=start_column, n_rows=1,
            n_columns=25, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04 + " - " + str_lbl_05, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04 + " - " + str_lbl_06, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        ## ENTRIES
        entr_01d = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 2, column_id=start_column + 13,
            n_rows=1, n_columns=12, fg=font_color_dark,
            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 event, variable=self.container_var[key_setting]["Matrix-Only Concentration Default"]:
            self.change_matrix_only_concentration(variable, event))
        entr_01d.bind(
            "<Return>", lambda event, variable=self.container_var[key_setting]["Matrix-Only Concentration Default"]:
            self.change_matrix_only_concentration(variable, event))

        # RADIOBUTTONS
        str_rb_01 = self.language_dict["without"][self.var_language]
        str_rb_02 = self.language_dict["with"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text="Heinrich et al. (2003)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text="SILLS (" + str_rb_01 + " R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text="SILLS (" + str_rb_02 + " R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=background_color_elements, fg=font_color_dark, text="Theory (simple intensity composition)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Concentration Calculation"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_01 + " x", sticky="nesw",
            relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Concentration Calculation"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text=str_rb_02 + " x", sticky="nesw",
            relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)

        ## OPTION MENUES
        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 + 1, column_id=start_column + 13,
            n_rows=1, n_columns=12, fg=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=accent_color,
            command=lambda var_opt=self.container_var[key_setting]["Host Only"]:
            self.change_matrix_only_tracer(var_opt))
        self.opt_01c["menu"].config(
            fg=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        self.opt_01c.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0)

        ## TREEVIEWS
        frm_smpl = SE(
            parent=self.subwindow_fi_setup_matrixonlytracer, row_id=start_row + 4, column_id=start_column,
            n_rows=n_rows - 5, n_columns=25, fg=font_color_dark,
            bg=background_color_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=background_color_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=background_color_light, fg=font_color_dark)
            text_smpl.window_create("end", window=lbl_i)
            text_smpl.insert("end", "\t")

            try:
                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")
            except:
                print("Problem with the variable 'Host-only tracer amount'. It's actually not needed anymore.")

            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())

            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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_2_i.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, 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=font_color_dark)
            text_smpl.window_create("insert", window=entr_2_i)
            text_smpl.insert("end", "\n")

    def fi_setup_second_internal_standard(self):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Setup 2nd IS"][0]
        n_columns = self.window_dimensions["Setup 2nd IS"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_fi_setup_secondinternalstandard = tk.Toplevel(self.parent)
        self.subwindow_fi_setup_secondinternalstandard.title(str_title_01 + " - Second internal standard")
        self.subwindow_fi_setup_secondinternalstandard.geometry(var_geometry)
        self.subwindow_fi_setup_secondinternalstandard.resizable(False, False)
        self.subwindow_fi_setup_secondinternalstandard["bg"] = background_color_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
        str_lbl_01 = self.language_dict["Default settings"][self.var_language]
        str_lbl_02 = self.language_dict["Concentration"][self.var_language]
        str_lbl_03 = self.language_dict["Sample Files"][self.var_language]
        str_lbl_04 = self.language_dict["Setup"][self.var_language]
        str_lbl_05 = self.language_dict["Inclusion intensity"][self.var_language]
        str_lbl_06 = self.language_dict["Inclusion concentration"][self.var_language]
        str_lbl_07 = self.language_dict["Matrix"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row, column_id=start_column, n_rows=1,
            n_columns=20, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01 + " - Second internal standard", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text="Second internal standard", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02 + " (" + str_lbl_07 + ") (ppm)", relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_03, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04 + " - " + str_lbl_05, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)
        lbl_01 = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 5, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04 + " - " + str_lbl_06, relief=tk.FLAT, fontsize="sans 10 bold", anchor=tk.W)

        ## 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=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.container_var[key_setting]["2nd Internal"], option_list=self.container_lists["ISOTOPES"],
            text_set=var_text, fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
            activebackground=accent_color)
        opt_01a.config(
            bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
            activeforeground=font_color_light, highlightthickness=0)

        # RADIOBUTTONS
        str_rb_01 = self.language_dict["without"][self.var_language]
        str_rb_02 = self.language_dict["with"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text="Heinrich et al. (2003)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text="SILLS (" + str_rb_01 + " R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text="SILLS (" + str_rb_02 + " R)",
            sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        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=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Intensity Calculation"], value_rb=3,
            color_bg=background_color_elements, fg=font_color_dark,
            text="Theory (simple intensity composition)", sticky="nesw", relief=tk.FLAT, font="sans 10 bold",
            anchor=tk.W)
        rb_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 6, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Concentration Calculation"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_01 + " x", sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)
        rb_01b = SE(
            parent=self.subwindow_fi_setup_secondinternalstandard, row_id=start_row + 7, column_id=start_column + 21,
            n_rows=1, n_columns=14, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.container_var[key_setting]["Inclusion Concentration Calculation"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark,
            text=str_rb_02 + " x", sticky="nesw", relief=tk.FLAT, font="sans 10 bold", anchor=tk.W)

        ## 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=font_color_dark,
            bg=background_color_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=font_color_dark, bg=background_color_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=background_color_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=background_color_light, fg=font_color_dark)
            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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_i.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, 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=font_color_dark)
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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):
        str_filename_long = var_file
        str_filetype = var_type

        # ## INPUT
        parts = str_filename_long.split("/")
        str_filename_short = parts[-1]

        if str_filetype == "STD":
            var_srm_file = self.container_var["STD"][str_filename_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"][str_filename_short]:
                    var_is_i = self.container_lists["Measured Elements"][str_filename_short][element][0]
                    self.container_var[str_filetype][str_filename_long]["IS Data"]["IS"].set(var_is_i)
                break
        else:
            if self.pysills_mode == "MA":
                var_mat_is = self.container_var[str_filetype][str_filename_long]["IS Data"]["IS"].get()
                var_is_i = var_mat_is
            else:
                var_mat_is = self.container_var[str_filetype][str_filename_long]["Matrix Setup"]["IS"]["Name"].get()
                var_incl_is = self.container_var[str_filetype][str_filename_long]["IS Data"]["IS"].get()
                var_is_i = var_incl_is

        self.specific_file_setup(filetype=str_filetype, filename_long=str_filename_long)

    def create_chart_analysis_window(self, filetype, filename_short):
        str_filetype = filetype
        self.ca_filetype = str_filetype
        str_filename_short = filename_short
        self.ca_filename_short = str_filename_short
        list_isotopes = self.container_lists["Measured Isotopes"][filename_short]
        list_opt_isotopes = list_isotopes.copy()
        list_opt_isotopes.insert(0, "None")
        df_data = self.container_measurements["Dataframe"][filename_short]
        list_keys = list_isotopes.copy()
        list_keys.insert(0, "None")
        list_keys.insert(1, "Time")

        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Quick Plot Extra"][0]
        n_columns = self.window_dimensions["Quick Plot Extra"][1] + 8

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_chart_analysis = tk.Toplevel(self.parent)
        subwindow_chart_analysis.title("Chart analysis")
        subwindow_chart_analysis.geometry(var_geometry)
        subwindow_chart_analysis.resizable(False, False)
        subwindow_chart_analysis["bg"] = background_color_light

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

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

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

        row_start = 0
        column_start = 0
        n_rows_navigation = n_rows
        n_colums_navigation = int(1/3.5*n_columns)
        n_columns_plot = n_columns - n_colums_navigation
        rows_tv = n_rows - 12
        n_rows_tv = 12
        row_start_lb = n_rows - 8
        column_start_lb = n_colums_navigation
        n_column_lb = int(1/3*n_columns_plot)

        ## TRANSLATIONS
        str_var_01 = self.language_dict["Plotting setup"][self.var_language]
        str_var_02 = self.language_dict["Isotope selection"][self.var_language]
        str_var_03 = self.language_dict["Show all"][self.var_language]
        str_var_04 = self.language_dict["Hide all"][self.var_language]
        str_var_05 = self.language_dict["Remove interval"][self.var_language]
        str_var_06 = self.language_dict["Data analysis"][self.var_language]
        str_var_07 = self.language_dict["Background"][self.var_language]
        str_var_08 = self.language_dict["Matrix"][self.var_language]
        str_var_09 = self.language_dict["Inclusion"][self.var_language]
        str_var_10 = self.language_dict["No selection"][self.var_language]
        str_var_11 = self.language_dict["Histogram plot"][self.var_language]
        str_var_12 = self.language_dict["Update"][self.var_language]

        ## FRAMES
        frm_01 = SE(
            parent=subwindow_chart_analysis, row_id=row_start, column_id=column_start, n_rows=n_rows_navigation,
            n_columns=n_colums_navigation, fg=font_color_dark, bg=background_color_dark).create_frame(relief=tk.FLAT)

        ## LABELS
        lbl_01 = SE(
            parent=subwindow_chart_analysis, row_id=row_start, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_01, relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_02 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 1, column_id=column_start, n_rows=1,
            n_columns=n_colums_navigation, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_var_02, relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_03 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 2, column_id=column_start, n_rows=1,
            n_columns=2, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="#1", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)
        lbl_04 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 3, column_id=column_start, n_rows=1,
            n_columns=2, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="#2", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)

        ## OPTION MENUS
        self.helper_opt_ca_1 = tk.StringVar()
        self.helper_opt_ca_1.set(list_opt_isotopes[0])
        self.helper_opt_ca_2 = tk.StringVar()
        self.helper_opt_ca_2.set(list_opt_isotopes[0])

        opt_ca_1 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 2, column_id=2, n_rows=1,
            n_columns=n_colums_navigation - 3, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_opt_ca_1, option_list=list_opt_isotopes, text_set=self.helper_opt_ca_1.get(),
            fg_active=font_color_light, bg_active=accent_color,
            command=lambda filename_short=str_filename_short, geometry=[
                subwindow_chart_analysis, 0, n_colums_navigation, row_start_lb - 3, n_columns_plot]:
            self.create_chart_analysis_diagram(filename_short, geometry))
        opt_ca_2 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 3, column_id=2, n_rows=1,
            n_columns=n_colums_navigation - 3, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_opt_ca_2, option_list=list_opt_isotopes, text_set=self.helper_opt_ca_2.get(),
            fg_active=font_color_light, bg_active=accent_color,
            command=lambda filename_short=str_filename_short, geometry=[
                subwindow_chart_analysis, 0, n_colums_navigation, row_start_lb - 3, n_columns_plot]:
            self.create_chart_analysis_diagram(filename_short, geometry))

        ## LISTBOXES
        frm_ca_iso = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 9, column_id=column_start + 2,
            n_rows=n_rows - 10, n_columns=n_colums_navigation - 3, fg=font_color_dark,
            bg=background_color_light).create_frame()
        vsb_ca_iso = ttk.Scrollbar(master=frm_ca_iso, orient="vertical")
        text_ca_iso = tk.Text(
            master=frm_ca_iso, width=30, height=25, yscrollcommand=vsb_ca_iso.set,
            bg=background_color_light)
        vsb_ca_iso.config(command=text_ca_iso.yview)
        vsb_ca_iso.pack(side="right", fill="y")
        text_ca_iso.pack(side="left", fill="both", expand=True)

        self.lb_ca_bg = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb, column_id=column_start_lb,
            n_rows=n_rows - row_start_lb, n_columns=n_column_lb, fg=font_color_dark,
            bg=self.colors_intervals["BG LB"]).create_simple_listbox()
        self.lb_ca_mat = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb,
            column_id=column_start_lb + n_column_lb, n_rows=n_rows - row_start_lb,
            n_columns=n_column_lb, fg=font_color_dark, bg=self.colors_intervals["MAT LB"]).create_simple_listbox()
        self.lb_ca_incl = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb, column_id=column_start_lb + 2*n_column_lb,
            n_rows=n_rows - row_start_lb, n_columns=n_column_lb, fg=font_color_dark,
            bg=self.colors_intervals["INCL LB"]).create_simple_listbox()

        ## BUTTONS
        btn_01 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 5, column_id=2, n_rows=1,
            n_columns=n_colums_navigation - 3, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_var_12, bg_active=accent_color, fg_active=font_color_light, command=self.refresh_plot_ca)
        btn_02 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 6, column_id=2, n_rows=1,
            n_columns=int((n_colums_navigation - 3)/2), fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_var_03, bg_active=accent_color, fg_active=font_color_light, command=self.chart_analysis_show_all)
        btn_03 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 6, column_id=2 + int((n_colums_navigation - 3)/2),
            n_rows=1, n_columns=int((n_colums_navigation - 3)/2), fg=font_color_dark,
            bg=background_color_elements).create_simple_button(
            text=str_var_04, bg_active=accent_color, fg_active=font_color_light, command=self.chart_analysis_hide_all)
        btn_04 = SE(
            parent=subwindow_chart_analysis, row_id=row_start + 7, column_id=2, n_rows=1,
            n_columns=n_colums_navigation - 3, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_var_05, bg_active=accent_color, fg_active=font_color_light, command=self.remove_interval_ca)

        ## RADIOBUTTONS
        self.helper_rb_ca_bg = tk.IntVar()
        self.helper_rb_ca_bg.set(0)

        rb_01 = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb - 1, column_id=column_start_lb, n_rows=1,
            n_columns=n_column_lb, fg=font_color_light, bg=self.colors_intervals["BG"]).create_radiobutton(
            var_rb=self.helper_rb_ca_bg, value_rb=1, color_bg=self.colors_intervals["BG"],
            fg=self.colors_intervals["BG LB"], text=str_var_07, sticky="nesw", relief=tk.FLAT)
        rb_02 = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb - 1, column_id=column_start_lb + n_column_lb, n_rows=1,
            n_columns=n_column_lb, fg=font_color_light, bg=self.colors_intervals["MAT"]).create_radiobutton(
            var_rb=self.helper_rb_ca_bg, value_rb=2, color_bg=self.colors_intervals["MAT"],
            fg=self.colors_intervals["MAT LB"], text=str_var_08, sticky="nesw", relief=tk.FLAT)
        rb_03 = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb - 1, column_id=column_start_lb + 2*n_column_lb,
            n_rows=1, n_columns=n_column_lb, fg=font_color_light, bg=self.colors_intervals["INCL"]).create_radiobutton(
            var_rb=self.helper_rb_ca_bg, value_rb=3, color_bg=self.colors_intervals["INCL"],
            fg=self.colors_intervals["INCL LB"], text=str_var_09, sticky="nesw", relief=tk.FLAT)
        rb_04 = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb - 2, column_id=column_start_lb, n_rows=1,
            n_columns=3*n_column_lb, fg=font_color_light, bg=background_color_dark).create_radiobutton(
            var_rb=self.helper_rb_ca_bg, value_rb=0, color_bg=background_color_dark, fg=font_color_light,
            text=str_var_10, sticky="nesw", relief=tk.FLAT)

        rb_01.configure(font=font_elements)
        rb_02.configure(font=font_elements)
        rb_03.configure(font=font_elements)
        rb_04.configure(font=font_elements)

        ## CHECKBOXES
        self.helper_cb_ca_bg = tk.IntVar()
        self.helper_cb_ca_mat = tk.IntVar()
        self.helper_cb_ca_incl = tk.IntVar()
        self.helper_cb_ca_bg.set(1)
        self.helper_cb_ca_mat.set(1)
        self.helper_cb_ca_incl.set(1)

        cb_01 = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb - 1,
            column_id=column_start_lb + (n_column_lb - 1), n_rows=1, n_columns=1,
            fg=font_color_dark, bg=self.colors_intervals["BG"]).create_simple_checkbox(
            var_cb=self.helper_cb_ca_bg, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Background": self.show_or_hide_intervals_ca(key))
        cb_02 = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb - 1,
            column_id=column_start_lb + n_column_lb + (n_column_lb - 1), n_rows=1, n_columns=1,
            fg=font_color_dark, bg=self.colors_intervals["MAT"]).create_simple_checkbox(
            var_cb=self.helper_cb_ca_mat, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Matrix": self.show_or_hide_intervals_ca(key))
        cb_03 = SE(
            parent=subwindow_chart_analysis, row_id=row_start_lb - 1,
            column_id=column_start_lb + 2*n_column_lb + (n_column_lb - 1), n_rows=1, n_columns=1,
            fg=font_color_dark, bg=self.colors_intervals["INCL"]).create_simple_checkbox(
            var_cb=self.helper_cb_ca_incl, text="", set_sticky="nesw", own_color=True,
            command=lambda key="Inclusion": self.show_or_hide_intervals_ca(key))

        ## INITIALIZATION
        self.temp_ca_cb_iso = {}
        for isotope in list_isotopes:
            self.temp_ca_cb_iso[isotope] = tk.IntVar()
            self.temp_ca_cb_iso[isotope].set(1)
            frm_i = tk.Frame(frm_ca_iso, bg=self.isotope_colors[isotope], relief=tk.SOLID, height=15, width=15,
                             highlightbackground="black", bd=1)
            text_ca_iso.window_create("end", window=frm_i)
            text_ca_iso.insert("end", "\t")

            cb_i = tk.Checkbutton(
                master=frm_ca_iso, text=isotope, fg=font_color_dark,
                bg=background_color_light, variable=self.temp_ca_cb_iso[isotope])

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

        text_ca_iso.configure(state="disabled")

        self.ca_geometry_diagram = [subwindow_chart_analysis, 0, n_colums_navigation, row_start_lb - 3, n_columns_plot]

        self.create_chart_analysis_diagram(filename_short=str_filename_short, geometry=self.ca_geometry_diagram,
                                           init=True)

        self.check_for_intervals_ca()

    def show_or_hide_intervals_ca(self, key):
        if key == "Background":
            var_key = "BG"
            state_var = self.helper_cb_ca_bg.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False
        elif key in ["Matrix", "Sample"]:
            var_key = "MAT"
            state_var = self.helper_cb_ca_mat.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False
        elif key == "Inclusion":
            var_key = "INCL"
            state_var = self.helper_cb_ca_incl.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False

        for id, container in self.container_helper[self.ca_filetype][self.ca_filename_short][var_key][
            "Content"].items():
            obj_interval = container["Object"]
            obj_interval.set_visible(state)

        self.var_canvas_ca.draw()

    def refresh_plot_ca(self):
        self.create_chart_analysis_diagram(filename_short=self.ca_filename_short, geometry=self.ca_geometry_diagram)

    def chart_analysis_show_all(self):
        for isotope, variable in self.temp_ca_cb_iso.items():
            variable.set(1)

        self.create_chart_analysis_diagram(filename_short=self.ca_filename_short, geometry=self.ca_geometry_diagram)

    def chart_analysis_hide_all(self):
        for isotope, variable in self.temp_ca_cb_iso.items():
            variable.set(0)

        self.create_chart_analysis_diagram(filename_short=self.ca_filename_short, geometry=self.ca_geometry_diagram)

    def create_chart_analysis_diagram(self, filename_short, geometry, init=False, refresh=False):
        if init == False:
            self.var_canvas_ca.get_tk_widget().destroy()
            self.var_toolbarFrame_ca.destroy()
            self.var_toolbar_ca.destroy()
            plt.close(self.var_canvas_ca.figure)

        df_data = self.container_measurements["Dataframe"][self.ca_filename_short]
        data_x = list(df_data.iloc[:, 0])
        self.dataset_time = data_x
        x_max = max(data_x)

        ref_iso_1 = self.helper_opt_ca_1.get()
        ref_iso_2 = self.helper_opt_ca_2.get()
        list_isotopes = []
        for isotope, variable in self.temp_ca_cb_iso.items():
            if variable.get() == 1 and isotope not in [ref_iso_1, ref_iso_2]:
                list_isotopes.append(isotope)

        # Diagram
        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_fig = Figure(figsize=(10, 5), tight_layout=True, facecolor=self.bg_colors["Very Light"])
        var_ax = var_fig.add_subplot(label=np.random.uniform())

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            # Time-Signal diagram
            for isotope in list_isotopes:
                data_y = df_data[isotope]
                var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=var_lw)
        else:
            # Time-Ratio diagram
            if ref_iso_1 != "None":
                for index, isotope in enumerate(list_isotopes):
                    data_ref_iso_1 = df_data[ref_iso_1]
                    data_i = df_data[isotope]
                    data_y = data_i/data_ref_iso_1
                    if index > 0:
                        var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=1)
                    else:
                        var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=1,
                                    label="i/" + ref_iso_1)

            if ref_iso_2 != "None":
                for index, isotope in enumerate(list_isotopes):
                    data_ref_iso_2 = df_data[ref_iso_2]
                    data_i = df_data[isotope]
                    data_y = data_i/data_ref_iso_2
                    if index > 0:
                        var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=2)
                    else:
                        var_ax.plot(data_x, data_y, color=self.isotope_colors[isotope], linewidth=2,
                                    label="i/" + ref_iso_2)

        var_ax.grid(True)
        var_ax.set_yscale("log")
        var_ax.set_xlim(left=0, right=x_max)
        var_ax.set_xticks(np.linspace(0, x_max, 11, endpoint=True))

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            var_ax.set_ylim(bottom=1e2, top=1e9)
            var_ax.set_yticks([1e2, 1e3, 1e4, 1e5, 1e6, 1e6, 1e7, 1e8, 1e9])
        else:
            var_ax.set_ylim(bottom=1e-4, top=1e5)
            var_ax.set_yticks([1e-4, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5])

        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(self.ca_filename_short, fontsize=9)
        var_ax.set_xlabel("Time (s)", labelpad=0.5, fontsize="x-small")

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            var_ax.set_ylabel("Signal intensity (cps)", labelpad=0.5, fontsize="x-small")
        else:
            var_ax.set_ylabel("Signal intensity ratio (cps/cps)", labelpad=0.5, fontsize="x-small")

        var_ax.xaxis.set_tick_params(labelsize="x-small")
        var_ax.yaxis.set_tick_params(labelsize="x-small")

        self.var_ax_ca = var_ax

        if ref_iso_1 == "None" and ref_iso_2 == "None":
            pass
        else:
            var_ax.legend(loc="upper left", framealpha=1.0, fontsize="x-small")

        subwindow = geometry[0]
        row_start = geometry[1]
        column_start = geometry[2]
        n_rows_diagram = geometry[3]
        n_columns_diagram = geometry[4]

        self.var_canvas_ca = FigureCanvasTkAgg(var_fig, master=subwindow)
        self.var_canvas_ca.get_tk_widget().grid(
            row=row_start, column=column_start, rowspan=n_rows_diagram, columnspan=n_columns_diagram,
            sticky="nesw")

        self.var_toolbarFrame_ca = tk.Frame(master=subwindow)
        self.var_toolbarFrame_ca.grid(
            row=n_rows_diagram, column=column_start, rowspan=1, columnspan=n_columns_diagram, sticky="ew")
        self.var_toolbar_ca = NavigationToolbar2Tk(self.var_canvas_ca, self.var_toolbarFrame_ca)
        self.var_toolbar_ca.config(
            bg=self.bg_colors["Very Light"], highlightthickness=0, highlightbackground=self.bg_colors["Very Light"],
            highlightcolor=self.bg_colors["Dark Font"], bd=0)
        self.var_toolbar_ca._message_label.config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"], font="sans 12")
        self.var_toolbar_ca.winfo_children()[-2].config(
            background=self.bg_colors["Very Light"], fg=self.bg_colors["Dark Font"])

        self.var_canvas_ca.mpl_connect(
            "button_press_event", lambda event, var_type=self.ca_filetype, var_file_short=self.ca_filename_short:
            self.add_interval_to_diagram_ca(var_type, var_file_short, event))

        if init == True:
            self.helper_intervals = {"BG": [], "MAT": [], "INCL": []}

            if self.ca_filetype not in self.container_helper:
                self.container_helper[self.ca_filetype] = {}
                if self.ca_filename_short not in self.container_helper[self.ca_filetype]:
                    self.container_helper[self.ca_filetype][self.ca_filename_short] = {}
                    if "AXES" not in self.container_helper[self.ca_filetype][self.ca_filename_short]:
                        self.container_helper[self.ca_filetype][self.ca_filename_short]["AXES"] = {
                            "Chart analysis": var_ax, "Canvas CA": self.var_canvas_ca}
            else:
                if self.ca_filename_short not in self.container_helper[self.ca_filetype]:
                    self.build_container_helper(mode=self.ca_filetype)

                for key in ["BG", "MAT", "INCL"]:
                    if key not in self.container_helper[self.ca_filetype][self.ca_filename_short]:
                        self.container_helper[self.ca_filetype][self.ca_filename_short][key] = {
                            "ID": 0, "Content": {}, "Indices": []}

                if "Chart analysis" not in self.container_helper[self.ca_filetype][self.ca_filename_short]["AXES"]:
                    self.container_helper[self.ca_filetype][self.ca_filename_short]["AXES"]["Chart analysis"] = var_ax
                    self.container_helper[self.ca_filetype][self.ca_filename_short]["AXES"][
                        "Canvas CA"] = self.var_canvas_ca

        if init == False:
            self.check_for_intervals_ca(only_boxes=True)

    def add_interval_to_diagram_ca(self, var_type, var_file_short, event):
        filename_index = self.container_lists[var_type]["Short"].index(var_file_short)
        var_file_long = self.container_lists[var_type]["Long"][filename_index]

        if self.helper_rb_ca_bg.get() == 1:  # BG
            var_key = "BG"
            var_color = self.colors_intervals[var_key]
        elif self.helper_rb_ca_bg.get() == 2:  # MAT
            var_key = "MAT"
            var_color = self.colors_intervals[var_key]
        elif self.helper_rb_ca_bg.get() == 3:  # INCL
            var_key = "INCL"
            var_color = self.colors_intervals[var_key]

        if self.helper_rb_ca_bg.get() in [1, 2, 3]:
            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.var_ax_ca.axvspan(time_0, time_1, alpha=0.35, color=var_color)
                self.var_canvas_ca.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}

                if var_key == "BG":
                    var_lb = self.lb_ca_bg
                elif var_key == "MAT":
                    var_lb = self.lb_ca_mat
                elif var_key == "INCL":
                    var_lb = self.lb_ca_incl

                var_lb.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.var_canvas_ca.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:
                if var_file_long in self.container_var[var_type]:
                    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:
                    if var_file_long in self.container_var[var_type]:
                        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:
                    if var_file_long in self.container_var[var_type]:
                        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:
                if var_file_long in self.container_var[var_type]:
                    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:
                    if var_file_long in self.container_var[var_type]:
                        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:
                    if var_file_long in self.container_var[var_type]:
                        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 remove_interval_ca(self):
        if self.helper_rb_ca_bg.get() == 1:  # BG
            var_key = "BG"
            var_lb = self.lb_ca_bg
        elif self.helper_rb_ca_bg.get() == 2:  # MAT
            var_key = "MAT"
            var_lb = self.lb_ca_mat
        elif self.helper_rb_ca_bg.get() == 3:  # INCL
            var_key = "INCL"
            var_lb = self.lb_ca_incl

        item = var_lb.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[self.ca_filetype][self.ca_filename_short][var_key]["Indices"].remove(var_id)
        var_lb.delete(tk.ANCHOR)
        self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][var_id][
            "Object"].set_visible(False)
        del self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][var_id]

        self.var_canvas_ca.draw()

    def remove_all_interval_ca(self):
        for var_key in ["BG", "MAT", "INCL"]:
            if var_key == "BG":
                var_lb = self.lb_ca_bg
            elif var_key == "MAT":
                var_lb = self.lb_ca_mat
            elif var_key == "INCL":
                var_lb = self.lb_ca_incl

            list_id = self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Indices"].copy()
            for var_id in list_id:
                self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][var_id][
                    "Object"].set_visible(False)
                del self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Content"][var_id]

            var_lb.delete(0, tk.END)

            self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["Indices"].clear()
            self.container_helper[self.ca_filetype][self.ca_filename_short][var_key]["ID"] = 0

        self.var_canvas_ca.draw()

    def check_for_intervals_ca(self, only_boxes=False, filesetup=False):
        if self.pysills_mode == "MA":
            list_sections = ["BG", "MAT"]
        else:
            list_sections = ["BG", "MAT", "INCL"]

        for section in list_sections:
            if len(self.container_helper[self.ca_filetype][self.ca_filename_short][section]["Indices"]) > 0:
                if section == "BG":
                    var_lb = self.lb_ca_bg
                elif section == "MAT":
                    var_lb = self.lb_ca_mat
                elif section == "INCL":
                    var_lb = self.lb_ca_incl

                var_color = self.colors_intervals[section]

                for key_id, container in self.container_helper[self.ca_filetype][self.ca_filename_short][section][
                    "Content"].items():
                    list_times = container["Times"]
                    time_0 = list_times[0]
                    time_1 = list_times[1]

                    if only_boxes == False:
                        var_lb.insert(tk.END, section + str(key_id) + " [" + str(time_0) + "-" + str(time_1) + "]")

                    box = self.var_ax_ca.axvspan(time_0, time_1, alpha=0.35, color=var_color)

                    container["Object"] = box

        self.var_canvas_ca.draw()

    def ca_show_or_hide_interval(self, key, var_type, var_file_short):
        if key == "Background":
            var_key = "BG"
            state_var = self.qpl_cb_bg.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False
        elif key in ["Matrix", "Sample"]:
            var_key = "MAT"
            state_var = self.qpl_cb_mat.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False
        elif key == "Inclusion":
            var_key = "INCL"
            state_var = self.qpl_cb_incl.get()
            if state_var == 1:
                state = True
            elif state_var == 0:
                state = False

        for id, container in self.container_helper[var_type][var_file_short][var_key]["Content"].items():
            obj_interval = container["Object"]
            obj_interval.set_visible(state)

        self.var_canvas_qpl.draw()

    def fi_show_time_signal_diagram(self, var_type, var_file, var_lb_state=True):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            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]

        frm_00 = SE(
            parent=self.subwindow_fi_checkfile, row_id=0, column_id=14, n_rows=24, n_columns=54, fg=font_color_dark,
            bg=background_color_light).create_frame(
            relief=tk.SOLID)

        ## 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

        try:
            errorframe = self.container_helper[str_filetype][str_filename_short]["ERROR FRAME"]

            if errorframe != None:
                errorframe.destroy()
        except AttributeError:
            pass

        self.fig_specific = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_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=22, columnspan=54, sticky="nesw")
        self.toolbarFrame = tk.Frame(master=self.subwindow_fi_checkfile)
        self.toolbarFrame.grid(row=22, column=14, rowspan=2, columnspan=54, sticky="w")
        self.toolbar_specific = NavigationToolbar2Tk(self.canvas_specific, self.toolbarFrame)
        self.toolbar_specific.config(background=background_color_light)
        self.toolbar_specific._message_label.config(
            background=background_color_light, fg=font_color_dark, font="sans 12")
        self.toolbar_specific.winfo_children()[-2].config(background=background_color_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:
                if self.container_var[key_setting]["Display RAW"][str_filetype][str_filename_short][isotope].get() == 1:
                    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
                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
                    ln_raw[0].set_visible(False)

                if self.container_var["Spike Elimination"][str_filetype]["State"] == True:
                    if isotope in self.container_spikes[str_filename_short]:
                        if self.container_var[key_setting]["Display SMOOTHED"][str_filetype][str_filename_short][
                            isotope].get() == 1:
                            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
                        else:
                            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
                            ln_smoothed[0].set_visible(False)

        if self.pysills_mode in ["FI", "MI", "INCL"]:
            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", "INCL"]:
                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)

        str_ax_01 = self.language_dict["Experiment time"][self.var_language]
        str_ax_02 = self.language_dict["Signal intensity"][self.var_language]

        ax.set_xlabel(str_ax_01 + " $t$ (s)", labelpad=0.5, fontsize=8)
        ax.set_ylabel(str_ax_02 + " $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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            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

        try:
            errorframe = self.container_helper[var_type][var_file_short]["ERROR FRAME"]

            if errorframe == None:
                errorframe.destroy()
        except AttributeError:
            pass

        frm_00 = SE(
            parent=self.subwindow_fi_checkfile, row_id=0, column_id=14, n_rows=24, n_columns=54, fg=font_color_dark,
            bg=background_color_light).create_frame(
            relief=tk.SOLID)

        if self.helper_opt_ri.get() == "Select isotope":
            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]
                        self.container_var[var_type][var_file]["IS Data"]["IS"].set(var_key_isotope)
                    break
            else:
                if self.pysills_mode == "MA":
                    var_mat_is = self.container_var[var_type][var_file]["IS Data"]["IS"].get()
                    var_key_isotope = var_mat_is
                else:
                    var_mat_is = self.container_var[var_type][var_file]["Matrix Setup"]["IS"]["Name"].get()
                    var_incl_is = self.container_var[var_type][var_file]["IS Data"]["IS"].get()
                    var_key_isotope = var_incl_is
        else:
            var_key_isotope = self.helper_opt_ri.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=22, columnspan=54, sticky="nesw")
        self.toolbarFrame_specific_ratio = tk.Frame(master=self.subwindow_fi_checkfile)
        self.toolbarFrame_specific_ratio.grid(row=22, 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)

        str_key_isotope = self.language_dict["Select isotope"][self.var_language]

        if var_key_isotope != str_key_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))

            if isinstance(y_max, (int, float)) and not np.isnan(y_max):
                ax_ratio.set_ylim(bottom=10**(-5), top=1.5*y_max)
            else:
                ax_ratio.set_ylim(bottom=10**(-5), top=10**(8))

            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)

            str_ax_01 = self.language_dict["Experiment time"][self.var_language]
            str_ax_02 = self.language_dict["Intensity ratio"][self.var_language]

            ax_ratio.set_xlabel(str_ax_01 + " $t$ (s)", labelpad=0.5, fontsize=8)
            ax_ratio.set_ylabel(str_ax_02 + " $I$/$I_{IS}$ (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_file, var_type, filesetup=False):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        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

        try:
            errorframe = self.container_helper[var_type][var_file_short]["ERROR FRAME"]

            if errorframe == None:
                errorframe.destroy()
        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]

        if filesetup == False:
            parent = self.subwindow_ma_checkfile
            val_row_start = 0
            val_column_start = 14
            val_row_span = 34
            val_column_span = 54
            frm_n_rows = val_row_span
            hb_start_row = val_column_start + 2
            vb_start_column = val_column_span + 15
            vb_n_rows = val_column_start + 2
        else:
            parent = self.var_geometry[0]
            val_row_start = self.var_geometry[1]
            val_column_start = self.var_geometry[2]
            val_row_span = self.var_geometry[3]
            val_column_span = self.var_geometry[4]
            frm_n_rows = val_row_span + 1
            hb_start_row = val_row_span
            vb_start_column = val_column_span + 17
            vb_n_rows = val_row_span

        ## FRAMES
        frm_quick = SE(
            parent=parent, row_id=val_row_start, column_id=val_column_start, n_rows=frm_n_rows,
            n_columns=val_column_span, fg=font_color_dark, bg=background_color_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]
                    self.container_var[var_type][var_file]["IS Data"]["IS"].set(var_is)
                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 self.container_var["Spike Elimination"][var_type]["State"] == False:
            str_keyword = "RAW"
        else:
            str_keyword = "SMOOTHED"

        if len(list_categories) > 1 and stop_calculation == False:
            self.tv_results_quick = SE(
                parent=parent, row_id=val_row_start, column_id=val_column_start, n_rows=vb_n_rows,
                n_columns=val_column_span - 1, fg=font_color_dark, 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(parent, orient="vertical")
            scb_h = ttk.Scrollbar(parent, 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=val_row_start, column=vb_start_column, rowspan=vb_n_rows, columnspan=1,
                       sticky="ns")
            scb_h.grid(row=hb_start_row, column=val_column_start, rowspan=1, columnspan=val_column_span - 1,
                       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=str_keyword, var_file_short=var_file_short, mode="Specific")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_type, var_datatype=str_keyword, 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=str_keyword, var_file_short=file_std_short,
                            mode="Specific")

                    self.fi_get_intensity_corrected(
                        var_filetype="STD", var_datatype=str_keyword, var_file_short=None, var_focus="MAT",
                        mode="only STD")

                    self.get_intensity(
                        var_filetype=var_type, var_datatype=str_keyword, var_file_short=var_file_short, mode="Specific")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_type, var_datatype=str_keyword, var_file_short=var_file_short, var_focus="MAT",
                        mode="Specific")
                    self.fi_get_intensity_corrected(
                        var_filetype=var_type, var_datatype=str_keyword, var_file_short=var_file_short,
                        var_focus="INCL", mode="Specific")
                    self.fi_get_intensity_ratio(
                        var_filetype=var_type, var_datatype=str_keyword, 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=str_keyword, var_file_short=var_file_short, mode="Specific")
                    self.get_analytical_sensitivity_std(
                        var_datatype=str_keyword, 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=str_keyword, 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=str_keyword, var_file_short=var_file_short,
                    var_file_long=var_file)
                results_is = self.determine_possible_is(filetype="ALL", consider_matrix=True)

                IQ(dataframe=None, project_type=self.pysills_mode,
                   results_container=self.container_intensity_ratio[var_type][str_keyword]).get_intensity_ratio(
                    data_container=self.container_intensity_corrected[var_type][str_keyword], dict_is=results_is,
                    filename_short=var_file_short)
                self.fi_get_rsf(
                    var_filetype=var_type, var_datatype=str_keyword, 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=str_keyword, var_file_short=var_file_short,
                    var_file_long=var_file)
                # Normalized Sensitivity
                self.fi_get_normalized_sensitivity(
                    var_filetype=var_type, var_datatype=str_keyword, 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=str_keyword, var_file_short=var_file_short,
                    var_file_long=var_file, var_focus="MAT")
                self.get_lod(
                    var_filetype=var_type, var_datatype=str_keyword, 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=str_keyword, 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=str_keyword, 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=str_keyword, var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="INCL")
                    self.get_lod(
                        var_filetype=var_type, var_datatype=str_keyword, var_file_short=var_file_short,
                        var_file_long=var_file, var_focus="INCL")
                    self.fi_get_mixed_concentration_ratio(
                        var_datatype=str_keyword, var_file_short=var_file_short, var_file_long=var_file)
                    self.fi_get_mixing_ratio(
                        var_datatype=str_keyword, var_file_short=var_file_short, var_file_long=var_file)
                    self.fi_get_concentration_mixed(var_datatype=str_keyword, 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_lob_i = ["Limit of Blank MAT"]
                entries_lod_i = ["Limit of Detection MAT"]
                entries_loq_i = ["Limit of Quantification 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_lob_incl_i = ["Limit of Blank INCL"]
                    entries_lod_incl_i = ["Limit of Detection INCL"]
                    entries_loq_incl_i = ["Limit of Quantification INCL"]

                for isotope in list_considered_isotopes:
                    entries_empty.append("")
                    # Intensity Results
                    intensity_bg_i = self.container_intensity[var_type][str_keyword][var_file_short]["BG"][isotope]
                    intensity_mat_i = self.container_intensity_corrected[var_type][str_keyword][var_file_short]["MAT"][
                        isotope]
                    intensity_ratio_i = self.container_intensity_ratio[var_type][str_keyword][var_file_short]["MAT"][
                        isotope]

                    if var_type == "SMPL":
                        intensity_incl_i = self.container_intensity_corrected[var_type][str_keyword][var_file_short][
                            "INCL"][isotope]
                        intensity_mix_i = self.container_intensity_mix[var_type][str_keyword][var_file_short][isotope]
                        intensity_ratio_incl_i = self.container_intensity_ratio[var_type][str_keyword][var_file_short][
                            "INCL"][isotope]

                    # Sensitivity Results
                    analytical_sensitivity_i = self.container_analytical_sensitivity[var_type][str_keyword][
                        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][str_keyword][
                            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][str_keyword][
                        var_file_short]["MAT"][isotope]
                    rsf_i = self.container_rsf[var_type][str_keyword][var_file_short]["MAT"][isotope]

                    if var_type == "SMPL":
                        analytical_sensitivity_incl_i = self.container_analytical_sensitivity[var_type][str_keyword][
                            var_file_short]["INCL"][isotope]
                        normalized_sensitivity_incl_i = self.container_normalized_sensitivity[var_type][str_keyword][
                            var_file_short]["INCL"][isotope]

                    # Concentration Results
                    concentration_i = self.container_concentration[var_type][str_keyword][var_file_short]["MAT"][
                        isotope]

                    if isotope in self.container_concentration[var_type][str_keyword][var_file_short]["1 SIGMA MAT"]:
                        concentration_sigma_mat_i = self.container_concentration[var_type][str_keyword][var_file_short][
                            "1 SIGMA MAT"][isotope]
                    else:
                        concentration_sigma_mat_i = np.nan

                    concentration_ratio_i = self.container_concentration_ratio[var_type][str_keyword][var_file_short][
                        "MAT"][isotope]
                    lob_i = self.container_lob[var_type][str_keyword][var_file_short]["MAT"][isotope]
                    lod_i = self.container_lod[var_type][str_keyword][var_file_short]["MAT"][isotope]
                    loq_i = self.container_loq[var_type][str_keyword][var_file_short]["MAT"][isotope]

                    if var_type == "SMPL":
                        concentration_incl_i = self.container_concentration[var_type][str_keyword][var_file_short][
                            "INCL"][isotope]
                        concentration_ratio_incl_i = self.container_concentration_ratio[var_type][str_keyword][
                            var_file_short]["INCL"][isotope]
                        concentration_sigma_incl_i = self.container_concentration[var_type][str_keyword][
                            var_file_short]["1 SIGMA INCL"][isotope]
                        concentration_mix_i = self.container_mixed_concentration["SMPL"][str_keyword][var_file_short][
                            isotope]
                        concentration_sigma_mix_i = self.container_mixed_concentration_error["SMPL"][str_keyword][
                            var_file_short][isotope]
                        lob_incl_i = self.container_lob[var_type][str_keyword][var_file_short]["INCL"][isotope]
                        lod_incl_i = self.container_lod[var_type][str_keyword][var_file_short]["INCL"][isotope]
                        loq_incl_i = self.container_loq[var_type][str_keyword][var_file_short]["INCL"][isotope]
                        a_i = self.container_mixed_concentration_ratio[var_type][str_keyword][var_file_short][isotope]
                        x_i = self.container_mixing_ratio[var_type][str_keyword][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_lob_i.append(f"{lob_i:.{4}f}")
                        entries_lod_i.append(f"{lod_i:.{4}f}")
                        entries_loq_i.append(f"{loq_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_lob_incl_i.append(f"{lob_incl_i:.{4}f}")
                        entries_lod_incl_i.append(f"{lod_incl_i:.{4}f}")
                        entries_loq_incl_i.append(f"{loq_incl_i:.{4}f}")

                ## Filling treeview
                if var_type == "SMPL":
                    self.tv_results_quick.insert("", tk.END, values=entries_concentration_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_sigma_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_concentration_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_concentration_sigma_mat_i)

                if var_type == "SMPL":
                    self.tv_results_quick.insert("", tk.END, values=entries_lod_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_lob_incl_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_loq_incl_i)

                    self.tv_results_quick.insert("", tk.END, values=entries_lob_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_lod_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_loq_i)

                    self.tv_results_quick.insert("", tk.END, values=entries_a_i)
                    self.tv_results_quick.insert("", tk.END, values=entries_x_i)

                self.tv_results_quick.insert("", tk.END, values=entries_empty)

                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_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_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)

    def fi_show_all_lines(self, var_type, var_file_short, key="ALL"):
        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
        for isotope in file_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)
                if key == "ALL":
                    try:
                        self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][isotope][
                            "SMOOTHED"][0].set_visible(True)
                        self.container_var[key_setting]["Display SMOOTHED"][var_type][var_file_short][isotope].set(1)
                    except:
                        print(var_file_short, isotope, "- There are no smoothed line curves.")
            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)

        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, key="ALL"):
        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        file_isotopes = self.container_lists["Measured Isotopes"][var_file_short]
        for isotope in file_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)
                if key == "ALL":
                    try:
                        self.container_var[key_setting]["Time-Signal Lines"][var_type][var_file_short][isotope][
                            "SMOOTHED"][0].set_visible(False)
                        self.container_var[key_setting]["Display SMOOTHED"][var_type][var_file_short][isotope].set(0)
                    except:
                        print(var_file_short, isotope, "- There are no smoothed line curves.")
            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)

        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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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")

    def fi_change_matrix_compound(self, var_opt, var_file=None, state_default=False, matrix_only=False):
        if self.pysills_mode in ["FI", "INCL"]:
            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_concentration(self, variable, event):
        for filename_long in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Value"].set(round(float(variable.get()), 4))

    def change_matrix_only_tracer(self, var_opt):
        for filename_long in self.container_lists["SMPL"]["Long"]:
            self.container_var["SMPL"][filename_long]["Host Only Tracer"]["Name"].set(var_opt)

    def change_matrix_only_tracer2(self, var_opt, var_file, state_default):
        if self.pysills_mode in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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)
        self.helper_var_opt["Mass/Charge balance"]["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 in ["FI", "INCL"]:
            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"]:
                                        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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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 setup_mass_charge_balance(self, mass_balance=True):
        """ Setup window where the concentration of the internal standard can be calculated based on a mass or charge
        balance calculation.
        -------
        Parameters
        -------
        Returns
        -------
        """
        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        # Initial parameters and variables
        str_title = self.language_dict["Setup"][self.var_language]
        bool_mass_balance = mass_balance
        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Window settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Setup mass balance"][0] + 3
        n_columns = self.window_dimensions["Setup mass balance"][1] + 12

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_mass_charge_balance = tk.Toplevel(self.parent)
        if mass_balance == True:
            str_title_02 = self.language_dict["Mass balance"][self.var_language]
            self.subwindow_mass_charge_balance.title(str_title + " - " + str_title_02)
        else:
            str_title_02 = self.language_dict["Charge balance"][self.var_language]
            self.subwindow_mass_charge_balance.title(str_title + " - " + str_title_02)
        #self.subwindow_mass_charge_balance.title(str_title + " - " + "Mass/Charge balance")
        self.subwindow_mass_charge_balance.geometry(var_geometry)
        self.subwindow_mass_charge_balance.resizable(False, False)
        self.subwindow_mass_charge_balance["bg"] = background_color_dark

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

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

        n_1st_column = int(0.25*n_columns)
        n_settings_column = n_columns - n_1st_column

        n_2nd_column = n_columns - n_1st_column - n_settings_column
        n_1st_column_half = int(n_1st_column/2)
        n_1st_column_third = int(n_1st_column/3)
        n_2nd_column_third = int(n_2nd_column/3)
        start_settings_row = n_rows - 7
        start_3rd_column = n_1st_column + n_2nd_column
        var_geometry = [self.subwindow_mass_charge_balance, 0, start_settings_row, n_rows - 11, n_2nd_column]
        self.var_geometry = var_geometry

        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Frames
        frm_00 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 1, column_id=n_1st_column + 1,
            n_rows=5, n_columns=n_settings_column - 2, fg=font_color_dark, bg=background_color_elements).create_frame(
            relief=tk.FLAT)

        # Labels
        lbl_01 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=0, column_id=0, n_rows=1, n_columns=n_1st_column,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="Chloride selection", relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_02 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row, column_id=n_1st_column + 1,
            n_rows=1, n_columns=n_settings_column, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="Settings", relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_03 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 1, column_id=n_1st_column + 27,
            n_rows=1, n_columns=9, fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text="Define salinity (wt.%)", relief=tk.FLAT, fontsize=font_elements, anchor=tk.E)
        lbl_04 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=0, column_id=n_1st_column + 1, n_rows=1,
            n_columns=n_settings_column, fg=font_color_light, bg=background_color_dark).create_simple_label(
            text="Results", relief=tk.FLAT, fontsize=font_header, anchor=tk.W)
        lbl_05 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 1, column_id=n_1st_column + 1,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text="Define internal standard", relief=tk.FLAT, fontsize=font_elements, anchor=tk.W)

        # Buttons
        btn_01 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=1, column_id=0, n_rows=1,
            n_columns=n_1st_column, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text="Guess composition", bg_active=accent_color, fg_active=font_color_light,
            command=self.guess_salt_composition)
        btn_02 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=n_rows - 2, column_id=n_1st_column + 1,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text="Previous file", bg_active=accent_color, fg_active=font_color_light,
            command=lambda mode="previous": self.switch_to_another_file_mass_charge_balance(mode))
        btn_03 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=n_rows - 2, column_id=n_1st_column + 11,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text="Next file", bg_active=accent_color, fg_active=font_color_light,
            command=lambda mode="next": self.switch_to_another_file_mass_charge_balance(mode))

        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        btn_04 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=n_rows - 4, column_id=n_1st_column + 37,
            n_rows=2, n_columns=13, fg=font_color_accent, bg=accent_color).create_simple_button(
            text="Calculate / Update", bg_active=accent_color, fg_active=font_color_accent,
            command=lambda mass_balance=bool_mass_balance:
            self.calculate_mass_charge_balance_concentrations(mass_balance))
        btn_05 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=n_rows - 2, column_id=n_1st_column + 37,
            n_rows=1, n_columns=13, fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text="Fix quantification", bg_active=accent_color, fg_active=font_color_light,
            command=self.fix_mass_charge_balance_calculation)

        # Radiobuttons
        rb_01 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 2, column_id=n_1st_column + 1,
            n_rows=1, n_columns=20, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["Mass/Charge balance"]["File selection"], value_rb=0,
            color_bg=background_color_elements, fg=font_color_dark, text="Apply to all files", sticky="nesw",
            relief=tk.FLAT)
        rb_02 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 3, column_id=n_1st_column + 1,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["Mass/Charge balance"]["File selection"], value_rb=1,
            color_bg=background_color_elements, fg=font_color_dark, text="Apply only to assemblage", sticky="nesw",
            relief=tk.FLAT)
        rb_01 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 4, column_id=n_1st_column + 1,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_radiobutton(
            var_rb=self.helper_var_rb["Mass/Charge balance"]["File selection"], value_rb=2,
            color_bg=background_color_elements, fg=font_color_dark, text="Apply only to file", sticky="nesw",
            relief=tk.FLAT)

        # Option Menues
        list_assemblages = []
        list_files = self.container_lists["SMPL"]["Short"]
        for filename_long in self.container_lists["SMPL"]["Long"]:
            file_id = self.container_var["SMPL"][filename_long]["ID"].get()
            if file_id not in list_assemblages:
                list_assemblages.append(file_id)

        list_potential_isotopes = []
        for isotope in self.container_lists["Measured Isotopes"]["All"]:
            key_isotope = re.search(r"(\D+)(\d+)", isotope)
            element = key_isotope.group(1)
            if element in ["Na", "Cl"]:
                list_potential_isotopes.append(isotope)

        opt_assemblage = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 3, column_id=n_1st_column + 11,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_var_opt["Mass/Charge balance"]["Assemblage"], option_list=list_assemblages,
            text_set=self.helper_var_opt["Mass/Charge balance"]["Assemblage"].get(), fg_active=font_color_light,
            bg_active=accent_color)
        opt_file = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 4, column_id=n_1st_column + 11,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_var_opt["Mass/Charge balance"]["File"], option_list=list_files,
            text_set=self.helper_var_opt["Mass/Charge balance"]["File"].get(), fg_active=font_color_light,
            bg_active=accent_color)
        self.opt_is_smpl_def = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 1, column_id=n_1st_column + 11,
            n_rows=1, n_columns=10, fg=font_color_dark, bg=background_color_elements).create_option_isotope(
            var_iso=self.helper_var_opt["Mass/Charge balance"]["IS"], option_list=list_potential_isotopes,
            text_set=self.helper_var_opt["Mass/Charge balance"]["IS"].get(), fg_active=font_color_light,
            bg_active=accent_color)

        # Entry fields
        if mass_balance == True:
            entr_01 = SE(
                parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 1, column_id=n_1st_column + 37,
                n_rows=1, n_columns=5, fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
                var=self.helper_var_entr["Mass/Charge balance"]["Salinity"],
                text_default=self.helper_var_entr["Mass/Charge balance"]["Salinity"].get(),
                command=lambda event, mass_balance=True:
                self.calculate_mass_charge_balance_concentrations_event(mass_balance, event))
        else:
            entr_01 = SE(
                parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 1, column_id=n_1st_column + 37,
                n_rows=1, n_columns=5, fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
                var=self.helper_var_entr["Mass/Charge balance"]["Salinity"],
                text_default=self.helper_var_entr["Mass/Charge balance"]["Salinity"].get(),
                command=lambda event, mass_balance=False:
                self.calculate_mass_charge_balance_concentrations_event(mass_balance, event))

        entr_02 = SE(
            parent=self.subwindow_mass_charge_balance, row_id=start_settings_row + 1, column_id=n_1st_column + 42,
            n_rows=1, n_columns=8, fg=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
            var=self.helper_var_entr["Mass/Charge balance"]["Concentration"],
            text_default=self.helper_var_entr["Mass/Charge balance"]["Concentration"].get())
        entr_02.configure(state="disabled")

        # Checkboxes
        # cb_01 = SE(
        #     parent=self.subwindow_mass_charge_balance, row_id=n_rows - 5, column_id=n_1st_column + 37,
        #     n_rows=1, n_columns=13, fg=font_color_dark, bg=background_color_elements).create_simple_checkbox(
        #     var_cb=self.helper_var_cb["Mass/Charge balance"]["Molality consideration"],
        #     text="Molality-based calculation", set_sticky="nesw", own_color=True, var_anchor=tk.W,
        #     command=lambda variable=self.helper_var_cb["Mass/Charge balance"]["Molality consideration"]:
        #     self.change_state_for_molality_consideration(variable))

        # Listboxes
        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_chlorides = SE(
            parent=self.subwindow_mass_charge_balance, row_id=2, column_id=0, n_rows=n_rows - 2, n_columns=n_1st_column,
            fg=font_color_dark, bg=background_color_light).create_frame()
        vsb_chlorides = ttk.Scrollbar(frm_chlorides, orient="vertical")
        text_chlorides = tk.Text(
            master=frm_chlorides, width=30, height=25, yscrollcommand=vsb_chlorides.set, bg=background_color_light,
            padx=10, pady=10)
        vsb_chlorides.config(command=text_chlorides.yview)
        vsb_chlorides.pack(side="right", fill="y")
        text_chlorides.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["fi_setting"]["Salt Correction"]["Chlorides"]:
                self.container_var["fi_setting"]["Salt Correction"]["Chlorides"][salt] = {
                    "State": tk.IntVar(), "Weight": tk.StringVar()}
                self.container_var["fi_setting"]["Salt Correction"]["Chlorides"][salt]["State"].set(0)
                self.container_var["fi_setting"]["Salt Correction"]["Chlorides"][salt]["Weight"].set("1.0")

            cb_i = tk.Checkbutton(
                master=frm_chlorides, text=salt + "\t", fg=font_color_dark, bg=background_color_light,
                variable=self.container_var["fi_setting"]["Salt Correction"]["Chlorides"][salt]["State"],
                command=self.fi_check_elements_checkbutton)
            text_chlorides.window_create("end", window=cb_i)
            text_chlorides.insert("end", "\t")

            entr_i = tk.Entry(
                frm_chlorides, textvariable=self.container_var["fi_setting"]["Salt Correction"]["Chlorides"][salt][
                    "Weight"], width=5, highlightthickness=0, bg=self.bg_colors["White"], fg=font_color_dark)
            text_chlorides.window_create("insert", window=entr_i)
            text_chlorides.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_chlorides, text=text + "\t", bg=background_color_light, fg=font_color_dark)
            text_chlorides.window_create("end", window=lbl_i)
            text_chlorides.insert("end", "\t")

            lbl2_i = tk.Label(frm_chlorides, text=magic_factor, bg=background_color_light, fg=font_color_dark)
            text_chlorides.window_create("end", window=lbl2_i)
            text_chlorides.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")

        text_chlorides.configure(state="disabled")

        # Treeviews
        self.tv_mass_charge_balance = SE(
            parent=self.subwindow_mass_charge_balance, row_id=1, column_id=n_1st_column + 1,
            n_rows=start_settings_row - 1, n_columns=n_settings_column - 2, fg=font_color_dark,
            bg=self.bg_colors["White"]).create_treeview(
            n_categories=7,
            text_n=["Filename", "Assemblage", "Salinity (wt.%)", "Internal standard", "Concentration (ppm)",
                    "Cation/Cl", "Considered chlorides"],
            width_n=["125", "100", "100", "125", "150", "100", "325"], individual=True)

        style = ttk.Style()
        style.configure("Treeview", font=font_table)
        style.configure("Treeview.Heading", font=font_elements)
        # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # Initialization
        self.helper_tv_entries = {}
        for index, filename_short in enumerate(list_files):
            filename_long = self.container_lists["SMPL"]["Long"][index]
            file_id = self.container_var["SMPL"][filename_long]["ID"].get()
            file_is = self.container_var["SMPL"][filename_long]["IS Data"]["IS"].get()
            if filename_short in self.helper_lists["Salinity"]:
                file_salinity = self.helper_lists["Salinity"][filename_short]
            else:
                file_salinity = "0.0"

            file_concentration_is = self.container_var["SMPL"][filename_long]["IS Data"]["Concentration"].get()
            if filename_short in self.helper_lists["Considered chlorides"]:
                list_file_chlorides = self.helper_lists["Considered chlorides"][filename_short]
                str_chlorides = "NaCl"
                for chloride in list_file_chlorides:
                    if chloride != "NaCl":
                        str_chlorides += ", " + chloride
            else:
                str_chlorides = "---"

            entries = [filename_short, file_id, file_salinity, file_is, file_concentration_is, "---", str_chlorides]
            row_file = self.tv_mass_charge_balance.insert("", tk.END, values=entries)
            self.helper_tv_entries[filename_short] = row_file

            if filename_short not in self.helper_salt_composition:
                self.helper_salt_composition[filename_short] = tk.StringVar()
                self.helper_salt_composition[filename_short].set("unknown composition")
            if filename_short not in self.charge_balance_check:
                self.charge_balance_check[filename_short] = tk.StringVar()
                self.charge_balance_check[filename_short].set("1.0")

    def change_state_for_molality_consideration(self, variable):
        if variable.get() == 0:
            self.molality_based_quantification.set(False)
        else:
            self.molality_based_quantification.set(True)

    def switch_to_another_file_mass_charge_balance(self, mode="next"):
        current_file = self.helper_var_opt["Mass/Charge balance"]["File"].get()
        bool_select_file = False
        if current_file == "Select file":
            current_file = self.container_lists["SMPL"]["Short"][0]
            index_new = 0
            bool_select_file = True

        if bool_select_file == False:
            index_current = self.container_lists["SMPL"]["Short"].index(current_file)
            n_files = len(self.container_lists["SMPL"]["Short"])
            if mode == "next":
                if index_current < n_files - 1:
                    index_new = index_current + 1
                else:
                    index_new = 0
            else:
                if index_current > 0:
                    index_new = index_current - 1
                else:
                    index_new = n_files - 1

        new_file = self.container_lists["SMPL"]["Short"][index_new]
        self.helper_var_opt["Mass/Charge balance"]["File"].set(new_file)
        self.helper_var_rb["Mass/Charge balance"]["File selection"].set(2)

    def calculate_mass_charge_balance_concentrations_event(self, mass_balance, event):
        var_salinity = self.helper_var_entr["Mass/Charge balance"]["Salinity"]
        val_salinity = float(var_salinity.get())
        if val_salinity < 0:
            var_salinity.set(0.0)
        elif val_salinity > 100:
            var_salinity.set(100.0)

        if self.helper_var_rb["Mass/Charge balance"]["File selection"].get() == 0:
            str_mode = "default"

            if mass_balance == True:
                self.calculate_mass_balance(var_entr=var_salinity, mode=str_mode, var_file=None)
            else:
                self.calculate_charge_balance(var_entr=var_salinity, mode=str_mode, var_file=None)

            list_values = []
            for index, str_filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
                str_filename_long = self.container_lists["SMPL"]["Long"][index]
                file_id = self.container_var["SMPL"][str_filename_long]["ID"].get()
                row_file = self.helper_tv_entries[str_filename_short]
                str_salinity = var_salinity.get()
                self.helper_lists["Salinity"][str_filename_short] = str_salinity
                file_is = self.container_var["SMPL"][str_filename_long]["IS Data"]["IS"].get()
                str_concentration = self.container_var["SMPL"][str_filename_long]["IS Data"]["Concentration"].get()
                list_values.append(float(str_concentration))
                str_cation_anion_ratio = self.charge_balance_check[str_filename_short].get()
                str_salts = "NaCl"
                self.helper_lists["Considered chlorides"][str_filename_short] = [str_salts]
                for salt in self.container_lists["Selected Salts"]:
                    if salt != "NaCl":
                        str_salts += ", " + salt
                        self.helper_lists["Considered chlorides"][str_filename_short].append(salt)
                entries = [str_filename_short, file_id, str_salinity, file_is, str_concentration,
                           str_cation_anion_ratio, str_salts]
                self.tv_mass_charge_balance.item(row_file, values=entries)
            self.helper_var_entr["Mass/Charge balance"]["Concentration"].set(round(np.mean(list_values), 4))
        elif self.helper_var_rb["Mass/Charge balance"]["File selection"].get() == 1:
            str_mode = "specific"
            str_assemblage = self.helper_var_opt["Mass/Charge balance"]["Assemblage"].get()
            list_values = []
            for str_filename_long in self.container_lists["SMPL"]["Long"]:
                file_id = self.container_var["SMPL"][str_filename_long]["ID"].get()
                if file_id == str_assemblage:
                    index_file = self.container_lists["SMPL"]["Long"].index(str_filename_long)
                    str_filename_short = self.container_lists["SMPL"]["Short"][index_file]
                    if mass_balance == True:
                        self.calculate_mass_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)
                    else:
                        self.calculate_charge_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)

                    row_file = self.helper_tv_entries[str_filename_short]
                    str_salinity = var_salinity.get()
                    self.helper_lists["Salinity"][str_filename_short] = str_salinity
                    file_is = self.container_var["SMPL"][str_filename_long]["IS Data"]["IS"].get()
                    str_concentration = self.container_var["SMPL"][str_filename_long]["IS Data"]["Concentration"].get()
                    list_values.append(float(str_concentration))
                    str_cation_anion_ratio = self.charge_balance_check[str_filename_short].get()
                    str_salts = "NaCl"
                    self.helper_lists["Considered chlorides"][str_filename_short] = [str_salts]
                    for salt in self.container_lists["Selected Salts"]:
                        if salt != "NaCl":
                            str_salts += ", " + salt
                            self.helper_lists["Considered chlorides"][str_filename_short].append(salt)
                    entries = [str_filename_short, file_id, str_salinity, file_is, str_concentration,
                               str_cation_anion_ratio, str_salts]
                    self.tv_mass_charge_balance.item(row_file, values=entries)
            self.helper_var_entr["Mass/Charge balance"]["Concentration"].set(round(np.mean(list_values), 4))
        elif self.helper_var_rb["Mass/Charge balance"]["File selection"].get() == 2:
            str_mode = "specific"
            str_filename_short = self.helper_var_opt["Mass/Charge balance"]["File"].get()
            index_file = self.container_lists["SMPL"]["Short"].index(str_filename_short)
            str_filename_long = self.container_lists["SMPL"]["Long"][index_file]
            file_id = self.container_var["SMPL"][str_filename_long]["ID"].get()

            if mass_balance == True:
                self.calculate_mass_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)
            else:
                self.calculate_charge_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)

            row_file = self.helper_tv_entries[str_filename_short]
            str_salinity = var_salinity.get()
            self.helper_lists["Salinity"][str_filename_short] = str_salinity
            file_is = self.container_var["SMPL"][str_filename_long]["IS Data"]["IS"].get()
            str_concentration = self.container_var["SMPL"][str_filename_long]["IS Data"]["Concentration"].get()
            str_cation_anion_ratio = self.charge_balance_check[str_filename_short].get()
            str_salts = "NaCl"
            self.helper_lists["Considered chlorides"][str_filename_short] = [str_salts]
            for salt in self.container_lists["Selected Salts"]:
                if salt != "NaCl":
                    str_salts += ", " + salt
                    self.helper_lists["Considered chlorides"][str_filename_short].append(salt)
            entries = [str_filename_short, file_id, str_salinity, file_is, str_concentration, str_cation_anion_ratio,
                       str_salts]
            self.tv_mass_charge_balance.item(row_file, values=entries)
            self.helper_var_entr["Mass/Charge balance"]["Concentration"].set(round(float(str_concentration), 4))

    def calculate_mass_charge_balance_concentrations(self, mass_balance=True):
        var_salinity = self.helper_var_entr["Mass/Charge balance"]["Salinity"]
        val_salinity = float(var_salinity.get())
        if val_salinity < 0:
            var_salinity.set(0.0)
        elif val_salinity > 100:
            var_salinity.set(100.0)

        if self.helper_var_rb["Mass/Charge balance"]["File selection"].get() == 0:
            str_mode = "default"

            if mass_balance == True:
                self.calculate_mass_balance(var_entr=var_salinity, mode=str_mode, var_file=None)
            else:
                self.calculate_charge_balance(var_entr=var_salinity, mode=str_mode, var_file=None)

            list_values = []
            for index, str_filename_short in enumerate(self.container_lists["SMPL"]["Short"]):
                str_filename_long = self.container_lists["SMPL"]["Long"][index]
                file_id = self.container_var["SMPL"][str_filename_long]["ID"].get()
                row_file = self.helper_tv_entries[str_filename_short]
                str_salinity = var_salinity.get()
                self.helper_lists["Salinity"][str_filename_short] = str_salinity
                file_is = self.container_var["SMPL"][str_filename_long]["IS Data"]["IS"].get()
                str_concentration = self.container_var["SMPL"][str_filename_long]["IS Data"]["Concentration"].get()
                list_values.append(float(str_concentration))
                str_cation_anion_ratio = self.charge_balance_check[str_filename_short].get()
                str_salts = "NaCl"
                self.helper_lists["Considered chlorides"][str_filename_short] = [str_salts]
                for salt in self.container_lists["Selected Salts"]:
                    if salt != "NaCl":
                        str_salts += ", " + salt
                        self.helper_lists["Considered chlorides"][str_filename_short].append(salt)
                entries = [str_filename_short, file_id, str_salinity, file_is, str_concentration,
                           str_cation_anion_ratio, str_salts]
                self.tv_mass_charge_balance.item(row_file, values=entries)
            self.helper_var_entr["Mass/Charge balance"]["Concentration"].set(round(np.mean(list_values), 4))
        elif self.helper_var_rb["Mass/Charge balance"]["File selection"].get() == 1:
            str_mode = "specific"
            str_assemblage = self.helper_var_opt["Mass/Charge balance"]["Assemblage"].get()
            list_values = []
            for str_filename_long in self.container_lists["SMPL"]["Long"]:
                file_id = self.container_var["SMPL"][str_filename_long]["ID"].get()
                if file_id == str_assemblage:
                    index_file = self.container_lists["SMPL"]["Long"].index(str_filename_long)
                    str_filename_short = self.container_lists["SMPL"]["Short"][index_file]
                    if mass_balance == True:
                        self.calculate_mass_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)
                    else:
                        self.calculate_charge_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)

                    row_file = self.helper_tv_entries[str_filename_short]
                    str_salinity = var_salinity.get()
                    self.helper_lists["Salinity"][str_filename_short] = str_salinity
                    file_is = self.container_var["SMPL"][str_filename_long]["IS Data"]["IS"].get()
                    str_concentration = self.container_var["SMPL"][str_filename_long]["IS Data"]["Concentration"].get()
                    list_values.append(float(str_concentration))
                    str_cation_anion_ratio = self.charge_balance_check[str_filename_short].get()
                    str_salts = "NaCl"
                    self.helper_lists["Considered chlorides"][str_filename_short] = [str_salts]
                    for salt in self.container_lists["Selected Salts"]:
                        if salt != "NaCl":
                            str_salts += ", " + salt
                            self.helper_lists["Considered chlorides"][str_filename_short].append(salt)
                    entries = [str_filename_short, file_id, str_salinity, file_is, str_concentration,
                               str_cation_anion_ratio, str_salts]
                    self.tv_mass_charge_balance.item(row_file, values=entries)
            self.helper_var_entr["Mass/Charge balance"]["Concentration"].set(round(np.mean(list_values), 4))
        elif self.helper_var_rb["Mass/Charge balance"]["File selection"].get() == 2:
            str_mode = "specific"
            str_filename_short = self.helper_var_opt["Mass/Charge balance"]["File"].get()
            index_file = self.container_lists["SMPL"]["Short"].index(str_filename_short)
            str_filename_long = self.container_lists["SMPL"]["Long"][index_file]
            file_id = self.container_var["SMPL"][str_filename_long]["ID"].get()

            if mass_balance == True:
                self.calculate_mass_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)
            else:
                self.calculate_charge_balance(var_entr=var_salinity, mode=str_mode, var_file=str_filename_long)

            row_file = self.helper_tv_entries[str_filename_short]
            str_salinity = var_salinity.get()
            self.helper_lists["Salinity"][str_filename_short] = str_salinity
            file_is = self.container_var["SMPL"][str_filename_long]["IS Data"]["IS"].get()
            str_concentration = self.container_var["SMPL"][str_filename_long]["IS Data"]["Concentration"].get()
            str_cation_anion_ratio = self.charge_balance_check[str_filename_short].get()
            str_salts = "NaCl"
            self.helper_lists["Considered chlorides"][str_filename_short] = [str_salts]
            for salt in self.container_lists["Selected Salts"]:
                if salt != "NaCl":
                    str_salts += ", " + salt
                    self.helper_lists["Considered chlorides"][str_filename_short].append(salt)
            entries = [str_filename_short, file_id, str_salinity, file_is, str_concentration, str_cation_anion_ratio,
                       str_salts]
            self.tv_mass_charge_balance.item(row_file, values=entries)
            self.helper_var_entr["Mass/Charge balance"]["Concentration"].set(round(float(str_concentration), 4))

    def calculate_mass_balance(self, var_entr, mode, var_file):
        if self.pysills_mode in ["FI", "INCL"]:
            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:
            if mode != "recalculate":
                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)
            else:
                amount_fluid = (100 - 5)/100
                amount_nacl_equiv = 5/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 in ["default", "recalculate"]:
                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 mode == "recalculate":
                        amount_fluid = (100 - float(self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                                                        file_smpl_short].get()))/100
                        amount_nacl_equiv = float(self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                                                      file_smpl_short].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["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)

                        if mode != "recalculate":
                            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 and define all necessary calculation intervals before you start "
                  "any calculation. Thank you very much!")
            self.parent.bell()

    def calculate_charge_balance(self, var_entr, mode, var_file):
        if self.pysills_mode in ["FI", "INCL"]:
            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 and define all necessary calculation intervals before you start "
                  "any calculation. Thank you very much!")
            self.parent.bell()

    def fi_calculate_chargebalance(self, var_entr, mode, var_file, event):
        if self.pysills_mode in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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:
            if mode != "recalculate":
                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)
            else:
                amount_fluid = (100 - 5)/100
                amount_nacl_equiv = 5/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 in ["default", "recalculate"]:
                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 mode == "recalculate":
                        amount_fluid = (100 - float(self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                                                        file_smpl_short].get()))/100
                        amount_nacl_equiv = float(self.container_var[key_setting]["Salt Correction"]["Salinity SMPL"][
                                                      file_smpl_short].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["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)

                        if mode != "recalculate":
                            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"

        str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Setup PyPitzer"][0]
        n_columns = self.window_dimensions["Setup PyPitzer"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        subwindow_fi_inclusion_pypitzer = tk.Toplevel(self.parent)
        subwindow_fi_inclusion_pypitzer.title(str_title_01 + " - PyPitzer")
        subwindow_fi_inclusion_pypitzer.geometry(var_geometry)
        subwindow_fi_inclusion_pypitzer.resizable(False, False)
        subwindow_fi_inclusion_pypitzer["bg"] = background_color_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

        ## LABELS
        str_lbl_01 = self.language_dict["Composition"][self.var_language]
        str_lbl_02 = self.language_dict["Cations"][self.var_language]
        str_lbl_03 = self.language_dict["Anions"][self.var_language]
        str_lbl_04 = self.language_dict["Default settings"][self.var_language]
        str_lbl_05 = self.language_dict["Internal standard"][self.var_language]
        str_lbl_06 = self.language_dict["Melting temperature of the last solid"][self.var_language]
        str_lbl_07 = self.language_dict["Last solid"][self.var_language]
        str_lbl_08 = self.language_dict["Melting temperature"][self.var_language]

        lbl_00a = SE(
            parent=subwindow_fi_inclusion_pypitzer, row_id=start_row, column_id=start_column, n_rows=1, n_columns=7,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_02, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_03, 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_06 + "(°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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_07, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_08 + "(°C)", 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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, 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=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize="sans 10 bold")

        ## BUTTONS
        str_btn_01 = self.language_dict["Import data"][self.var_language]
        str_btn_02 = self.language_dict["Run"][self.var_language]

        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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_btn_01, bg_active=accent_color, fg_active=font_color_light)
        btn_00c.configure(state="disabled")

        if self.var_os == "darwin":
            font_color_accent = font_color_dark
        else:
            font_color_accent = font_color_light

        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=font_color_accent, bg=accent_color).create_simple_button(
            text=str_btn_02, bg_active=accent_color, fg_active=font_color_accent,
            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"]

        str_opt_01 = self.language_dict["Select last solid"][self.var_language]
        self.container_var[key_setting]["Last solid"].set(str_opt_01)

        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=font_color_dark, bg=background_color_elements).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=font_color_light,
            bg_active=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=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=accent_color)
        opt_last_solid_default.config(
            bg=background_color_elements, fg=font_color_dark,
            activeforeground=font_color_light,
            activebackground=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=font_color_dark, bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements,
            activeforeground=font_color_light,
            activebackground=accent_color)
        opt_is_default.config(
            bg=background_color_elements, fg=font_color_dark,
            activeforeground=font_color_light,
            activebackground=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=font_color_dark, 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=font_color_dark, 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=background_color_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=font_color_dark,
                        bg=background_color_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=font_color_dark, 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=background_color_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=font_color_dark,
                    bg=background_color_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=font_color_dark, 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=background_color_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"]) and element_i != "S":
                                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=font_color_dark,
                        bg=background_color_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=font_color_dark, 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=background_color_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=background_color_light, fg=font_color_dark)
            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=font_color_dark, 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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_last_compound_i.config(
                bg=background_color_elements, fg=font_color_dark,
                activeforeground=font_color_light, activebackground=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=font_color_dark, 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=background_color_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=background_color_light, fg=font_color_dark)
            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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light, activebackground=accent_color)
            opt_is.config(
                bg=background_color_elements, fg=font_color_dark,
                activeforeground=font_color_light, activebackground=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=font_color_dark, 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)

                if var_datatype not in self.container_var["SMPL"][file_smpl_long]["IS Data"]:
                    self.container_var["SMPL"][file_smpl_long]["IS Data"][var_datatype] = {
                        "Concentration": tk.StringVar(), "IS": tk.StringVar()}

                self.container_var["SMPL"][file_smpl_long]["IS Data"][var_datatype]["Concentration"].set(
                    val_concentration_incl_is)
                self.container_var["SMPL"][file_smpl_long]["IS Data"][var_datatype]["IS"].set(str_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_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"):
        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"

        if "IS" not in self.container_optionmenu["SMPL"]:
            self.container_optionmenu["SMPL"]["IS"] = {}

        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

        ## INITIALIZATION
        if mode == "mass balance":
            self.setup_mass_charge_balance(mass_balance=True)
        elif mode == "charge balance":
            self.setup_mass_charge_balance(mass_balance=False)

        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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
            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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        if self.pysills_mode in ["FI", "INCL"]:
            key_setting = "fi_setting"
            str_title_01 = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            key_setting = "mi_setting"
            str_title_01 = self.language_dict["Melt Inclusions"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Setup external calculation"][0]
        n_columns = self.window_dimensions["Setup external calculation"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        if self.bool_incl_is_custom:
            str_title_02 = self.language_dict["Custom data"][self.var_language]
            if self.pysills_mode in ["FI", "INCL"]:
                str_title = str_title_01 + " - " + str_title_02
            elif self.pysills_mode == "MI":
                str_title = str_title_01 + " - " + str_title_02
        else:
            str_title_02 = self.language_dict["External quantification support"][self.var_language]
            if self.pysills_mode in ["FI", "INCL"]:
                str_title = str_title_01 + " - " + str_title_02
            elif self.pysills_mode == "MI":
                str_title = str_title_01 + " - " + str_title_02

        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"] = background_color_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_02 = self.language_dict["Import data"][self.var_language]

        ## LABELS
        if self.str_incl_is_custom_external == "External":
            str_lbl_01 = self.language_dict["LA-ICP-MS data export"][self.var_language]
            str_lbl_02 = self.language_dict["Import external data"][self.var_language]

            lbl_01 = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row, column_id=start_column, n_rows=1, n_columns=10,
                fg=font_color_light, bg=background_color_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=font_color_light, bg=background_color_dark).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")
        else:
            str_lbl_01 = self.language_dict["Default settings"][self.var_language]
            str_lbl_02 = self.language_dict["Import external data"][self.var_language]

            lbl_02 = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row, column_id=start_column + 22, n_rows=1,
                n_columns=10, fg=font_color_light, bg=background_color_dark).create_simple_label(
                text=str_lbl_01, 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=font_color_light, bg=background_color_dark).create_simple_label(
                text=str_lbl_02, relief=tk.FLAT, fontsize="sans 10 bold")

        if self.str_incl_is_custom_external == "External":
            ## CHECKBOXES
            str_cb_01 = self.language_dict["Intensity"][self.var_language]
            str_cb_02 = self.language_dict["Background"][self.var_language]
            str_cb_03 = self.language_dict["Matrix"][self.var_language]
            str_cb_04 = self.language_dict["Mixed signal"][self.var_language]
            str_cb_05 = self.language_dict["Inclusion"][self.var_language]
            str_cb_06 = self.language_dict["Analytical sensitivity"][self.var_language]
            str_cb_07 = self.language_dict["Concentration"][self.var_language]

            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=font_color_dark, n_rows=1, n_columns=10,
                bg=background_color_elements).create_simple_checkbox(
                var_cb=var_cb_01a, text=str_cb_01 + " (" + str_cb_02 + ")", set_sticky="nesw", own_color=True)
            cb_01b = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 2, column_id=start_column,
                fg=font_color_dark, n_rows=1, n_columns=10,
                bg=background_color_elements).create_simple_checkbox(
                var_cb=var_cb_01b, text=str_cb_01 + " (" + str_cb_03 + ")", set_sticky="nesw", own_color=True)
            cb_01c = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 3, column_id=start_column,
                fg=font_color_dark, n_rows=1, n_columns=10,
                bg=background_color_elements).create_simple_checkbox(
                var_cb=var_cb_01c, text=str_cb_01 + " (" + str_cb_04 + ")", set_sticky="nesw", own_color=True)
            cb_01d = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 4, column_id=start_column,
                fg=font_color_dark, n_rows=1, n_columns=10,
                bg=background_color_elements).create_simple_checkbox(
                var_cb=var_cb_01d, text=str_cb_01 + " (" + str_cb_05 + ")", set_sticky="nesw", own_color=True)
            cb_01e = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 5, column_id=start_column,
                fg=font_color_dark, n_rows=1, n_columns=10,
                bg=background_color_elements).create_simple_checkbox(
                var_cb=var_cb_01e, text=str_cb_06, set_sticky="nesw", own_color=True)
            cb_01f = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 6, column_id=start_column,
                fg=font_color_dark, n_rows=1, n_columns=10,
                bg=background_color_elements).create_simple_checkbox(
                var_cb=var_cb_01f, text=str_cb_07 + " (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
            str_btn_01 = self.language_dict["Export results"][self.var_language]

            btn_01h = SE(
                parent=subwindow_fi_inclusion_plugin, row_id=start_row + 7, column_id=start_column, n_rows=1,
                n_columns=10, fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark,
                bg=background_color_elements).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=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements, activeforeground=font_color_light,
                activebackground=accent_color)
            opt_05a.config(
                bg=background_color_elements, fg=font_color_dark, activeforeground=font_color_light,
                activebackground=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=font_color_dark, 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=font_color_dark, bg=background_color_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=font_color_dark, bg=background_color_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=background_color_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=background_color_light,
                             fg=font_color_dark)
            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=font_color_dark, bg=background_color_elements,
                                    activeforeground=font_color_light,
                                    activebackground=accent_color)
            opt_is_i.config(bg=background_color_elements, fg=font_color_dark,
                            activeforeground=font_color_light, activebackground=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=font_color_dark)
            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 in ["FI", "INCL"]:
            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 in ["FI", "INCL"]:
                    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 var_file_short in self.container_intervals:
                    for var_object in self.container_intervals[var_file_short]["Checker"][mode]:
                        var_object.set_visible(False)

                    self.canvas_time_signal_checker.draw()

        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"):
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_element = self.font_settings["Elements"] # "sans 10 bold"
        font_option = self.font_settings["Options"]

        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 in ["FI", "INCL"]:
            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=font_color_dark, bg=background_color_elements).create_simple_label(
                text=str_lbl_01, relief=var_relief, fontsize=font_element, anchor=tk.W)
            lbl_09d = SE(
                parent=var_parent, row_id=start_row + 4, column_id=0, n_rows=1, n_columns=7,
                fg=font_color_dark, bg=background_color_elements).create_simple_label(
                text=str_lbl_02, relief=var_relief, fontsize=font_element, anchor=tk.W)
            lbl_09e = SE(
                parent=var_parent, row_id=start_row + 5, column_id=0, n_rows=1, n_columns=7,
                fg=font_color_dark, bg=background_color_elements).create_simple_label(
                text=str_lbl_03, relief=var_relief, fontsize=font_element, anchor=tk.W)
            lbl_09f = SE(
                parent=var_parent, row_id=start_row + 6, column_id=0, n_rows=1, n_columns=7,
                fg=font_color_dark, bg=background_color_elements).create_simple_label(
                text=str_lbl_04, relief=var_relief, fontsize=font_element, 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=font_color_dark, 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=font_color_dark, bg=self.bg_colors["White"]).create_simple_entry(
                var=var_threshold, text_default=var_entr_09d_default)
            entr_09c.configure(font=font_option)
            entr_09d.configure(font=font_option)

            # Buttons
            btn_09e1 = SE(
                parent=var_parent, row_id=start_row + 5, column_id=7, n_rows=1, n_columns=5,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                command=lambda filetype="STD", algorithm="Grubbs", mode=self.pysills_mode, calculation=True:
                self.spike_elimination_all(filetype, algorithm, mode, calculation))
            self.btn_09e2 = SE(
                parent=var_parent, row_id=start_row + 5, column_id=12, n_rows=1, n_columns=5,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_01, bg_active=accent_color, fg_active=font_color_light,
                command=lambda filetype="SMPL", algorithm="Grubbs", mode=self.pysills_mode, calculation=True:
                self.spike_elimination_all(filetype, algorithm, mode, calculation))
            self.btn_09f2 = SE(
                parent=var_parent, row_id=start_row + 6, column_id=12, n_rows=1, n_columns=5,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_02, bg_active=accent_color, fg_active=font_color_light,
                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=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_btn_03, bg_active=accent_color, fg_active=font_color_light,
                command=self.create_spike_elimination_threshold_window)

            btn_09e1.configure(font=font_element)
            btn_09f1.configure(font=font_element)
            btn_09d.configure(font=font_element)

            if self.initial_spike_elimination_std == False:
                self.btn_09e2.configure(font=font_element, state="disabled")
            else:
                self.btn_09e2.configure(font=font_element, state="normal")

            if self.initial_spike_elimination_smpl == False:
                self.btn_09f2.configure(font=font_element, state="disabled")
            else:
                self.btn_09f2.configure(font=font_element, state="normal")

            # 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=background_color_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=background_color_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"):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        str_filetype = mode
        if self.pysills_mode == "MA":
            str_focus = self.language_dict["Mineral Analysis"][self.var_language]
        elif self.pysills_mode in ["FI", "INCL"]:
            str_focus = self.language_dict["Fluid Inclusions"][self.var_language]
        elif self.pysills_mode == "MI":
            str_focus = self.language_dict["Melt Inclusions"][self.var_language]

        str_title = self.language_dict["Outlier check"][self.var_language]

        ## Window Settings
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Custom spike check"][0]
        n_columns = self.window_dimensions["Custom spike check"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        self.subwindow_spike_check = tk.Toplevel(self.parent)
        if self.pysills_mode == "MA":
            self.subwindow_spike_check.title(str_focus + " - " + str_title)
        elif self.pysills_mode in ["FI", "INCL"]:
            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"] = background_color_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=font_color_dark,
            bg=background_color_light).create_frame(relief=tk.FLAT)

        ## LABELS
        str_lbl_01 = self.language_dict["File selection"][self.var_language]
        str_lbl_02 = self.language_dict["Before"][self.var_language]
        str_lbl_03 = self.language_dict["Next"][self.var_language]
        str_lbl_04 = self.language_dict["Isotope selection"][self.var_language]
        str_lbl_05 = self.language_dict["Outlier correction"][self.var_language]
        str_lbl_06 = self.language_dict["Original value"][self.var_language]
        str_lbl_07 = self.language_dict["Smoothed value"][self.var_language]
        str_lbl_08 = self.language_dict["Current value"][self.var_language]
        str_lbl_09 = self.language_dict["Outlier selection"][self.var_language]
        str_lbl_10 = self.language_dict["Number of outliers"][self.var_language]
        str_lbl_11 = self.language_dict["Value selection"][self.var_language]

        lbl_01 = SE(
            parent=self.subwindow_spike_check, row_id=start_row, column_id=start_column, n_rows=1, n_columns=12,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_01, 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=font_color_dark, bg=background_color_elements).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=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_04, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 11, column_id=start_column, n_rows=1, n_columns=12,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_05, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_03a1 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 12, column_id=start_column, n_rows=1, n_columns=6,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_06, relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_03a = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 12, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=font_color_light, bg=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 + 13, column_id=start_column, n_rows=1, n_columns=6,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_07, relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_03b = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 13, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=font_color_light, bg=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 + 14, column_id=start_column, n_rows=1, n_columns=6,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_08, relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_03c = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 14, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=font_color_light, bg=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 + 6, column_id=start_column, n_rows=1, n_columns=12,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_09, relief=tk.FLAT, fontsize="sans 10 bold")
        lbl_04a1 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 7, column_id=start_column, n_rows=1, n_columns=6,
            fg=font_color_dark, bg=background_color_elements).create_simple_label(
            text=str_lbl_10, relief=tk.FLAT, fontsize="sans 10 bold")
        self.lbl_04a2 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 7, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=font_color_light, bg=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 + 15, column_id=start_column, n_rows=1, n_columns=12,
            fg=font_color_light, bg=background_color_dark).create_simple_label(
            text=str_lbl_11, 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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_02, bg_active=accent_color, fg_active=font_color_light,
            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=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_03, bg_active=accent_color, fg_active=font_color_light,
            command=lambda mode="Next": self.change_file_spk(mode))

        str_opt_01 = self.language_dict["Select isotope"][self.var_language]
        self.var_opt_spk_iso = tk.StringVar()
        self.var_opt_spk_iso.set(str_opt_01)

        btn_03 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 5, column_id=start_column, n_rows=1, n_columns=6,
            fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_02, bg_active=accent_color, fg_active=font_color_light,
            command=lambda var_opt_iso=self.var_opt_spk_iso, mode="Before", list_isotopes=list_spk_isotopes:
            self.change_spk_isotope(var_opt_iso, mode, list_isotopes))
        btn_04 = SE(
            parent=self.subwindow_spike_check, row_id=start_row + 5, column_id=start_column + 6, n_rows=1, n_columns=6,
            fg=font_color_dark, bg=background_color_elements).create_simple_button(
            text=str_lbl_03, bg_active=accent_color, fg_active=font_color_light,
            command=lambda var_opt_iso=self.var_opt_spk_iso, mode="Next", list_isotopes=list_spk_isotopes:
            self.change_spk_isotope(var_opt_iso, mode, list_isotopes))

        if len(list_spk_isotopes) > 0:
            btn_05a1 = SE(
                parent=self.subwindow_spike_check, row_id=start_row + 16, column_id=start_column, n_rows=1, n_columns=6,
                fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_06, bg_active=accent_color, fg_active=font_color_light,
                command=lambda mode="RAW": self.replace_spike_value(mode))
            btn_05a2 = SE(
                parent=self.subwindow_spike_check, row_id=start_row + 16, column_id=start_column + 6, n_rows=1,
                n_columns=6, fg=font_color_dark, bg=background_color_elements).create_simple_button(
                text=str_lbl_07, bg_active=accent_color, fg_active=font_color_light,
                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=background_color_elements, foreground=font_color_dark,
                activebackground=accent_color, troughcolor=background_color_elements, highlightthickness=0,
                command=self.change_spk_id)
            self.scl_01.grid(row=start_row + 8, column=start_column, rowspan=3, columnspan=12, sticky="nesw")

        ## OPTION MENUS
        str_opt_02 = self.language_dict["Select file"][self.var_language]
        self.var_opt_spk_file = tk.StringVar()
        self.var_opt_spk_file.set(str_opt_01)

        if len(var_list_files) > 0:
            self.current_file_spk = var_list_files[0]
        else:
            self.current_file_spk = "No file"

        var_opt_spk_file_default = self.current_file_spk

        if len(var_list_files) > 0:
            self.opt_spke_file = SE(
                parent=self.subwindow_spike_check, row_id=start_row + 1, column_id=start_column, n_rows=1, n_columns=12,
                fg=font_color_dark, bg=background_color_elements).create_option_isotope(
                var_iso=self.var_opt_spk_file, option_list=var_list_files, text_set=var_opt_spk_file_default,
                fg_active=font_color_light, bg_active=accent_color,
                command=lambda mode="Option", var_opt=self.var_opt_spk_file: self.change_file_spk(mode, var_opt))
            self.opt_spke_file["menu"].config(
                fg=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            self.opt_spke_file.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0)

        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=font_color_dark, bg=background_color_elements).create_option_isotope(
                var_iso=self.var_opt_spk_iso, option_list=list_spk_isotopes, text_set=var_opt_is_default,
                fg_active=font_color_light, bg_active=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=font_color_dark, bg=background_color_elements,
                activeforeground=font_color_light,
                activebackground=accent_color)
            self.opt_02a.config(
                bg=background_color_elements, fg=font_color_dark, activebackground=accent_color,
                activeforeground=font_color_light, highlightthickness=0)

        ## INITIALIZATION
        self.possible_spk_isotopes_updated = None
        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 in ["FI", "INCL"]:
            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 = []
        helper_list_incl = []
        limits_incl = {}
        df_isotopes = self.container_lists["Measured Isotopes"][var_file]
        var_threshold = int(self.container_var[key_setting]["SE Threshold"].get())

        if var_file in self.container_lists["SMPL"]["Short"]:
            str_filetype = "SMPL"
            if self.pysills_mode in ["FI", "MI", "INCL"]:
                for id, dataset in self.container_helper["SMPL"][var_file]["INCL"]["Content"].items():
                    limits_incl[id] = dataset["Indices"]
        else:
            str_filetype = "STD"

        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
            if "Indices INCL" not in self.container_spikes[var_file][var_isotope]["Indices"] and len(limits_incl) > 0:
                self.container_spikes[var_file][var_isotope]["Indices INCL"] = []

            for id, limits in limits_incl.items():
                for index in updated_indices:
                    if index >= limits[0] and limits[1] >= index:
                        self.container_spikes[var_file][var_isotope]["Indices INCL"].append(index)
                        if var_isotope not in helper_list_incl:
                            helper_list_incl.append(var_isotope)

        if str_filetype == "SMPL":
            if self.container_var["check INCL"].get() == False:
                return helper_list
            elif self.container_var["check INCL"].get() == True:
                return helper_list_incl
        else:
            return helper_list

    def helper_spike_values(
            self, var_file_short, var_isotope, var_value_raw, var_value_smoothed, mode=None, var_index=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 "fi_setting" in self.container_var:
            bool_incl = self.container_var["fi_setting"]["Check Inclusion Exclusion"].get()
        elif "mi_setting" in self.container_var:
            bool_incl = self.container_var["fi_setting"]["Check Inclusion Exclusion"].get()

        # Original data
        self.container_spike_values[var_file_short][var_isotope]["RAW"].append(var_value_raw)
        #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)

        # Smoothed data
        self.container_spike_values[var_file_short][var_isotope]["SMOOTHED"].append(var_value_smoothed)
        if var_index == None:
            index_value = self.container_spikes[var_file_short][var_isotope]["Data SMOOTHED"].index(
                var_value_smoothed)
        else:
            index_value = var_index

        if var_file_short in self.container_lists["SMPL"]["Short"]:
            if bool_incl == True:
                if var_file_short in self.container_helper["SMPL"]:
                    for i, dataset in self.container_helper["SMPL"][var_file_short]["INCL"]["Content"].items():
                        interval_limits = dataset["Indices"]
                        if interval_limits[0] <= index_value <= interval_limits[1]:
                            self.container_spike_values[var_file_short][var_isotope]["Save"][
                                index_value] = var_value_raw
                            self.container_spike_values[var_file_short][var_isotope]["Current"].append(var_value_raw)
                        else:
                            self.container_spike_values[var_file_short][var_isotope]["Save"][
                                index_value] = var_value_smoothed
                            self.container_spike_values[var_file_short][var_isotope]["Current"].append(
                                var_value_smoothed)
            else:
                self.container_spike_values[var_file_short][var_isotope]["Save"][index_value] = var_value_smoothed
                self.container_spike_values[var_file_short][var_isotope]["Current"].append(var_value_smoothed)
        else:
            self.container_spike_values[var_file_short][var_isotope]["Save"][index_value] = var_value_smoothed
            self.container_spike_values[var_file_short][var_isotope]["Current"].append(var_value_smoothed)

        # 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_index == None:
        #         index_value = self.container_spikes[var_file_short][var_isotope]["Data SMOOTHED"].index(
        #             var_value_smoothed)
        #     else:
        #         index_value = var_index
        #     self.container_spike_values[var_file_short][var_isotope]["Save"][index_value] = var_value_smoothed
        #     self.container_spike_values[var_file_short][var_isotope]["Current"].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:
        #         print("a")
        #         self.container_spike_values[var_file_short][var_isotope]["Current"].append(var_value_smoothed)
        #     else:
        #         print("b")
        #         index_value = self.container_spikes[var_file_short][var_isotope]["Data SMOOTHED"].index(
        #             var_value_smoothed)
        #         self.container_spike_values[var_file_short][var_isotope]["Save"][index_value] = var_value_smoothed
        #         self.container_spike_values[var_file_short][var_isotope]["Current"].append(var_value_smoothed)
                # 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)

        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"]:
                            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"):
        self.var_calculation = False
        if self.var_calculation == False:
            for index, var_file_short in enumerate(self.container_lists[mode]["Short"]):
                file_long = self.container_lists[mode]["Long"][index]
                if var_file_short not in self.container_spike_values:
                    self.container_spike_values[var_file_short] = {}
                else:
                    self.container_spike_values[var_file_short].clear()
                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 not in self.container_spike_values[var_file_short]:
                                self.container_spike_values[var_file_short][var_isotope] = {
                                    "RAW": [], "SMOOTHED": [], "Current": [], "Save": {}}
                            else:
                                self.container_spike_values[var_file_short][var_isotope].clear()
                            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]
                                        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=None,
                                            var_index=var_index)
                            # print("File:", var_file_short)
                            # print("Isotope:", var_isotope)
                            # print("Spikes found at index:", self.container_spikes[var_file_short][var_isotope]["Indices"],
                            #       len(self.container_spikes[var_file_short][var_isotope]["Indices"]))
                            # if var_isotope in self.container_spike_values[var_file_short]:
                            #     print("Comparison 'Save':",
                            #           list(self.container_spike_values[var_file_short][var_isotope]["Save"].keys()),
                            #           len(list(self.container_spike_values[var_file_short][var_isotope]["Save"].keys(
                            #
                            #           ))))
                            #     print("Current:", self.container_spike_values[var_file_short][var_isotope]["Current"],
                            #           len(self.container_spike_values[var_file_short][var_isotope]["Current"]))
                            # else:
                            #     print("Comparison 'Save': [], 0")
        else:
            self.refresh_smoothed_data(filetype=mode)

    def refresh_smoothed_data(self, filetype):
        for index, file_short in enumerate(self.container_lists[filetype]["Short"]):
            file_long = self.container_lists[filetype]["Long"][index]
            self.container_spike_values[file_short] = {}
            if self.container_var[filetype][file_long]["Checkbox"].get() == 1:
                list_isotopes = self.container_lists["Measured Isotopes"][file_short]
                for isotope in list_isotopes:
                    self.container_spike_values[file_short][isotope] = {
                        "RAW": [], "SMOOTHED": [], "Current": [], "Save": {}}
                    list_indices = self.container_spikes[file_short][isotope]["Indices"]
                    values_raw = self.container_spikes[file_short][isotope]["Data RAW"]
                    values_smoothed = self.container_spikes[file_short][isotope]["Data SMOOTHED"]
                    if len(list_indices) > 0:
                        for j in list_indices:
                            value_raw = values_raw[j]
                            value_smoothed = values_smoothed[j]
                            self.container_spike_values[file_short][isotope]["RAW"].append(value_raw)
                            self.container_spike_values[file_short][isotope]["SMOOTHED"].append(value_smoothed)
                            self.container_spike_values[file_short][isotope]["Current"].append(value_smoothed)
                            self.container_spike_values[file_short][isotope]["Save"][j] = value_smoothed
                            self.container_spikes[file_short][isotope]["Data IMPROVED"][j] = value_smoothed
                    else:
                        pass

    def show_spike_data(self, mode=None):
        var_isotope = self.var_opt_spk_iso.get()
        var_file = self.current_file_spk

        if var_file in self.container_lists["SMPL"]["Short"]:
            str_filetype = "SMPL"
        else:
            str_filetype = "STD"

        if str_filetype == "SMPL":
            if self.container_var["check INCL"].get() == False:
                self.list_indices = self.container_spikes[var_file][var_isotope]["Indices"]
            elif self.container_var["check INCL"].get() == True:
                self.list_indices = self.container_spikes[var_file][var_isotope]["Indices INCL"]
        else:
            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)

        if len(self.list_indices) > 0:
            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, mode=None, list_isotopes=None):
        if self.possible_spk_isotopes_updated != None:
            list_isotopes = self.possible_spk_isotopes_updated

        if mode == None:
            var_isotope = var_opt_iso
            self.var_opt_spk_iso.set(var_isotope)
            self.current_isotope = var_isotope
        else:
            if mode == "Before":
                var_isotope = var_opt_iso.get()
                self.var_opt_spk_iso.set(var_isotope)
                isotope_id = list_isotopes.index(var_isotope)

                if isotope_id > 0:
                    isotope_id -= 1
                elif isotope_id == 0:
                    isotope_id = len(list_isotopes) - 1

                var_isotope = list_isotopes[isotope_id]
                self.var_opt_spk_iso.set(var_isotope)
                self.current_isotope = var_isotope
            elif mode == "Next":
                var_isotope = var_opt_iso.get()
                self.var_opt_spk_iso.set(var_isotope)
                isotope_id = list_isotopes.index(var_isotope)

                if isotope_id < len(list_isotopes) - 1:
                    isotope_id += 1
                elif isotope_id == len(list_isotopes) - 1:
                    isotope_id = 0

                var_isotope = list_isotopes[isotope_id]
                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, var_opt=None):
        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)
            self.var_opt_spk_file.set(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)
            self.var_opt_spk_file.set(self.current_file_spk)
        elif mode not in ["Next", "Before"]:
            var_opt = self.var_opt_spk_file.get()
            if self.current_file_spk in self.container_lists["STD"]["Short"]:
                var_filetype = "STD"
            else:
                var_filetype = "SMPL"

            var_opt_id = self.container_lists[var_filetype]["Short"].index(var_opt)
            self.current_file_id = var_opt_id
            self.current_file_spk = self.container_lists[var_filetype]["Short"][self.current_file_id]
            self.lbl_01a.configure(text=self.current_file_spk)
            self.var_opt_spk_file.set(self.current_file_spk)

        possible_spk_isotopes = self.check_spikes_isotope()
        self.possible_spk_isotopes_updated = possible_spk_isotopes

        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):
        # Colors
        font_color_dark = self.bg_colors["Dark Font"]
        font_color_light = self.bg_colors["Light Font"]
        background_color_dark = self.bg_colors["BG Window"]
        background_color_elements = self.bg_colors["Light"]
        background_color_light = self.bg_colors["Very Light"]
        accent_color = self.bg_colors["Accent"]  # self.accent_color
        font_header = self.font_settings["Header"]
        font_elements = self.font_settings["Elements"]
        font_option = self.font_settings["Options"]
        font_table = self.font_settings["Table"]

        color_original = "#3A615E"
        color_smoothed = "#E7A152"
        color_position = background_color_dark

        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

        if var_file in self.container_lists["STD"]["Short"]:
            var_filetype = "STD"
        else:
            var_filetype = "SMPL"

        var_isotope = self.current_isotope
        current_id = self.scl_01.get()

        if len(self.list_indices) > 1:
            var_id_real = self.list_indices[current_id - 1]
        else:
            var_id_real = self.list_indices[0]

        ## Diagram
        self.fig_spikes = Figure(figsize=(10, 5), tight_layout=True, facecolor=background_color_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=background_color_light)
        self.toolbar_spikes._message_label.config(
            background=background_color_light, fg=font_color_dark, font="sans 12")
        self.toolbar_spikes.winfo_children()[-2].config(background=background_color_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)

        str_lbl_01 = self.language_dict["Original data"][self.var_language]
        str_lbl_02 = self.language_dict["Smoothed data"][self.var_language]
        str_lbl_03 = self.language_dict["Current data"][self.var_language]
        str_lbl_04 = self.language_dict["Current outlier"][self.var_language]

        self.ax_spikes.scatter(
            data_x, data_y_raw, color=color_original, label=str_lbl_01)
        self.ax_spikes.plot(
            data_x, data_y_raw, color=color_original, linewidth=2, alpha=0.75)
        self.ax_spikes.scatter(data_x, data_y_smoothed, color=color_smoothed, label=str_lbl_02)
        self.ax_spikes.plot(
            data_x, data_y_smoothed, color=color_smoothed, linewidth=2, alpha=0.75)
        self.ax_spikes.plot(
            data_x, data_y_valid, color=self.accent_color, label=str_lbl_03, linewidth=2)
        self.ax_spikes.axvline(
            x=data_x[var_id_real], color=color_position, label=str_lbl_04, linewidth=2,
            linestyle="dotted")

        signal_key = "MAT"
        var_check_sig = self.container_helper[var_filetype][var_file][signal_key]["Content"]

        if len(var_check_sig) > 0:
            for var_id, var_content in self.container_helper[var_filetype][var_file][signal_key][
                "Content"].items():
                times_sig = var_content["Times"]
                var_color = self.colors_intervals[signal_key]
                if times_sig[0] != None and times_sig[1] != None:
                    box_mat = self.ax_spikes.axvspan(times_sig[0], times_sig[1], alpha=0.35, color=var_color)
                    var_content["Object"] = box_mat

        if self.pysills_mode != "MA":
            signal_key = "INCL"
            var_check_sig = self.container_helper[var_filetype][var_file][signal_key]["Content"]

            if len(var_check_sig) > 0:
                for var_id, var_content in self.container_helper[var_filetype][var_file][signal_key][
                    "Content"].items():
                    times_incl = var_content["Times"]
                    var_color = self.colors_intervals[signal_key]
                    if times_incl[0] != None and times_incl[1] != None:
                        box_incl = self.ax_spikes.axvspan(times_incl[0], times_incl[1], alpha=0.35, color=var_color)
                        var_content["Object"] = box_incl

        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)

        str_lbl_05 = self.language_dict["Experiment time"][self.var_language]
        str_lbl_06 = self.language_dict["Signal intensity"][self.var_language]

        self.ax_spikes.set_xlabel(str_lbl_05 + " $t$ (s)", labelpad=0.5, fontsize=8)
        self.ax_spikes.set_ylabel(str_lbl_06 + " $I$ (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.095, 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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Popup window error"][0]
        n_columns = self.window_dimensions["Popup window error"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)
 
        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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["BG Window"]
        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["BG Window"]).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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Popup window progress"][0]
        n_columns = self.window_dimensions["Popup window progress"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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["BG Window"]

        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["BG Window"]).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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Popup window progress datareduction"][0]
        n_columns = self.window_dimensions["Popup window progress datareduction"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        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["BG Window"]

        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["BG Window"]).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 create_starter_file(self):
        str_path_to_python = self.container_var["Python path"].get()
        str_path_to_pysills_folder = os.path.join(self.path_pysills_main, "pysills")
        str_path_to_pysills_app = self.container_var["PySILLS path"].get()
        str_path_to_pysills_icon = os.path.join(self.path_pysills_main, "pysills", "lib", "images", "PySILLS_Icon.png")

        if self.var_os == "linux":
            filename = os.path.join(str_path_to_pysills_folder, "pysills_app.desktop")
        elif self.var_os == "darwin":
            filename = os.path.join(str_path_to_pysills_folder, "pysills_app.sh")
        else:
            filename = os.path.join(str_path_to_pysills_folder, "pysills_app.bat")

        if os.path.exists(filename):
            os.remove(filename)

        with open(filename, "w") as file_content:
            if self.var_os == "linux":
                file_content.write("#!/usr/bin/python3" + "\n")
                file_content.write("[Desktop Entry]" + "\n")
                file_content.write("Name=PySILLS" + "\n")
                file_content.write("Version=" + str(self.str_version_number) + "\n")
                file_content.write("Exec=" + str(str_path_to_python) + " " + str(str_path_to_pysills_app) + "\n")
                file_content.write("Icon=" + str(str_path_to_pysills_icon) + "\n")
                file_content.write("Path=" + str(self.path_pysills_main) + "\n")
                file_content.write("Terminal=true" + "\n")
                file_content.write("Type=Application" + "\n")
                file_content.write("Categories=Utility;Application;")

            elif self.var_os == "darwin":
                file_content.write("#!/bin/bash" + "\n")
                file_content.write("echo Running Script" + "\n")
                file_content.write(str(str_path_to_python) + " " + str(str_path_to_pysills_app) + "\n")
                file_content.write("echo Script ended")
            else:
                file_content.write(str(str_path_to_python) + " " + str(str_path_to_pysills_app))

    def get_current_path_pysills_folder(self):
        str_path_to_pysills_app = os.path.join(self.path_pysills_main, "pysills", "pysills_app.py")
        self.container_var["PySILLS path"].set(str_path_to_pysills_app)

    def get_current_path_pysills_script(self):
        str_path_to_pysills_app = os.path.join(self.path_pysills_main, "pysills", "pysills_app.py")
        str_path_to_pysills_app = os.path.join(self.path_pysills_main, "pysills", "pysills_app.py")
        str_path_to_pysills_icon = os.path.join(self.path_pysills_main, "pysills", "lib", "images", "PySILLS_Icon.png")

        if self.var_os == "linux":
            filename = os.path.join(self.path_pysills_main, "pysills_app.desktop")
        elif self.var_os == "darwin":
            filename = os.path.join(self.path_pysills_main, "pysills_app.sh")
        else:
            filename = os.path.join(self.path_pysills_main, "pysills_app.bat")

        list_paths = sys.path
        for path in list_paths:
            if "site-packages" in path:
                key_path = path
                if self.var_os == "win32":
                    path_parts = key_path.split("\\")
                    raw_path = "C:\\"
                else:
                    path_parts = key_path.split("/")
                    raw_path = "/"

                str_python_name = "python"

                for part in path_parts:
                    if "python" in part:
                        str_python_name = part

                for part in path_parts:
                    if part in ["lib", "Lib"]:
                        break
                    else:
                        raw_path = os.path.join(raw_path, part)

                if self.var_os == "win32":
                    str_path_to_pysills_app = os.path.join(raw_path, "Scripts", "pysills.exe")
                elif self.var_os == "linux":
                    str_path_to_pysills_app = os.path.join("usr", "bin", str_python_name)
                else:
                    str_path_to_pysills_app = os.path.join(raw_path, "bin", "python")
                break

        self.container_var["PySILLS script"].set(str_path_to_pysills_app)

    def get_current_path_python(self):
        str_path_to_python = os.path.join(self.path_pysills_main, "pysills", "pysills_app.py")

        list_paths = sys.path
        for path in list_paths:
            if "site-packages" in path:
                key_path = path
                if self.var_os == "win32":
                    path_parts = key_path.split("\\")
                    raw_path = "C:\\"
                else:
                    path_parts = key_path.split("/")
                    raw_path = "/"

                str_python_name = "python"

                for part in path_parts:
                    if "python" in part:
                        str_python_name = part

                for part in path_parts:
                    if part in ["lib", "Lib"]:
                        break
                    else:
                        raw_path = os.path.join(raw_path, part)

                if self.var_os == "win32":
                    str_path_to_python = os.path.join(raw_path, "python.exe")
                elif self.var_os == "linux":
                    str_path_to_python = os.path.join("usr", "bin", str_python_name)
                else:
                    str_path_to_python = os.path.join(raw_path, "bin", "python")
                break

        self.container_var["Python path"].set(str_path_to_python)

    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
        row_min = self.row_height
        column_min = self.column_width
        n_rows = self.window_dimensions["Project manager"][0]
        n_columns = self.window_dimensions["Project manager"][1]

        window_width = int(n_columns*self.column_width)
        window_height = int(n_rows*self.row_height)

        var_geometry = str(window_width) + "x" + str(window_height) + "+" + str(0) + "+" + str(0)

        #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["BG Window"]

        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

        self.new_id = None

        ## 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["BG Window"]).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.update_table_manager(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 Manager": self.update_table_manager(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]
        var_btn_05 = self.language_dict["Up"][self.var_language]
        var_btn_06 = self.language_dict["Down"][self.var_language]

        btn_01 = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 1, column_id=var_column_start, 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_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 + 2, column_id=var_column_start, 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 + 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_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 + 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_04, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda filetype=type: self.rename_file_manager(filetype))
        btn_05 = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 1, column_id=2*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_05, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_filetype=type + " Manager", key="up": self.change_file_order(var_filetype, key))
        btn_06 = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 2, column_id=2*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_06, bg_active=self.accent_color, fg_active=self.bg_colors["Dark Font"],
            command=lambda var_filetype=type + " Manager", key="down": self.change_file_order(var_filetype, key))

        btn_01.configure(state="disabled")
        btn_02.configure(state="disabled")
        btn_03.configure(state="disabled")
        btn_04.configure(state="disabled")

        ## 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")
        rb_01a.configure(state="disabled")
        rb_01b.configure(state="disabled")

        ## TABLE
        self.tv_data = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 4, column_id=3*int_category_n + 1, n_rows=n_rows - 5,
            n_columns=n_columns - (3*int_category_n + 1) - 1, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_treeview(
            n_categories=2, text_n=["A", "B"], width_n=["100", "100"], individual=True)

        self.scb_v_manager = ttk.Scrollbar(self.subwindow_manager, orient="vertical")
        self.scb_h_manager = ttk.Scrollbar(self.subwindow_manager, orient="horizontal")
        self.tv_data.configure(xscrollcommand=self.scb_h_manager.set, yscrollcommand=self.scb_v_manager.set)
        self.scb_v_manager.config(command=self.tv_data.yview)
        self.scb_h_manager.config(command=self.tv_data.xview)
        self.scb_v_manager.grid(row=var_row_start + 4, column=n_columns - 1, rowspan=n_rows - 5, columnspan=1,
                                sticky="ns")
        self.scb_h_manager.grid(row=n_rows - 1, column=3*int_category_n + 1, rowspan=1,
                                columnspan=n_columns - (3*int_category_n + 1) - 1, sticky="ew")

        ## INITIALIZATION
        self.fill_lb_manager(type=type, init=True)

    def change_file_order(self, var_filetype, key):
        if var_filetype == "STD Manager":
            var_filetype = "STD"
            click_id = self.lb_std_manager.curselection()
        elif var_filetype == "SMPL Manager":
            var_filetype = "SMPL"
            click_id = self.lb_smpl_manager.curselection()

        if self.new_id == None:
            click_id = click_id[0]
        else:
            if len(click_id) > 0:
                click_id = click_id[0]
            else:
                click_id = self.new_id

        if key == "up":
            if click_id > 0:
                file_long = self.container_lists[var_filetype]["Long"].pop(click_id)
                file_short = self.container_lists[var_filetype]["Short"].pop(click_id)
                self.container_lists[var_filetype]["Long"].insert(click_id - 1, file_long)
                self.container_lists[var_filetype]["Short"].insert(click_id - 1, file_short)
                self.new_id = click_id - 1
        elif key == "down":
            if click_id < len(self.container_lists[var_filetype]["Long"]) - 1:
                file_long = self.container_lists[var_filetype]["Long"].pop(click_id)
                file_short = self.container_lists[var_filetype]["Short"].pop(click_id)
                self.container_lists[var_filetype]["Long"].insert(click_id + 1, file_long)
                self.container_lists[var_filetype]["Short"].insert(click_id + 1, file_short)
                self.new_id = click_id + 1

        # Update listboxes
        self.fill_lb_manager(type=var_filetype, init=True)

        if var_filetype == "STD":
            self.fill_lb_manager(type=var_filetype, init=True, var_lb=self.lb_std)
        elif var_filetype == "SMPL":
            self.fill_lb_manager(type=var_filetype, init=True, var_lb=self.lb_smpl)

        if var_filetype == "STD Manager":
            self.lb_std_manager.selection_clear(0, tk.END)
            self.lb_std_manager.selection_set(click_id)
            self.lb_std_manager.activate(click_id)
            self.lb_std_manager.see(click_id)
            self.lb_std_manager.focus_set()
        elif var_filetype == "SMPL Manager":
            self.lb_smpl_manager.selection_clear(0, tk.END)
            self.lb_smpl_manager.selection_set(self.new_id)
            self.lb_smpl_manager.activate(self.new_id)
            self.lb_smpl_manager.see(self.new_id)
            self.lb_smpl_manager.focus_set()

    def update_table_manager(self, var_filetype, event):
        n_rows = self.window_dimensions["Project manager"][0]
        n_columns = self.window_dimensions["Project manager"][1]
        var_row_start = 0
        var_column_start = 0
        var_header_n = 15
        int_category_n = 5

        if var_filetype == "STD Manager":
            click_id = self.lb_std_manager.curselection()
            var_filetype = "STD"
        elif var_filetype == "SMPL Manager":
            click_id = self.lb_smpl_manager.curselection()
            var_filetype = "SMPL"

        self.tv_data.grid_remove()
        self.scb_v_manager.grid_remove()
        self.scb_h_manager.grid_remove()

        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]
        df_data = self.container_measurements["Dataframe"][file_short]

        list_categories = ["Index", "Time"]
        list_categories.extend(file_isotopes)

        self.tv_data = SE(
            parent=self.subwindow_manager, row_id=var_row_start + 4, column_id=3*int_category_n + 1, n_rows=n_rows - 5,
            n_columns=n_columns - (3*int_category_n + 1) - 1, fg=self.bg_colors["Dark Font"],
            bg=self.bg_colors["Very Light"]).create_treeview(
            n_categories=len(list_categories), text_n=list_categories,
            width_n=np.full(len(list_categories), 100).tolist(), individual=True)

        self.scb_v_manager = ttk.Scrollbar(self.subwindow_manager, orient="vertical")
        self.scb_h_manager = ttk.Scrollbar(self.subwindow_manager, orient="horizontal")
        self.tv_data.configure(xscrollcommand=self.scb_h_manager.set, yscrollcommand=self.scb_v_manager.set)
        self.scb_v_manager.config(command=self.tv_data.yview)
        self.scb_h_manager.config(command=self.tv_data.xview)
        self.scb_v_manager.grid(row=var_row_start + 4, column=n_columns - 1, rowspan=n_rows - 5, columnspan=1,
                                sticky="ns")
        self.scb_h_manager.grid(row=n_rows - 1, column=3*int_category_n + 1, rowspan=1,
                                columnspan=n_columns - (3*int_category_n + 1) - 1, sticky="ew")

        for index in range(len(df_data.index)):
            entry_data = []
            entry_data.append(index)
            data_values = np.array((df_data.iloc[[index]].values)).tolist()[0]
            for index2, value in enumerate(data_values):
                if index2 == 0:
                    entry_data.append(round(value, 4))
                else:
                    entry_data.append(round(value, 2))
            
            self.tv_data.insert("", tk.END, values=entry_data)

    def fill_lb_manager(self, type, init=False, var_lb=None):
        if type == "STD" and var_lb == None:
            var_lb_manager = self.lb_std_manager
        elif type == "SMPL" and var_lb == None:
            var_lb_manager = self.lb_smpl_manager
        else:
            var_lb_manager = var_lb

        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_lob[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_lob[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
            self.container_lod[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_lod[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
            self.container_loq[var_filetype]["RAW"][var_file_short] = {"MAT": {}}
            self.container_loq[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}}
        else:
            self.container_lob[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_lob[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_lod[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_lod[var_filetype]["SMOOTHED"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_loq[var_filetype]["RAW"][var_file_short] = {"MAT": {}, "INCL": {}}
            self.container_loq[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_lob[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_lob[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            self.container_lod[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_lod[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None
            self.container_loq[var_filetype]["RAW"][var_file_short]["MAT"][isotope] = None
            self.container_loq[var_filetype]["SMOOTHED"][var_file_short]["MAT"][isotope] = None

            if mode != "MA":
                self.container_lob[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_lob[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
                self.container_lod[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_lod[var_filetype]["SMOOTHED"][var_file_short]["INCL"][isotope] = None
                self.container_loq[var_filetype]["RAW"][var_file_short]["INCL"][isotope] = None
                self.container_loq[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()