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

% Last Modified by GUIDE v2.5 13-Dec-2012 16:00:00

% 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', @DeerStitch_OpeningFcn, ...
                   'gui_OutputFcn',  @DeerStitch_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 DeerStitch is made visible.
function DeerStitch_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 DeerStitch (see VARARGIN)

% Choose default command line output for DeerStitch
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);;

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

%%%will need to change these values in the individual CreateFcn commands if
%%%want to change the defaults.
handles.d3_3p = 0;
handles.d30_3p = 8;
handles.p0_3p = 32;
handles.p2_3p = 12;
handles.d1_4p = 400;
handles.d3_4p = 80;
handles.d30_4p = 8;
handles.p0_4p = 32;
handles.p2_4p = 12;
handles.dim = 3;
handles.m = 0;
handles.phaseques = 0;
handles.displayphaseques = 0;
handles.B_fit = 0;
handles.trialcutques = 0;
handles.startm = 0;
handles.finalm = 0;
handles.trialm = 1;
handles.trialoutput = 1;
handles.stitchcount = 0;

guidata(hObject, handles);

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

%disp('hello')
%keyboard
[fname,pname] = uigetfile('*.DTA', 'Load 3pDEER');
cd(pname);
[handles.t3p1,handles.deer3p,handles.pars3p] = eprload(fname);
guidata(hObject,handles);

axesHandle3p= findobj(gcf,'Tag','deer3p_axes');
cla(axesHandle3p);
plot(axesHandle3p,handles.t3p1,real(handles.deer3p),'k',handles.t3p1,imag(handles.deer3p),'c');axis 'tight'
set(axesHandle3p,'Tag','deer3p_axes');

%disp(handles.t3p1)

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

[fname,pname] = uigetfile('*.DTA', 'Load 4pDEER');
cd(pname);
[handles.t4p1,handles.deer4p,handles.pars4p] = eprload(fname);
guidata(hObject,handles);

axesHandle4p= findobj(gcf,'Tag','deer4p_axes');
cla(axesHandle4p);
plot(axesHandle4p,handles.t4p1,real(handles.deer4p),'k',handles.t4p1,imag(handles.deer4p),'c');axis 'tight'
set(axesHandle4p,'Tag','deer4p_axes');

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


phasequesContents = cellstr(get(hObject,'String'));
phaseans = phasequesContents{get(hObject,'Value')};
tf = strcmp(phaseans,'Yes');
handles.phaseques = tf;
guidata(hObject,handles);

