clear;
clc;
close all
try
    fclose(instrfind) %close any bogus serial connections
end

img = zeros(4800,1);
s = serial('com4','baudrate',38400,'databits',8,'parity','none','stopbits',1);
fopen(s);
%basic setting for serial communication
last_num=0;
last_gesture='NULL';%used to judge the gesture

while 1
    close all
    fprintf(s,'t');
    fscanf(s); %fscanf will firstly read 's'   
    data=0;
    img_length=1;
    flag=0;
    while(img_length<=4800)
        data=fscanf(s,'%d');
        i=1;
        for i = 1:data
            if(flag~=0)
                img(img_length)=255;
            else
                img(img_length)=0;
            end
            img_length=img_length+1;    
        end
        flag=~flag;
    end
	%extract the pictures come from MCU
    b=uint8(reshape(img,80,60));
    pic =zeros(70,50);
    num=0;
    for i=1:70
        for j=1:50
            pic(i,j)=b(i+5,j+5);
            if(pic(i,j)<128)
                num=num+1;
            end      
        end
    end
    %get rid of edge noise
    figure,imshow(pic);
    %judge if we get the available picture
    if(num<400)
        gesture='NULL'

    else
        gesture=imageprocess(pic);
        %call image process function to do the judgement
        if (strcmp(gesture,last_gesture))
            if(strcmp(gesture,'PAPER'))
               fprintf(s,'p');
               gesture
            elseif(strcmp(gesture,'ROCK'))
               fprintf(s,'r');
               gesture
            elseif(strcmp(gesture,'SCISSORS'))
               fprintf(s,'s');
               gesture
            elseif(strcmp(gesture,'SPOCK'))
               fprintf(s,'k');
               gesture
            elseif(strcmp(gesture,'LIZARD'))
               fprintf(s,'l');
               gesture
            end
			%send the result to MCU
            fscanf(s);
        end
        last_gesture=gesture;
    end
end
