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

# In[3350]:


import tkinter as tk #The main library for GUI design in Python
from tkinter import ttk
from tkinter import filedialog, Text
import tkinter.font as font
import os #Allows the GUI to interact with the rest of the PC
import numpy as np # Offers more manipulative numeric data types
import pandas as pd # Offers CSV reading and data storage
import re
import matplotlib # Allows us to plot our data
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk) # Little Documentation
from matplotlib.figure import Figure
import subprocess # Gives the ability to use "command line" functions
from datetime import datetime # Allows us to get the current date and time


# In[3351]:


#Create a window with a canvas to work off of
root = tk.Tk()
#root.attributes('-fullscreen', True)
root.state("zoomed")

canvas = tk.Canvas(root, height = 600, width = 1024, bg = "black")
canvas.pack()

frame = tk.Frame(root, bg = "white")
frame.place(anchor = "c", relwidth = 0.95, relheight = 0.9, relx = 0.5, rely = 0.5)


# In[3352]:


# Create a figure for the plot to reside
fig = Figure(figsize = (6.4, 4.1), dpi = 100)

# Create a subplot to add data too
plot1 = fig.add_subplot(111)
plot1.set_xlabel("Raman Shift", fontsize = 10)
plot1.set_ylabel("Intensity (Counts)", fontsize = 10)
plot1.set_title("Spectrum", fontsize = 16)
plot1.set_xlim(left = 150, right = 4000)
plot1.set_ylim(bottom = 0, top = 8000)
plot1.plot()

# Put the plot in a tkinter canvas
plotframe = FigureCanvasTkAgg(fig, master = frame)

# Add a toolbar to control the plot
toolbar = NavigationToolbar2Tk(plotframe, frame)

# Dark set dataframe
dark_set = pd.DataFrame()
dark_counts_list = list()

# Create a global array to hold multiple test sets
test_sets_680 = []
test_sets_785 = []

# Create a global to hold our control samples
ctrl_680_h2o = pd.DataFrame()
ctrl_680_bio = pd.DataFrame()
ctrl_785_h2o = pd.DataFrame()
ctrl_785_bio = pd.DataFrame()

# Global lists to store the x's and y's for future use
# 680 h2o
h2o_680_cmi_shifted_list = []
h2o_680_dark_list = []
# 680 bio
bio_680_cmi_shifted_list = []
bio_680_dark_list = []
# 785 h2o
h2o_785_cmi_shifted_list = []
h2o_785_dark_list = []
# 785 bio
bio_785_cmi_shifted_list = []
bio_785_dark_list = []
# 680 test
test_waves_data = []
test_680_cmi_shifted_list = []
test_680_dark_list = []
# 785 test
test_785_cmi_shifted_list = []
test_785_dark_list = []

# Warning flags
# Set all to 1 to debug with pre-provided data
dark_flag = 0
ctrl_flags = [0, 0, 0, 0]
test_flags = [0, 0]


# In[3353]:


# Function that attatches a plot to the frame
def plot():
    # Pull the outside plotframe and toolbar, needed to stop the toolbar from duplicating
    global plotframe
    global toolbar
    toolbar.destroy()

    # containing the Matplotlib figure
    plotframe = FigureCanvasTkAgg(fig, master = frame)
    plotframe.draw()

    # placing the canvas on the Tkinter window
    plotframe.get_tk_widget().place(x = 390, y = -20)

    # creating the Matplotlib toolbar
    toolbar = NavigationToolbar2Tk(plotframe, frame)
    toolbar.update()

    # placing the toolbar on the Tkinter window
    plotframe.get_tk_widget().place()


# In[3354]:


#Initialize fonts
title_font = font.Font(family = "Arial", size = 25)
button_font = font.Font(family = "Arial", size = 15)
label_font = font.Font(family = "Arial", size = 20, underline = True)
ticker_font = font.Font(family = "Arial", size = 16)
control_font = font.Font(family = "Arial", size = 12)
sample_font = font.Font(family = "Arial", size = 18)
dropdown_font = font.Font(family = "Arial", size = 15)
laser_font = font.Font(family = "Arial", size = 12)
new_label = font.Font(family = "Arial", size = 15)