% --- Executes during object creation, after setting all properties.
function phaseques_CreateFcn(hObject, eventdata, handles)
% hObject    handle to phaseques (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 displayphaseques.
function displayphaseques_Callback(hObject, eventdata, handles)
% hObject    handle to displayphaseques (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 displayphaseques contents as cell array
%        contents{get(hObject,'Value')} returns selected item from displayphaseques

displayphasequesContents = cellstr(get(hObject,'String'));
displayphaseans = displayphasequesContents{get(hObject,'Value')};
tf = strcmp(displayphaseans,'Yes');
handles.displayphaseques = tf;
guidata(hObject,handles);

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

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

% --- Executes during object creation, after setting all properties.
function d3_3p_CreateFcn(hObject, eventdata, handles)
% hObject    handle to d3_3p (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
d3_3p = 0;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(d3_3p));
handles.d3_3p = str2double(get(hObject,'String'));
 guidata(hObject, handles);

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

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

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

initval = 8;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.d30_3p = str2double(get(hObject,'String'));
 guidata(hObject, handles);

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


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

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

initval = 32;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.p0_3p = str2double(get(hObject,'String'));
guidata(hObject, handles);


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

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

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

initval = 12;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.p2_3p = str2double(get(hObject,'String'));
guidata(hObject, handles);




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

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

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

initval = 80;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.d3_4p = str2double(get(hObject,'String'));
guidata(hObject, handles);

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

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

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

initval = 8;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.d30_4p = str2double(get(hObject,'String'));
guidata(hObject, handles);

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

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

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

initval = 32;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.p0_4p = str2double(get(hObject,'String'));
guidata(hObject, handles);

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

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

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

initval = 12;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.p2_4p = str2double(get(hObject,'String'));
guidata(hObject, handles);

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


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

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

initval = 400;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.d1_4p = str2double(get(hObject,'String'));
guidata(hObject, handles);

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

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

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

initval = 3;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.dim_4p = str2double(get(hObject,'String'));
guidata(hObject, handles);

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

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

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

initval = 0;%will need to alter this number here and in OpeningFcn if want to change default.
set(hObject,'String',num2str(initval));
handles.m = str2double(get(hObject,'String'));
guidata(hObject, handles);


% --- Executes on button press in Update_Exp.
function Update_Exp_Callback(hObject, eventdata, handles)
% hObject    handle to Update_Exp (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,'zerotime_3p') == 1;
handles = rmfield(handles, 'zerotime_3p');
handles = rmfield(handles, 'cut3p');
handles = rmfield(handles, 'zerotime_4p');
handles = rmfield(handles, 'deer3pRe_load');
handles = rmfield(handles, 'length_deer3pRaw');
handles = rmfield(handles, 'deer3pIm_load');
handles = rmfield(handles, 't3p_load');
handles = rmfield(handles, 't3p_zero');
handles = rmfield(handles, 'deer3pRe_zero');
handles = rmfield(handles, 'deer3pIm_zero');
handles = rmfield(handles, 't3p');
handles = rmfield(handles, 'deer3pRe');
handles = rmfield(handles, 't4p_load');
handles = rmfield(handles, 't4p');
handles = rmfield(handles, 'deer4p_load');
handles = rmfield(handles, 'length_deer4pRaw');
handles = rmfield(handles, 'deer4pRe_load');
handles = rmfield(handles, 'deer4pIm_load');
handles = rmfield(handles, 'deer4pRe_interp');
handles = rmfield(handles, 'deer4pIm_interp');
handles = rmfield(handles, 'deer4pRe_m');
handles = rmfield(handles, 'deer4pIm_m');
handles = rmfield(handles, 'deer4pIm');
handles = rmfield(handles, 'deer3pIm');
handles = rmfield(handles, 'length_deer4pInterpZerotimeCorr');
handles = rmfield(handles, 'deer4pRe_neg');
handles = rmfield(handles, 't4p_neg');
end

handles.zerotime_3p = (handles.p0_3p/2)-(handles.p2_3p/2)-handles.d3_3p;
handles.cut3p = [handles.p0_3p/2 + handles.p2_3p/2 + 8];

handles.zerotime_4p = handles.d1_4p-handles.d3_4p+handles.p0_4p/2-handles.p2_4p/2;

handles.deer3pRe_load = real(handles.deer3p);
handles.length_deer3pRaw = length(handles.deer3pRe_load);
handles.deer3pIm_load = imag(handles.deer3p);
handles.t3p_load = handles.t3p1 - handles.zerotime_3p;

handles.t3p_zero = handles.t3p_load(1):handles.t3p_load(length(handles.t3p_load));
handles.deer3pRe_zero = interp1(handles.t3p_load,handles.deer3pRe_load,handles.t3p_zero,'spline');
handles.deer3pIm_zero = interp1(handles.t3p_load,handles.deer3pIm_load,handles.t3p_zero,'spline');

if handles.zerotime_3p >= 0;
    handles.t3p = 0:handles.t3p_zero(length(handles.t3p_zero));
    handles.deer3pRe = handles.deer3pRe_zero((handles.zerotime_3p+1):length(handles.deer3pRe_zero));
    handles.deer3pIm = handles.deer3pIm_zero((handles.zerotime_3p+1):length(handles.deer3pIm_zero));
else
    handles.t3p = handles.t3p_zero(1):handles.t3p_zero(length(handles.t3p_zero));
    handles.deer3pRe = handles.deer3pRe_zero;
    handles.deer3pIm = handles.deer3pIm_zero;
end


if handles.phaseques == 1;
phi = atan2(handles.deer3pIm,handles.deer3pRe);
phi2 = atan2(handles.deer3pIm(length(handles.deer3pIm*1/8):length(handles.deer3pIm*7/8)),handles.deer3pRe(length(handles.deer3pRe*1/8):length(handles.deer3pRe*7/8)));%use middle 3/4 of data to find the average phase offset
phiav = sum(phi2)./length(phi2);
phideg = phiav*180/pi;

sig3p = handles.deer3pRe + i*handles.deer3pIm;
r3p = abs(sig3p);
sumr3p = sum(r3p);

%%%%%this is just giving the real the absolute value and is a crude method
% handles.deer3pRe = r3p;
% handles.deer3pIm = zeros(size(r3p));
% 
% sig3p2 = handles.deer3pRe + i*handles.deer3pIm;
% r3p2 = abs(sig3p2);
% sumr3p2 = sum(r3p2)
% phi2 = angle(sig3p2);
% phi2av = sum(phi2)./length(phi2)

%%%%%end of crude method
if phideg > 0;
handles.deer3pRe = real(r3p.*exp(i.*(phi-phiav)));
handles.deer3pIm = imag(r3p.*exp(i.*(phi-phiav)));
else
handles.deer3pRe = real(r3p.*exp(i.*(phi+phiav)));
handles.deer3pIm = imag(r3p.*exp(i.*(phi+phiav)));
end
% sig3p2 = handles.deer3pRe + i*handles.deer3pIm;
% r3p2 = abs(sig3p2);
% sumr3p2 = sum(r3p2)

end


handles.t4p_load = handles.t4p1;
handles.t4p = handles.t4p_load(1):handles.t4p_load(length(handles.t4p_load));

handles.deer4p_load = handles.deer4p;
handles.length_deer4pRaw = length(handles.deer4p_load);
handles.deer4pRe_load = real(handles.deer4p_load);
handles.deer4pIm_load = imag(handles.deer4p_load);
handles.deer4pRe_interp = interp1(handles.t4p_load,handles.deer4pRe_load,handles.t4p,'spline');
handles.deer4pIm_interp = interp1(handles.t4p_load,handles.deer4pIm_load,handles.t4p,'spline');


handles.deer4pRe_m = handles.deer4pRe_interp(1:length(handles.deer4pRe_interp)-handles.m);
handles.deer4pIm_m = handles.deer4pIm_interp(1:length(handles.deer4pIm_interp)-handles.m);



handles.deer4pRe = handles.deer4pRe_m((handles.zerotime_4p+1):length(handles.deer4pRe_m));
handles.deer4pIm = handles.deer4pIm_m((handles.zerotime_4p+1):length(handles.deer4pIm_m));


handles.t4p = handles.t4p(1:length(handles.deer4pRe));
handles.length_deer4pInterpZerotimeCorr = length(handles.deer4pRe);

handles.deer4pRe_neg = handles.deer4pRe_interp(1:handles.zerotime_4p);
handles.deer4pIm_neg = handles.deer4pIm_m(1:handles.zerotime_4p);
handles.t4p_neg = -handles.zerotime_4p:1:-1;

if handles.phaseques == 1;
phi = atan2(handles.deer4pIm,handles.deer4pRe);
phi2 = atan2(handles.deer4pIm(length(handles.deer4pIm*1/8):length(handles.deer4pIm*7/8)),handles.deer4pRe(length(handles.deer4pRe*1/8):length(handles.deer4pRe*7/8)));%use middle 3/4 of data to find the average phase offset
phi_neg = atan2(handles.deer4pIm_neg,handles.deer4pRe_neg);
phiav = sum(phi2)./length(phi2);
phideg = phiav*180/pi;

sig4p = handles.deer4pRe + i*handles.deer4pIm;
r4p = abs(sig4p);
sumr4p = sum(r4p);
sig4p_neg = handles.deer4pRe_neg + i*handles.deer4pIm_neg;
r4p_neg = abs(sig4p_neg);

if phideg > 0;
handles.deer4pRe = real(r4p.*exp(i.*(phi-phiav)));
handles.deer4pIm = imag(r4p.*exp(i.*(phi-phiav)));
handles.deer4pRe_neg = real(r4p_neg.*exp(i.*(phi_neg-phiav)));
handles.deer4pIm_neg = imag(r4p_neg.*exp(i.*(phi_neg-phiav)));
else
handles.deer4pRe = real(r4p.*exp(i.*(phi+phiav)));
handles.deer4pIm = imag(r4p.*exp(i.*(phi+phiav)));
handles.deer4pRe_neg = real(r4p_neg.*exp(i.*(phi_neg+phiav)));
handles.deer4pIm_neg = imag(r4p_neg.*exp(i.*(phi_neg+phiav)));
end
% sig4p2 = handles.deer4pRe + i*handles.deer4pIm;
% r4p2 = abs(sig4p2);
% sumr4p2 = sum(r4p2)




end

handles.n = handles.cut3p+1;
    
if handles.d3_3p > handles.cut3p
    handles = rmfield(handles, 'n');
    handles.n = 0;
end


if handles.displayphaseques == 1;
    axesHandle3p= findobj(gcf,'Tag','deer3p_axes');
    cla(axesHandle3p);
    plot(axesHandle3p,handles.t3p(1:handles.n),handles.deer3pRe(1:handles.n),'r',handles.t3p(handles.n+1:end),handles.deer3pRe(handles.n+1:end),'k',handles.t3p(1:handles.n),handles.deer3pIm(1:handles.n),'r',handles.t3p(handles.n+1:end),handles.deer3pIm(handles.n+1:end),'c');axis 'tight'
    set(axesHandle3p,'Tag','deer3p_axes');
    
    axesHandle4p= findobj(gcf,'Tag','deer4p_axes');
    cla(axesHandle4p);
    plot(axesHandle4p,handles.t4p,handles.deer4pRe,'k',handles.t4p_neg,handles.deer4pRe_neg,'r',handles.t4p,handles.deer4pIm,'c',handles.t4p_neg,handles.deer4pIm_neg,'r');axis 'tight'
    set(axesHandle4p,'Tag','deer4p_axes');
else
    axesHandle3p= findobj(gcf,'Tag','deer3p_axes');
    cla(axesHandle3p);
    plot(axesHandle3p,handles.t3p(1:handles.n),handles.deer3pRe(1:handles.n),'r',handles.t3p(handles.n+1:end),handles.deer3pRe(handles.n+1:end),'k');axis 'tight'
    set(axesHandle3p,'Tag','deer3p_axes');
    
    axesHandle4p= findobj(gcf,'Tag','deer4p_axes');
    cla(axesHandle4p);
    plot(axesHandle4p,handles.t4p,handles.deer4pRe,'k',handles.t4p_neg,handles.deer4pRe_neg,'r');axis 'tight'
    set(axesHandle4p,'Tag','deer4p_axes');
end


set(handles.deer3p_zt,'String',num2str(handles.zerotime_3p));
set(handles.deer4p_zt,'String',num2str(handles.zerotime_4p));


guidata(hObject,handles)



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

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

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


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

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

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

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

% disp(handles.stitchcount)
if handles.stitchcount > 0;
% disp('counting stitches');
handles = rmfield(handles, 'res_s');
handles = rmfield(handles, 'tres_s');
handles = rmfield(handles, 't4p_s');
handles = rmfield(handles, 'deers1_s');
handles = rmfield(handles, 'deers2_s');
handles = rmfield(handles, 'deer4pfit_s');
handles = rmfield(handles, 't3p_s');
handles = rmfield(handles, 'deer3pRe_s');
% handles = rmfield(handles, 't3p_deers_s');
% handles = rmfield(handles, 't3p_start_s');
% handles = rmfield(handles, 'deer3pRe_start_s');
handles = rmfield(handles, 'leastsquares');
handles = rmfield(handles, 'flag');
handles = rmfield(handles, 'deer4pRe_s');
end

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

for c = 1:handles.trialm;
%     disp(size(handles.deer4pReUSE));
%     disp(isfield(handles,'deer4pReUSE'));
    if isfield(handles,'deer4pReUSE') == 1;
%         disp('hello inside isfield');
        handles = rmfield(handles, 'deer4pReUSE');
        handles = rmfield(handles, 't4pUSE');
        handles = rmfield(handles, 'deer4pfit');
        handles = rmfield(handles, 'deers1');
        handles = rmfield(handles, 'deers2');
        handles = rmfield(handles, 't3p_deers');
        handles = rmfield(handles, 'deer4pfit_neg');
        handles = rmfield(handles, 'deer3pReNORM');
        handles = rmfield(handles, 'deer4pfit_comp');
        handles = rmfield(handles, 't4p_comp');
%         handles = rmfield(handles, 'mUSE');
    end
    if handles.trialcutques == 1;
        if abs(handles.finalm - handles.startm) > 0
        trialstep = round(abs((handles.finalm - handles.startm)/(handles.trialm-1)));
        mUSE = handles.startm + (c-1).*trialstep;
        handles.deer4pReUSE = handles.deer4pRe(1:(end-mUSE));
        handles.t4pUSE = handles.t4p(1:length(handles.t4p)-mUSE);
        else
            mUSE = handles.startm;
                    handles.deer4pReUSE = handles.deer4pRe(1:(end-mUSE));
        handles.t4pUSE = handles.t4p(1:length(handles.t4p)-mUSE); 
        end
    else
        handles.deer4pReUSE = handles.deer4pRe;
        handles.t4pUSE = handles.t4p;
    end
    
    handles.length_overlap(:,c) = length(handles.deer4pReUSE)-handles.n-handles.d3_3p;
    
    x = [10^(-6) 1 1];%background (k), stretch (A), modulation depth (B)
    guidata(hObject, handles);
    
    options = optimset('MaxFunEvals',10000000);
    [fit_val,fval,flag,info] = fminsearch(@DEERSminsq,x,options,handles.deer4pReUSE,handles.deer3pRe,handles.d3_3p,handles.n,handles.dim,handles.t4pUSE,handles.B_fit);
    tilt = exp(-(handles.t4pUSE .*fit_val(1)).^(handles.dim/3));
    stretch = fit_val(2);
    if handles.B_fit == 0;
        B = 0;
    else
        B = fit_val(3);
    end
    
    handles.deer4pfit = (handles.deer4pReUSE+B).*tilt*stretch;
    
    if handles.d3_3p == 0;
        deers1 = handles.deer3pRe;
        deers2 = handles.deer3pRe;
        if handles.n >= 1;
            deers1(1:handles.n) = handles.deer4pfit(1:handles.n);
%             disp(size(deers1));
            deers2(1:length(handles.deer4pfit)) = handles.deer4pfit;
        end
        handles.t3p_deers = handles.t3p;
    else
        if handles.n <1;
            deers1 = handles.deer3pRe;
            deers2 = handles.deer3pRe;
        end
        deers1(1:(handles.n-handles.zerotime_3p))= handles.deer4pfit(1:(handles.n-handles.zerotime_3p));
        deers1((handles.n-handles.zerotime_3p+1):(length(handles.deer3pRe)-handles.zerotime_3p)) = handles.deer3pRe(handles.n+1:length(handles.deer3pRe));
        handles.t3p_deers(1:(handles.n-handles.zerotime_3p))= handles.t4p(1:(handles.n-handles.zerotime_3p));
        handles.t3p_deers((handles.n-handles.zerotime_3p+1):(length(handles.deer3pRe)-handles.zerotime_3p)) = handles.t3p((handles.n+1):length(handles.deer3pRe));
        deers2(1:(length(handles.deer4pfit)))= handles.deer4pfit;
        deers2((length(handles.deer4pfit)+1):(length(handles.deer3pRe)-handles.zerotime_3p)) = handles.deer3pRe(length(handles.deer4pfit)+1+handles.zerotime_3p:length(handles.deer3pRe));
    end
    
    
    normalise = max(deers1);
    handles.deers1 = deers1/normalise;
    handles.deers2 = deers2/normalise;
    handles.deer4pfit = handles.deer4pfit./normalise;
    handles.deer3pReNORM = handles.deer3pRe./normalise;
    
    tilt_neg = exp((handles.t4p_neg.*fit_val(1)).^(handles.dim/3));
    deer4pfit_neg = (handles.deer4pRe_neg+B).*tilt_neg*stretch;
    handles.deer4pfit_neg = deer4pfit_neg./normalise;
    
    if handles.d3_3p == 0
        res = handles.deer3pReNORM(handles.t3p(handles.n+1):(handles.length_overlap(:,c)-1)) - handles.deer4pfit((handles.t3p(handles.n+1)):(handles.length_overlap(:,c)-1));
        tres = handles.t3p(handles.n+1:handles.length_overlap(:,c));
    else
        res = handles.deer3pReNORM(1:(handles.length_overlap(:,c))) - handles.deer4pfit((handles.t3p(handles.n+1)):(handles.length_overlap(:,c)-handles.zerotime_3p-1));
        tres = handles.t3p(handles.n+1:handles.length_overlap(:,c));
    end

    handles.leastsquares(1,c) = fval;
    handles.flag(1,c) = flag;
    
    res = res';
    tres = tres';
    handles.res_s{:,c} = res;
    handles.tres_s{:,c} = tres;

    handles.deer4pRe_s(:,c) = handles.deer4pRe;
    handles.deer4pfit_comp(1:length(handles.deer4pfit_neg)) = handles.deer4pfit_neg;
    handles.deer4pfit_comp(length(handles.deer4pfit_neg)+1:length(handles.deer4pfit_neg)+length(handles.deer4pfit)) = handles.deer4pfit;
    handles.t4p_comp(1:length(handles.deer4pfit_neg)) = handles.t4p_neg;
    handles.t4p_comp(length(handles.deer4pfit_neg)+1:length(handles.deer4pfit_neg)+length(handles.deer4pfit)) = handles.t4p(1:length(handles.deer4pfit));
    handles.t4p_s{:,c} = handles.t4p_comp';    
    handles.deer4pfit_s{:,c} = handles.deer4pfit_comp';
    handles.t3p_s(:,c) = handles.t3p(handles.n+1:end);
    handles.deer3pRe_s(:,c) = handles.deer3pReNORM(handles.n+1:end);
    handles.t3p_deers_s(:,c) = handles.t3p_deers;   
    handles.deers1_s(:,c) = handles.deers1';
    handles.deers2_s(:,c) = handles.deers2';
    
    handles.Bfit(:,c) = handles.B_fit;
%     if handles.n > handles.d3_3p;
%         handles.t3p_start_s(:,c) = handles.t3p(1:handles.n);
%         handles.deer3pRe_start_s(:,c) = handles.deer3pReNORM(1:handles.n);
%     else
%         handles.t3p_start_s(:,c) = zeros();
%         handles.deer3pRe_start_s(:,c) = zeros();
%     end
    
colour=[0 0 0; 1 0 0; 0 0.5 0; 0 0 0.5];
set(0,'DefaultAxesColorOrder',colour);
axesHandledeers= findobj(gcf,'Tag','deers_axes');
cla(axesHandledeers);
plot(axesHandledeers,handles.t3p_s(:,c),handles.deer3pRe_s(:,c),handles.t4p_s{1,c},handles.deer4pfit_s{1,c},handles.t3p_deers_s(:,c),handles.deers1_s(:,c)+0.2,handles.t3p_deers_s(:,c),handles.deers2_s(:,c)+0.4);axis 'tight'
set(axesHandledeers,'Tag','deers_axes');

axesHandledeers= findobj(gcf,'Tag','residuals_axes');
cla(axesHandledeers);
set(axesHandledeers,'Tag','residuals_axes');

set(handles.flagoutput,'String','?');
set(handles.leastsquaresoutput,'String','?');
set(handles.lengthoverlapoutput,'String','0');


%pause%%%%%%%%%%%%need to carriage return to carry on, allows data to be seen in turn

end

handles.stitchcount = handles.stitchcount + 1;
guidata(hObject, handles);
% handles



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

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

if handles.flag(1,c) == 1;
    fitsuccess = 'Yes';
else
    fitsuccess = 'No';
end
set(handles.flagoutput,'String',fitsuccess);
set(handles.leastsquaresoutput,'String',num2str(handles.leastsquares(1,c),3));
set(handles.lengthoverlapoutput,'String',num2str(handles.length_overlap(1,c)));

colour=[0 0 0; 1 0 0; 0 0.5 0; 0 0 0.5; 0 1 1];
set(0,'DefaultAxesColorOrder',colour);
axesHandledeers= findobj(gcf,'Tag','deers_axes');
cla(axesHandledeers);
plot(axesHandledeers,handles.t3p_s(:,c),handles.deer3pRe_s(:,c),handles.t4p_s{1,c},handles.deer4pfit_s{1,c},handles.t3p_deers_s(:,c),handles.deers1_s(:,c)+0.2,handles.t3p_deers_s(:,c),handles.deers2_s(:,c)+0.4,handles.tres_s{:,c},handles.res_s{:,c});axis 'tight'
set(axesHandledeers,'Tag','deers_axes');

axesHandledeers= findobj(gcf,'Tag','residuals_axes');
cla(axesHandledeers);
x = min(handles.res_s{:,c}):0.000005:max(handles.res_s{:,c});
g1 = gaussian(x,0,2.355*std(handles.res_s{:,c}));
i = hist(handles.res_s{:,c},50);
g1 = max(i)*g1./max(g1);
hist(axesHandledeers,handles.res_s{:,c},50);hold on
plot(axesHandledeers,x,g1);axis 'tight'
set(axesHandledeers,'Tag','residuals_axes');

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


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


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


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



directoryname = uigetdir('', 'Save to directory');
cd(directoryname);

for c = 1:handles.trialm;
overlap = handles.length_overlap(:,c);

if handles.Bfit(1,c) == 1;
    modfit = 'yes';
else
    modfit = 'no';
end

clear result
result(:,1) = handles.t3p_deers_s(:,c);
result(:,2) = handles.deers1_s(:,c);
result(:,3) = zeros(size(handles.t3p_deers_s(:,c)));%this ignores any contribution from the imaginary
fOut = sprintf('deers_RepShort_modfit_%s_ol_%01dns.txt',modfit,overlap);
save(fOut, 'result', '-ascii');
clear result

clear result
result(:,1) = handles.t3p_deers_s(:,c);
result(:,2) = handles.deers2_s(:,c);
result(:,3) = zeros(size(handles.t3p_deers_s(:,c)));%this ignores any contribution from the imaginary
fOut = sprintf('deers_RepLong_modfit_%s_ol_%01dns.txt',modfit,overlap);
save(fOut, 'result', '-ascii');
clear result
    
clear result
result(:,1) = handles.tres_s{:,c};
result(:,2) = handles.res_s{:,c};
result(:,3) = zeros(size(handles.tres_s{:,c}));
fOut = sprintf('residuals_modfit_%s_ol_%01dns.txt',modfit,overlap);
save(fOut, 'result', '-ascii');
clear result

disp(handles)
result(:,1) = handles.t4p_s{:,c};
result(:,2) = handles.deer4pfit_s{:,c};
fOut = sprintf('deer4p_fitted_modfit_%s_ol_%01dns.txt',modfit,overlap);
save(fOut, 'result', '-ascii');
clear result

result(:,1) = handles.t3p_s(:,c);
result(:,2) = handles.deer3pRe_s(:,c);
fOut = sprintf('deer3p_modfit_%s_ol_%01dns.txt',modfit,overlap);
save(fOut, 'result', '-ascii');
clear result

end

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

c = handles.c;


colour=[0 0 0; 1 0 0; 0 0.5 0; 0 0 0.5; 0 1 1];
set(0,'DefaultAxesColorOrder',colour);
f1 = figure(1);
reset(gca);
h1 = plot(handles.t3p_s(:,c),handles.deer3pRe_s(:,c),handles.t4p_s{1,c},handles.deer4pfit_s{1,c},handles.t3p_deers_s(:,c),handles.deers1_s(:,c)+0.2,handles.t3p_deers_s(:,c),handles.deers2_s(:,c)+0.4,handles.tres_s{:,c},handles.res_s{:,c});axis 'tight'
xlabel('time / ns','fontsize',12,'fontname','arial');
ylabel('intensity','fontsize',12,'fontname','arial');
legend('3p-DEER','4p-DEER','DEERS (short replace)','DEERS (Long replace)','Residuals')
title('DEERS time traces','fontsize',12,'fontname','arial')
set(f1,'color','white','units','centimeters','outerposition',[10 10 30 30]);
set(gca,'fontsize',12);
set(gca,'tickdir','out');
set(h1,'linestyle','-','linewidth',1.0);
set(gca,'box','off');


x = min(handles.res_s{:,c}):0.000005:max(handles.res_s{:,c});
g1 = gaussian(x,0,2.355*std(handles.res_s{:,c}));
i = hist(handles.res_s{:,c},50);
g1 = max(i)*g1./max(g1);
f2 = figure(2);
reset(gca);
hist(handles.res_s{:,c},50,'k');hold on
plot(x,g1,'k');axis 'tight'
set(f2,'color','white','units','centimeters','outerposition',[10 10 15 15]);
h = findobj(gca,'Type','patch');
set(h,'FaceColor','k','EdgeColor','k')
title('Histogram of residuals with comparative normal distribution','fontsize',12,'fontname','arial')
xlabel('residual intensity','fontsize',12,'fontname','arial');
ylabel('frequency','fontsize',12,'fontname','arial');
