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

% Last Modified by GUIDE v2.5 04-Feb-2015 19:41:50

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

% Choose default command line output for Simulation_V18
profile on

handles.output = hObject;
set(handles.AnzahlSimulationen,'String','1');
set(handles.AnzahlKanaele,'String','100');
handles.k = str2double(get(handles.AnzahlSimulationen,'String'));
handles.N = str2double(get(handles.AnzahlKanaele,'String'));

set(handles.figure1, 'UserData',[]);
userData.stop = false;
set(handles.figure1, 'UserData',userData);

% Update handles structure
guidata(hObject, handles);

title(handles.axes1,'Mittelwert Strom'); 
title(handles.axes2,'Mittelwert Fluor');
title(handles.axes3,'Standardabweichung Strom');
title(handles.axes4,'Standardabweichung Fluor');

guidata(hObject, handles);   % handles.fh1 wird in handles struktur aufgenommen
                
% UIWAIT makes Simulation_V18 wait for user response (see UIRESUME)
uiwait(handles.figure1);



% --- Outputs from this function are returned to the command line.
function varargout = Simulation_V18_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;
delete(hObject); 


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

% Hint: get(hObject,'Value') returns toggle state of Zeitschritt_fest

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

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

% Hint: get(hObject,'Value') returns toggle state of glatt


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

% Hint: get(hObject,'Value') returns toggle state of automatisch


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

% Hint: get(hObject,'Value') returns toggle state of variabel


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

set(handles.Start,'BackgroundColor','red'); % START-BUTTON gedrückt ändert die Farbe auf rot
cla(handles.axes1); % Löscht (falls vorhanden) alle Grafiken im axes1
cla(handles.axes2);
cla(handles.axes3);
cla(handles.axes4);

moreWork = true;
userData = get(handles.figure1, 'UserData');
userData.stop = false; %reset for next time
set(handles.figure1,'UserData',userData);

N_ch = str2double(get(handles.AnzahlKanaele,'String'));        % number of channels in the patch
N_it = str2double(get(handles.AnzahlSimulationen,'String'));    % number of iterations
 
Modellname=get(handles.Modellname, 'String');
Modell=Modellname(1:end-2);
Pulsname=get(handles.Pulsname, 'String');
Puls=Pulsname(1:end-2);
       
if (N_ch==0&&N_it==0)
       warndlg('Bitte Anzahl Kanäle und Simulationen eingeben');
end