# In[3355]:


# RSCL label
rscl_text = tk.Label(frame, font = title_font, text = "RSCL", bg = "white", fg = "orange")
rscl_text.place(x = 300, y = 10)


# In[3356]:


# Tries to take a dark, will give an error message if fails
def get_spec_dark(int_time):
    try:
        # Run OceanDirect Program to get dark
        subprocess.run(["Release/get_spec.exe", f"{int_time}", "dark.csv"])

        # import relevant globals
        global dark_set
        global dark_counts_list
        global dark_flag

        # Read in dark data and save it to a list
        dark_set = pd.read_csv('dark.csv', header = None)
        dark_counts = dark_set.iloc[:, 1]
        dark_counts_list = dark_counts.values.tolist()

        # Confirm to the rest of the program that a dark has been collected
        dark_flag = 1

    # Show a error message if the dark fails to collect
    except FileNotFoundError:
        tk.messagebox.showwarning(title = "Dark Not Collected", message = "Dark not collected. Please check spectrometer connection.")


# In[3357]:


#Collect Dark Button

collect_dark_btn = tk.Button(frame, text = "Collect Dark", height = 1, width = 14, padx = 10, pady = 5, fg = "white", bg = "gray", command = lambda: get_spec_dark(time.get()))
collect_dark_btn.place(x = 25, y = 25)
collect_dark_btn["font"] = font.Font(family = "Arial", size = 16)


# In[3358]:


# Ticker Box for Integration time
time_val = tk.IntVar()
int_spb = tk.Spinbox(frame, from_ = 1, to = 5000, increment = 1, textvariable = time_val, font = ticker_font, width = 3)
int_spb.place(x = 230, y = 80)


# In[3359]:


# Time variable drop down for integration time
root.option_add("*TCombobox*Listbox*Font", ticker_font)
OPTIONS = [
"s",
"us",
] #etc

time_var = tk.StringVar(frame)
time_var.set(OPTIONS[0]) # default value

int_opt = ttk.Combobox(frame, textvariable = time_var, values = OPTIONS)
int_opt.config(width = 3, height = 4, font = dropdown_font)
int_opt.place(x = 290, y = 80)


# In[3360]:
def set_int_time(time_val, time_var):
    if time_var == "s":
        time.set((time_val * np.power(10, 6)))
    else:
        time.set(time_val)

#Integration time Button
time = tk.IntVar(value = 1000000)
int_time_btn = tk.Button(frame, text = "Set Integration Time", height = 1, width = 14, padx = 10, pady = 5, fg = "white", bg = "gray", command = lambda: set_int_time(time_val.get(), time_var.get()))
int_time_btn.place(x = 25, y = 80)
int_time_btn["font"] = font.Font(family = "Arial", size = 16)


# In[3361]:


# Controls Label
ctrl_text = tk.Label(frame, font = label_font, text = "Control", bg = "white")
ctrl_text.place(x = 25, y = 130)


# In[3362]:


# Control Sample name label

# Controls Label
ctrl_sample_text = tk.Label(frame, font = new_label, text = "Control Sample Name:", bg = "white")
ctrl_sample_text.place(x = 25, y = 170)


# In[3363]:


# Control Sample drop down
from tkinter import *
root.option_add("*TCombobox*Listbox*Font", control_font)
TEST_OPTIONS = [
"100%_Water",
"100%_Biofuel"
] #etc

control_var = tk.StringVar(frame)
control_var.set(TEST_OPTIONS[0]) # default value

int_opt = ttk.Combobox(frame, textvariable = control_var, values = TEST_OPTIONS)
int_opt.config(width = 11, height = 5, font = dropdown_font)
int_opt.place(x = 230, y = 170)


# In[3364]:


# Check to see if a dark has been taken, if so, get the 680 control sample
def try_get_ctrl_680():
    global dark_flag

    if dark_flag == 0:
        tk.messagebox.showwarning(title = "No Dark", message = "You have not collected a dark! Please collect a dark before continuing.")
    else:
        get_ctrl("680", time.get())


