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

% Last Modified by GUIDE v2.5 21-Oct-2015 09:50:46

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

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

% Update handles structure
guidata(hObject, handles);

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


% --- Outputs from this function are returned to the command line.
function varargout = gui_plot_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 selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (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 popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1


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



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


% --- Executes during object creation, after setting all properties.
function endtime_CreateFcn(hObject, eventdata, handles)
% hObject    handle to endtime (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 starttime_Callback(hObject, eventdata, handles)
% hObject    handle to starttime (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 starttime as text
%        str2double(get(hObject,'String')) returns contents of starttime as a double


% --- Executes during object creation, after setting all properties.
function starttime_CreateFcn(hObject, eventdata, handles)
% hObject    handle to starttime (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 enddate_Callback(hObject, eventdata, handles)
% hObject    handle to enddate (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 enddate as text
%        str2double(get(hObject,'String')) returns contents of enddate as a double


% --- Executes during object creation, after setting all properties.
function enddate_CreateFcn(hObject, eventdata, handles)
% hObject    handle to enddate (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 startdate_Callback(hObject, eventdata, handles)
% hObject    handle to startdate (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 startdate as text
%        str2double(get(hObject,'String')) returns contents of startdate as a double


% --- Executes during object creation, after setting all properties.
function startdate_CreateFcn(hObject, eventdata, handles)
% hObject    handle to startdate (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 pfad_Callback(hObject, eventdata, handles)
% hObject    handle to pfad (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 pfad as text
%        str2double(get(hObject,'String')) returns contents of pfad as a double


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


% --- Executes on button press in profil.
function profil_Callback(hObject, eventdata, handles)
% hObject    handle to profil (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 profil


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

%Pfad einlesen
path = evalin('base','path');

% Zeitraum einlesen
if get(handles.rbzeitraum1,'Value')     % bestimmter Zeitraum
    
    %Zeiten einlesen
    start_hour=evalin('base','start_hour');
    start_min=evalin('base','start_min');
    start_day=evalin('base','start_day');
    start_month=evalin('base','start_month');
    start_year=evalin('base','start_year');
    end_hour=evalin('base','end_hour');
    end_min=evalin('base','end_min');
    end_day=evalin('base','end_day');
    end_month=evalin('base','end_month');
    end_year=evalin('base','end_year');
    
    
elseif get(handles.rbzeitraum2,'Value')     %ausgewählte Monate & Jahre
    %mult_month = get(handles.lbmonat,'Value');
    %mult_year = get(handles.lbjahr,'Value');
    %mult_year = mult_year+2009-1;
    errordlg('Nur für bestimmte Zeiträume') %momentan nicht implementiert
    return
end

%Flags einlesen
sonic_ID = get(handles.rbsonic,'Value');
sodar_ID = get(handles.rbsodar,'Value');
both_ID = get(handles.rbbeide,'Value');

if get(handles.xy,'Value')  %xy-Plot
    
    % Plot ID
    plot_ID=1;
    
    % x-Achse
    popup_idx=get(handles.popupmenu1,'Value');
    if sonic_ID == 1    %Nummerierung Sonic
        switch popup_idx
            case 1
                spalte_x = 8; %Zeit
                xlab='day';
            case 2
                spalte_x = 27;    %u*
                xlab='u*';
            case 3
                spalte_x= 80;    %Richardson !!!
                xlab='Ri';
            case 4
                spalte_x = 30;   % w'T'
                xlab='w''T''';
            case 5
                spalte_x = 77;     % Tpot !!!
                xlab='Tpot';
            case 6
                spalte_x = 23;    % q
                xlab='q';
            case 7
                spalte_x = 22;    % RH
                xlab='RH';
            case 8
                spalte_x = 29;    % z/L
                xlab='z/L';
            case 11
                spalte_x = 12;   % WD
                xlab='WD';
            case 12
                spalte_x = 13;   % WS
                xlab='WS';
            case 13
                spalte_x = 16;   % w
                xlab='w';
            case 14
                spalte_x = 117;   % T
                xlab='T';
            case 15
                spalte_x = 41;   % CT^2
                xlab='CT^2';
            case 16
                spalte_x = 48;   % Cn^2
                xlab='Cn^2';
            otherwise
                errordlg('Variable nicht für Sonic verfügbar!');
                return
        end
    elseif sodar_ID == 1    %Nummerierung Sodar (Cn2 nur bei Profil)
        switch popup_idx
            case 1
                spalte_x = 1; %Zeit
                xlab='day';
            case 9
                spalte_x = 8;    % sigw
                xlab='RH';
            case 10
                spalte_x = 11;    % Tv
                xlab='z/L';
            case 11
                spalte_x = 13;   % WD
                xlab='WD';
            case 12
                spalte_x = 12;   % WS
                xlab='WS';
            case 13
                spalte_x = 7;   % w
                xlab='w';
            case 14
                spalte_x = 10;   % T
                xlab='T';
            case 15
                spalte_x = 9;   % CT^2
                xlab='CT^2';
            otherwise
                errordlg('Variable nicht für Sodar verfügbar!');
                return
        end
        
    end
    
    % y-Achse
    spalte_y = get(handles.yax,'String');
    
    if sonic_ID == 1    %Beschriftung Sonic
        if strcmp(spalte_y,'12')
            ylab='wind direction';
        elseif strcmp(spalte_y,'13')
            ylab='wind velocity';
        elseif strcmp(spalte_y,'22')
            ylab='RH';
        elseif strcmp(spalte_y,'27')
            ylab='u*';
        elseif strcmp(spalte_y,'30')
            ylab='w''T''';
        elseif strcmp(spalte_y,'41')
            ylab='C_T^2';
        elseif strcmp(spalte_y,'48')
            ylab='C_n^2';
        elseif strcmp(spalte_y,'16')
            ylab = 'w';
        elseif strcmp(spalte_y,'17')
            ylab = 'T';
        end
    elseif sodar_ID == 1    %Beschriftung Sodar
        if strcmp(spalte_y,'13')
            ylab='wind direction';
        elseif strcmp(spalte_y,'12')
            ylab='wind velocity';
        elseif strcmp(spalte_y,'11')
            ylab='Tv';
        elseif strcmp(spalte_y,'8')
            ylab='sigw';
        elseif strcmp(spalte_y,'9')
            ylab='C_T^2';
        elseif strcmp(spalte_y,'7')
            ylab = 'w';
        elseif strcmp(spalte_y,'10')
            ylab = 'T';
        end
    end
    
    % Höhe
    height=str2double(get(handles.edheight,'String'));
    
    % in workspace
    assignin('base','plot_ID',plot_ID);
    assignin('base','spalte_x',spalte_x);
    assignin('base','spalte_y',str2double(spalte_y));
    assignin('base','height',height);
    
else get(handles.profil,'Value')    %Profil
    
    % Plot ID
    plot_ID=2;
    
    % Profilvariable
    spalte_var = str2double(get(handles.var_profil,'String'))
    
    % in workspace
    assignin('base','plot_ID',plot_ID);
    assignin('base','spalte_var',spalte_var);
end

%Fehler abfangen
if plot_ID==1 && both_ID==1
    errordlg('Auswahl "beide" zum Plotten nicht möglich!');
    return
end
if plot_ID==1 && (sonic_ID==1 && height>64)
    errordlg('Sonic-Daten nur bis 64m!');
    return
end


if sonic_ID ==1     % Sonic
    if get(handles.rbzeitraum1,'Value')     % bestimmter Zeitraum
        if plot_ID == 1                     % xy Plot
            
            daten=evalin('base','daten_sonic_xy');  %Daten einlesen
            
            if spalte_x==8  %normaler Plot für Zeitreihe
                if (spalte_y~=48)||(spalte_y~=41)
                   plot(daten(:,spalte_x),daten(:,str2double(spalte_y)));
                else    %log bei Cn2,CT2
                    plot(daten(:,spalte_x),log10(daten(:,str2double(spalte_y))));
                end
            elseif (spalte_x==48)||(spalte_x==41)    %Scatterplot für Rest
                if (spalte_y==48)||(spalte_y==41)
                  plot(log10(daten(:,spalte_x)),log10(daten(:,str2double(spalte_y))),'+');
                else
                  plot(log10(daten(:,spalte_x)),daten(:,str2double(spalte_y)),'+');  
                end
            else
                plot(daten(:,spalte_x),daten(:,str2double(spalte_y)),'+');
            end
            xlabel(xlab)
            ylabel(ylab)
            
        elseif plot_ID == 2                 % Profil Plot
            
            daten = evalin('base','daten_sonic_prof');  %Daten einlesen
            idx = evalin('base','idx');
            
            if get(handles.alle_profile,'Value')    %alle Profile plotten
                
                colo{1} = 'b';  %einfache Farbpalette
                colo{2} = 'r';
                colo{3} = 'g';
                colo{4} = 'k';
                
                plot(daten(idx(1):idx(1)+4,spalte_var),daten(idx(1):idx(1)+4,1));
                hold on
                
                for l=2:size(idx,1)
                    
                    %Farbe für Plot festlegen (beliebig)
                    if mod(l,2)==0
                        col=2;
                        if mod(l,4)==0
                            col = 4;
                        end
                    elseif mod(l,3)==0
                        col = 3;
                    else
                        col=1;
                    end
                    plot(daten(idx(l):idx(l)+4,spalte_var),daten(idx(l):idx(l)+4,1),colo{col});
                    
                end
                hold off
                
            else    %nur das erste Profil plotten
                if (spalte_var==41)||(spalte_var==48)
                    plot(log10(daten(idx(1):idx(1)+4,spalte_var)),daten(idx(1):idx(1)+4,1));
                else
                    plot(daten(idx(1):idx(1)+4,spalte_var),daten(idx(1):idx(1)+4,1));
                end
            end
            
            ylabel('z [m]')
            if spalte_var==3
                xlabel('wind direction')
            elseif spalte_var==4
                xlabel('wind speed')
            elseif spalte_var==6
                xlabel('T')
            elseif spalte_var==7
                xlabel('RH')
            elseif spalte_var==15
                xlabel('C_T^2')
            elseif spalte_var==16
                xlabel('C_n^2')
            end
        end
    end
    
elseif sodar_ID == 1
    if get(handles.rbzeitraum1,'Value')     % bestimmter Zeitraum  
        
        plot_h=evalin('base','print_hour');
        plot_m=evalin('base','print_min');
        height_sodar=evalin('base','height_sodar');
        
        if plot_ID == 1     %xy-Plot
            daten=evalin('base','daten_sodar');
            if spalte_x==1  %normaler Plot für Zeitreihe
                deztag = daten(:,3)+daten(:,4)/24+daten(:,5)/1440; %deztag ausrechnen
                id = find(daten(:,6)==height);
                if (spalte_y~=9)
                    plot(deztag(id),daten(id,str2double(spalte_y)));
                else
                    plot(deztag(id),log10(daten(id,str2double(spalte_y))));
                end
            elseif (spalte_x==9)
                if (spalte_y==9)
                    plot(log10(daten(:,spalte_x)),log10(daten(:,str2double(spalte_y))),'+');
                else
                    plot(log10(daten(:,spalte_x)),daten(:,str2double(spalte_y)),'+');
                end
            else    %Scatterplot für Rest
                plot(daten(:,spalte_x),daten(:,str2double(spalte_y)),'+');
            end
            
            
        elseif plot_ID == 2     %Profil
            hour_sodar=evalin('base','hour_sodar');
            minute_sodar=evalin('base','minute_sodar');
            
            ylab='z [m]';
            if spalte_var==7    %entsprechende Daten einlesen
                xlab='w';
                daten = evalin('base','sodar_w');
            elseif spalte_var==8
                xlab='sigma_w';
                daten = evalin('base','sodar_sigw');
            elseif spalte_var==9
                xlab='C_T^2';
                daten = evalin('base','sodar_Ct2');
            elseif spalte_var==10
                xlab='T';
                daten = evalin('base','sodar_T');
            elseif spalte_var==11
                xlab='T_v';
                daten = evalin('base','sodar_Tv');
            elseif spalte_var==12
                xlab='wind speed';
                daten = evalin('base','sodar_speed');
            elseif spalte_var==13
                xlab='wind direction';
                daten = evalin('base','sodar_dir');
            end
            
            % angegebene Uhrzeit finden
            id = find(hour_sodar==plot_h);
            id2 = find(minute_sodar(id)==plot_m);
            
            if strcmp(xlab,'C_T^2')
               plot(log10(daten(:,id2(1))),height_sodar);
            else
               plot(daten(:,id2(1)),height_sodar);  
            end
            xlabel(xlab)
            ylabel(ylab)
            
        end
    end
end




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

%Plot in neue figure kopieren
figure('visible','off');
copy_im = axes;
copyobj(allchild(handles.axes1),copy_im);
%Dateiname abfragen
prompt = {'Dateiname angeben:'};
dlg_title = 'Speichern';
num_lines=1;
def={'Plot1'};
outfile=inputdlg(prompt,dlg_title,num_lines,def);
%Pfad einlesen und mit Dateinamen kombinieren
path = evalin('base','path');
out = strcat(path,outfile);
%speichern & schließen
saveas(gca, out{1,1},'png');
close(figure);



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


% --- Executes during object creation, after setting all properties.
function var_profil_CreateFcn(hObject, eventdata, handles)
% hObject    handle to var_profil (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 yax_Callback(hObject, eventdata, handles)
% hObject    handle to yax (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 yax as text
%        str2double(get(hObject,'String')) returns contents of yax as a double


% --- Executes during object creation, after setting all properties.
function yax_CreateFcn(hObject, eventdata, handles)
% hObject    handle to yax (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 selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (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 popupmenu2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu2


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


% --- Executes on button press in alle_profile.
function alle_profile_Callback(hObject, eventdata, handles)
% hObject    handle to alle_profile (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 alle_profile


% --- 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


% --- 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

% 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 on selection change in lbmonat.
function lbmonat_Callback(hObject, eventdata, handles)
% hObject    handle to lbmonat (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 lbmonat contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lbmonat


% --- Executes during object creation, after setting all properties.
function lbmonat_CreateFcn(hObject, eventdata, handles)
% hObject    handle to lbmonat (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 on selection change in lbjahr.
function lbjahr_Callback(hObject, eventdata, handles)
% hObject    handle to lbjahr (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 lbjahr contents as cell array
%        contents{get(hObject,'Value')} returns selected item from lbjahr


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



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


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

%Pfad einlesen
path = get(handles.pfad,'String');
%ggf "\" hinten anfügen
if ~strcmp(path(end),'\')
    path(end+1)='\';
end
path = strtrim(path);           % Leerzeichen entfernen
assignin('base','path',path);   % in workspace

% Zeitraum einlesen
if get(handles.rbzeitraum1,'Value')     % bestimmter Zeitraum
    startdate = get(handles.startdate,'String');
    assignin('base','startdate',startdate);
    enddate = get(handles.enddate,'String');
    assignin('base','enddate',enddate);
    starttime = get(handles.starttime,'String');
    assignin('base','starttime',starttime);
    endtime = get(handles.endtime,'String');
    assignin('base','endtime',endtime);
    
    % einzelne Teile auslesen
    start_hour=(starttime(1:2));
    start_min=(starttime(4:5));
    start_day=startdate(1:2);
    start_month=(startdate(4:5));
    start_year=(startdate(7:10));
    end_hour=(endtime(1:2));
    end_min=(endtime(4:5));
    end_day=enddate(1:2);
    end_month=(enddate(4:5));
    end_year=(enddate(7:10));
    
    % in workspace
    assignin('base','start_hour',start_hour);
    assignin('base','start_min',start_min);
    assignin('base','start_day',start_day);
    assignin('base','start_month',start_month);
    assignin('base','start_year',start_year);
    assignin('base','end_hour',end_hour);
    assignin('base','end_min',end_min);
    assignin('base','end_day',end_day);
    assignin('base','end_month',end_month);
    assignin('base','end_year',end_year);
    
elseif get(handles.rbzeitraum2,'Value')     %ausgewählte Monate & Jahre
    
    %einlesen
    mult_month = get(handles.lbmonat,'Value');
    mult_year = get(handles.lbjahr,'Value');
    mult_year = mult_year+2009-1;
    
    % in workspace
    assignin('base','mult_month',mult_month);
    assignin('base','mult_year',mult_year);
end

%Gerät einlesen
sonic_ID = get(handles.rbsonic,'Value');
sodar_ID = get(handles.rbsodar,'Value');
both_ID = get(handles.rbbeide,'Value');
% in workspace
assignin('base','sonic_ID',sonic_ID);
assignin('base','sodar_ID',sodar_ID);
assignin('base','both_ID',both_ID);

if get(handles.xy,'Value')  %xy-Plot
    
    % Plot ID
    plot_ID=1;
    
    % Höhe
    height=str2double(get(handles.edheight,'String'));
    
    %Spalte
    ycol = str2double(get(handles.yax,'String'));
    
    % in workspace
    assignin('base','plot_ID',plot_ID);
    assignin('base','height',height);
    assignin('base','ycol',ycol);
    
else get(handles.profil,'Value') %Profil
    
    % Plot ID
    plot_ID=2;
    
    % Profilvariable
    spalte_var = str2double(get(handles.var_profil,'String'));
    
    %Uhzeit für Ausgabe
    temp = get(handles.printtime_vert,'String');
    print_hour = str2double(temp(1:2));
    print_min = str2double(temp(4:5));
       
    % in workspace
    assignin('base','plot_ID',plot_ID);
    assignin('base','spalte_var',spalte_var);
    assignin('base','print_hour',print_hour);
    assignin('base','print_min',print_min);
    
end

%mögliche Fehler abfangen
if plot_ID==1 && both_ID==1
    errordlg('Auswahl "beide" nur für Profil!');
    return
end
if plot_ID==1 && (sonic_ID==1 && height>64)
    errordlg('Daten Sonic nur bis 64m!');
    return
end

%Sonic-Daten einlesen
if sonic_ID == 1     % Sonic
    if get(handles.rbzeitraum1,'Value')     % bestimmter Zeitraum
        if plot_ID == 1                     % xy Plot
            run('sonic_xy_GUI.m');
        elseif plot_ID == 2                 % Profil Plot
            run('sonic_Profil_GUI.m');
        end
    elseif get(handles.rbzeitraum2,'Value')     % mehrere Monate
        run('sonic_multmon_GUI.m');
    end
%Sodar-Daten einlesen    
elseif sodar_ID == 1    % Sodar
    if get(handles.rbzeitraum1,'Value')     % bestimmter Zeitraum
        run('Sodar_GUI.m');                % gleiche Daten für Zeitraum & Profil
    elseif get(handles.rbzeitraum2,'Value')
        run('Sodar_multmon_GUI.m');
    end
%beide Datensätze einlesen (nur Profil)
elseif both_ID == 1
    if get(handles.rbzeitraum1,'Value')
        run('Sodar_GUI.m');
        run('sonic_Profil_GUI.m');
    elseif get(handles.rbzeitraum2,'Value')
        run('Sodar_multmon_GUI.m');
        run('sonic_multmon_GUI.m');
    end
    
end
helpdlg('Einlesen beendet'); %Anzeige, dass Einlesen beendet (dauert ggf länger)




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


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

%Parameter & Höhe konstant, nur xy-Plot

%Daten einlesen
plot_ID = evalin('base','plot_ID');
if plot_ID==2
    errordlg('Nur für xy-Plots möglich!');
    return
end

sonic_ID = evalin('base','sonic_ID');
sodar_ID = evalin('base','sodar_ID');
start_year = evalin('base','start_year');
start_month = evalin('base','start_month');
start_day = evalin('base','start_day');
end_year = evalin('base','end_year');
end_month = evalin('base','end_month');
end_day = evalin('base','end_day');
path = evalin('base','path');
ycol = evalin('base','ycol');
hoehe = evalin('base','height');

if sonic_ID == 1    %Sonic
 
    %Datein einlesen
    daten = evalin('base','daten_sonic_xy');
    
    output{1,1} = strcat(num2str(ycol)); %Spalte in erstes Element eintragen
    
    if get(handles.rbzeitraum2,'Value')
        
        
    %Ausgabedatei
    
        mult_year = evalin('base','mult_year');
        mult_month = evalin('base','mult_month');
        outfile = ['sonic_xy_',num2str(mult_month(1),'%02d'),num2str(mult_year(1)),'-',num2str(mult_month(end),'%02d'),num2str(mult_year(end)),'.dat'];
        
        idx1 = find((daten(:,5)==0));
        idx2 = find((daten(idx1,6)==0));
        for l=idx1(idx2(1)):idx1(idx2(2))-1
            output{l+1,1} = strcat(num2str(daten(l,5),'%02d'),':',num2str(daten(l,6),'%02d'));
        end
        
        for y=1:size(mult_year,2)
            year = mult_year(y);
            for m=1:size(mult_month,2)
                month = mult_month(m);
                idy = find(daten(:,2)==year);
                idm = find(daten(idy,3)==month);
                idym=idy(idm);
                for d=1:31
                    idday=find(daten(idym,4)==d);
                    if isempty(idday)
                        break
                    end
                    output{1,end+1}=strcat(num2str(d,'%02d'),'.',num2str(month,'%02d'),'.',num2str(year));
                    for l=1:size(idday,1)
                        output{l+1,end} = daten(idday(l),ycol);
                    end
                end
            end
        end
        
        
    else
        
    %Ausgabedatei
    outfile = ['sonic_xy_',start_year,start_month,start_day,'-',end_year,end_month,end_day,'.dat'];
        %Daten in Zeitraum auswählen
        for l=0:(str2double(end_day)-str2double(start_day)) %nicht monatsüberschreitend
            id{l+1} = find(daten(:,4)==str2double(start_day)+l);
            output{1,l+2} = strcat(num2str(str2double(start_day)+l,'%02d'),'.',start_month,'.',start_year);
        end
        
        for l = 1:size(id,2)
            sizelist(l) = size(id{1,l},1);
        end
        time_id = find(sizelist==max(sizelist));
        time_id = time_id(1);
        
        idx = id{1,time_id};
        for l=1:size(idx,1)
            hour(l,1) = daten(idx(l),5);
            minute(l,1) = daten(idx(l),6);
            dectime(l,1) = daten(idx(l),5)+daten(idx(l),6)/60;
            output{l+1,1} = strcat(num2str(hour(l),'%02d'),':',num2str(minute(l),'%02d'));
        end
        
        %Daten mit kleinstem Zeitunterschied
        for l=1:size(id,2)
            idx = id{1,l};
            if isempty(idx)
                break
            end
            dtime = daten(idx(1),5)+daten(idx(1),6)/60;
            temp = dectime-dtime;
            ids = find(temp == min(abs(temp)));
            clearvars temp
            for m=1:size(idx,1)
                output{m+ids,l+1} = daten(idx(m),ycol);
            end
        end
        
    end
    
else    %Sodar
    
    %Ausgabedatei
    outfile = ['sodar_xy_',start_year,start_month,start_day,'-',end_year,end_month,end_day,'.dat'];
    
    %entsprechende Daten einlesen
    switch ycol
        case 7
            daten_spalte = evalin('base','sodar_w');
            vari = 'w';
        case 8
            daten_spalte = evalin('base','sodar_sigw');
            vari = 'sigw';
        case 9
            daten_spalte = evalin('base','sodar_Ct2');
            vari = 'CT2';
        case 14
            daten_spalte = evalin('base','sodar_Cn2');
            vari = 'Cn2';
        case 10
            daten_spalte = evalin('base','sodar_T');
            vari = 'T';
        case 11
            daten_spalte = evalin('base','sodar_Tv');
            vari = 'Tv';
        case 12
            daten_spalte = evalin('base','sodar_speed');
            vari = 'speed';
        case 13
            daten_spalte = evalin('base','sodar_dir');
            vari = 'dir';
    end
    daten = evalin('base','daten_sodar');
    height_sodar = evalin('base','height_sodar');
    hour = evalin('base','hour_sodar');
    minute = evalin('base','minute_sodar');
    dectime = evalin('base','dectime_sodar');
    
    %Daten in richtiger Höhe finden
    del = find(daten(:,6)==hoehe);
    daten = daten(del,:);
    del = find(height_sodar==hoehe);
    daten_spalte = daten_spalte(del,:);
    
    output{1,1} = vari;     %Variablenname in erstes Element
    for l=1:size(dectime,1)
        output{l+1,1} = strcat(num2str(hour(l),'%02d'),':',num2str(minute(l),'%02d'));
    end
    
    %Daten aus Zeitraum finden
    for l=0:(str2double(end_day)-str2double(start_day)) %nicht monatsüberschreitend
        id{l+1} = find(daten(:,3)==str2double(start_day)+l);
        output{1,l+2} = strcat(num2str(str2double(start_day)+l,'%02d'),'.',start_month,'.',start_year);
    end
    
    %kleinste zeitliche Abweichung
    for l=1:size(id,2)
        idx = id{1,l};
        dtime = daten(idx(1),4)+daten(idx(1),5)/60;
        temp = dectime-dtime;
        ids = find(temp == min(abs(temp)));
        clearvars temp
        for m=1:size(idx,1)
            output{m+ids,l+1} = daten_spalte(1,idx(m));
        end
    end
    
end

%Daten ohne Header-Zeilen
output_daten = output(2:end,2:end);
%leere Elemente mit NaN füllen
a = find(cellfun(@isempty, output_daten));
for l=1:size(a,1)
    output_daten{a(l)} = NaN;
end
% als Double-Matrix speichern (zum Rechnen)
output_daten = cell2mat(output_daten);

% Zeilenstatistik
%Gesamtzahl (ohne leere Spalten)
output{1,end+1} = 'N gesamt';
for l=2:size(output,1)  %erste Zeile überspringen
    temp = output(l,:);
    nempty = find(cellfun(@isempty, temp));
    output{l,end} = size(output,2)-1-size(nempty,2); %-1 wegen Uhrzeit-Spalte
end
%Mittelwert
output{1,end+1} = 'Mittelwert';
for m = 1:size(output_daten,1)
    output{m+1,end} = nanmean(output_daten(m,:));
end
%Standardabweichung
output{1,end+1} = 'Standardabweichung';
sigma = nanstd(output_daten,0,2); %flag=0: 1/(n-1); flag=1: 1/n --> Matlab
for l=1:size(output_daten,1)
    output{l+1,end} = sigma(l);
end
%Minimum
output{1,end+1} = 'Minimum';
mini = nanmin(output_daten,[],2);
for l=1:size(output_daten,1)
    output{l+1,end} = mini(l);
end
%Median
output{1,end+1} = 'Median';
med = nanmedian(output_daten,2);
for l=1:size(output_daten,1)
    output{l+1,end} = med(l);
end
%Maximum
output{1,end+1} = 'Maximum';
maxi = nanmax(output_daten,[],2);
for l=1:size(output_daten,1)
    output{l+1,end} = maxi(l);
end

%Ausgabedatei öffnen und speichern
fout = fopen([path,outfile],'w+');
for i4=1:size(output,1)
    for i3=1:size(output,2)
        if (i3==1)&&(i4~=1)
            if ~isnan(output{i4,i3})
                fprintf(fout,'\r\n%s\t', num2str(output{i4,i3}));
            else
                fprintf(fout,'\r\n%s\t', '-'); %NaN mit - ersetzen
            end
        else
            if ~isnan(output{i4,i3})
                fprintf(fout,'%s\t', num2str(output{i4,i3}));
            else
                fprintf(fout,'%s\t', '-'); %NaN mit - ersetzen
            end
        end
    end
end
fclose(fout);



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

%Tageszeit & Parameter konstant

%Daten einlesen
plot_ID = evalin('base','plot_ID');
if plot_ID==1
    errordlg('Nur für Profildaten möglich!');
    return
end

sonic_ID = evalin('base','sonic_ID');
sodar_ID = evalin('base','sodar_ID');
both_ID = evalin('base','both_ID');
print_hour = evalin('base','print_hour');
print_min = evalin('base','print_min');
spalte_var = evalin('base','spalte_var');
start_year = evalin('base','start_year');
start_month = evalin('base','start_month');
start_day = evalin('base','start_day');
end_year = evalin('base','end_year');
end_month = evalin('base','end_month');
end_day = evalin('base','end_day');
path = evalin('base','path');

if sonic_ID == 1    %Sonic
    
    %Ausgabedatei
    outfile = ['sonic_profil_',start_year,start_month,start_day,'-',end_year,end_month,end_day,'.dat'];
    
    daten = evalin('base','daten_sonic_prof');
    zeit = evalin('base','time_sonic_prof');
    anz_hoehe=5;
    
    % Ausgabeuhrzeit finden
    id1 = find(zeit(:,4)==print_hour);
    temp = abs(zeit(id1,5)-print_min);
    id2 = find(temp==min(temp));
    id = id1(id2);
    id = id(1:5:end); %nur jeden 5. Eintrag (5 Höhen)
    
    %Ausgabe füllen
    for l=1:size(id,1)
        tag = num2str(zeit(id(l),3),'%02d');
        monat = num2str(zeit(id(l),2),'%02d');
        jahr = num2str(zeit(id(l),1));
        stunde = num2str(zeit(id(l),4),'%02d');
        minu = num2str(zeit(id(l),5),'%02d');
        
        output{1,l} = [tag,'.',monat,'.',jahr,' ',stunde,':',minu];
        output{2,l} = daten(id(l),spalte_var+2);    %damit spalte_var bei 1 beginnen kann
        output{3,l} = daten(id(l)+1,spalte_var+2);
        output{4,l} = daten(id(l)+2,spalte_var+2);
        output{5,l} = daten(id(l)+3,spalte_var+2);
        output{6,l} = daten(id(l)+4,spalte_var+2);
        
        output_dat(1,l) = daten(id(l),spalte_var+2);
        output_dat(2,l) = daten(id(l)+1,spalte_var+2);
        output_dat(3,l) = daten(id(l)+2,spalte_var+2);
        output_dat(4,l) = daten(id(l)+3,spalte_var+2);
        output_dat(5,l) = daten(id(l)+4,spalte_var+2);
        
    end
    a=3;
    
elseif sodar_ID==1  %Sodar
    %Ausgabedatei
    outfile = ['sodar_profil_',start_year,start_month,start_day,'-',end_year,end_month,end_day,'.dat'];
    %entsprechende Daten einlesen
    switch spalte_var
        case 7
            daten_spalte = evalin('base','sodar_w');
        case 8
            daten_spalte = evalin('base','sodar_sigw');
        case 9
            daten_spalte = evalin('base','sodar_Ct2');
        case 14
            daten_spalte = evalin('base','sodar_Cn2');
        case 10
            daten_spalte = evalin('base','sodar_T');
        case 11
            daten_spalte = evalin('base','sodar_Tv');
        case 12
            daten_spalte = evalin('base','sodar_speed');
        case 13
            daten_spalte = evalin('base','sodar_dir');
    end
    daten = evalin('base','daten_sodar');
    anz_hoehe = size(daten_spalte,1);
    
    %nur Daten um xx:00 und xx:30 --> Ausgabeuhrzeit zuweisen
    if print_min<16
        print_min = 0;
    elseif print_min>45
        print_min = 0;
        print_hour = print_hour+1;
    else
        print_min = 30;
    end
    
    %Ausgabeuhrzeit finden
    id1 = find(daten(:,4)==print_hour);
    id2 = find(daten(id1,5)==print_min);
    id = id1(id2);
    step = find(diff(id)~=1);
    idx=id(1);
    for l=1:size(step,1)
        idx(l+1) = id(step(l)+1);
    end
    idx2=ceil(idx./anz_hoehe);
    %Ausgabe füllen
    for l=1:size(idx,2)
        tag = num2str(daten(idx(l),3),'%02d');
        monat = num2str(daten(idx(l),2),'%02d');
        jahr = num2str(daten(idx(l),1));
        stunde = num2str(daten(idx(l),4),'%02d');
        minu = num2str(daten(idx(l),5),'%02d');
        
        output{1,l} = [tag,'.',monat,'.',jahr,' ',stunde,':',minu];
        for m=1:anz_hoehe
            output{m+1,l} = daten_spalte(m,idx2(l));    %damit spalte_var bei 1 beginnen kann
            output_dat(m,l) = daten_spalte(m,idx2(l));
        end
    end
    
elseif both_ID == 1
    
    outfile = ['beide_profil_',start_year,start_month,start_day,'-',end_year,end_month,end_day,'.dat'];
    % sonic
    switch spalte_var
        case 7
            spalte_sonic = 99;
        case 8
            spalte_sonic = 99;
        case 9
            spalte_sonic = 13;
        case 4
            spalte_sonic = 14;
        case 10
            spalte_sonic = 4;
        case 11
            spalte_sonic = 18;
        case 12
            spalte_sonic = 2;
        case 13
            spalte_sonic = 1;
    end
    
    daten = evalin('base','daten_sonic_prof');
    zeit = evalin('base','time_sonic_prof');
    anz_hoehe=5;
    hoehe_sonic = [1.2; 4; 8;32;64];
    
    %Ausgabeuhrzeit finden
    id1 = find(zeit(:,4)==print_hour);
    temp = abs(zeit(id1,5)-print_min);
    id2 = find(temp==min(temp));
    id = id1(id2);
    id = id(1:5:end); %nur jeden 5. Eintrag (5 Höhen)
    
    for l=1:size(id,1)
        tag = num2str(zeit(id(l),3),'%02d');
        monat = num2str(zeit(id(l),2),'%02d');
        jahr = num2str(zeit(id(l),1));
        stunde = num2str(zeit(id(l),4),'%02d');
        minu = num2str(zeit(id(l),5),'%02d');
        
        %Output Sonic
        output_sonic{1,l} = [tag,'.',monat,'.',jahr,' ',stunde,':',minu];
        if spalte_sonic ~= 99
            if (spalte_sonic==4) || (spalte_sonic==18) %T in °C
                output_sonic{2,l} = daten(id(l),spalte_sonic+2)-273.15;    %damit spalte_var bei 1 beginnen kann
                output_sonic{3,l} = daten(id(l)+1,spalte_sonic+2)-273.15;
                output_sonic{4,l} = daten(id(l)+2,spalte_sonic+2)-273.15;
                output_sonic{5,l} = daten(id(l)+3,spalte_sonic+2)-273.15;
                output_sonic{6,l} = daten(id(l)+4,spalte_sonic+2)-273.15;
                
                output_dat_sonic(1,l) = daten(id(l),spalte_sonic+2)-273.15;
                output_dat_sonic(2,l) = daten(id(l)+1,spalte_sonic+2)-273.15;
                output_dat_sonic(3,l) = daten(id(l)+2,spalte_sonic+2)-273.15;
                output_dat_sonic(4,l) = daten(id(l)+3,spalte_sonic+2)-273.15;
                output_dat_sonic(5,l) = daten(id(l)+4,spalte_sonic+2)-273.15;
                
            else
                output_sonic{2,l} = daten(id(l),spalte_sonic+2);    %damit spalte_var bei 1 beginnen kann
                output_sonic{3,l} = daten(id(l)+1,spalte_sonic+2);
                output_sonic{4,l} = daten(id(l)+2,spalte_sonic+2);
                output_sonic{5,l} = daten(id(l)+3,spalte_sonic+2);
                output_sonic{6,l} = daten(id(l)+4,spalte_sonic+2);
                
                output_dat_sonic(1,l) = daten(id(l),spalte_sonic+2);
                output_dat_sonic(2,l) = daten(id(l)+1,spalte_sonic+2);
                output_dat_sonic(3,l) = daten(id(l)+2,spalte_sonic+2);
                output_dat_sonic(4,l) = daten(id(l)+3,spalte_sonic+2);
                output_dat_sonic(5,l) = daten(id(l)+4,spalte_sonic+2);
            end
        else
            output_sonic{2,l} = NaN;    %damit spalte_var bei 1 beginnen kann
            output_sonic{3,l} = NaN;
            output_sonic{4,l} = NaN;
            output_sonic{5,l} = NaN;
            output_sonic{6,l} = NaN;
            
            output_dat_sonic(1,l) = NaN;
            output_dat_sonic(2,l) = NaN;
            output_dat_sonic(3,l) = NaN;
            output_dat_sonic(4,l) = NaN;
            output_dat_sonic(5,l) = NaN;
        end
        
    end
    
    %Sodar
    switch spalte_var
        case 7
            daten_spalte = evalin('base','sodar_w');
        case 8
            daten_spalte = evalin('base','sodar_sigw');
        case 9
            daten_spalte = evalin('base','sodar_Ct2');
        case 14
            daten_spalte = evalin('base','sodar_Cn2');
        case 10
            daten_spalte = evalin('base','sodar_T');
        case 11
            daten_spalte = evalin('base','sodar_Tv');
        case 12
            daten_spalte = evalin('base','sodar_speed');
        case 13
            daten_spalte = evalin('base','sodar_dir');
    end
    daten = evalin('base','daten_sodar');
    anz_hoehe = size(daten_spalte,1);
    h_0 = daten(1,6);
    hoe = find(daten(:,6) == h_0);
    hoe = hoe(2);
    hoehe_sodar = daten(1:hoe-1,6);
    
    %Ausgabeuhrzeit zuordnen
    if print_min<16
        print_min = 0;
    elseif print_min>45
        print_min = 0;
        print_hour = print_hour+1;
    else
        print_min = 30;
    end
    % Ausgabeuhrzeit finden
    id1 = find(daten(:,4)==print_hour);
    id2 = find(daten(id1,5)==print_min);
    id = id1(id2);
    step = find(diff(id)~=1);
    idx=id(1);
    for l=1:size(step,1)
        idx(l+1) = id(step(l)+1);
    end
    idx2=ceil(idx./anz_hoehe);
    %Outpu Sodar
    for l=1:size(idx,2)
        tag = num2str(daten(idx(l),3),'%02d');
        monat = num2str(daten(idx(l),2),'%02d');
        jahr = num2str(daten(idx(l),1));
        stunde = num2str(daten(idx(l),4),'%02d');
        minu = num2str(daten(idx(l),5),'%02d');
        
        output_sodar{1,l} = [tag,'.',monat,'.',jahr,' ',stunde,':',minu];
        for m=1:anz_hoehe
            output_sodar{m+1,l} = daten_spalte(m,idx2(l));    %damit spalte_var bei 1 beginnen kann
            output_dat_sodar(m,l) = daten_spalte(m,idx2(l));
        end
    end
    
    ida=find(hoehe_sodar==25);
    hoehe_sodar(1:ida,:)=[]
    output_dat_sodar(1:ida,:)=[];
    output_sodar(2:ida+1,:)=[];
    
    id30=find(hoehe_sodar==30);
    id60=find(hoehe_sodar==60);
    
    output = cell(size(output_sonic,1)+size(output_sodar,1)-1,size(output_sonic,2)+1);
    output{1,1} = 'Hoehe';
    output_dat = zeros(size(output,1)-1,size(output,2)-1);
    
    %Output zusammenfügen
    output = cell(size(output_sonic,1)+size(output_sodar,1)-1,size(output_sonic,2)+1);
    output{1,1} = 'Hoehe';
    output(1:size(output_sonic,1)-2,2:end) = output_sonic(1:4,1:end);
    output_dat(1:3,:) = output_dat_sonic(1:3,:);
    for l=1:size(hoehe_sonic,1)-2
        output{l+1,1} = hoehe_sonic(l);
    end
    for l=1:id30
        output{size(hoehe_sonic,1)+l-1,1} = hoehe_sodar(l);
        output(size(hoehe_sonic,1)+l-1,2:end) = output_sodar(l+1,1:end);
        output_dat(size(hoehe_sonic,1)+l-2,:) = output_dat_sodar(l,:);
    end
    output{size(hoehe_sonic,1)+id30,1} = hoehe_sonic(4);
    output(size(hoehe_sonic,1)+id30,2:end) = output_sonic(5,1:end);
    output_dat(size(hoehe_sonic,1)+id30-1,:) = output_dat_sonic(4,:);
    for l=1:id60
        output{size(hoehe_sonic,1)+id30+l,1} = hoehe_sodar(l+id30);
        output(size(hoehe_sonic,1)+id30+l,2:end) = output_sodar(l+id30+1,1:end);
        output_dat(size(hoehe_sonic,1)+id30+l-1,:)= output_dat_sodar(l+id30,:);
    end
    output{size(hoehe_sonic,1)+id60+1,1} = hoehe_sonic(5);
    output(size(hoehe_sonic,1)+id60+1,2:end) = output_sonic(6,1:end);
    output_dat(size(hoehe_sonic,1)+id60,:) = output_dat_sonic(5,:);
        
    for l=id60+1:size(hoehe_sodar,1)
        output{size(hoehe_sonic,1)+l+1,1} = hoehe_sodar(l);
    end
    output(size(hoehe_sonic,1)+id60+1:end,2:end) = output_sodar(id60+1:end,1:end);
    output_dat(size(hoehe_sonic,1)+id60+1:end,:) = output_dat_sodar(id60+1:end,:);
    for l=1:size(output_sonic,2)
        time2 = output_sodar{1,l};
        time2 = time2(end-4:end);
        time1 = output{1,l+1};
        output{1,l+1} = strcat(time1,'\',time2);
    end

end

% Zeilenstatistik
%Gesamtzahl
output{1,end+1} = 'N gesamt';
for l=1:size(output_dat,1)
    output{l+1,end} = size(output_dat,2);
end
%Mittelwert
output{1,end+1} = 'Mittelwert';
mw = nanmean(output_dat,2);
for l=1:size(output_dat,1)
    output{l+1,end} = mw(l);
end
%Standardabweichung
output{1,end+1} = 'Standardabweichung';
sigma = nanstd(output_dat,0,2); %flag=0: 1/(n-1); flag=1: 1/n
for l=1:size(output_dat,1)
    output{l+1,end} = sigma(l);
end
%Minimum
output{1,end+1} = 'Minimum';
mini = nanmin(output_dat,[],2);
for l=1:size(output_dat,1)
    output{l+1,end} = mini(l);
end
%Median
output{1,end+1} = 'Median';
med = nanmedian(output_dat,2);
for l=1:size(output_dat,1)
    output{l+1,end} = med(l);
end
%Maximum
output{1,end+1} = 'Maximum';
maxi = nanmax(output_dat,[],2);
for l=1:size(output_dat,1)
    output{l+1,end} = maxi(l);
end

%in Datei schreiben
fout = fopen([path,outfile],'w+');
for i4=1:size(output,1)
    for i3=1:size(output,2)
        if (i3==1)&&(i4~=1)
            if ~isnan(output{i4,i3})
                fprintf(fout,'\r\n%s\t', num2str(output{i4,i3}));
            else
                fprintf(fout,'\r\n%s\t', '-');
            end
        else
            if ~isnan(output{i4,i3})
                fprintf(fout,'%s\t', num2str(output{i4,i3}));
            else
                fprintf(fout,'%s\t', '-');
            end
        end
    end
end
fclose(fout);


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

%Daten einlesen
plot_ID = evalin('base','plot_ID');
if plot_ID==2
    errordlg('Nur für xy-Plots möglich!');
    return
end

sonic_ID = evalin('base','sonic_ID');
spalte = evalin('base','ycol');
path = evalin('base','path');
start_year = evalin('base','start_year');
start_month = evalin('base','start_month');
start_day = evalin('base','start_day');
end_year = evalin('base','end_year');
end_month = evalin('base','end_month');
end_day = evalin('base','end_day');
Cn2_flag = 0;


if sonic_ID == 1    %SOnic
    daten = evalin('base','daten_sonic_xy');
    if or(spalte == 48,or(spalte==49,spalte==66))
        Cn2_flag=1;     %Falls Cn2, muss log benutzt werden
    end
    statistik = daten(:,2:6);
else    %Sodar
    daten = evalin('base','daten_sodar');
    Cn2 = evalin('base','sodar_Cn2');
    height_sodar = evalin('base','height_sodar');
    height = evalin('base','height');
    
    %Cn2 in Datensatz einfügen
    id = find(daten(:,6) == height);
    daten = daten(id,:);
    id = find(height_sodar == height);
    Cn2 = Cn2(id,:);
    daten(:,end+1) = Cn2';
    if spalte == 14 %Cn2
        Cn2_flag = 1;
    end
    statistik = daten(:,1:5);
end

%"Statistik-Matrix"
statistik(:,end+1) = daten(:,spalte);
if Cn2_flag     %ggf log einfügen
    statistik(:,end+1) = log10(statistik(:,end));
end

%Min und Max finden
ma = max(statistik(:,end));
mi = min(statistik(:,end));
%Schrittweite einteilen (max-min)/100
d = ma-mi;
stepsize = d/100;

statistik_out{1,1} = 'Anfangswert';
statistik_out{1,2} = 'Mittelpunkt';
statistik_out{1,3} = 'Endwert';
statistik_out{1,4} = 'Anzahl';
statistik_out{1,5} = 'kumulative Anzahl';
statistik_out{1,6} = 'relative Häufigkeit';
statistik_out{1,7} = 'kumulative Häufigkeit';
if Cn2_flag
    statistik_out{1,8} = '10^(Spalte 2)';
end

anz=0;
total = size(statistik,1);
%Elemente der Intervalle zählen
for n=1:100
    statistik_out{n+1,1} = mi+(n-1)*stepsize;
    statistik_out{n+1,3} = mi+(n)*stepsize;
    statistik_out{n+1,2} = (statistik_out{n+1,1} + statistik_out{n+1,3})/2;
    c1 = find(statistik_out{n+1,1} <= statistik(:,end));
    c2 = find(statistik(:,end) <= statistik_out{n+1,3});
    B = ismember(c1,c2);
    c12 = c1(B);
    statistik_out{n+1,4}=size(c12,1);
    anz = anz + size(c12,1);
    statistik_out{n+1,5}=anz;
    statistik_out{n+1,6} = statistik_out{n+1,4}/total*100;
    statistik_out{n+1,7} = statistik_out{n+1,5}/total*100;
    if Cn2_flag
    statistik_out{n+1,8} = 10^(statistik_out{n+1,2});
    end
end

% Ausgabeordner
foldout=strcat(path,'\GUI\Statistik\');
if (~isdir(foldout))
    mkdir(foldout)
end

% Ausgabedatei öffnen
if sonic_ID==1
    if get(handles.rbzeitraum2,'Value')
        mult_month=evalin('base','mult_month');
        mult_year=evalin('base','mult_year');
     Out = fopen([foldout,'sonic_',num2str(mult_month(1),'%02d'),num2str(mult_year(1)),'-',num2str(mult_month(end),'%02d'),num2str(mult_year(end)),'_',num2str(spalte,'%02d'),'.dat'],'w+');   
    else
    Out = fopen([foldout,'sonic_',start_year,start_month,start_day,'-',end_year,end_month,end_day,'_',num2str(spalte,'%02d'),'.dat'],'w+');
    end
else
    Out = fopen([foldout,'sodar_',start_year,start_month,start_day,'-',end_year,end_month,end_day,'_',num2str(spalte,'%02d'),'.dat'],'w+');
end
% elementweise in Ausgabedatei speichern, Zeilenumbruch bei erstem Element
for i4=1:size(statistik_out,1)
    for i3=1:size(statistik_out,2)
        if (i3==1)&&(i4~=1)
            if ~isnan(statistik_out{i4,i3})
                fprintf(Out,'\r\n%s\t', num2str(statistik_out{i4,i3}));
            else
                fprintf(Out,'\r\n%s\t', '-');
            end
        else
            if ~isnan(statistik_out{i4,i3})
                fprintf(Out,'%s\t', num2str(statistik_out{i4,i3}));
            else
                fprintf(Out,'%s\t', '-');
            end
        end
    end
end
%alle offenen Dateien schließen
fclose(Out);
