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

% Last Modified by GUIDE v2.5 27-Apr-2009 12:18:37

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

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

handles.sPort = 'COM5';
handles.s = serial(handles.sPort, 'BaudRate', 9600, 'Terminator', 13, 'Timeout', 1);
handles.dFile = 'accelerometerDataOut.txt';

handles.x = [0]; handles.y = [0]; handles.z = [0]; 
handles.a = [0];
handles.t = [0];

handles.wThresh = 0;
handles.rThresh = 0;

axes(handles.aplot)
handles.aplotH = scatter(handles.aplot, handles.t,handles.a,'.');
set(get(gca,'YLabel'),'String','Magnitude of Acceleration');

axes(handles.xplot)
handles.xplotH = scatter(handles.xplot, handles.t,handles.x,'.');
set(get(gca,'YLabel'),'String','X Acceleration');

axes(handles.yplot)
handles.yplotH = scatter(handles.yplot, handles.t,handles.y,'.');
set(get(gca,'YLabel'),'String','Y Acceleration');

axes(handles.zplot)
handles.zplotH = scatter(handles.zplot, handles.t,handles.z,'.');
set(get(gca,'YLabel'),'String','Z Acceleration');

handles.wThresh = 0;
handles.rThresh = 0;

axes(handles.aplot);
handles.waLine = line([handles.t(1) handles.t(length(handles.t))], [300 300], 'Color', 'w');
axes(handles.xplot);
handles.wxLine = line([handles.t(1) handles.t(length(handles.t))], [200 200], 'Color', 'w');
axes(handles.yplot);
handles.wyLine = line([handles.t(1) handles.t(length(handles.t))], [160 160], 'Color', 'w');
axes(handles.zplot);
handles.wzLine = line([handles.t(1) handles.t(length(handles.t))], [150 150], 'Color', 'w');

axes(handles.aplot);
handles.raLine = line([handles.t(1) handles.t(length(handles.t))], [350 350], 'Color', 'w');
axes(handles.xplot);
handles.rxLine = line([handles.t(1) handles.t(length(handles.t))], [250 250], 'Color', 'w');
axes(handles.yplot);
handles.ryLine = line([handles.t(1) handles.t(length(handles.t))], [175 175], 'Color', 'w');
axes(handles.zplot);
handles.rzLine = line([handles.t(1) handles.t(length(handles.t))], [165 165], 'Color', 'w');

handles.tcount = 0;
handles.told = 0;
handles.tend = 500;
handles.numSamples = 0;
handles.sleepingCount = 0;

% Update handles structure
guidata(hObject, handles);

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

