function varargout = HydroWatch(varargin)
% HYDROWATCH MATLAB code for HydroWatch.fig
%      HYDROWATCH, by itself, creates a new HYDROWATCH or raises the existing
%      singleton*.
%
%      H = HYDROWATCH returns the handle to a new HYDROWATCH or the handle to
%      the existing singleton*.
%
%      HYDROWATCH('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in HYDROWATCH.M with the given input arguments.
%
%      HYDROWATCH('Property','Value',...) creates a new HYDROWATCH or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before HydroWatch_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to HydroWatch_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help HydroWatch

% Last Modified by GUIDE v2.5 27-Mar-2019 14:33:45

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @HydroWatch_OpeningFcn, ...
                   'gui_OutputFcn',  @HydroWatch_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before HydroWatch is made visible.
function HydroWatch_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to HydroWatch (see VARARGIN)
clearvars -global

% Choose default command line output for HydroWatch
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes HydroWatch wait for user response (see UIRESUME)
% uiwait(handles.figure1);  

% --- Executes during object creation, after setting all properties.
%function figure1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called
global hi
% This creates the 'background' axes
background = axes('units','normalized', ...
            'position',[0 0 1 1]);
        
% Move the background axes to the bottom

uistack(background,'bottom');

% Load in a background image and display it using the correct colors

I=imread('water12.jpg');
hi = imagesc(I);
colormap gray

% Test data for plot one (hydration test)

out = readtable('OutputBecca.csv');

%cast into double from table
LED=out.LED_code;
values=out.Hex_Output;
[m,n]=size(out);

%initialize the LEDs
L1=0;
L2=0;
L3=0;
L4=0;

% note units are in volts
for i=1:m
    code=LED(i,1);
    switch code
        case 1
            L1=L1+1;
            LED1(L1)=convertAFE(values(i));
            
        case 2
            L2=L2+1;
            LED2(L2)=convertAFE(values(i));
            
        case 3
            L3=L3+1;
            LED3(L3)=convertAFE(values(i));
            
        case 4
            L4=L4+1;
            LED4(L4)=convertAFE(values(i));
    end
end


max=length(LED4);

hydro=.05*ones(1,max);


time=linspace(0, 200*10^-3*length(LED4), length(LED4));

axes(handles.axes1);
plot(time, LED1(1:max), 'b','LineWidth',1 );
ylim([0 .2]);
xlabel('Time (s)');
ylabel('Voltage measured (V)');
title('\color{white}450nm: skin contact');

ax = gca;
set(ax, {'XColor', 'YColor'}, {'w','w'});

axes(handles.axes4);
plot(time, LED2(1:max), 'r','LineWidth',1 );
ylim([0 1.2]);
xlabel('Time (s)');
ylabel('Voltage measured (V)');
title('\color{white}660nm: Red LED');
ax = gca;
set(ax, {'XColor', 'YColor'}, {'w','w'});

axes(handles.axes5);
plot(time, LED3(1:max),'b', time, hydro, 'g','LineWidth',1 );
ylim([0 .07]);
xlabel('Time (s)');
ylabel('Voltage measured (V)');
title('\color{white}1200nm: Relative hydration');
legend('Measured', 'Relative Hydration', 'Location', 'best');
ax = gca;
set(ax, {'XColor', 'YColor'}, {'w','w'});


axes(handles.axes6);
plot(time, LED4(1:max),'b','LineWidth',1 );
ylim([0 .07]);
xlabel('Time (s)');
ylabel('Voltage measured (V)');
title('\color{white}970nm: Near-infared');
ax = gca;
set(ax, {'XColor', 'YColor'}, {'w','w'});



% change to dehydrated
%handles.status.String = 'Dehydrated!';
%handles.status.ForegroundColor=[1,0,0];

%Load absoption sec for water 
axes(handles.axes2)
[red, ir, time]= pulseox();
plot(time, red, time, ir,'LineWidth',2);
xlabel('Time (s)');
ylabel('Voltage (V)');
legend('Red LED', 'IR LED');
ax = gca;
set(ax, {'XColor', 'YColor'}, {'w','w'}); 

% Turn the handlevisibility off so that we don't inadvertently plot into the axes again
% Also, make the axes invisible
set(background,'handlevisibility','off', ...
            'visible','off')   
        
        



% --- Outputs from this function are returned to the command line.
function varargout = HydroWatch_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton.
function pushbutton_Callback(hObject, eventdata, handles)
global Number email provider
% hObject    handle to pushbutton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% This is where we will go through the log file and do all the post
% processing 

% read log file
system('python logfileparse.py');


% post process data
out = readtable('Output.csv');

%cast into double from table
LED=out.LED_code;
values=out.Hex_Output;
[m,n]=size(out);

%initialize the LEDs
L1=0;
L2=0;
L3=0;
L4=0;

% note units are in volts
for i=1:m
    code=LED(i,1);
    switch code
        case 1
            L1=L1+1;
            LED1(L1)=convertAFE(values(i));
            
        case 2
            L2=L2+1;
            LED2(L2)=convertAFE(values(i));
            
        case 3
            L3=L3+1;
            LED3(L3)=convertAFE(values(i));
            
        case 4
            L4=L4+1;
            LED4(L4)=convertAFE(values(i));
    end
end


max=length(LED4);

hydro=.05*ones(1,max);

%% determine if good skin contact
badcontact=false;
count=0;
for i=1:length(LED1)
    if LED1(i)==0 || LED1(i)>.15
        count=count+1;
    end
end

if count>=length(LED4)/2
    badcontact=true;
end

if (badcontact==true)
    handles.status.String = 'Bad Contact!';
    handles.status.ForegroundColor=[1,1,0];
else
    % determine if hydrated or not
    % state 1 --> hydrated
    % state 0 --> dehydrated
    
    state=sum(LED3)/length(LED3);
    
    hydrate=sum(hydro)/length(hydro);
    
    if (state-hydrate>0)
        status=false;
    else
        status=true;
    end
    
    
    %% update everything
    
    if isempty(provider)==1
        provider='sprint';
    end


    % send out notification
        %check they changed number or email
        if isempty(Number)==0
            if status==true
                message='Hydrated! Keep it up!';
                handles.status.String = 'Hydrated!';
                handles.status.ForegroundColor=[1,1,1];
            else
                message='Dehydrated! Drink Water!';
                handles.status.String = 'Dehydrated!';
                handles.status.ForegroundColor=[1,0,0];
            end

            send_text_message(Number,provider, ...
            message);
        elseif isempty(email)==0
            send_email(email, state);
        else
            handles.status.String = 'Enter info';
            handles.status.ForegroundColor=[1,1,0];
        end

    % update plot and text based on hydrated or not
    time=linspace(0, 200*10^-3*length(LED4), length(LED4));

    axes(handles.axes1);
    plot(time, LED1(1:max), 'b','LineWidth',1 );
    ylim([0 .2]);
    xlabel('Time (s)');
    ylabel('Voltage measured (V)');
    title('\color{white}450nm: skin contact');
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});

    axes(handles.axes4);
    plot(time, LED2(1:max), 'r','LineWidth',1 );
    ylim([0 1.2]);
    xlabel('Time (s)');
    ylabel('Voltage measured (V)');
    title('\color{white}660nm: Red LED');
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});

    axes(handles.axes5);
    plot(time, LED3(1:max),'b', time, hydro, 'g','LineWidth',1 );
    ylim([0 .07]);
    xlabel('Time (s)');
    ylabel('Voltage measured (V)');
    title('\color{white}1200nm: Relative hydration');
    legend('Measured', 'Relative Hydration','Location', 'best');
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});


    axes(handles.axes6);
    plot(time, LED4(1:max),'b','LineWidth',1 );
    ylim([0 .07]);
    xlabel('Time (s)');
    ylabel('Voltage measured (V)');
    title('\color{white}970nm: Near-infared');
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});
end


