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

% Last Modified by GUIDE v2.5 18-Dec-2012 10:28:22

% This is version April 2013 (1.1).

% Written by Janet E. Lovett. Please cite J. E. Lovett, B. W. Lovett and J. Harmer, 
% DEER-Stitch: Combining three- and four-pulse DEER measurements for high 
% sensitivity, deadtime free data, Journal of Magnetic Resonance, 223, (2012) 98-106.

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

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

% Update handles structure
guidata(hObject, handles);

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

handles.ol = 0;
handles.B_fit = 0;
handles.trialcutques = 0;
handles.startol = 0;
handles.finalol = 0;
handles.trials = 1;
handles.ol_tts = 0;
handles.ttt = [];
handles.ttd = [];
handles.ttd_ol = [];

guidata(hObject, handles);

% --- Outputs from this function are returned to the command line.
function varargout = DADeers_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in loadsets.
function loadsets_Callback(hObject, eventdata, handles)
% hObject    handle to loadsets (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,'dd') == 1;
    handles = rmfield(handles, 'dd');
    handles = rmfield(handles, 'dnmplot');
    handles = rmfield(handles, 'ddmn');
    handles = rmfield(handles, 'ddmaxn');
    handles = rmfield(handles, 'ddminn');
    handles = rmfield(handles, 'ttt');
    handles = rmfield(handles, 'ttd');
    handles = rmfield(handles, 'ttd_ol');
                
end

if handles.trialcutques == 0;
    handles.trials = 1;
end

for c = 1:handles.trials
    
    if handles.trialcutques == 1;
        if abs(handles.finalol - handles.startol) > 0
            trialstep = round(abs((handles.finalol - handles.startol)/(handles.trials-1)));
            ol = handles.startol - (c-1).*trialstep;
        else
            ol = handles.ol;
        end
    else
        ol = handles.ol;
    end

    if handles.B_fit == 1;
        modfit = 'yes';
    else
        modfit = 'no';
    end

if c == 1;
[fname,pname] = uigetfile('*.dat', 'Where are the DEERS?');
cd(pname);
cc = 1;
end

fIn = sprintf('deers_RepLong_modfit_%s_ol_%01dns_distr.dat',modfit,ol);
distr = importdata(fIn);
dnm(:,cc) = distr(:,1);
dd(:,cc) = distr(:,2);

fIn = sprintf('deers_RepLong_modfit_%s_ol_%01dns_fit.dat',modfit,ol);
tt = importdata(fIn);%import the background corrected time trace
ttt(:,cc) = tt(:,1);
ttd(:,cc) = tt(:,2)+cc*0.05;%plots time traces with slight y-axis displacement
ttd_ol(:,cc) = tt(:,2);%plots time traces on top of each other

cc = cc + 1;

fIn = sprintf('deers_RepShort_modfit_%s_ol_%01dns_distr.dat',modfit,ol);
distr = importdata(fIn);
dnm(:,cc) = distr(:,1);
dd(:,cc) = distr(:,2);

fIn = sprintf('deers_RepShort_modfit_%s_ol_%01dns_fit.dat',modfit,ol);
tt = importdata(fIn);%import the background corrected time trace
ttt(:,cc) = tt(:,1);
ttd(:,cc) = tt(:,2)+cc*0.05;
ttd_ol(:,cc) = tt(:,2);

cc = cc +1;

end

dnmplot = dnm(:,1);
ddm = mean(dd,2);
ddmin = min(dd,[],2);
ddmax = max(dd,[],2);
norm = max(ddm);
ddmn = ddm./norm;
ddminn = ddmin./norm;
ddmaxn = ddmax./norm;

colour=[1 0 0; 0 0 0.5; 0 0.5 0];
set(0,'DefaultAxesColorOrder',colour);
axesHandledeers= findobj(gcf,'Tag','distributions');
cla(axesHandledeers);
plot(axesHandledeers,dnmplot,ddminn,dnmplot,ddmaxn,dnmplot,ddmn);axis 'tight'
set(axesHandledeers,'Tag','distributions');

colour=[0 0 0; 1 0 0; 0 0.5 0; 0 0 0.5];
set(0,'DefaultAxesColorOrder',colour);
axesHandledeers= findobj(gcf,'Tag','timetraces');
cla(axesHandledeers);
if handles.ol_tts == 0;
plot(axesHandledeers,ttt,ttd);axis 'tight'
else
plot(axesHandledeers,ttt,ttd_ol);axis 'tight'
end
set(axesHandledeers,'Tag','timetraces');


