function varargout = stimDesigner(varargin)
% STIMDESIGNER MATLAB code for stimDesigner.fig
%      STIMDESIGNER, by itself, creates a new STIMDESIGNER or raises the existing
%      singleton*.
%
%      H = STIMDESIGNER returns the handle to a new STIMDESIGNER or the handle to
%      the existing singleton*.
%
%      STIMDESIGNER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in STIMDESIGNER.M with the given input arguments.
%
%      STIMDESIGNER('Property','Value',...) creates a new STIMDESIGNER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before stimDesigner_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to stimDesigner_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 stimDesigner

% Last Modified by GUIDE v2.5 23-Oct-2018 11:46:43

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @stimDesigner_OpeningFcn, ...
                   'gui_OutputFcn',  @stimDesigner_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 stimDesigner is made visible.
function stimDesigner_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 stimDesigner (see VARARGIN)

global stopStim
stopStim = 1;

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

handles.start = 0;  %reached the start stimulation portion
handles.dummy = 0;  %No Daq mode
handles.closeFig = 0;

try
    %DAQ setup
    daqreset
    handles.s = daq.createSession('ni');    %Creates a National Instrument Session
    addAnalogOutputChannel(handles.s,'cDAQ1Mod3','ao0','Voltage');   %Add an analogue output channel
    handles.s.Rate = 1000;     %Sampling frequency
catch
    resp = questdlg({'The DAQ is not connecting/software is not installed.',...
        'Continue on Dummy mode?'},'Dummy Mode','Yes','No','Yes');
    if strcmp(resp,'No')
        handles.closeFig = 1; 
    else
        handles.dummy = 1;
    end
end

axes(handles.example)
imshow('StandardWaveform.png')

axes(handles.pulseFig)
datacursormode on
set(gcf,'toolbar','figure')
    

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = stimDesigner_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;

if handles.closeFig
    figure1_CloseRequestFcn(hObject,eventdata,handles)
end


% --- Executes on button press in brstMd.
function brstMd_Callback(hObject, eventdata, handles)
% hObject    handle to brstMd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
brstF = get(hObject,'value');

if brstF 
    
    axes(handles.example)
    imshow('Burst Waveform.png')

    set(handles.burstFreq, 'visible', 'on');
    set(handles.E,'visible','on')
    set(handles.burstFreqTxt,'visible','on')
    set(handles.F,'visible','on')
    set(handles.ppb,'visible','on')
    set(handles.pulsesBurstTxt,'visible','on')
else
    axes(handles.example)
    imshow('StandardWaveform.png')
    
    set(handles.burstFreq, 'visible', 'off');
    set(handles.E,'visible','off')
    set(handles.burstFreqTxt,'visible','off')
    set(handles.F,'visible','off')
    set(handles.ppb,'visible','off')
    set(handles.pulsesBurstTxt,'visible','off')
end


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



