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

% Last Modified by GUIDE v2.5 13-Dec-2012 12:47:14

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @guitest_OpeningFcn, ...
                   'gui_OutputFcn',  @guitest_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 guitest is made visible.
function guitest_OpeningFcn(hObject, eventdata, handles, varargin)
handles = guidata(hObject);

handles.sframe=0;
handles.M=zeros(1,11);
handles.video=0;
a=imaqhwinfo;
camera_name = char(a.InstalledAdaptors);
camera_info = imaqhwinfo(camera_name);
[A,B]=size(camera_info.DeviceIDs);

for k = 1 : B
        C=camera_info.DeviceInfo(1,k).DeviceName;
        dropdownListStrings{k+2}=sprintf(C, num2str(k));
end
dropdownListStrings{1}=['Image from file'];
dropdownListStrings{2}=['DEMO'];
uicontrol('Style', 'popup',...
          'Position', [20 455 200 60],...
          'String', dropdownListStrings,...
          'Callback' , @popupmenu1_Callback );
      
      
handles.log = uitable('Position', [20 5 530 20]);
handles.t = uitable('Position', [20 20 530 100]);
set(handles.t, 'ColumnName', {'Object', 'Compilancy', 'Bounding box 1', ...
                              'Bounding box 2', 'Red', 'Green', 'Blue', ...
                              'Centroid 1','Centroid 2'});
set(handles.t, 'RowName', []);  
set(handles.log, 'RowName', []);
set(handles.log, 'ColumnName',[]);
                        
% Choose default command line output for guitest
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
end
end


function varargout = guitest_OutputFcn(hObject, eventdata, handles) 
varargout{1} = handles.output;
end

%select image input
function popupmenu1_Callback(hObject, eventdata, handles) 
handles = guidata(hObject);
val = get(hObject,'Value');

%from file
if val == 1
    [FileName,PathName] = uigetfile('*.tif','Select image');
    Imwork=imread(FileName);
    handles.Imwork = imresize(Imwork, [240 320]);
    imshow(handles.Imwork,'Parent', handles.axes4);
    handles.mode=0;
%demo mode
elseif val == 2
    handles.imagelist = dir('*.tif');
    handles.N = numel(handles.imagelist);
    handles.Imback = imread(handles.imagelist(1).name);
    handles.Imback = imresize(handles.Imback, [240 320]);
    handles.Imwork=imread(handles.imagelist(1).name);
    handles.Imwork = imresize(handles.Imwork, [240 320]);
    imshow(handles.Imwork,'Parent', handles.axes4);
    handles.mode=2;
    handles.modeb=2;
%camara 1
elseif val == 3
    handles.video = videoinput('winvideo', 1);
    set(handles.video, 'FramesPerTrigger', Inf);
    set(handles.video, 'ReturnedColorspace', 'rgb');
    handles.video.FrameGrabInterval = 5;
    vidRes = get(handles.video, 'VideoResolution');
    nBands = get(handles.video, 'NumberOfBands');
    hImage = image(zeros(vidRes(2),vidRes(1), nBands),'Parent',handles.axes4);
    start(handles.video);
    preview(handles.video, hImage);
    handles.mode=1;
%camara 2
elseif val == 4
    handles.video = videoinput('winvideo', 2);
    set(handles.video, 'FramesPerTrigger', Inf);
    set(handles.video, 'ReturnedColorspace', 'rgb');
    handles.video.FrameGrabInterval = 5;
    vidRes = get(handles.video, 'VideoResolution');
    nBands = get(handles.video, 'NumberOfBands');
    hImage = image(zeros(vidRes(2),vidRes(1), nBands),'Parent',handles.axes4);
    start(handles.video);
    preview(handles.video, hImage);
    handles.mode=1;
end


   
% Update handles structure
guidata(hObject, handles);
end


function popupmenu1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
end

%select background
function popupmenu2_Callback(hObject, eventdata, handles)
handles = guidata(hObject);

val = get(hObject,'Value');
if val == 1
    [FileName,PathName] = uigetfile('*.tif','Select background image');
    Imback=imread(FileName);
    handles.Imback = imresize(Imback, [240 320]);
    handles.modeb=0;
elseif val == 2
    handles.imagelist = dir('*.tif');
    handles.N = numel(handles.imagelist);
    handles.Imback = imread(handles.imagelist(1).name);
    handles.Imback = imresize(handles.Imback, [240 320]);
    handles.Imwork=imread(handles.imagelist(1).name);
    handles.Imwork = imresize(handles.Imwork, [240 320]);
    imshow(handles.Imwork,'Parent', handles.axes4);
    handles.mode=2;
    handles.modeb=2;
elseif val == 3
    preview(handles.video);
    Imback = getsnapshot(handles.video);
    handles.Imback = imresize(Imback, [240 320]);    
    handles.modeb=1;