function serialPort_Callback(hObject, eventdata, handles)
% hObject    handle to serialPort (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 serialPort as text
%        str2double(get(hObject,'String')) returns contents of serialPort as a double
handles.sPort = get(hObject,'String');

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

function dataFile_Callback(hObject, eventdata, handles)
% hObject    handle to dataFile (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 dataFile as text
%        str2double(get(hObject,'String')) returns contents of dataFile as a double
handles.dFile = get(hObject,'String');
if(exist(handles.dFile, 'file') == 0)
    save(handles.dFile)
end

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

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

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

switch get(handles.thresholdPullDownMenu,'Value')   
    case 1
        handles.wThresh = 0;
        handles.rThresh = 0;
    case 2
        handles.wThresh = 1;
        handles.rThresh = 0;
    case 3
        handles.wThresh = 0;
        handles.rThresh = 1;
    case 4
        handles.wThresh = 1;
        handles.rThresh = 1;
    otherwise
end
guidata(hObject, handles);

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

% --- Executes on button press in startButton.
function startButton_Callback(hObject, eventdata, handles)
% hObject    handle to startButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if(exist(handles.dFile, 'file') == 0)
    save handles.dFile;
end

handles.s = serial(handles.sPort, 'BaudRate', 9600, 'Terminator', 13, 'Timeout', 1);

status = get(handles.s, 'Status'); % check to see if serial connection open
if (strcmp(status,'open'))
else
    fopen(handles.s);
end
    
set(handles.startButton,'UserData',1); 

%while the flag variable is one, the loop continues
while (get(handles.startButton,'UserData') == 1)

    status = get(handles.s, 'Status'); % check to see if serial connection open
    if (strcmp(status,'open'))
    
        fprintf(handles.s,''); pause(.0001);

        out = fgetl(handles.s); pause(.0001);   
        out = fgetl(handles.s); pause(.0001);   
        out = fgetl(handles.s); pause(.0001);    

        if(length(out)>3)
            if(out(2)=='(' && out(length(out)-1)==')')

                handles.sleepingCount = 0;
                set(handles.statusText,'String','Plotting New Data From The Serial Port');

                out = strrep(out, '(', '');
                out = strrep(out, ')', '');

                [xt rem] = strtok(out);
                xtemp = str2num(xt);
                [yt rem] = strtok(rem);
                ytemp = str2num(yt);
                [zt rem] = strtok(rem);
                ztemp = str2num(zt);
                [tt rem] = strtok(rem);
                ttemp = str2num(tt);
                if(ttemp < handles.told)
                    handles.tcount = handles.tcount+256;
                end
                handles.told = ttemp;
                ttemp = ttemp + handles.tcount;

                save handles.dFile 'xtemp' 'ytemp' 'ztemp' 'ttemp' -append -ASCII -tabs;

                if(isempty(yt)||isempty(zt)||isempty(tt)||(xtemp>4096)||(ytemp>4096)||(ztemp>4096)||(length(rem)>1))
                else
                    handles.numSamples = handles.numSamples + 1;
                    if(handles.numSamples<handles.tend)
                        handles.x = [handles.x xtemp];
                        handles.y = [handles.y ytemp];
                        handles.z = [handles.z ztemp];

                        xytemp = nthroot((xtemp^2+ytemp^2), 2);
                        atemp = nthroot((xytemp^2+ztemp^2), 2);

                        handles.t = [handles.t ttemp];
                        handles.a = [handles.a atemp];
                    else
                        handles.x = [handles.x(2:(handles.tend-1)) xtemp];
                        handles.y = [handles.y(2:(handles.tend-1)) ytemp];
                        handles.z = [handles.z(2:(handles.tend-1)) ztemp];

                        xytemp = nthroot((xtemp^2+ytemp^2), 2);
                        atemp = nthroot((xytemp^2+ztemp^2), 2);

                        handles.t = [handles.t(2:(handles.tend-1)) ttemp];
                        handles.a = [handles.a(2:(handles.tend-1)) atemp];
                    end

                    set(handles.aplotH, 'XData', handles.t, 'YData', handles.a);
                    set(handles.xplotH, 'XData', handles.t, 'YData', handles.x);
                    set(handles.yplotH, 'XData', handles.t, 'YData', handles.y);
                    set(handles.zplotH, 'XData', handles.t, 'YData', handles.z);

                    if(handles.wThresh == 0)
                        axes(handles.aplot);
                        handles.waLine = line([handles.t(1) handles.t(length(handles.t))], [300 300], 'Color', 'w');
                        axes(handles.xplot);
                        handles.wxLine = line([handles.t(1) handles.t(length(handles.t))], [200 200], 'Color', 'w');
                        axes(handles.yplot);
                        handles.wyLine = line([handles.t(1) handles.t(length(handles.t))], [160 160], 'Color', 'w');
                        axes(handles.zplot);
                        handles.wzLine = line([handles.t(1) handles.t(length(handles.t))], [150 150], 'Color', 'w');
                    end
                    if(handles.wThresh == 1)
                        axes(handles.aplot);
                        handles.waLine = line([handles.t(1) handles.t(length(handles.t))], [300 300], 'Color', 'g');
                        axes(handles.xplot);
                        handles.wxLine = line([handles.t(1) handles.t(length(handles.t))], [200 200], 'Color', 'g');
                        axes(handles.yplot);
                        handles.wyLine = line([handles.t(1) handles.t(length(handles.t))], [160 160], 'Color', 'g');
                        axes(handles.zplot);
                        handles.wzLine = line([handles.t(1) handles.t(length(handles.t))], [150 150], 'Color', 'g');
                    end
                    if(handles.rThresh == 0)
                        axes(handles.aplot);
                        handles.raLine = line([handles.t(1) handles.t(length(handles.t))], [350 350], 'Color', 'w');
                        axes(handles.xplot);
                        handles.rxLine = line([handles.t(1) handles.t(length(handles.t))], [250 250], 'Color', 'w');
                        axes(handles.yplot);
                        handles.ryLine = line([handles.t(1) handles.t(length(handles.t))], [175 175], 'Color', 'w');
                        axes(handles.zplot);
                        handles.rzLine = line([handles.t(1) handles.t(length(handles.t))], [165 165], 'Color', 'w');
                    end
                    if(handles.rThresh == 1)
                        axes(handles.aplot);
                        handles.raLine = line([handles.t(1) handles.t(length(handles.t))], [350 350], 'Color', 'r');
                        axes(handles.xplot);
                        handles.rxLine = line([handles.t(1) handles.t(length(handles.t))], [250 250], 'Color', 'r');
                        axes(handles.yplot);
                        handles.ryLine = line([handles.t(1) handles.t(length(handles.t))], [175 175], 'Color', 'r');
                        axes(handles.zplot);
                        handles.rzLine = line([handles.t(1) handles.t(length(handles.t))], [165 165], 'Color', 'r');
                    end
                end
            end
        end
        if(length(out)==1)
            handles.sleepingCount = handles.sleepingCount + 1;
            if(handles.sleepingCount > 5)
                set(handles.statusText,'String','Transmitter in Power Save Mode: Plotting Paused');
            end
        end
        %"flushes the event queue" and updates the figure window
        %since Matlab is a single thread process, this command is requierd
        drawnow
        guidata(hObject, handles);
    else
        set(handles.statusText,'String','Could Not Open Specified Serial Port');
    end
end


% --- Executes on button press in stopButton.
function stopButton_Callback(hObject, eventdata, handles)
% hObject    handle to stopButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.startButton,'UserData',0);
set(handles.statusText,'String','Plotting Stopped');

%pause(5); %wait for plotting to recognize that needs to stop

status = get(handles.s, 'Status'); % check to see if serial connection open
if (strcmp(status,'open'))
    fclose(handles.s);
end
guidata(hObject, handles);

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

axes(handles.aplot);
handles.waLine = line([handles.t(1) handles.t(length(handles.t))], [300 300], 'Color', 'w');
axes(handles.xplot);
handles.wxLine = line([handles.t(1) handles.t(length(handles.t))], [200 200], 'Color', 'w');
axes(handles.yplot);
handles.wyLine = line([handles.t(1) handles.t(length(handles.t))], [160 160], 'Color', 'w');
axes(handles.zplot);
handles.wzLine = line([handles.t(1) handles.t(length(handles.t))], [150 150], 'Color', 'w');

axes(handles.aplot);
handles.raLine = line([handles.t(1) handles.t(length(handles.t))], [350 350], 'Color', 'w');
axes(handles.xplot);
handles.rxLine = line([handles.t(1) handles.t(length(handles.t))], [250 250], 'Color', 'w');
axes(handles.yplot);
handles.ryLine = line([handles.t(1) handles.t(length(handles.t))], [175 175], 'Color', 'w');
axes(handles.zplot);
handles.rzLine = line([handles.t(1) handles.t(length(handles.t))], [165 165], 'Color', 'w');

handles.a = [0];
handles.x = [0]; handles.y = [0]; handles.z = [0];
handles.t = [0];

handles.tcount = 0;
handles.told = 0;
handles.numSamples = 0;

set(handles.statusText,'String','Begin Plotting Now');
 
set(handles.aplotH, 'XData', handles.t, 'YData', handles.a);
set(handles.xplotH, 'XData', handles.t, 'YData', handles.x);
set(handles.yplotH, 'XData', handles.t, 'YData', handles.y);
set(handles.zplotH, 'XData', handles.t, 'YData', handles.z);

guidata(hObject, handles);

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