# In[3365]:


# Check to see if a dark has been taken, if so, get the 785 control sample
def try_get_ctrl_785():
    global dark_flag

    if dark_flag == 0:
        tk.messagebox.showwarning(title = "No Dark", message = "You have not collected a dark! Please collect a dark before continuing.")
    else:
        get_ctrl("785", time.get())


# In[3366]:


# Get Control Function
def get_ctrl(laser, int_time):
    # Call the necessary globals
    global ctrl_680_h2o
    global ctrl_680_bio
    global ctrl_785_h2o
    global ctrl_785_bio
    global dark_counts_list
    global h2o_680_cmi_shifted_list
    global h2o_680_dark_list
    global bio_680_cmi_shifted_list
    global bio_680_dark_list
    global h2o_785_cmi_shifted_list
    global h2o_785_dark_list
    global bio_785_cmi_shifted_list
    global bio_785_dark_list
    global ctrl_flags

    # Clear the plot
    plot1.clear()

    # The next four blocks all function the same way as the commented one below
    if laser == "680":
        if control_var.get() == "100%_Water":
            # OceanDirect driver to get spectrum
            subprocess.run(["Release/get_spec.exe", f"{int_time}", "680_100%_Water.csv"])
            # Read spectrum
            ctrl_680_h2o = pd.read_csv("680_100%_Water.csv", header = None)

            # Convert wavelengths and counts to list form
            h2o_680_waves = ctrl_680_h2o.iloc[:, 0]
            h2o_680_waves_list = h2o_680_waves.values.tolist()
            h2o_680_counts = ctrl_680_h2o.iloc[:, 1]
            h2o_680_counts_list = h2o_680_counts.values.tolist()

            # Dark correct the counts
            h2o_680_counts_np = np.array(h2o_680_counts_list)
            dark_counts_np = np.array(dark_counts_list)
            h2o_dark_np = h2o_680_counts_np - dark_counts_np
            h2o_680_dark_list = h2o_dark_np.tolist()

            # Convert the wavelengths to centimeters inverse and Raman Shift them.
            h2o_cmi = np.power(10, 7)/np.array(h2o_680_waves_list)
            shift_constant_680 = np.power(10, 7)/680
            h2o_cmi_shifted = (shift_constant_680) - (h2o_cmi)
            h2o_680_cmi_shifted_list = h2o_cmi_shifted.tolist()

            plot1.plot(h2o_680_cmi_shifted_list, h2o_680_dark_list)

            # Flip the control flag
            ctrl_flags[0] = 1

        if control_var.get() == "100%_Biofuel":
            subprocess.run(["Release/get_spec.exe", f"{int_time}", f"680_{control_var.get()}.csv"])
            ctrl_680_bio = pd.read_csv('680_100%_Biofuel.csv', header = None)

            bio_680_waves = ctrl_680_bio.iloc[:, 0]
            bio_680_waves_list = bio_680_waves.values.tolist()
            bio_680_counts = ctrl_680_bio.iloc[:, 1]
            bio_680_counts_list = bio_680_counts.values.tolist()


            bio_680_counts_np = np.array(bio_680_counts_list)
            dark_counts_np = np.array(dark_counts_list)
            bio_dark_np = bio_680_counts_np - dark_counts_np
            bio_680_dark_list = bio_dark_np.tolist()

            bio_cmi = np.power(10, 7)/np.array(bio_680_waves_list)
            shift_constant_680 = np.power(10, 7)/680
            bio_cmi_shifted = (shift_constant_680) - (bio_cmi)
            bio_680_cmi_shifted_list = bio_cmi_shifted.tolist()

            plot1.plot(bio_680_cmi_shifted_list, bio_680_dark_list)

            ctrl_flags[1] = 1

    if laser == "785":
        if control_var.get() == "100%_Water":
            subprocess.run(["Release/get_spec.exe", f"{int_time}", f"785_{control_var.get()}.csv"])
            ctrl_785_h2o = pd.read_csv('785_100%_Water.csv', header = None)

            h2o_785_waves = ctrl_785_h2o.iloc[:, 0]
            h2o_785_waves_list = h2o_785_waves.values.tolist()
            h2o_785_counts = ctrl_785_h2o.iloc[:, 1]
            h2o_785_counts_list = h2o_785_counts.values.tolist()


            h2o_785_counts_np = np.array(h2o_785_counts_list)
            dark_counts_np = np.array(dark_counts_list)
            h2o_dark_np = h2o_785_counts_np - dark_counts_np
            h2o_785_dark_list = h2o_dark_np.tolist()

            h2o_cmi = np.power(10, 7)/np.array(h2o_785_waves_list)
            shift_constant_785 = np.power(10, 7)/785
            h2o_cmi_shifted = (shift_constant_785) - (h2o_cmi)
            h2o_785_cmi_shifted_list = h2o_cmi_shifted.tolist()

            plot1.plot(h2o_785_cmi_shifted_list, h2o_785_dark_list)

            ctrl_flags[2] = 1

        if control_var.get() == "100%_Biofuel":
            subprocess.run(["Release/get_spec.exe", f"{int_time}", f"785_{control_var.get()}.csv"])
            ctrl_785_bio = pd.read_csv('785_100%_Biofuel.csv', header = None)

            bio_785_waves = ctrl_785_bio.iloc[:, 0]
            bio_785_waves_list = bio_785_waves.values.tolist()
            bio_785_counts = ctrl_785_bio.iloc[:, 1]
            bio_785_counts_list = bio_785_counts.values.tolist()


            bio_785_counts_np = np.array(bio_785_counts_list)
            dark_counts_np = np.array(dark_counts_list)
            bio_dark_np = bio_785_counts_np - dark_counts_np
            bio_785_dark_list = bio_dark_np.tolist()

            bio_cmi = np.power(10, 7)/np.array(bio_785_waves_list)
            shift_constant_785 = np.power(10, 7)/785
            bio_cmi_shifted = (shift_constant_785) - (bio_cmi)
            bio_785_cmi_shifted_list = bio_cmi_shifted.tolist()

            plot1.plot(bio_785_cmi_shifted_list, bio_785_dark_list)

            ctrl_flags[3] = 1

    plot1.set_xlabel("Raman Shift", fontsize = 10)
    plot1.set_ylabel("Intensity (Counts)", fontsize = 10)
    plot1.set_title("Spectrum", fontsize = 16)
    plot1.set_xlim(left = 150, right = 4000)
    plot1.set_ylim(bottom = 0, top = 8000)
    plot()


