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

% Last Modified by GUIDE v2.5 08-Nov-2012 08:58:40

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @AnalysisGSP_OpeningFcn, ...
                   'gui_OutputFcn',  @AnalysisGSP_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 AnalysisGSP is made visible.
function AnalysisGSP_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 AnalysisGSP (see VARARGIN)

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

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = AnalysisGSP_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 during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% r=dir;
% index=1;
% 
% for i=1:1:length(r)
%     
%     if ( r(i).isdir == 1 )
%         directory(index) = r(i)
%         index=index+1;
%     end
% end

dir_struct = dir('*.mat');

% [sorted_names1,sorted_index1] = sortrows({directory.name}');
[sorted_names2,sorted_index2] = sortrows({dir_struct.name}');



% handles.file_names = [ sorted_names1  ;  sorted_names2 ];



for i=1:1:length(sorted_names2 ) 
    mechanism_file = sorted_names2{i};
    mechanism_file = mechanism_file(1:(length(mechanism_file)-4) );
    sorted_names2{i} = mechanism_file;
end    

handles.file_names = sorted_names2;

set(    hObject,    'String',handles.file_names,...
                    'Value',1)

%  strFolder = [ 'FOLDER :   ' pwd ];
% 
% handles.txt_Folder = uicontrol('Style','text',...
%         'Position',[29 13 73 1],...
%         'String',strFolder);
    
% Populate the listbox
%load_listbox(initial_dir,handles)
% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.




% --- Executes on button press in pb_InverseKinematics.
function pb_InverseKinematics_Callback(hObject, eventdata, handles)
% hObject    handle to pb_InverseKinematics (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
contents = cellstr(get(handles.listbox1,'String'));

selected = contents{get(handles.listbox1,'Value')};

setappdata(0,'Selected_Mechanism', selected );

analysisGUI = gcf;
delete(analysisGUI);

inverseGSP;

% --- Executes on button press in pb_Workspace.
function pb_Workspace_Callback(hObject, eventdata, handles)
% hObject    handle to pb_Workspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
contents = cellstr(get(handles.listbox1,'String'));

selected = contents{get(handles.listbox1,'Value')};

setappdata(0,'Selected_Mechanism', selected );

analysisGUI = gcf;
delete(analysisGUI);

workspace_GSP;


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

contents = cellstr(get(handles.listbox1,'String'));

selected = contents{get(handles.listbox1,'Value')};

setappdata(0,'Selected_Mechanism', selected );

analysisGUI = gcf;
delete(analysisGUI);

Jacobian_GSP;


% --- Executes on button press in pb_Dexterity.
function pb_Dexterity_Callback(hObject, eventdata, handles)
% hObject    handle to pb_Dexterity (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
contents = cellstr(get(handles.listbox1,'String'));

selected = contents{get(handles.listbox1,'Value')};

setappdata(0,'Selected_Mechanism', selected );

analysisGUI = gcf;
delete(analysisGUI);

DexterityGSP;
% close;



% --- Executes on button press in pb_Singularity.
function pb_Singularity_Callback(hObject, eventdata, handles)
% hObject    handle to pb_Singularity (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
contents = cellstr(get(handles.listbox1,'String'));

selected = contents{get(handles.listbox1,'Value')};

setappdata(0,'Selected_Mechanism', selected );

analysisGUI = gcf;
delete(analysisGUI);

SingularityGSP;





% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (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 selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

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

contents = cellstr(get(hObject,'String'));

selected = contents{get(hObject,'Value')};

setappdata(0,'Selected_Mechanism', selected );

% r = dir;
% for i=1:1:length(r)
%     if ( strcmp ( r(i).name , selected ) == 1 )
%        if ( r(i).isdir == 1 )
%            cd(r(i).name);
%            
% 
%                 r_sub=dir;
%                 index=1;
% 
%                 for i=1:1:length(r_sub)
% 
%                     if ( r_sub(i).isdir == 1 )
%                         directory(index) = r_sub(i)
%                         index=index+1;
%                     end
%                 end
% 
%                 dir_struct = dir('*.mat');
% 
%                 [sorted_names1,sorted_index1] = sortrows({directory.name}');
%                 [sorted_names2,sorted_index2] = sortrows({dir_struct.name}');
% 
%                 handles.file_names = [ sorted_names1  ;  sorted_names2 ]
% 
%                 set(    hObject,    'String',handles.file_names,...
%                                     'Value',1)           
%            
%            return;
%        end
%     end
% end

load(  selected  );


set(handles.axes1,'visible', 'on');
set(handles.txt_Preview,'visible','on');
set(handles.frame_Preview,'visible','on');
grid on;rotate3d on;zlabel('Z');ylabel('Y');xlabel('X');
axis auto

try
    if ( isempty(Base) == 1 ) 
        return;
    end
catch
    return;
end

%base platform connection points as B1, B2, .. , B6
setappdata( 0 , 'Base' , Base );

%mobile platform connection points PTable as P1, P2, .. , P6
Platform.P = Platform.PTable;

%P1,P2,..,P6 SHOULD BE GIVEN IN MOBILE PLATFORM COORDINATE SYSTEM
%THESE VARIABLES SHOULD BE CONSTANT AND SHOULD'NT BE CHANGED
Platform.PBase = Platform; %will be overwritten. performance consideration

%translation (Translate) == current platform points 
Platform.currentPx = Platform.Translate(1);
Platform.currentPy = Platform.Translate(2);
Platform.currentPz = Platform.Translate(3);

%orientation (Rotation) of mobile platform
Platform.currentAlpha = Platform.Rotation(1);
Platform.currentBeta = Platform.Rotation(2);
Platform.currentGamma = Platform.Rotation(3);

setappdata( 0 , 'Platform' ,Platform );

%Connection Matrix 
setappdata( 0 , 'ConMatrix' , ConMatrix );

%minimum and maximum values for each leg as LegLimit Table
setappdata( 0 , 'LegLimits' , LegLimits );

%minimum and maximum angle for each joint as JointLimits Table
setappdata( 0 , 'JointLimits' , JointLimits );

%thicnkness of base and platform (for now this will be only use to display 
%platform thickness but maybe these values use for dynamic calculation
setappdata( 0 , 'Thickness_Base', Thickness_Base );
setappdata( 0 , 'Thickness_Moving', Thickness_Moving );

% set(handles.currentPx, 'String', Platform.currentPx );
% set(handles.currentPy, 'String', Platform.currentPy );
% set(handles.currentPz, 'String', Platform.currentPz );
% set(handles.currentAlpha, 'String', Platform.currentAlpha );
% set(handles.currentBeta, 'String', Platform.currentBeta );
% set(handles.currentGamma, 'String', Platform.currentGamma );

%destination of the mobile platform coordinate axes and rotation
%P should be on base coordinate system
Platform.targetPx = 0; 
Platform.targetPy = 0;
Platform.targetPz = 0;
Platform.targetAlpha = 0;
Platform.targetBeta = 0;
Platform.targetGamma = 0;

handles = Plot_Mechanism( handles );
guidata(hObject, handles);
view(-23,18);

saveas(handles.axes1,'functionsaveas.eps','eps2c');

return;



% set(handles.editPx, 'String', Platform.targetPx );
% set(handles.editPy, 'String', Platform.targetPy );
% set(handles.editPz, 'String', Platform.targetPz );
% set(handles.editAlpha, 'String', Platform.targetAlpha );
% set(handles.editBeta, 'String', Platform.targetBeta );
% set(handles.editGamma, 'String', Platform.targetGamma );

Platform.PBase = ones(6,3) * NaN;
%platform coordinates in terms of the base coordinate frame   
%NaN as a number does not cause a problem. But NaN as an index is a fatal
%error.
for index = 1:1:6
        Platform.PBase(index,:) = Platform.Rotation * Platform.P(index,:)' + Platform.Translate;
end

%Maximum Leg Length and Minimum Leg Length
% set(handles.editLmax, 'String', LegLimits(1,2) );
% set(handles.editLmin, 'String', LegLimits(1,1) );
% 
% set(handles.editJointMax, 'String', JointLimits(1,2) );
% set(handles.editJointMin, 'String', JointLimits(1,1) );

Leg.L = [ 0, 0, 0, 0, 0, 0 ];

setappdata(0, 'Platform', Platform );
setappdata(0, 'Leg', Leg );


Base = getappdata( 0 , 'Base' );
Platform = getappdata( 0 , 'Platform' );
ConMatrix = getappdata( 0 , 'ConMatrix' );
LegLimits = getappdata( 0 , 'LegLimits' );
JointLimits = getappdata( 0 , 'JointLimits' );
Thickness_Base = getappdata( 0 , 'Thickness_Base' );
Thickness_Moving = getappdata( 0 , 'Thickness_Moving' );

Platform.Translate = [ Platform.Px ; Platform.Py  ; Platform.Pz ];
Platform.Rotation = Rotation( Platform.alpha, Platform.beta, Platform.gamma , 'RPY' ) ;
[ Leg, Platform.PBase, ErrorMsg ]= inverse_kinematic(Base, Platform, ConMatrix, LegLimits, JointLimits );

%handle to axes save to update or draw GSP 
hAxes = handles.axes1;
%use the figure's Axess = axesAnalysis
%axes(hAxes);

%to reset the platform we must check mechanism 
    %if it is already plotted before or plot it from scratch.
try
    ishandle( handles.Base_handle );
    delete( handles.Base_handle);
    handles.Base_handle = tabla_cizimi_genel ( Base.BTable , Thickness_Base , [ 222/255, 235/255, 250/255 ] );
catch exception                     
    handles.Base_handle = tabla_cizimi_genel ( Base.BTable , Thickness_Base , [ 222/255, 235/255, 250/255 ] );
end

try
    ishandle( Platform.Platform_handle );
    delete( Platform.Platform_handle);
    Platform.Platform_handle  = tabla_cizimi_genel( Platform.PBase, -Thickness_Moving , [ 255/255, 242/255, 221/255]  );
catch exception
    Platform.Platform_handle  = tabla_cizimi_genel( Platform.PBase, -Thickness_Moving , [ 255/255, 242/255, 221/255]  );
end

%sabit platformdaki hangi nokta ile haraketli platformdaki hangi nokta
%birle?tirilmelidir ? Bu sorunun cevab? için Connection Matrix
%kullan?lmal?d?r.

%E?er connection matrix içinde NaN varsa ve bu NaN matris i?lemlerinde
%indis olarak kullan?yorsa MATLAB hata vermektedir. Dolay?s?yla önce bu
%indis NaN de?il mi diye emin olmak gerekir.
Leg.Leg_handle=zeros(6,1);


for index = 1:1:6
    if ~isnan(ConMatrix(1,index)) && ~isnan(ConMatrix(2,index))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        
% Bacaklar?n çizilmesi
% draw legs as line with the use of conMatrix
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        
        Leg.Leg_handle(index) = line(...
            'XData',[Base.BTable(ConMatrix(1,index),1); Platform.PBase(ConMatrix(2,index),1)],...
            'YData',[Base.BTable(ConMatrix(1,index),2); Platform.PBase(ConMatrix(2,index),2)],...
            'ZData',[Base.BTable(ConMatrix(1,index),3); Platform.PBase(ConMatrix(2,index),3)],...
            'Color','g','LineWidth',5,'Marker','o','MarkerFaceColor','b','MarkerSize',6);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        
%inverse kinematics = ters kinematik hesab?
        Leg.Leg.L(index) = norm ( Platform.PBase(ConMatrix(2,index),:) - Base.BTable(ConMatrix(1,index),:) );

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%set editbox with Leg lengths
%         eval( sprintf( 'set(handles.textL%d, ''String'', %f)',index, Leg.Leg.L(index) ) );
  
    else
        Leg.Leg_handle(index) = 0;
    end
end
   
% Update handles structure
guidata(hObject, handles);


if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
  
% Update handles structure
guidata(hObject, handles);


end


% --- Executes on button press in pb_Trajectory_Planning.
function pb_Trajectory_Planning_Callback(hObject, eventdata, handles)
% hObject    handle to pb_Trajectory_Planning (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
contents = cellstr(get(handles.listbox1,'String'));

selected = contents{get(handles.listbox1,'Value')};

setappdata(0,'Selected_Mechanism', selected );

Trajectory_planning_GSP;


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure

delete(hObject);
StewSIM_1;


% --- Executes on button press in pb_ForwardKinematics.
function pb_ForwardKinematics_Callback(hObject, eventdata, handles)
% hObject    handle to pb_ForwardKinematics (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
contents = cellstr(get(handles.listbox1,'String'));

selected = contents{get(handles.listbox1,'Value')};

setappdata(0,'Selected_Mechanism', selected );

analysisGUI = gcf;
delete(analysisGUI);

forwardGSP;