if get(handles.Zeitschritt_fest,'Value')==true
       
    [MC,MK,uc,ub,nb] = feval(Modell);  % Modelldaten einlesen
    [PP,dt] = feval(Puls);             % Pulsdaten einlesen       
    AnzMP =  PP(1,:)/dt;               % Anzahl Messpunkte in Pulsen
    AnzMPkum = cumsum(AnzMP);          % kumulative Summe
    np = length(PP(1,:));              % Anzahl Pulse
    ns = length(MC(1,:));              % Anzahl Zustände
    nMK = ones(ns,ns)- MK;          % Matrixwerte ohne Konzentrationen
    CC  = zeros(ns,ns,np);          % Besetzung des CC - Arrays
    ev3 = zeros(ns,ns,np);          % Besetzung des Eigenvektor-Arrays
    ew3 = zeros(ns,np);             % Besetzung des Eigenwerte -Arrays
    for k = 1:np
        konz = PP(3,k);             % Konzentration im Puls
        C = konz*MK.*MC+nMK.*MC;    % Multiplikation mit konz
        for i=1:ns                  % Hauptdiagonale von C berechnen
            C(i,i)=0;
            element=0;
            for j=1:ns
                element=element-C(j,i);
            end
            C(i,i)=element;
        end
        CC(:,:,k) = C;              % alle C-Matrizen
        [ev,ew]   = eig(C);         % Eigenvektoren und Eigenwerte
        ev3(:,:,k)= ev;            % np Matrizen mit Eigenvektoren
        ew3(:,k)  = diag(ew);      % np Spalten mit Eigenwerten
    end
    GGWB1 = zeros(ns,1);
    CG = CC(:,:,1);
    CG(end,:) = 1;
    b = [zeros(ns-1,1);1];          % b-Vektor mit [0; 0; ...; 0; 1]
    GGWB1 = CG\b;                   % Zustandsvektor im GGW als Spaltenvektor
    E = eye(ns);         % Einheitsmatrix, Spaltenvektoren sind Anfangszustände
    D = triu(ones(ns));  % obere Dreiecksmatrix mit Einsen belegt
    B = [];              % sicherheitshalber;
    % Berechnet für jeden Puls und jeden möglichen Ausgangszustand (k)
    % die Matrix B.pmat
    for pu = 1:np
        EV = ev3(:,:,pu);    % Matrix der Eigenvektoren in Array
        for k = 1:ns
            Anf_Besetzung = E(:,k);                      % nur Zustand k besetzt
            B(pu,k).pmat  = EV*(diag(EV\Anf_Besetzung)); % .pmat von typ und k
        end
    end
    % Berechnung u. Speicherung der Übergangswahrscheinlichkeitsmatrizen
    for pu =1:np    
       EW = ew3(:,pu);
       for k = 1:ns                      % k ist ein bestimmter Anfangszustand
         probl = B(pu,k).pmat*exp(EW*dt); % Wahrscheinlichkeiten nach dt
         TIS(pu).sprobl(:,k) = D*probl;   % summierte Wahrscheinlichkeiten 
       end
    end
    % Speicherplatz reservieren
    SEc = zeros(AnzMPkum(np),1);	% Summe der einzelnen Simulationen
    SQc = SEc;                      % Summe der quadrierten Werte
    SEb = SEc;                      % Summe der einzelnen Simulationen
    SQb = SEc;                      % Summe der quadrierten Werte

    m=0;
    while (moreWork && m<N_it)
        %check if user hit STOP button
        userData = get(handles.figure1, 'UserData');
        if userData.stop == true
            userData.stop = false; %reset for next time
            set(handles.figure1,'UserData',userData);
            moreWork = false; %to stop the loop
        else
            m =m+1;
            set(handles.Zaehler,'String',m); %Zähler für Simulationen
            drawnow;
            zust_0 = zeros(ns,AnzMPkum(np));
            zust_s = zust_0;                    % Summe der Einzelströme
          
        
            
             for nr = 1:N_ch  
          
                 userData = get(handles.figure1, 'UserData');
                 if userData.stop == true
                userData.stop = false; %reset for next time
                set(handles.figure1,'UserData',userData);
                moreWork = false; %to stop the loop
                else
                  set(handles.ZaehlerN,'String',nr); %Zähler für Anzahl Kanäle      
                  drawnow; 
         
              
              zust = zust_0;                  % Nullmatrix für Zustände  
                sBesetzung = D*GGWB1;           % summierte Besetzungswahrscheinlichkeiten
                a = rand(1,AnzMPkum(np)+1);           % Zufallszahl entscheidet Vor - Besetzung   
                rz = max(find(sBesetzung>a(end)));    % zufälliger Zustand in Vor-Besetzung
                j = 0;
                for pu = 1:np         
                   for i=1:AnzMP(pu)
                             j = j+1;
                             % a=rand;
                             sBesetzung = TIS(pu).sprobl(:,rz); 
                             rz = max(find(sBesetzung>a(j))); 
                             zust(:,j) = zust(:,j) + E(:,rz);
                   end
             
                end
                zust_s = zust_s + zust;
        end 
     end
            zust = zust_s / N_ch;
            strom = uc*zust;
            fluor = ub*zust;
            SEc = SEc + strom';
            SQc = SQc + strom'.*strom';
            SEb = SEb + fluor';
            SQb = SQb + fluor'.*fluor';
            end
        end
   
       
    % die Vektoren SQ und SE erhalten jetzt neue Bedeutungen, 
    % um nicht noch weiteren Speicherplatz zu "vergeuden"
    if N_it==1
        SQc = zeros(AnzMPkum(np),1);
        SQb = zeros(AnzMPkum(np),1);
      else
        SQc = ((SQc - SEc.*SEc/N_it) / (N_it-1));	 % das sind jetzt die Standardabweichungen Strom
        SEc = SEc/N_it;						    % das sind jetzt die Mittelwerte Strom
        SQb = ((SQb - SEb.*SEb/N_it) / (N_it-1));	 % das sind jetzt die Standardabweichungen Fluor
        SEb = SEb/N_it;	% das sind jetzt die Mittelwerte Fluor
    end

    handles.SEc = SEc;
    handles.SQc = SQc;
    handles.SEb = SEb;
    handles.SQb = SQb;
    t = dt*(1:length(strom));
    handles.t = t;
    plot(handles.axes1,t,SEc); % Mittelwert Strom
    plot(handles.axes2,t,SEb);  % Mittelwert Fluoreszenz
    plot(handles.axes3,t,SQc);  %Standardabweichung Strom
    plot(handles.axes4,t,SQb);  %Standardabweichung Fluoreszenz
    title(handles.axes1,'Mittelwert Strom'); 
    title(handles.axes2,'Mittelwert Fluor');
    title(handles.axes3,'Standardabweichung Strom');
    title(handles.axes4,'Standardabweichung Fluor');