# In[3367]:


# Collect 680 Control Button

collect_680_ctrl_btn = tk.Button(frame, text = "Take 680 nm", height = 1, width = 12, padx = 7, pady = 3, fg = "white", bg = "gray", command = lambda: try_get_ctrl_680())
collect_680_ctrl_btn.place(x = 25, y = 210)
collect_680_ctrl_btn["font"] = laser_font


# In[3368]:


# Collect 785 Control Button

collect_785_ctrl_btn = tk.Button(frame, text = "Take 785 nm", height = 1, width = 12, padx = 7, pady = 3, fg = "white", bg = "gray", command = lambda: try_get_ctrl_785())
collect_785_ctrl_btn.place(x = 160, y = 210)
collect_785_ctrl_btn["font"] = laser_font


# In[3369]:


# Data Label
data_text = tk.Label(frame, font = label_font, text = "Data", bg = "white")
data_text.place(x = 25, y = 250)


# In[3370]:


# Test Number Label
test_num_text = tk.Label(frame, font = new_label, text = "Test Number:", bg = "white")
test_num_text.place(x = 25, y = 290)


# In[3371]:


# Ticker Box for Integration time
var2 = tk.IntVar()
int_spb = tk.Spinbox(frame, from_ = 1, to = 100, increment = 1, textvariable = var2, font = ticker_font, width = 3)
int_spb.place(x = 230, y = 290)


# In[3372]:


