function serialObj = openSerialWithHandles(portNumber,handles)
%portNumber = 8;
portStr = sprintf('COM%d',portNumber);
fprintf('Connecting to %s...',portStr);
serialObj = serial(portStr, 'BaudRate', 19200,...
    'TimeOut',1,...
    'Terminator',10,...
    'BytesAvailableFcnMode','terminator',...
    'BytesAvailableFcn',{@serial_PICDEM_BytesAvailableFcn,handles});
fprintf('Status is %s\n',serialObj.Status);
fprintf('Opening...');
fopen(serialObj);
fprintf('Status is %s\n',serialObj.Status);
end

function serial_PICDEM_BytesAvailableFcn(serialObj, eventData, handles)
%serial_PICDEM_BytesAvailableFcn bytes from serial object
%  This is the callback function after a 'terminator' is received

% Get time value
time = eventData.Data.AbsTime;
year = time(1);month = time(2);day = time(3);hour = time(4);minute = time(5);second = time(6);

if (hour > 13)
    hour = hour - 12;    amPm = 'pm';
elseif (hour == 0)
    hour = 12;    amPm = 'am';
else
    amPm = 'am';
end

numChars = get(serialObj, 'BytesAvailable');
% Assuming there is a message print to screen and process it
if(numChars > 0)
    [charRead,numRead,errorMsg] = fread(serialObj,numChars,'char');
    receivedCommand = char(charRead');
    fprintf('On %d/%d/%d at %d:%0.2d%s (%d secs) received %d char(s) = \n%s \n',...
        month,day,year,hour,minute,amPm,second, numRead, receivedCommand);

    % Up to 3 commands come in together, break each up using 'Terminator'
    remain = receivedCommand;
    while true
        [str, remain] = strtok(remain, 10);
        if isempty(str),  break;  end
        processCommand(str,handles)
    end
    
end
end

function processCommand(receivedCommand,handles)
%PROCESSCOMMAND Breaks up the recieved command to process appropriately

% Break up the string into pieces
receivedStrings = textscan(receivedCommand, '%s %s %s %s');

% Determine number of string pieces
numStrings = 0;
while(numStrings <= 3 && ~isempty(receivedStrings{numStrings+1}))
    numStrings = numStrings+1;
end

%Printing out info for debugging.  Remove when finished
%fprintf('numStrings = %d\n',numStrings);
%receivedStrings

% TODO: Add your code here to update the static text boxes of the GUI

end