end

% if get(handles.variabel,'Value')==true
     
 %end
 
if get(handles.glatt,'Value')==true
    [strom,fluor,t]=simulator_glatt1(Modell,Puls);
    handles.strom = strom;
    handles.fluor = fluor;
    handles.t = t;

    plot(handles.axes1,t,strom);
    plot(handles.axes2,t,fluor);
    plot(handles.axes3,t,zeros(size(t))); 
    plot(handles.axes4,t,zeros(size(t)));
 
end
 
set(handles.Start,'BackgroundColor','green'); % wechselt die Farbe wieder auf grün
 %if get(handles.automatisch,'Value')==true
%end   
% Die handles-struktur aktualisieren

%profile viewer
%p = profile('info');
%profsave(p,'profile_results')

guidata(hObject, handles);


% --- Executes on button press in Stop.
function Stop_Callback(hObject, eventdata, handles)
% hObject    handle to Stop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
userData.stop = true;
set(handles.figure1,'UserData',userData);


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

 handles.N = str2double(get(hObject,'String'));  % Variable N=Anzahl Kanäle
 
 % Die handles-struktur aktualisieren
guidata(hObject, handles);

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



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

handles.k = str2double(get(hObject,'String'));  % Variable k=Anzahl Simulationen
 
 % Die handles-struktur aktualisieren
guidata(hObject, handles);

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


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

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