# Check to see if four control samples have been taken, one for each laser + control combination. If so get a test sample
def try_get_test_680():
    global ctrl_flags

    if ctrl_flags != [1, 1, 1, 1]:
        tk.messagebox.showwarning(title = "Not Enough Controls", message = "You have not collected all four control samples! Please collect all four control samples before continuing.")
    else:
        get_test_680(time.get(), var2.get())


# In[3373]:


# Check to see if four control samples have been taken, one for each laser + control combination. If so get a test sample
def try_get_test_785():
    global ctrl_flags

    if ctrl_flags != [1, 1, 1, 1]:
        tk.messagebox.showwarning(title = "Not Enough Controls", message = "You have not collected all four control samples! Please collect all four control samples before continuing.")
    else:
        get_test_785(time.get(), var2.get())


# In[3374]:


# Function to get a test sample
def get_test_680(int_time, testnum):
    # Call in the relevant globals
    global test_waves_data
    global test_sets_680
    global dark_counts_list
    global test_cmi
    global test_680_cmi_shifted_list
    global test_680_dark_list
    global test_flags

    # Clear the plot
    plot1.clear()

    # Check to see if the potential test number is at most one more than the current number of tests taken
    if len(test_sets_680) + 1 >= testnum:
        # Run the OceanDirect driver to collect the spectrum
        subprocess.run(["Release/get_spec.exe", f"{int_time}", f"test{testnum}_680.csv"])
        # Check if the test has been taken or not already. If so, we overwrite the data
        if len(test_sets_680) >= testnum:
            test_sets_680[testnum - 1] = pd.read_csv(f"test{testnum}_680.csv", header = None)
        else:
            test_sets_680.append(pd.read_csv(f"test{testnum}_680.csv", header = None))

        # Convert the wavelengths and counts to lists
        test_waves = test_sets_680[testnum-1].iloc[:, 0]
        test_waves_list = test_waves.values.tolist()
        test_counts = test_sets_680[testnum-1].iloc[:, 1]
        test_counts_list = test_counts.values.tolist()

        # Dark correct the counts
        test_counts_np= np.array(test_counts_list)
        dark_counts_np = np.array(dark_counts_list)
        test_dark_np = test_counts_np - dark_counts_np
        test_680_dark_counts = test_dark_np.tolist()

        # Convert the wavelengths to centimeters inverse
        test_cmi = np.power(10, 7)/np.array(test_waves_list)
        shift_constant_680 = np.power(10, 7)/680
        # Raman Shift
        test_cmi_shifted = (shift_constant_680) - (test_cmi)
        # Same check to determine if an overwrite should occur
        if len(test_680_cmi_shifted_list) >= testnum:
            test_680_cmi_shifted_list[testnum - 1] = test_cmi_shifted.tolist()
            test_680_dark_list[testnum - 1] = test_680_dark_counts
            test_waves_data[testnum - 1] = test_waves_list
        else:
            test_680_cmi_shifted_list.append(test_cmi_shifted.tolist())
            test_680_dark_list.append(test_680_dark_counts)
            test_waves_data.append(test_waves_list)
        # Plot the data
        plot1.plot(test_680_cmi_shifted_list[testnum - 1], test_680_dark_list[testnum - 1])

        plot1.set_xlabel("Raman Shift", fontsize = 10)
        plot1.set_ylabel("Intensity (Counts)", fontsize = 10)
        plot1.set_title("Spectrum", fontsize = 16)
        plot1.set_xlim(left = 150, right = 4000)
        plot1.set_ylim(bottom = 0, top = 8000)
        plot()

        # Flip the flag to confirm the test was taken
        test_flags[0] = 1

    else:
        tk.messagebox.showerror(message = "Please take prior tests before continuing.")




# In[3375]:


