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

% Last Modified by GUIDE v2.5 17-Sep-2013 10:52:01


% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @set_ber5_OpeningFcn, ...
                   'gui_OutputFcn',  @set_ber5_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 set_ber5 is made visible.

function set_ber5_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 set_ber5 (see VARARGIN)

% Choose default command line output for set_ber5
handles.output = hObject;       % Standardausgabe, werden wir ändern

handles.dat = varargin{1};      % das sind die Daten

% handles.AnzBer=0;  % Ist Unsinn - siehe Hinweise Matlab2408.docx
% handles.tab=[];    % Erst mal noch nicht, später vielleicht 
% guidata(hObject, handles); % erst nach Zeile 67  % aktualisiert handles 


handles.xy=[0,0];   % Ausgewähltes Element der Tabelle, 
                    % erst mal [0,0] und damit keines ausgewählt 

guidata(hObject, handles); % Jetzt handles aktualisieren

set(handles.tabelle,'Parent',handles.uipanel,...
                'Units','normalized','Position',[0 0 1 1],...
                'Data',[0;0;0]);
% Zeilenbeschriftung erstellen    
ZT = {'first point';'last point';'number of points'};
set(handles.tabelle,'RowName',ZT); 
% Spaltenkopf erstellen
ST = '';
set(handles.tabelle,'ColumnName',ST,'ColumnEditable',true);

% Anzahl Fitbereiche a=1
set(handles.AnzBer,'String','1');



A=handles.dat;       %Matrix handles.dat wird kurz als A bezeichnet

[zz,sz]=size(A);     %Zeilenzahl und Spaltenzahl von A ermitteln

if (sz>zz)           %wenn Spaltenzahl größer Zeilenzahl
A=A';                %Matrix transponieren
end

[zz,sz]=size(A);

