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

% Last Modified by GUIDE v2.5 24-Feb-2010 23:42:38

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Chose_OpeningFcn, ...
                   'gui_OutputFcn',  @Chose_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 Chose is made visible.
function Chose_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Chose (see VARARGIN)

% Choose default command line output for Chose
handles.output = hObject;

% backgroundImage = importdata('Activemarker.png');
% % backgroundImage = importdata('Vicon_IQ_motion.jpg');
% % %select the axes
% axes(handles.sfondo);
% % %place image onto the axes
%  image(backgroundImage);
% % %remove the axis tick marks
%  axis off

handles.cams   = getappdata(0,'cams');
handles.voxels = getappdata(0,'voxels');
handles.space  = getappdata(0,'space');
handles.latovoxel = getappdata(0,'latovoxel');
handles.pixels = getappdata(0,'pixels');

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Chose wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Chose_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in push_next.
function push_next_Callback(hObject, eventdata, handles)
% hObject    handle to push_next (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if ~isfield(handles,'markers')
   errordlg('Non esiste il set di markers da analizzare',...
           'Incorrect Selection','modal')
else
  setappdata(0,'cams',handles.cams);
  setappdata(0,'voxels',handles.voxels);
  setappdata(0,'space',handles.space);
  setappdata(0,'latovoxel',handles.latovoxel);
  setappdata(0,'markers',handles.markers);
  setappdata(0,'pixels',handles.pixels);
  
  if get(handles.radio_dynamic,'value')==1
     setappdata(0,'mode',1);
     Mark4Cam
     close(Chose);
  else
    [handles.cams handles.voxels]=mark2vox(handles.markers, handles.cams,...
                                       handles.voxels,...
                                       handles.space,handles.latovoxel);
    for j=1:size(handles.cams,2)  
        set=[];
        n=size(handles.cams(j).setmarkers(1,:),2);
        for i=1:n
            a=rand(1);
            if a>0.1
                set=[set i];
            end
        end
        X_view=handles.cams(j).setmarkers(1,set);
        handles.cams(j).setmarkers_visti=X_view; 
    end
    setappdata(0,'cams',handles.cams);
    setappdata(0,'mode',0);
     
     Show_Tree
     close(Chose);
  end
end

function edit_num_markers_Callback(hObject, eventdata, handles)
% hObject    handle to edit_num_markers (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_num_markers as text
%        str2double(get(hObject,'String')) returns contents of edit_num_markers as a double


% --- Executes during object creation, after setting all properties.
function edit_num_markers_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_num_markers (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in push_genera.
function push_genera_Callback(hObject, eventdata, handles)
% hObject    handle to push_genera (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

num_mark = str2double(get(handles.edit_num_markers,'String'));
handles.markers = marker_generator(handles.space,num_mark);
% for i=1:size(handles.markers,2)
%     handles.markers(:,i);
% end

guidata(hObject,handles);

% --- Executes on button press in push_random.
function push_random_Callback(hObject, eventdata, handles)
% hObject    handle to push_random (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles.markers = marker_generator(handles.space);
guidata(hObject,handles);

% --- Executes on button press in push_import.
function push_import_Callback(hObject, eventdata, handles)
% hObject    handle to push_import (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

    list_entries = get(handles.listbox_workspace,'String');
    index_selected = get(handles.listbox_workspace,'Value');

    if length(index_selected) ~= 1
        errordlg('You must select 1 variable','Incorrect Selection','modal')
    else 
        var1 = list_entries{index_selected(1)};
        %var1.position
        handles.cams=evalin('base',var1);
        if ~isfield(handles.cams,'position') | ...
           ~isfield(handles.cams,'angles')   | ...
           ~isfield(handles.cams,'voxels')
            errordlg('Not a correct struct variable',...
                     'Incorrect Selection','modal');
        else
            set(handles.push_import,'visible','off');
            set(handles.push_import_mark,'visible','on');
            handles.pixels = handles.cams(1).intrinsic(1,3)
        end
        
    end 
    guidata(hObject,handles)
    

% --- Executes on selection change in listbox_workspace.
function listbox_workspace_Callback(hObject, eventdata, handles)
% hObject    handle to listbox_workspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox_workspace contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox_workspace


% --- Executes during object creation, after setting all properties.
function listbox_workspace_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox_workspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes when selected object is changed in uipanel_mode.
function uipanel_mode_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanel_mode 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
if hObject == handles.radio_static
    set(handles.uipanel_static,'visible','on');
    set(handles.uipanel_dynamic,'visible','off');
else
    set(handles.uipanel_static,'visible','off');
    set(handles.uipanel_dynamic,'visible','on');
end
guidata(hObject,handles);

% --- Executes when selected object is changed in uipanel_frame.
function uipanel_frame_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanel_frame 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)


% --- Executes when selected object is changed in uipanel_display.
function uipanel_display_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanel_display 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
if hObject == handles.radio_risultato
    set(handles.uipanel_sicuro,'visible','on');
else
    set(handles.uipanel_sicuro,'visible','off');
end
guidata(hObject,handles);

% --- Executes when selected object is changed in uipanel_chosegener.
function uipanel_chosegener_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in uipanel_chosegener 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)
if hObject == handles.radio_import
    set(handles.text_bug,'visible','off');
    set(handles.uipanel_genera,'visible','off');
    set(handles.listbox_workspace,'visible','on');
    set(handles.push_import,'visible','on');
    set(handles.push_import_mark,'visible','off');
    
    worksp = evalin('base','who')
    
    for i=1:length(worksp)
        worksp{i}
        %namevar=strcat('worksp.',names{i}); %name of the struct field
        clear (cell2str(worksp(1))) %locate the var in workspace
    end    
   
    set(handles.listbox_workspace,'String',[])
    
    [filename, pathname] = uigetfile({'*.mat';'*.*'}, 'open a matlab workspace');
    if numel(filename)
        
    % Call the loadc3d script
    FullFileName = [pathname, filename]
    dati=load(FullFileName)
    
    names = fieldnames(dati, '-full'); %recover the names of the fiields in the struct
    p=length(names); %number of fields

    for i=1:p 
    namevar=strcat('dati.',names{i}); %name of the struct field
    tempvar=eval(namevar); %recover the value of var in struct
    assignin('base',names{i},tempvar); %locate the var in workspace
    end    
    worksp = evalin('base','who')
    set(handles.listbox_workspace,'String',worksp);

    end
    clear filename pathname;
   
    
elseif hObject == handles.radiobutton11
    set(handles.text_bug,'visible','off');
    set(handles.push_import_mark,'visible','off');
    set(handles.uipanel_genera,'visible','on');
    set(handles.listbox_workspace,'visible','off');
    set(handles.push_import,'visible','off');
else hObject == handles.radio_import_mark
    set(handles.text_bug,'visible','on');
    set(handles.uipanel_genera,'visible','off');
    set(handles.listbox_workspace,'visible','off');
    set(handles.push_import,'visible','off');
    [filename, pathname] = uigetfile({'*.c3d';'*.m';'*.mdl';'*.mat';'*.*'}, 'Pick a C3D data file');
    if numel(filename)
    % Call the loadc3d script
    FullFileName = [pathname, filename];
    filename = C3D_VaxD2PC('ConvertFile', filename)
    [Markers, VideoFrameRate, AnalogSignals, AnalogFrameRate, Event, ParameterGroup, CameraInfo, ResidualError] = loadc3d(FullFileName);
    handles.markers=Markers(1,:,:)
    d=zeros(3,size(Markers,2));
    count=1;
    for i=1:size(Markers,2)
        %prendo il frame intermedio
        a=Markers(floor(size(Markers,2)/2),i,1)/1000+handles.space(1)/2;
        b=Markers(floor(size(Markers,2)/2),i,2)/1000+handles.space(2)/2;
        c=Markers(floor(size(Markers,2)/2),i,3)/1000;
        if a~=handles.space(1)/2 && b~=handles.space(2)/2 && c~=0
            d(:,i)=[a;b;c];
            count=count+1;
        end
    end
    d=d(1:3,1:count-1)
    handles.markers=d;
    
    %set(handles.popup_frame,'visible','on')
    end
    clear filename pathname;  
end
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function radio_static_CreateFcn(hObject, eventdata, handles)
% hObject    handle to radio_static (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function radio_dynamic_CreateFcn(hObject, eventdata, handles)
% hObject    handle to radio_dynamic (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function radiobutton11_CreateFcn(hObject, eventdata, handles)
% hObject    handle to radiobutton11 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function radio_import_CreateFcn(hObject, eventdata, handles)
% hObject    handle to radio_import (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function radio_risultato_CreateFcn(hObject, eventdata, handles)
% hObject    handle to radio_risultato (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function radio_passi_interm_CreateFcn(hObject, eventdata, handles)
% hObject    handle to radio_passi_interm (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes on button press in push_generaimg.
function push_generaimg_Callback(hObject, eventdata, handles)
% hObject    handle to push_generaimg (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

dP=(0.05)^2*ones(1,size(handles.markers,2));
[handles.cams handles.voxels]=mark2vox(handles.markers, handles.cams,...
                                       handles.voxels,...
                                       handles.space,handles.latovoxel);
X=real_marker(handles.markers,dP);
%lato=handles.latofig
lato=handles.pixels;

h = waitbar(0,'Please wait...', 'BarColor', 'r');
    dP=(0.05)^2*ones(1,size(handles.markers,2));
    X=real_marker(handles.markers,dP);
    for i=1:size(handles.cams,2)
    if ~isempty(handles.cams(i).setmarkers)
        [cams,P,raysf,uv_hat]= im_simulation(handles.markers,X,dP,handles.cams,i,handles.pixels,0.1,handles.cams(i).fov_angle);
        Real=genera_piano_3D(P, lato, handles.pixels, handles.cams(i).dist(1), handles.cams(i).dist(2), 50, 10000);
        handles.cams=cams;
        handles.cams(i).realimg=Real;
        handles.cams(i).fictiousimg=[uv_hat;raysf];
        [A,blob] = im_overlap(handles.markers,dP,handles.cams,i,Real,lato,pi/3);
        handles.cams(i).setmarkers(2,:) = A(2,:);
    end
     handles.cams
%     figure;
%     imshow(Real);
%     hold on
%     for j=1:size(uv_hat,2)
%     %     PlotCircle(uv_hat(1,i),uv_hat(2,i),rays(i),10000,color(i,:))
%         PlotCircle(uv_hat(1,j),uv_hat(2,j),rays(j),10000,'r');
%         hold on;
%     end
 waitbar(i/size(handles.cams,2), h);
end
close(h);

guidata(hObject,handles);


% --- Executes on button press in push_import_mark.
function push_import_mark_Callback(hObject, eventdata, handles)
% hObject    handle to push_import_mark (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    list_entries = get(handles.listbox_workspace,'String');
    index_selected = get(handles.listbox_workspace,'Value');

    if length(index_selected) ~= 1
        errordlg('You must select 1 variable','Incorrect Selection','modal')
    else 
        var1 = list_entries{index_selected(1)};
        %var1.position
        handles.markers=evalin('base',var1);       
    end 
    guidata(hObject,handles)


% --- Executes on selection change in popup_frame.
function popup_frame_Callback(hObject, eventdata, handles)
% hObject    handle to popup_frame (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popup_frame contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popup_frame


% --- Executes during object creation, after setting all properties.
function popup_frame_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popup_frame (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