def get_test_785(int_time, testnum):
    global test_sets_785
    global dark_counts_list
    global test_785_cmi_shifted_list
    global test_785_dark_list
    global test_flags

    plot1.clear()

    if len(test_sets_785) + 1 >= testnum:
        subprocess.run(["Release/get_spec.exe", f"{int_time}", f"test{testnum}_785.csv"])
        if len(test_sets_785) >= testnum:
            test_sets_785[testnum - 1] = pd.read_csv(f"test{testnum}_785.csv", header = None)
        else:
            test_sets_785.append(pd.read_csv(f"test{testnum}_785.csv", header = None))

        test_waves = test_sets_785[testnum-1].iloc[:, 0]
        test_waves_list = test_waves.values.tolist()
        test_counts = test_sets_785[testnum-1].iloc[:, 1]
        test_counts_list = test_counts.values.tolist()

        test_counts_np= np.array(test_counts_list)
        dark_counts_np = np.array(dark_counts_list)
        test_dark_np = test_counts_np - dark_counts_np
        test_785_dark_list = test_dark_np.tolist()

        test_cmi = np.power(10, 7)/np.array(test_waves_list)
        shift_constant_785 = np.power(10, 7)/785
        test_cmi_shifted = (shift_constant_785) - (test_cmi)
        if len(test_785_cmi_shifted_list) >= testnum:
            test_785_cmi_shifted_list[testnum - 1] = test_cmi_shifted.tolist()
        else:
            test_785_cmi_shifted_list.append(test_cmi_shifted.tolist())

        plot1.plot(test_785_cmi_shifted_list[testnum - 1], test_785_dark_list)

        plot1.set_xlabel("Raman Shift", fontsize = 10)
        plot1.set_ylabel("Intensity (Counts)", fontsize = 10)
        plot1.set_title("Spectrum", fontsize = 16)
        plot1.set_xlim(left = 150, right = 4000)
        plot1.set_ylim(bottom = 0, top = 8000)
        plot()

        test_flags[1] = 1

    else:
        tk.messagebox.showerror(message = "Please take prior tests before continuing.")




# In[3376]:


# Collect 680 Test Button

collect_680_test_btn = tk.Button(frame, text = "Take 680 nm", height = 1, width = 12, padx = 7, pady = 3, fg = "white", bg = "gray", command = lambda: try_get_test_680())
collect_680_test_btn.place(x = 25, y = 330)
collect_680_test_btn["font"] = laser_font


# In[3377]:


# Collect 785 Test Button

collect_785_test_btn = tk.Button(frame, text = "Take 785 nm", height = 1, width = 12, padx = 7, pady = 3, fg = "white", bg = "gray", command = lambda: try_get_test_785())
collect_785_test_btn.place(x = 160, y = 330)
collect_785_test_btn["font"] = laser_font


# In[3378]:


# Percent Label
percent_text = tk.Label(frame, font = new_label, text = "Percent H2O:", bg = "white")
percent_text.place(x = 430, y = 390)


# In[3379]:


# Text box to update percentage
percent_box = Text(frame, height = 1, width = 5)
percent_box.configure(font = new_label)
percent_box.place(x = 560, y = 390)


# In[3380]:


# Check to see if atleast one test sample has been collect with both the 680 and 785 laser. If so plot the graphs and show the percentage
def try_plot_concatenate():
    global test_flags

    if test_flags != [1, 1]:
        tk.messagebox.showwarning(title = "Not Enough Tests", message = "You have not collected test samples for both lasers! Please collect test samples for both lasers before continuing.")
    else:
        plot_concatenate(var2.get())


# In[3381]:


