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

% Last Modified by GUIDE v2.5 09-May-2018 17:56:07

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

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

% Update handles structure for Axes 1
guidata(hObject, handles);
axes(handles.axes1);
xlabel('Absolute Position [rad]')
ylabel('Drehmoment [Nm]')
grid on
hold on

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


% --- Outputs from this function are returned to the command line.
function varargout = mainGui_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 pushbuttonLoadXLSX.
function pushbuttonLoadXLSX_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonLoadXLSX (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


handles.loadedData = uigetfile('*.csv', 'Wähle .csv datei: ');

% Bearbeitet von F.:

tableT = nan(1,6);

handles.files = xlsread(handles.loadedData);
Time = handles.files(:,4);
handles.groupends = find(diff(Time)>100); %Gruppenenden
handles.groupends = [0; handles.groupends];
handles.ngroups = length(handles.groupends);

for i = 1:handles.ngroups-1
    handles.Daten = handles.files(handles.groupends(i)+1:handles.groupends(i+1),[9 10])
    guidata(hObject, handles);
    
%     tableDaten(i,:) = handles.Daten;
    
    % Plotten
     axes(handles.axes1);
     y = handles.Daten(:,1);
     x = handles.Daten(:,2);
%      plot(x,y)
     
%      xx = smooth(x,'lowess');
%      yy = smooth(y,'lowess');
%      plot(xx,yy)


    % Ellipsenparameter berechnen
    % initialize
    orientation_tolerance = 1e-3;
    
    % empty warning stack
    lastwarn( '' );
    
    mean_x = mean(x);
    mean_y = mean(y);
    x = x-mean_x;
    y = y-mean_y;
    
    
    % the estimation for the conic equation of the ellipse
    X = [x.^2, x.*y, y.^2, x, y ];
    a = sum(X)/(X'*X);
    
    % check for warnings
    if ~isempty( lastwarn )
        disp( 'stopped because of a warning regarding matrix inversion' );
        ellipse_t = [];
        return
    end
    
    % extract parameters from the conic equation
    [a,b,c,d,e] = deal( a(1),a(2),a(3),a(4),a(5) );
    
    % remove the orientation from the ellipse
    if ( min(abs(b/a),abs(b/c)) > orientation_tolerance )
        
        orientation_degree = radtodeg(1/2 * atan( b/(c-a) ));
        cos_phi = cos( orientation_degree );
        sin_phi = sin( orientation_degree );
        [a,b,c,d,e] = deal(...
            a*cos_phi^2 - b*cos_phi*sin_phi + c*sin_phi^2,...
            0,...
            a*sin_phi^2 + b*cos_phi*sin_phi + c*cos_phi^2,...
            d*cos_phi - e*sin_phi,...
            d*sin_phi + e*cos_phi );
        [mean_x,mean_y] = deal( ...
            cos_phi*mean_x - sin_phi*mean_y,...
            sin_phi*mean_x + cos_phi*mean_y );
    else
        orientation_degree = 0;
        cos_phi = cos( orientation_degree );
        sin_phi = sin( orientation_degree );
    end
    
    % Bearbeitet von F.: berechnet Xdim und Ydim
    Xdimx = max(x)-min(x);
    Ydimy = max(y)-min(y);
    
    % check if conic equation represents an ellipse
    test = a*c;
    switch (1)
        case (test>0),  status = '';
        case (test==0), status = 'Parabola found';  warning( 'fit_ellipse: Did not locate an ellipse' );
        case (test<0),  status = 'Hyperbola found'; warning( 'fit_ellipse: Did not locate an ellipse' );
    end
    
    % if we found an ellipse return it's data
    if (test>0)
        
        % make sure coefficients are positive as required
        if (a<0), [a,c,d,e] = deal( -a,-c,-d,-e ); end
        
        % final ellipse parameters
        X0          = mean_x - d/2/a;
        Y0          = mean_y - e/2/c;
        F           = 1 + (d^2)/(4*a) + (e^2)/(4*c);
        [a,b]       = deal( sqrt( F/a ),sqrt( F/c ) );
        long_axis   = 2*max(a,b);
        short_axis  = 2*min(a,b);
        
        % rotate the axes backwards to find the center point of the original TILTED ellipse
        R           = [ cos_phi sin_phi; -sin_phi cos_phi ];
        P_in        = R * [X0;Y0];
        X0_in       = P_in(1);
        Y0_in       = P_in(2);
        
        Lw = i;
        % pack ellipse into a structure
        ellipse_t = struct( ...
            'Lastwechsel', Lw, ...
            'Xcenter',X0_in,...
            'Ycenter',Y0_in,...
            'Xdim',Xdimx,...
            'Ydim',Ydimy,...
            'phi',orientation_degree);
        
        
        disp(ellipse_t);
        
        % Bearbeitet von F.:
        table = struct2array(ellipse_t);
        handles.tableT(i,:) = table;

    else
        % report an empty structure
        ellipse_t = struct( ...
            'a',[],...
            'b',[],...
            'phi',[],...
            'X0',[],...
            'Y0',[],...
            'X0_in',[],...
            'Y0_in',[],...
            'long_axis',[],...
            'short_axis',[],...
            'status',status );
    end
   % Parameterize the equation.
   
   % Regressions-Ellipsen berechnen und Plotten
axes(handles.axes1);
t = linspace(0, 360,1000);
xAmplitude = (0.8*handles.tableT(i,4))/2;
yAmplitude = (handles.tableT(i,5))/2;
xCenter = handles.tableT(i,2);
yCenter = handles.tableT(i,3);
xOriginal = xAmplitude * sind(t) + xCenter;
yOriginal = yAmplitude * cosd(t) + yCenter;
grid on;
drawnow;
hold on;

 rotationAngle = 360-handles.tableT(i,6)
	transformMatrix = [cosd(rotationAngle), sind(rotationAngle);...
		-sind(rotationAngle), cosd(rotationAngle)];
	xAligned = (xOriginal - xCenter);
	yAligned = (yOriginal - yCenter/2);
	xyAligned = [xAligned; yAligned]';
	xyRotated = xyAligned * transformMatrix;
	xRotated = xyRotated(:, 1) + xCenter;
	yRotated = xyRotated(:, 2) + yCenter/2;
	hold on;
	plot(xRotated, yRotated);
end

%manipulate the data here
set(handles.uitable1, 'data',handles.tableT);

% manipulate popupmenu here
set(handles.popupmenuLw1,'String', handles.tableT(:,1));
set(handles.popupmenuLw2,'String', handles.tableT(:,1));
set(handles.popupmenuLw3,'String', handles.tableT(:,1));


% Axes1
function axes1_CreateFcn(~, eventdata, handles)
% hObject    handle to axes1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes1

% Uitable1
function uitable1_CellEditCallback(~, ~, handles)
% hObject    handle to uitable1 (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.CONTROL.TABLE)
%	Indices: row and column indices of the cell(s) edited
%	PreviousData: previous data for the cell(s) edited
%	EditData: string(s) entered by the user
%	NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
%	Error: error string when failed to convert EditData to appropriate value for Data
% handles    structure with handles and user data (see GUIDATA)
% --- Executes on selection change in popupmenuLw1.


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

% aus Internet kopiert
axes(handles.axes1);
popup_index = get(handles.popupmenuLw1, 'Value');

switch popup_index
   
    case 1
            y = handles.Daten(:,1);
            x = handles.Daten(:,2);
            plot(x,y)
    case 2
            y = handles.Daten(:,1);
            x = handles.Daten(:,2);
            plot(x,y)
end

% Hints: contents = cellstr(get(hObject,'String')) returns popupmenuLw1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenuLw1
% --- Executes during object creation, after setting all properties.


% Popupmenu1
function popupmenuLw1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenuLw1 (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


% Popupmenu2
function popupmenuLw2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenuLw2 (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 popupmenuLw2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenuLw2


% Popupmenu2
function popupmenuLw2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenuLw2 (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



% Popupmenu3
function popupmenuLw3_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenuLw3 (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 popupmenuLw3 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenuLw3


% Popupmenu3
function popupmenuLw3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenuLw3 (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


% fab = {'2','3'};
% 
% set(hObject, 'String', fab);

% set(hObject, 'String', handles.tableT(:,1));





% Clear figure
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cla(handles.axes1);


% Clear Table
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
t = handles.uitable1
set(t,'Data',[])


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


data = get(handles.uitable1,'Data');
cnames = {'Lastwechsel', 'Xcenter', 'Ycenter', 'Xdim' , 'Ydim', 'Phi'};

A = [cnames ; num2cell(data)];

FileName = uiputfile('*.xls','Save as');

xlswrite(FileName,A);
winopen(FileName);


% Update figure
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% axes(handles.axes1);
% popup_index = get(handles.popupmenuLw1, 'Value');
% 
% switch popup_index
%     case 1
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 2
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 3
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 4
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 5
%         surf(peaks);
% end
% 
% popup_index = get(handles.popupmenuLw2, 'Value');
% 
% switch popup_index
%     case 1
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 2
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 3
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 4
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 5
%         surf(peaks);
% end
% 
% popup_index = get(handles.popupmenuLw3, 'Value');
% 
% switch popup_index
%     case 1
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 2
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 3
%             y = handles.Daten(:,1);
%             x = handles.Daten(:,2);
%             plot(x,y)
%     case 4
%             y = rand(10);
%             x = rand(10);
%             plot(x,y)
%     case 5
%         surf(peaks);
% end
% 
