%% Use the following commands to clear serial port after/before every use
% close all
% clear
%     if ~isempty(instrfind)
%      fclose(instrfind);
%       delete(instrfind);
%     end
% load('frcnn_semiWorking.mat', 'frcnn')
% emotionDetector = frcnn

%%
% clears object
vidObj = 0; 
% add webcam object
vidObj = webcam;
% customize webcam resolution
vidObj.Resolution = '320x240'
% load Viola-Jone Algorithm to detect faces
faceDetector = vision.CascadeObjectDetector();
% Kanade-Lucas-Tomasi (KLT) algorithm to track objects
tracker = MultiObjectTrackerKLT;


%% Get a frame for frame-size information
frame = snapshot(vidObj);
frameSize = size(frame);


arduino = serial('COM7','BaudRate',9600);
fopen(arduino);
if isvalid (arduino) == 1
    deviceCondition = 'connection established!'
else
    deviceCondition = 'No connection established!!'
end

go = true;
while go
    
if arduino.BytesAvailable
    parameter = fgetl(arduino);
    if parameter == '1'
                 initiateFRCNN = 'starting facial recognition'
        %% Create a video player instance
        videoPlayer  = vision.VideoPlayer('Position',[200 100 fliplr(frameSize(1:2)+30)]);
        bboxes = [];
        while isempty(bboxes)
            framergb = snapshot(vidObj);
            frame = rgb2gray(framergb);
            bboxes = faceDetector.step(frame);
        end
        tracker.addDetections(frame, bboxes);
        %% And loop until the player is closed
        frameNumber = 0;
        keepRunning = true;
        disp('Press Ctrl-C to exit...');
        while keepRunning
            
            framergb = snapshot(vidObj);
            frame = rgb2gray(framergb);
            
            if mod(frameNumber, 10) == 0

                bboxes = 2 * faceDetector.step(imresize(frame, 0.5));
                [bboxes2,scores,labels] = detect(emotionDetector,framergb)
                rois = [bboxes2];
                if ~isempty(bboxes)
                    tracker.addDetections(frame, bboxes);
                end
            else
                % Track faces
                tracker.track(frame);
            end
          
            % Display bounding boxes and tracked points.
% %             displayFrame = insertObjectAnnotation(framergb, 'rectangle',...
% %                 tracker.Bboxes, tracker.BoxIds);
            if ~isempty(bboxes2)
                displayFrame = insertObjectAnnotation(framergb, 'rectangle',...
                    rois,cellstr(labels));
            end
            videoPlayer.step(displayFrame);
            
            frameNumber = frameNumber + 1;
        end
        %% Clean up
        release(videoPlayer);
    end
    
    
    if parameter == '0'
        inititateFRCNN = 'stop facial recognition'
    end
end

end