if sz==1             %wenn Spaltenzahl gleich 1
 A=[(1:zz)',A];      % dann wird in die erste Spalte die durchlaufend Nummer 1,2,3.... geschrieben
                     % und die Daten werden in die 2.Spalte verschoben
end

[zz,sz]=size(A);     %Zeilenzahl und Spaltenzahl von A ermitteln

if sz==2             %wenn Spaltenzahl gleich 2
    A=[A,zeros(zz,1)] ;     % Muss zz sein, 3. Spalte mit Nullen dranhängen
end

axes(handles.axes1);   % aktuelle axes für plot ist axes1 
                       % (evtl. überflüssig, denn es gibt ja nur axes1 
x=A(:,1);
y=A(:,2);

if sz==2;  
    plot(x,y);          %plotten der Matrix
end

if sz==3;
    c=A(:,3);           % 3.Spalte von A, Zeile nicht relevant   
    biplot1(x,y,c);     % geändert Schulz
end

handles.dat=A;
%A=handles.dat;
 handles.dcm_obj = datacursormode;	% Einschalten datacursormode und Objektname 
  

% Update handles structure
guidata(hObject, handles);

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

 
% --- Outputs from this function are returned to the command line.
function FB = set_ber5_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

FB{1} = 'Fitbereiche';
FB{2} =  str2double(get(handles.AnzBer,'String')); % Anzahl Fitbereiche
FB{3} = handles.output;
%FB{4} = NeueTabelle;
delete(hObject);  

    
function AnzBer_Callback(hObject, ~, handles)
% hObject    handle to AnzBer (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 AnzBer as text
%        str2double(get(hObject,'String')) returns contents of AnzBer as a double

% Zahl a aus dem Editorfenster auslesen

a = str2double(get(hObject,'String'));  % Variable a= Anzahl an Fitbereichen 

x= sscanf(get(hObject, 'String'), '%g', 1); 
if isempty(x) || x < 1 || x ~= floor(x)  %prüfen ob eingegebene Variable ein Integer ist
  warndlg('This number must be a positive integer');
  set(hObject, 'String', '');
  return
end

% Jetzt müssen verschiedene Fälle unterschieden werden

% 1. Fall:
% Falls a=0 aber schon eine tabelle da war, muss diese nun auf der 
% Oberfläche gelöscht werden und das handle.tabelle muss entfernt werden
 
if (a==0) 
  set(handles.tabelle,'Visible','off');
end


% 2. Fall:
% Falls a>0 und schon eine tabelle da ist, muss diese nun eventuell in der
% Spaltenanzahl geändert werden. Dabei sollen die bereits vorhandenen
% Einträge aber beibehalten werden:

if (a>0) && (isfield(handles,'tabelle'))
    TabInhalt = get(handles.tabelle,'Data'); % Tabelleninhalt lesen
    TabInhalt = [TabInhalt, zeros(3,a)];   % a Spalten mit Nullen anhängen
    TabInhalt = TabInhalt(:,1:a);         % die ersten a Spalten nehmen
    set(handles.tabelle,'Data',TabInhalt); % neuen Tabelleninhalt eintragen 
end    

% 3. Fall:
% Es ist a>0 aber noch keine tabelle war da (wie am Anfang)
% Nun muss eine tabelle mit der geeigneten Anzahl Spalten erzeugt werden
% die Beschriftung der Zeilenköpfe und Spaltenköpfe muss geeignet erfolgen
    
%if (a>0) && (~isfield(handles,'tabelle'))

% tabelle auf GUI erzeugen    
   % handles.tabelle = uitable('Parent',handles.uipanel,...
    %            'Units','normalized','Position',[0 0 1 1]);    
% Erst mal nur Nullen in die tabelle eintragen
  %  set(handles.tabelle,'Data',zeros(3,a));
% Zeilenbeschriftung erstellen    
   % ZT = {'first point';'last point';'number of points'};
   % set(handles.tabelle,'RowName',ZT);
%end
 

% Nun in Abhängigkeit von a die geforderte Anzahl Spaltenköpfe schreiben 
% und alle enthaltenen Spalten editierbar machen 

if a<=15
    ST=cell(1,a);
    for k=1:a
    ST{k}=sprintf('Bereich%d', k);  
    end
    set(handles.tabelle,'ColumnEditable',true(1,a))
    set(handles.tabelle,'ColumnName',ST); 
else
   warndlg('This number must be less than 16');
  set(hObject, 'String', '');
  return 
end

% Die handles-struktur aktualisieren
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function AnzBer_CreateFcn(hObject, eventdata, handles)
%Anzahl Bereiche
% hObject    handle to AnzBer (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 Messpunktspeichern.
function Messpunktspeichern_Callback(hObject, eventdata, handles)
% Messpunkt speichern
% hObject    handle to Messpunktspeichern (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% dcm_obj = datacursormode;	% Einschalten datacursormode und Objektname 
info_struct = getCursorInfo(handles.dcm_obj);
					% Strukturvariable, erhält Cursor-Info
                    
p = info_struct.Position;	% geeignete Variable x erhält Cursorposition 

% datacursormode off;		% datacursormode ausschalten (notwendig ?)

[a,b]=size(handles.xy);            % Zeilen-, Spaltenzahl
if  (a*b)~=0                        % nur wenn Tabellenzelle ausgewählt
                                    % sonst Zeilenzahl Null
    c = handles.xy(1,1);
    d = handles.xy(1,2);
    
    if (c*d)~=0                     % nur wenn nicht Index 0,0 (Start)
        TabInhalt = get(handles.tabelle,'Data'); % Tabelle auslesen
        TabInhalt(c,d) = p(1);      % hier dann x - Wert von datacursor
        set(handles.tabelle,'Data',TabInhalt); %Tabelle neu schreiben
    end
end


% --- Executes on button press in Bereicheloeschen.
function Bereicheloeschen_Callback(hObject, eventdata, handles)
%Bereiche löschen
% hObject    handle to Bereicheloeschen (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.tabelle,'Parent',handles.uipanel,...
                'Units','normalized','Position',[0 0 1 1],...
                'Data',[0;0;0]);
  % Zeilenbeschriftung erstellen    
ZT = {'first point';'last point';'number of points'};
set(handles.tabelle,'RowName',ZT); 
% Spaltenkopf erstellen
ST = '';
set(handles.tabelle,'ColumnName',ST,'ColumnEditable',[true]);

% Anzahl Fitbereiche a=1
set(handles.AnzBer,'String','1');


%-----------------------------------------------------------------------

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

handles.output   =  get(handles.tabelle,'Data');    % Übernahme Tabelle
% handles.ausgabe = 2013;       % war nur Beispiel, nicht mehr benötigt
guidata (hObject, handles);     % handles aktualisieren
close(handles.figure1);


% --- 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); entfernt durch %
uiresume(handles.figure1)


%-----------------------------------------------------------------------
function biplot1(x,y,c)

% Plottet die Messreihe mit x- und y- Werten
% x, y und c sind gleichlange Spaltenvektoren
% in c stehen Nullen für aktive Messpunkte (plot dunkelblau)
% in c stehen Einsen für deaktivierte Messpunkte (plot cyan)
% Verbinungen zwischen benachbarten aktiven und deaktivierten Punkten
% erscheinen in ganzer Länge cyan

number = length(x);         % Anzahl Messpunkte
xx=x(1);                    % erster x-Wert
yy=y(1);                    % erster y-Wert

% Falls nur aktive Werte
if sum(c)==0
    plot(x,y,'b');
end

% Falls nur deaktivierte Werte
if sum(c)==length(c)
    plot(x,y,'c');
end

for i=2:number
    if c(i)==1
        c(i-1)=1;
    end
end    

% Falls korrigierte und Originalwerte
if (sum(c)~=0) && (sum(c)~=0)
    for i=1:number-1
        xx = [xx,x(i+1)];
        yy = [yy,y(i+1)];
        if (c(i+1)==1) && (c(i)==0)
            plot(xx,yy,'b');
            hold on;                    % weiterplotten im selben figure
            xx = x(i+1);
            yy = y(i+1);
        end
        if (c(i+1)==0) && (c(i)==1)
            plot(xx,yy,'c');
            hold on;                    % weiterplotten im selben figure
            xx = x(i+1);
            yy = y(i+1);
        end
    end
    
    % das letzte Linienstück wird gezeichnet
    if c(i)==c(number)
        if c(i)==1
            plot(xx,yy,'c');
        else
            plot(xx,yy,'b');
        end   
    end
    drawnow;
    hold off;
end

%-----------------------------------------------------------------------

% --- Executes during object creation, after setting all properties.
function uipanel_CreateFcn(hObject, eventdata, handles)
% hObject    handle to uipanel (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 axes1_CreateFcn(hObject, 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


% --- Executes when selected cell(s) is changed in tabelle.
function tabelle_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to tabelle (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)

 handles.xy = eventdata.Indices;
guidata(hObject,handles);
    

