clear all
%%
%.... get info about the devices connected to the computers
%.... get adaptors
%imaqhwinfo
%.... get info about adaptor, where adaptor is named 'winvideo'
%imaqhwinfo('winvideo')
%....  get device ID and other info
%my_cam = imaqhwinfo ('winvideo',1)

%%

%.... construct video object
obj_test  = videoinput('winvideo','Logitech QuickCam Pro 4000','RGB24_640x480');

%%
%.... preview video
% preview(obj_test);


%% 
% configure triggering type - if not manual after start will stop
% imediately after aquring the default number of frames
triggerconfig(obj_test,'manual');
% configure number of frames per trigger
obj_test.FramesPerTrigger = 1;
%%
% start the object = video input streaming; 
start(obj_test);
% leave the camera to make the initial setup
pause (6);
%% 
% start the main loop of the program
if isrunning(obj_test) == 1
    
    % the stop condition is given by exit_buton state 
    % or video input streaming interuption
    
    % initialize variables
    exit_condition = 1;  % condition for ending the program loop
    wait_time = 3;       % waiting time for grabing a new loop
    threshold =  2200000;        % threshold value for movement/change detection
    table_pos = zeros(2,2);
    bord_det = zeros(9,2);
    
    curr_img = peekdata(obj_test,1);
    bord_det =  board_detect(rgb2gray(curr_img));
    last_image = curr_img; 
    golden_frame = curr_img;
    old_game_config = [16 0 16 0 16 0 16 0;
                        0 16 0 16 0 16 0 16;
                        16 0 16 0 16 0 16 0;
                        0 16 0 16 0 16 0 16;
                        16 0 16 0 16 0 16 0;
                        0 16 0 16 0 16 0 16;
                        16 0 16 0 16 0 16 0;
                        0 16 0 16 0 16 0 16];

     
    pause (1);
    color_suggest = 1; % for which player to give suggestion
    old_color = 1;
    
    % create the GUI
    figure(1);
    set(1, 'Position',[100 100 1000 400]);
    uicontrol(  'Parent',1, ...
        'Style', 'pushbutton', ...
        'Callback', 'exit_condition=0;', ...
        'Position',[0 0 100 20], ...
        'String', 'Exit/Stop', ...
        'Tag','Exit_button');

    checkbox1 = uicontrol(  'Parent',1, ...
        'Style', 'checkbox', ...
        'Callback', 'checkbox1Callback(checkbox1);', ...
        'Position',[102 0 150 20], ...
        'String', 'Color_of_sugestion', ...
        'Tag','checkbox1');
    
    jwhile=0; % used for loop tracking
    
    while (exit_condition)

        jwhile =  jwhile+1    % used for while loop tracking  
        
        % grab a frame from the camera
        curr_img = peekdata(obj_test,1);
      
        
        % perform movement tracking of the scene, threshold = 2200000
        table_pos = [bord_det(1,1) bord_det(1,2); bord_det(9,1) bord_det(9,2)];
        is_similar = isSimilar(curr_img, golden_frame, threshold, table_pos);
                                
        if is_similar == 1
                                 
            % replace golden_frame with the new one;
            golden_frame = curr_img;

            % detect board
            bord_det =  board_detect(rgb2gray(curr_img));

            % extract game position
            [game_config positions] = game_extraction( curr_img ,bord_det);

            % draw gui if detection_is_made

            % scientifical part of GUI
            %----------------------------------------------------------
           
            subplot(1,2,1);
            imshow(curr_img);
            text(320, -30, 'Science-View: detection results', ...
                'HorizontalAlignment','center',...
                'FontSize', 12, 'FontWeight', 'bold' );
                        
            % draw the pieces
            for i=1:1:24
                if (positions(i,1) ~= 0)
                    rectangle('Position',[positions(i,2)-12 , positions(i,1)-12, 25 , 25], ...
                        'EdgeColor','r', 'LineWidth', 2, 'Curvature', 1 );
                end
            end

            % draw the board
            for i=1:9
                for j=1:9
                    hold on;
                    plot(bord_det(i,1), bord_det(j,2), 'r*');
                end;
            end;
            
            % user part of GUI
            %----------------------------------------------------------
            subplot(1,2,2);
            imshow(curr_img);
            text(320, -30, 'User-view: suggestion', ...
                'HorizontalAlignment','center',...
                'FontSize', 12, 'FontWeight', 'bold' );

            % check for detected game position changes or
            % for player color changes
            game_change = sum(sum(abs(game_config - old_game_config)));
            color_suggest = get(checkbox1, 'Value');

            if ((game_change ~= 0) || (color_suggest ~= old_color ))  % there are changes
                % get new game suggestion
                [from to suggest] = getmove(game_config, (color_suggest+1))
                old_color = color_suggest;
            end

            % check the value of the suggestion
            if (strcmp (suggest, 'Invalid game state')== 1 )
                text(320, 500,suggest, ...
                    'HorizontalAlignment','center',...
                    'FontSize', 10, 'FontWeight', 'bold' );
            else
                % use draw_det and sugest variables to draw the on the board
                [arr_orr arr_head] = arrow_position(positions, bord_det, to,from);
                arrow(arr_orr,arr_head, 'LineWidth', 2, 'EdgeColor', 'r', 'FaceColor','r' );
                text(320, 500, strcat('suggested move: ',suggest), ...
                    'HorizontalAlignment','center',...
                    'FontSize', 10, 'FontWeight', 'bold' );
                drawLabels(table_pos);
            end

            % set the waiting time for grabbing the new frame
            wait_time = 1;

        else   % if not similar
            % set the waiting time for grabbing the new frame
            wait_time = 1;
        end

        old_game_config = game_config; % save game config ; need for game state tracking
        last_image = curr_img; % save frame; need for movement detection
        
        pause (wait_time);     % wait the specified waiting_time before grabbing a new frame
    end % end while

trigger (obj_test); % trigger the camera before exiting to avoid errors
end

%%
% after finish working clean up
delete(obj_test)
clear obj_test

close (1)  

clear all
%%