# Function to plot the controls and currently selected test sample.
def plot_concatenate(testnum):
    # Clear the plot
    plot1.clear()

    # Plot the plots
    plot1.plot(h2o_680_cmi_shifted_list, h2o_680_dark_list, c = "blue")

    plot1.plot(bio_680_cmi_shifted_list, bio_680_dark_list, c = "green")

    plot1.plot(test_680_cmi_shifted_list[testnum - 1], test_680_dark_list[testnum - 1], c = "orange")

    plot1.plot(h2o_785_cmi_shifted_list, h2o_785_dark_list, c = "blue")

    plot1.plot(bio_785_cmi_shifted_list, bio_785_dark_list, c = "green")

    plot1.plot(test_785_cmi_shifted_list[testnum - 1], test_785_dark_list, c = "orange")


    # Array of our m & b found using data analytics
    coeff = [ 0.19440593616483076, -158.27747274277147]
    m = coeff[0]
    b = coeff[1]

    # Find the maximum peak on the 680 test
    x = test_waves_data[testnum - 1]
    y = ctrl_680_bio.iloc[:, 1].values.tolist()
    max_val = 0
    max_index = 0
    for i in range(len(list(x))):
        if x[i] >= 860 and x[i] <=900:
            if y[i] > max_val:
                max_val = y[i]
                max_index = 374
    print(max_index)
    print(max_val)
    print(test_680_dark_list[testnum - 1][max_index])
    # Calculate percentage
    percent = ((test_680_dark_list[testnum - 1][max_index] * m) + b)
    percent_box.delete('1.0', END)
    percent_box.insert(INSERT, f"{percent}%")

    plot1.set_xlabel("Raman Shift", fontsize = 10)
    plot1.set_ylabel("Intensity (Counts)", fontsize = 10)
    plot1.set_title("Spectrum", fontsize = 16)
    plot1.legend(['Water', 'Biofuel', 'Test'])
    plot1.set_xlim(left = 150, right = 4000)
    plot1.set_ylim(bottom = 0, top = 8000)
    plot()


# In[3382]:


# Concatenate Button

concatenate_btn = tk.Button(frame, text = "Concatenate", height = 1, width = 12, padx = 7, pady = 3, fg = "white", bg = "gray", command = lambda: try_plot_concatenate())
concatenate_btn.place(x = 25, y = 390)
concatenate_btn["font"] = laser_font


# In[3383]:


# Function that creates a folder if one doesn't already exist, and then moves the relevant files to that folder, while also
# appending a timestamp to prevent overwrite.
def save_data():
    date = datetime.now().strftime("%m_%d_%Y_%I_%M_%p")

    try:
        os.mkdir("Saved_Data")
    except:
        pass

    try:
        os.replace("dark.csv", f"Saved_Data/dark_{date}.csv")
    except:
        pass

    try:
        os.replace("680_100%_Water.csv", f"Saved_Data/680_100%_Water_{date}.csv")
    except:
        pass

    try:
        os.replace("680_100%_Biofuel.csv", f"Saved_Data/680_100%_Biofuel_{date}.csv")
    except:
        pass

    try:
        os.replace("785_100%_Water.csv", f"Saved_Data/785_100%_Water_{date}.csv")
    except:
        pass

    try:
        os.replace("785_100%_Biofuel.csv", f"Saved_Data/785_100%_Biofuel_{date}.csv")
    except:
        pass

    for i in range(len(test_sets_680)):
        try:
            os.replace(f"test{i + 1}_680.csv", f"Saved_Data/test{i + 1}_680_{date}.csv")
        except:
            pass

    for i in range(len(test_sets_785)):
        try:
            os.replace(f"test{i + 1}_785.csv", f"Saved_Data/test{i + 1}_785_{date}.csv")
        except:
            pass


# In[3384]:


# Save data button
save_data_btn = tk.Button(frame, text = "Save Data", height = 1, width = 12, padx = 7, pady = 3, fg = "white", bg = "gray", command = lambda: save_data())
save_data_btn.place(x = 825, y = 390)
save_data_btn["font"] = laser_font

# In[3386]:


plot()
root.mainloop()


# In[ ]:


# Delete files in order to free up space and ensure no data is reused on the next use of the device.
try:
    os.remove("dark.csv")
except:
    pass

try:
    os.remove("680_100%_Water.csv")
except:
    pass

try:
    os.remove("680_100%_Biofuel.csv")
except:
    pass

try:
    os.remove("785_100%_Water.csv")
except:
    pass

try:
    os.remove("785_100%_Biofuel.csv")
except:
    pass

for i in range(len(test_sets_680)):
    try:
        os.remove(f"test{i + 1}_680.csv")
    except:
        pass

for i in range(len(test_sets_785)):
    try:
        os.remove(f"test{i + 1}_785.csv")
    except:
        pass