end

imshow(handles.Imback,'Parent', handles.axes2);
   
% Update handles structure
guidata(hObject, handles);
end


function popupmenu2_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
end

%START
function togglebutton1_Callback(hObject, eventdata, handles)
handles = guidata(hObject);


if handles.mode == 0 || handles.modeb == 0
    tic
    Imwork=handles.Imwork;
    Imback=handles.Imback;
    im=rgb2gray(Imwork);
    bg=rgb2gray(handles.Imback);
    bgim=imabsdiff(bg,im);    
    dif=sum(sum(bgim));
    if dif > 0  
        [nobg,fore]=removebackground(Imwork,Imback);
        imshow(fore,'Parent',handles.axes3);
        S=objectstat(nobg,fore);
        if sum(handles.M)==0 
            handles.M=S; 
        else
           [S,handles.M]=matrixfind2(S,handles.M);
        end
        imshow(Imwork,'Parent',handles.axes6);
        objecttext(S)
        set(handles.t, 'Data', handles.M);
    else
        set(handles.log,'Data',{'error: no object found'});
    end 
    
    %time control display
    v=toc;
    uicontrol('position',[500,150,50,10],'style','edit','string',v);
    v=0;
    
    %frame counter   
    uicontrol('position',[500,190,50,10],'style','edit','string',handles.sframe);
    handles.sframe=handles.sframe+1;
    
    
elseif handles.mode==1 || handles.modeb==1
    %closepreview(handles.video);
    bg=rgb2gray(handles.Imback);
    for i=0:60
        
    tic   
    Imwork=getsnapshot(handles.video);
    Imwork = imresize(Imwork, [240 320]);
    
    im=rgb2gray(Imwork);
    bgim=imabsdiff(bg,im);    
    dif=sum(sum(bgim));
    
    %si la diferencia es mayor que 150k interpretamos
    if dif > 150000
        [nobg,fore]=removebackground(Imwork,handles.Imback);
        imshow(fore,'Parent',handles.axes3);
           
        S=objectstat(nobg,fore);
        
        %si la matriz maestra es nula, inicializamos con S
        if sum(handles.M)==0 
            handles.M=S; 
        else
        [S,handles.M]=matrixfind2(S,handles.M);
        end
        imshow(Imwork,'Parent',handles.axes6);
        objecttext(S)
    %si no es mayor que 150k, error no hay objeto
    else
        fore=zeros(240,320);
        set(handles.log, 'Data', {'error: no object found'});
        imshow(fore,'Parent',handles.axes3);
    end
    
    %Show master matrix in data box t
    set(handles.t, 'Data', handles.M);
    
    %time control display
    v=toc;
    uicontrol('position',[500,150,50,10],'style','edit','string',v);
    v=0;
    
    %frame counter
    uicontrol('position',[500,190,50,10],'style','edit','string',i);
    

    end
    stop(handles.video);
    flushdata(handles.video);
elseif handles.mode==2 || handles.modeb==2
    Imback=handles.Imback;
    bg=rgb2gray(Imback);
    for k = 2: handles.N
        tic
        Imwork=imread(handles.imagelist(k).name);    
        Imwork = imresize(Imwork, [240 320]);
        im=rgb2gray(Imwork);
        bgim=imabsdiff(bg,im);    
        dif=sum(sum(bgim));
        if dif > 0  
            [nobg,fore]=removebackground(Imwork,Imback);
            imshow(fore,'Parent',handles.axes3);
            S=objectstat(nobg,fore);
            if sum(handles.M)==0 
                handles.M=S; 
            else
            [S,handles.M]=matrixfind2(S,handles.M);
            end
            imshow(Imwork,'Parent',handles.axes6);
            objecttext(S)
            set(handles.t, 'Data', handles.M);
        else
            set(handles.log,'Data',{'error: no object found'});
        end 
    
        %time control display
        v=toc;
        uicontrol('position',[500,150,50,10],'style','edit','string',v);
        v=0;
    
        %frame counter
        uicontrol('position',[500,190,50,10],'style','edit','string',handles.sframe);
        handles.sframe=handles.sframe+1;   
        pause(0.5);
    end
    
else
    set(handles.log, 'Data', {'error: input & backround missmatch'});
end



% Update handles structure
guidata(hObject, handles);
end


% --- Executes on button press in togglebutton2.
function togglebutton2_Callback(hObject, eventdata, handles)
handles = guidata(hObject);

handles.sframe=0;
handles.M=zeros(1,11);
set(handles.log, 'Data', {'reset variables'});
set(handles.t, 'Data', handles.M);
if handles.video ~= 0
    stop(handles.video)
    flushdata(handles.video)
end


% Update handles structure
guidata(hObject, handles);
end