function cellnum_Callback(hObject, eventdata, handles)
% hObject    handle to cellnum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of cellnum as text
%        str2double(get(hObject,'String')) returns contents of cellnum as a double
global Number
Number = get(hObject,'String');

% --- Executes during object creation, after setting all properties.
function cellnum_CreateFcn(hObject, eventdata, handles)
% hObject    handle to cellnum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes on selection change in popupmenu.
function popupmenu_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu

global provider

% this is where they select their cell phone provider
contents = cellstr(get(hObject,'String'));
item= contents{get(hObject,'Value')};

provider=item;




% --- Executes during object creation, after setting all properties.
function popupmenu_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end





function email_Callback(hObject, eventdata, handles)
% hObject    handle to email (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of email as text
%        str2double(get(hObject,'String')) returns contents of email as a double

global email

email=get(hObject,'String');


% --- Executes during object creation, after setting all properties.
function email_CreateFcn(hObject, eventdata, handles)
% hObject    handle to email (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu2

axes(handles.axes2)

contents = cellstr(get(hObject,'String'));
item=contents{get(hObject,'Value')};

if strcmp(item, 'H2O')
    [Wavelength, Absorption]= heavyH20();
    plot(Wavelength, Absorption,'LineWidth',2);
    xlabel('Wavelength (nm)');
    ylabel('Absorption (cm^{-1})');
    legend('Heavy Water','Location','best')
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});
    
elseif strcmp(item, 'Hb')
    [Wavelength, Oxyhemoglobin_Absorption, Deoxyhemoglobin_Absorption]=oxy_deoxy();
    plot(Wavelength, Deoxyhemoglobin_Absorption,'LineWidth',2);
    xlabel('Wavelength (nm)');
    ylabel('Absorption (cm^{-1})');
    legend('Deoxyhemoglobin','Location','best')
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});
    
elseif strcmp(item, 'HbO') 
    [Wavelength, Oxyhemoglobin_Absorption, Deoxyhemoglobin_Absorption]=oxy_deoxy();
    plot(Wavelength, Oxyhemoglobin_Absorption,'LineWidth',2);
    xlabel('Wavelength (nm)');
    ylabel('Absorption (cm^{-1})');
    legend('Oxyhemoglobin','Location','best')
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});
    
elseif strcmp(item, 'All Conc.')  
    [Wavelength, Oxyhemoglobin_Absorption, Deoxyhemoglobin_Absorption]=oxy_deoxy();
    [Wavelength2, Absorption]= heavyH20();
    plot(Wavelength, Oxyhemoglobin_Absorption,Wavelength, Oxyhemoglobin_Absorption,Wavelength2, Absorption, 'LineWidth',2);
    xlabel('Wavelength (nm)');
    ylabel('Absorption (cm^{-1})');
    legend('HbO','Hb','H2O','Location','best')
    xlim([600 1400]);
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'});
    
    
elseif strcmp(item, 'Pulse')
    [red, ir, time]= pulseox();
    plot(time, red, time, ir,'LineWidth',2);
    xlabel('Time (s)');
    ylabel('Voltage (V)');
    legend('Red LED', 'IR LED');
    ax = gca;
    set(ax, {'XColor', 'YColor'}, {'w','w'}); 
end

% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