% --- Executes during object creation, after setting all properties.
function Hz_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Hz (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



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


% --- Executes during object creation, after setting all properties.
function iti_CreateFcn(hObject, eventdata, handles)
% hObject    handle to iti (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



function trialLngth_Callback(hObject, eventdata, handles)
% hObject    handle to trialLngth (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 trialLngth as text
%        str2double(get(hObject,'String')) returns contents of trialLngth as a double


% --- Executes during object creation, after setting all properties.
function trialLngth_CreateFcn(hObject, eventdata, handles)
% hObject    handle to trialLngth (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


function SessionnDur_Callback(hObject, eventdata, handles)
% hObject    handle to SessionnDur (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 SessionnDur as text
%        str2double(get(hObject,'String')) returns contents of SessionnDur as a double


% --- Executes during object creation, after setting all properties.
function SessionnDur_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SessionnDur (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 button press in verify.
function verify_Callback(hObject, eventdata, handles)
% hObject    handle to verify (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global stopStim
stopStim = 1;
paramCheck = 1;

% Check for all parameters
[inputParam,w] = checkParam(handles);

if ~w
    try
        handles.wave = make_tVNS_wave(inputParam);
    catch
       warning('Problem creating waveform.');
       paramCheck = 0;
    end
end

%Stimulation/Verification of stimulation 
if paramCheck
    if handles.start
        resp = questdlg('You are about to start stimulation', 'Verify', ...
            'Continue','Go Back','Go Back');
        if strcmp(resp,'Continue')
            set(handles.verify, 'visible', 'off');
            set(handles.stop,'visible','on')
            set(handles.back,'visible','off')
            set(handles.clock,'visible','on')
            
            RT = str2num(get(handles.SessionnDur,'String'));
            
            % Start stimulation
            if ~handles.dummy
                queueOutputData(handles.s,handles.wave);
                handles.s.startBackground();
            end
            
            tic
            while (stopStim) && toc <= RT*60
                elapsed = datestr(toc./(60*60*24), 'MM:SS');
                set(handles.clock,'String', sprintf(['Time: ' elapsed]))
                drawnow
            end
            
            if ~handles.dummy
                stop(handles.s)
                handles.output_data1 = 0;
                queueOutputData(handles.s,handles.output_data1);
                startForeground(handles.s);
            end
        else
            set(handles.verify, 'String', 'Verify');
            set(handles.back,'visible','off')
        end
        
    else
        resp = questdlg('You are about to confirm your final waveform', 'Verify', ...
            'Continue','Go Back','Go Back');
        if strcmp(resp,'Continue')
            set(handles.verify, 'String', 'Start');
            set(handles.back,'visible','on')
            handles.start = 1;
        end
    end
end

% Update handles structure
guidata(hObject, handles);


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

[inputParam,w] = checkParam(handles);

if ~w
    try
        handles.wave = make_tVNS_wave(inputParam);
        
        RT = str2num(get(handles.SessionnDur,'String'));
        
        x = linspace(0,RT*60,numel(handles.wave));
        axes(handles.pulseFig)
        plot(x,handles.wave)
        zoom reset
        curYLim = ylim;
        ylim([curYLim(1) curYLim(2)*2])
        datacursormode on
        set(gcf,'toolbar','figure'); 
        title('Your Waveform (click and drag to zoom)')
        xlabel('Seconds')
    catch
         warndlg('Problem creating waveform.');
    end
end

% Update handles structure
guidata(hObject, handles);


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

set(handles.verify, 'String', 'Verify Graph');
set(handles.back,'visible','off')
handles.start = 0;

% Update handles structure
guidata(hObject, handles);
        
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global stopStim
stopStim = 0;

drawnow

% Try to release the device if it was quit suddenly
try
    stop(handles.s)
    release(handles.s)
catch

end

% Hint: delete(hObject) closes the figure
delete(hObject);


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

% Try to release the device
% toc
global stopStim
stopStim = 0;
drawnow

set(handles.stop,'Enable','off')

try
    %Stop Stim
    stop(handles.s)
    drawnow
catch
end
guidata(hObject, handles);

function burstFreq_Callback(hObject, eventdata, handles)
% hObject    handle to burstFreq (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 burstFreq as text
%        str2double(get(hObject,'String')) returns contents of burstFreq as a double

% Update handles structure
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function burstFreq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to burstFreq (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

function ppb_Callback(hObject, eventdata, handles)
% hObject    handle to ppb (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 ppb as text
%        str2double(get(hObject,'String')) returns contents of ppb as a double


% --- Executes during object creation, after setting all properties.
function ppb_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ppb (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

function waveform = make_tVNS_wave(input)
% This script sets up a waveform to apply to a National Instruments
% converter. Currently coded as a square wave
%
% input : 1x4 vector with [freq, ITI,runTime, trialLngth]

buffer = [];        %buffer of zeros 
volt = 5;            %pulse voltage
sRate = 40000;      %Sampling frequency
pulseW = .00005;    %Pulse width in seconds

wFreq = input(1);       %Pulse frequency in Hz
wITI = input(2);         %Inter trial interval 'off time'
wTrialLngth = input(3);   % 'on' time
wRnTme =input(4)*60;        %Experiment time sec

if numel(input)== 4
     repNum = wRnTme/(wITI+wTrialLngth);  %number of times to repeat a trial
    
     if ~isinteger(repNum)
        %If the trial length and experiment time don't match, add a buffer
        %of zeros
        repNum = floor(repNum);
        buffer = zeros(1,sRate*(wRnTme-repNum*(wITI+wTrialLngth)));
     end
     
    %create pulse wave 
    t = 0 : 1/sRate : (wTrialLngth+wITI);
    d = pulseW/2: 1/wFreq : wTrialLngth; 
    y =pulstran(t,d,'rectpuls',pulseW);
    
    %adjust w/buffers
    y(end)= [];
    waveform = repmat(y',repNum,1);
    waveform = [waveform buffer];
    
else 
    wBurstFreq = input(5);
    wNumPulse = input(6);
    
    burstNum = wTrialLngth*wBurstFreq; %# bursts to repeat 

    if ~isinteger(burstNum)
        burstNum = floor(burstNum);
        burstBuffer = zeros(1,(wTrialLngth - (burstNum/wBurstFreq))*sRate);
    end
    
    %create waveform
    t = 0 : 1/sRate : 1/wBurstFreq; % sampling frequency 
    d = pulseW/2: 1/wFreq : (wNumPulse)/wFreq; %repetition frequency   
    y =pulstran(t,d,'rectpuls',pulseW);
    
    %repeat trial/burst units
    y(end) = [];    
    waveform = repmat(y',burstNum,1);
    waveform = [waveform' burstBuffer zeros(1,sRate*wITI)];
    waveform = [repmat(waveform,1,5) buffer];
    
end

% Apply scaler
waveform = volt*waveform;

function [inputParam,wrng] = checkParam(handles)

flag = get(handles.brstMd, 'Value');
wrng = 0;

freq = str2num(get(handles.Hz,'String'));
ITI = str2num(get(handles.iti,'String'));
TL = str2num(get(handles.trialLngth,'String'));
RT = str2num(get(handles.SessionnDur,'String'));

BF = str2num(get(handles.burstFreq,'String'));
PPB = str2num(get(handles.ppb,'String'));

if isempty(freq) || isempty(ITI) || isempty(TL) || isempty(RT)
   warndlg('Please enter all parameters. Use only Numbers.');
   wrng = 1;
else
    inputParam = [freq, ITI, TL, RT];
end

if flag
    if isempty(BF) || isempty(PPB) 
        warndlg('Please enter all parameters. Use only Numbers.');
        wrng = 1;
    else
        inputParam = [inputParam, BF, PPB];
    end
end