av_mean = sum(dnmplot.*ddmn)./sum(ddmn);
min_mean = sum(dnmplot.*ddminn)./sum(ddminn);
max_mean = sum(dnmplot.*ddmaxn)./sum(ddmaxn);
set(handles.av_mean,'String',num2str(av_mean,3));
set(handles.min_mean,'String',num2str(min_mean,3));
set(handles.max_mean,'String',num2str(max_mean,3));


handles.ddmn = ddmn;
handles.ddminn = ddminn;
handles.ddmaxn = ddmaxn;
handles.dnmplot = dnmplot;
handles.dd = dd;
handles.ttt = ttt;
handles.ttd = ttd;
handles.ttd_ol = ttd_ol;
guidata(hObject, handles);

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

suggestion=['deers_av-distr.txt']; 
[fname,pname]=uiputfile('*.txt','Save results',suggestion);
cd(pname)

clear result
result(:,1) = handles.dnmplot;
result(:,2) = handles.ddmn;
result(:,3) = handles.ddminn;
result(:,4) = handles.ddmaxn;
fOut = sprintf('%s',fname);
save(fOut, 'result', '-ascii');
clear result




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

colour=[0 0 0; 1 0 0; 0 0.5 0; 0 0 0.5];
set(0,'DefaultAxesColorOrder',colour);
f1 = figure(1);
reset(gca);
if handles.ol_tts == 0;
h1 = plot(handles.ttt,handles.ttd);axis 'tight'
else
h1 = plot(handles.ttt,handles.ttd_ol);axis 'tight'
end
xlabel('time / ns','fontsize',12,'fontname','arial');
ylabel('intensity','fontsize',12,'fontname','arial');
title('DEERS time traces','fontsize',12,'fontname','arial')
set(f1,'color','white','units','centimeters','outerposition',[10 10 20 20]);
set(gca,'fontsize',12);
set(gca,'tickdir','out');
set(h1,'linestyle','-','linewidth',1.0);
set(gca,'box','off');

colour=[1 0 0; 0 0 0.5; 0 0.5 0];
set(0,'DefaultAxesColorOrder',colour);
f1 = figure(2);
reset(gca);
h1 = plot(handles.dnmplot,handles.ddminn,handles.dnmplot,handles.ddmaxn,handles.dnmplot,handles.ddmn);axis 'tight'
xlabel('time / ns','fontsize',12,'fontname','arial');
ylabel('intensity','fontsize',12,'fontname','arial');
legend('Min','Max','Average')
title('DEERS distance distributions','fontsize',12,'fontname','arial')
set(f1,'color','white','units','centimeters','outerposition',[25 10 20 20]);
set(gca,'fontsize',12);
set(gca,'tickdir','out');
set(h1,'linestyle','-','linewidth',1.0);
set(gca,'box','off');

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


moddepthquesContents = cellstr(get(hObject,'String'));
moddepthans = moddepthquesContents{get(hObject,'Value')};
tf = strcmp(moddepthans,'Yes');
handles.B_fit = tf;
guidata(hObject,handles);




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

trialcutquesContents = cellstr(get(hObject,'String'));
trialcutans = trialcutquesContents{get(hObject,'Value')};
tf = strcmp(trialcutans,'Yes');
handles.trialcutques = tf;
guidata(hObject,handles);

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

handles.startol = str2double(get(hObject,'String'));
guidata(hObject, handles);


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

handles.finalol = str2double(get(hObject,'String'));
guidata(hObject, handles);


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

handles.trials = str2double(get(hObject,'String'));
guidata(hObject, handles);


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

handles.ol = str2double(get(hObject,'String'));
guidata(hObject, handles);

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

ol_timetraces_tick = get(hObject,'Value');
handles.ol_tts = ol_timetraces_tick;
guidata(hObject,handles);

ttt = handles.ttt;
ttd = handles.ttd;
ttd_ol = handles.ttd_ol;


colour=[0 0 0; 0 0.5 0; 1 0 0; 0 0 0.5];
set(0,'DefaultAxesColorOrder',colour);
axesHandledeers= findobj(gcf,'Tag','timetraces');
cla(axesHandledeers);
if handles.ol_tts == 0;
plot(axesHandledeers,ttt,ttd);axis 'tight'
else
plot(axesHandledeers,ttt,ttd_ol);axis 'tight'
end
set(axesHandledeers,'Tag','timetraces');