% --- Executes during object creation, after setting all properties.
function Zaehler_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Zaehler (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 close.
    function close_Callback(hObject, eventdata, handles)
% hObject    handle to close (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,'N')==1
    Abfrage = questdlg('Speichern?','title','Ja','Nein','default'); 
    if strcmp(Abfrage, 'Ja') 

       if get(handles.Zeitschritt_fest,'Value')==true
         N=handles.N;
         k=handles.k; 
         DefaultName = [num2str(k),'_Sim_N_',num2str(N)];
         [FileName,PathName]=uiputfile('*.xls','EXCEL-Datei speichern',DefaultName);
         if FileName~=0      % Nur wenn ein file ausgewählt wurde
            FilePath=fullfile(PathName,FileName);
            xlswrite(FilePath,[handles.t',handles.SEc,handles.SQc,handles.SEb,handles.SQb]);
         end
       end 

       if get(handles.glatt,'Value')==true
         N=handles.N;
         k=handles.k; 
         DefaultName = [num2str(k),'_Sim_N_',num2str(N)];
         [FileName,PathName]=uiputfile('*.xls','EXCEL-Datei speichern',DefaultName); %Fenster öffnet sich
         if FileName~=0      % Nur wenn ein file ausgewählt wurde
            FilePath=fullfile(PathName,FileName);
            xlswrite(FilePath,[handles.t',handles.strom',handles.fluor']);
         end
       end
    end
end

close(handles.figure1);         %Fenster schließen



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


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


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


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


% --- Executes on button press in checkbox2.
function checkbox2_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox2
 
%mit glatter Kurve

 Modellname=get(handles.Modellname,'String');
 Modell=Modellname(1:end-2);
 Pulsname=get(handles.Pulsname,'String');
 Puls=Pulsname(1:end-2);
 
 if get(handles.Zeitschritt_fest,'Value')==true
       
      [strom,fluor,t]=simulator_glatt1(Modell,Puls);
      axes(handles.axes1);
      hold on;
      plot(t,strom,'r');
      hold off;
      axes(handles.axes2);
      hold on;
      plot(t,fluor,'r');
      hold off;
      title(handles.axes1,'Mittelwert Strom'); 
      title(handles.axes2,'Mittelwert Fluor');
 
 end
 
    if get(handles.checkbox2,'Value')==false
    cla(handles.axes1); % löschen der axes
    cla(handles.axes2);
    plot(handles.axes1,handles.t,handles.SEc); %Neu plotten: Mittelwert Strom
    plot(handles.axes2,handles.t,handles.SEb);  % Mittelwert Fluoreszenz
    title(handles.axes1,'Mittelwert Strom'); 
    title(handles.axes2,'Mittelwert Fluor');
    end 



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

% --------------------------------------------------------------------
function Pulsprotokoll_Callback(hObject, eventdata, handles)
% hObject    handle to Pulsprotokoll (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
 

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


% --------------------------------------------------------------------
function alles_Speichern_Excel_Callback(hObject, eventdata, handles)
% hObject    handle to alles_Speichern_Excel (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,'N')==1
     
   if get(handles.Zeitschritt_fest,'Value')==true
     %N  = handles.N;
     %k  = handles.k; 
     %DefaultName = [num2str(k),'_Sim_N_',num2str(N)];
     DefaultName = ['GlattSim'];
     [FileName,PathName]=uiputfile('*.xls','EXCEL-Datei speichern',DefaultName);
     if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        xlswrite (FilePath,[handles.t',handles.SEc,handles.SQc,handles.SEb,handles.SQb]);
     end
   end
end   

if get(handles.glatt,'Value')==true
    DefaultName = ['GlattSim'];
    [FileName,PathName]=uiputfile('*.xls','EXCEL-Datei speichern',DefaultName);
    if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        xlswrite (FilePath,[handles.t';handles.strom;handles.fluor]');
    end
end 

   

% --------------------------------------------------------------------
function MW_Strom_Callback(hObject, eventdata, handles)
% hObject    handle to MW_Strom (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,'N')==1
   
   if get(handles.Zeitschritt_fest,'Value')==true
     N=handles.N;
     k=handles.k; 
     DefaultName = [num2str(k),'_Sim_N_',num2str(N),'_Strom_MW','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
     if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        csvwrite(FilePath,handles.SEc);
     end
   end 
 
   if get(handles.glatt,'Value')==true
     DefaultName = ['Strom_Glatt','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
     if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        csvwrite(FilePath,handles.strom');
     end
   end
end

% --------------------------------------------------------------------
function MW_Fluoreszenz_Callback(hObject, eventdata, handles)
% hObject    handle to MW_Fluoreszenz (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,'N')==1
     
   if get(handles.Zeitschritt_fest,'Value')==true
     N=handles.N;
     k=handles.k; 
     DefaultName = [num2str(k),'_Sim_N_',num2str(N),'_Fluor_MW','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
     if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        csvwrite(FilePath,handles.SEb);
     end
   end 
 
   if get(handles.glatt,'Value')==true
     DefaultName = ['Fluor_Glatt','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
     if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        csvwrite(FilePath,handles.fluor');
     end
   end
end

% --------------------------------------------------------------------
function ST_Strom_Callback(hObject, eventdata, handles)
% hObject    handle to ST_Strom (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,'N')==1
     
   if get(handles.Zeitschritt_fest,'Value')==true
     N=handles.N;
     k=handles.k; 
     DefaultName = [num2str(k),'_Sim_N_',num2str(N),'_Strom_SAW','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
     if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        csvwrite(FilePath,handles.SQc);
     end
   end
   
   if get(handles.glatt,'Value')==true
        warndlg('Achtung hier ist die Standardabweichung gleich Null');
   end
end

% --------------------------------------------------------------------
function ST_Fluoreszenz_Callback(hObject, eventdata, handles)
% hObject    handle to ST_Fluoreszenz (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,'N')==1
     
   if get(handles.Zeitschritt_fest,'Value')==true
     N=handles.N;
     k=handles.k; 
     DefaultName = [num2str(k),'_Sim_N_',num2str(N),'_Fluor_SAW','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
     if FileName~=0      % Nur wenn ein file ausgewählt wurde
        FilePath=fullfile(PathName,FileName);
        csvwrite(FilePath,handles.SQb);
     end
   end
   
   if get(handles.glatt,'Value')==true
        warndlg('Achtung hier ist die Standardabweichung gleich Null');
   end
end

% --------------------------------------------------------------------
function Pulsprotokoll_neu_laden_Callback(hObject, eventdata, handles)
% hObject    handle to Pulsprotokoll_neu_laden (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 [FileNameP,PathNameP]=uigetfile('*.m');
    if FileNameP~=0      % Nur wenn ein file ausgewählt wurde
        FilePathP=fullfile(PathNameP,FileNameP);
        set(handles.Pulsname,'String',FileNameP);
         Pulsname=get(handles.Pulsname, 'String');
    Puls=Pulsname(1:end-2);
    [PP,dt] = feval(Puls);          % Pulsdaten einlesen 
  
    n=[];
    C=[];
    U=[];
   
    c= PP(3,:); % Konzentration
    i=length(c);
    for m=1:i
    C=[C,c(m),c(m)]; 
    end
    
    u= PP(2,:); %Spannung
    i=length(u);
    for m=1:i
    U=[U,u(m),u(m)];
    end
    
    %für das Darstellen der Zeit
    a=PP(1,:);
    b=length(a);
    i=b-1;   % letzten Wert weg schneiden
    a=cumsum(a); 
    for m=1:i
    n=[n,a(m),a(m)];           
    end
    x=[0,n,a(i+1)];
       
    axes(handles.axes5);   % Axes 5 ausgewählt
    ymin = min(U)-0.1*(max(U));
    ymax = max(U)+0.1*(max(U));
    xmin=min(x);
    xmax=max(x);
    plot(x,U); %Spannung plotten
    hold on;
    plot(x,zeros(size(x)),':k');
    hold off;
    axis([xmin, xmax, ymin, ymax]);
    xlabel('t');
    ylabel('U');
    
    axes(handles.axes7);   % Axes 7 ausgewählt
    ymin = min(C)-0.1*(max(C)-min(C));
    ymax = max(C)+0.1*(max(C)-min(C));
    xmin=min(x);
    xmax=max(x);
    plot(x,C); %Konzentration plotten
    hold on;
    plot(x,zeros(size(x)),':k');
    hold off;
    axis([xmin, xmax, ymin, ymax]);
    xlabel('t');
    ylabel('C');
    end       
    
    % Die handles-struktur aktualisieren
guidata(hObject, handles);

% --------------------------------------------------------------------
function Modell_neu_laden_Callback(hObject, eventdata, handles)
% hObject    handle to Modell_neu_laden (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[FileNameM,PathNameM]=uigetfile('*.m');
    if FileNameM~=0      % Nur wenn ein file ausgewählt wurde
        FilePathM=fullfile(PathNameM,FileNameM);
        set(handles.Modellname,'String',FileNameM);
     end
    
    % Die handles-struktur aktualisieren
guidata(hObject, handles);
     


% --------------------------------------------------------------------
function uitoggletool4_ClickedCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h = zoom;
set(h,'Motion','both','Enable','on','Direction', 'in');
% zoom in direction:both aber auch 'horizontal'|'vertical' möglich

% --------------------------------------------------------------------
function uitoggletool5_ClickedCallback(hObject, eventdata, handles)
% hObject    handle to uitoggletool5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
h = zoom;
set(h,'Motion','both','Enable','on','Direction', 'out');
