%This program can calculate the deltaF/F of the calcium signal
%Author:    Qinchun Guo
%           Imaging Facility of Chinese Institute for Brain
%           Research,Beijing(CIBR)
%           guoqingchun@cibr.ac.cn
function varargout = CaImAnalyzer(varargin)
% CAIMANALYZER MATLAB code for CaImAnalyzer.fig
%      CAIMANALYZER, by itself, creates a new CAIMANALYZER or raises the existing
%      singleton*.
%
%      H = CAIMANALYZER returns the handle to a new CAIMANALYZER or the handle to
%      the existing singleton*.
%
%      CAIMANALYZER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in CAIMANALYZER.M with the given input arguments.
%
%      CAIMANALYZER('Property','Value',...) creates a new CAIMANALYZER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before CaImAnalyzer_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to CaImAnalyzer_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 CaImAnalyzer

% Last Modified by GUIDE v2.5 15-Mar-2019 16:30:46

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

% Choose default command line output for CaImAnalyzer
clc;
handles.output = hObject;
axes(handles.axes1);
axis off;
imshow(imread('Background.tif'));
axes(handles.axes2);
axis off;
imshow(imread('Background.tif'));


% Update handles structure
guidata(hObject, handles);

% This sets up the initial plot - only do when we are invisible
% so window can get raised using CaImAnalyzer.
if strcmp(get(hObject,'Visible'),'off')
    plot(rand(5));
end

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


% --- Outputs from this function are returned to the command line.
function varargout = CaImAnalyzer_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 pb_load.
function pb_load_Callback(hObject, eventdata, handles)
% hObject    handle to pb_load (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[fileName,filePath]=uigetfile('.tif');
info=imfinfo([filePath fileName]);
mImage=info.Height;
nImage=info.Width;
numberImage=length(info);
bitDepth=info.BitDepth;
if bitDepth==24
    Image=zeros(mImage,nImage,3,numberImage);    
    h=waitbar(0,'Loading...');
    for i=1:numberImage
        Image(:,:,:,i)=imread([filePath fileName],i);
        if ~rem(i,20)
            waitbar(i/numberImage);
        end
    end
    Image=reshape(Image(:,:,2,:),mImage,nImage,numberImage);
    close(h); 
else
    Image=zeros(mImage,nImage,numberImage);
    h=waitbar(0,'Loading...');
    for i=1:numberImage
        Image(:,:,i)=imread([filePath fileName],i);
        if ~rem(i,20)
            waitbar(i/numberImage);
        end
    end
    close(h); 
end
handles.fileName=fileName;
handles.filePath=filePath;
handles.info=info;
handles.Image=Image;
set(handles.slider,'Min',0,'Max',1,'SliderStep',[0.01,0.1],'Value',0);
set(handles.text_filePath,'String',[filePath fileName]);
axes(handles.axes1);
cla;
imagesc(Image(:,:,1));
colormap gray;
axis off;
axes(handles.axes2);
cla;
imagesc(Image(:,:,1));
colormap gray;
axis off;
% handles.hRef=hRef;
guidata(hObject,handles);

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


% --------------------------------------------------------------------
function OpenMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to OpenMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
file = uigetfile('*.fig');
if ~isequal(file, 0)
    open(file);
end

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

% --------------------------------------------------------------------
function CloseMenuItem_Callback(hObject, eventdata, handles)
% hObject    handle to CloseMenuItem (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...
                     ['Close ' get(handles.figure1,'Name') '...'],...
                     'Yes','No','Yes');
if strcmp(selection,'No')
    return;
end

delete(handles.figure1)


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

set(hObject, 'String', {'plot(rand(5))', 'plot(sin(1:0.01:25))', 'bar(1:.5:10)', 'plot(membrane)', 'surf(peaks)'});



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


% --- Executes during object creation, after setting all properties.
function text_filePath_CreateFcn(hObject, eventdata, handles)
% hObject    handle to text_filePath (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_add.
function pb_add_Callback(hObject, eventdata, handles)
% hObject    handle to pb_add (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
axes(handles.axes2);
Image=handles.Image;
refImage=Image(:,:,1);
imagesc(refImage);
axis off;
colormap gray;
% nROI=str2double(get(handles.edit_nROI,'String'));
% ROI=cell(nROI,1);
% hRef=handles.hRef;
i=1;
e=imellipse(gca);
while ~isempty(e)
    e.setColor('red');
    ROI{i}=e.createMask;
    p=e.getPosition;
    text(p(1)+p(3)/3,p(2)+p(4)/3,num2str(i),'Color','green');     
    i=i+1;
    e=imellipse(gca);   
end
% for i=1:nROI
%     e=imellipse(gca);
%     e.setColor('red');
%     ROI{i}=e.createMask;
%     p=e.getPosition;
%     text(p(1)+p(3)/3,p(2)+p(4)/3,num2str(i),'Color','green');
%     
% %     ROI{i}=createMask(e,hRef);
% end
handles.ROI=ROI;
guidata(hObject,handles);


% --- Executes on button press in pb_plot.
function pb_plot_Callback(hObject, eventdata, handles)
% hObject    handle to pb_plot (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Image=handles.Image;
ROI=handles.ROI;
nROI=length(ROI);
numberImage=length(handles.info);
cal=zeros(numberImage,nROI);
f=str2double(get(handles.edit_f,'String'));
t=(0:numberImage-1)/f;
% ROIexpend=zeros(size(cal));
h=waitbar(0,'Analyzing...');
for i=1:nROI
    ROIexpend=repmat(ROI{i},[1,1,numberImage]);
    ROIimage=Image.*ROIexpend;
    cal(:,i)=reshape((sum(sum(ROIimage,1),2))/sum(sum(ROIexpend(:,:,1))),numberImage,1);
    waitbar(i/nROI);
end
close(h);
baselTime=str2num(get(handles.edit_baselTime,'String'));
baselTime=round(baselTime*f);
calData=cal(:,2:end)-repmat(cal(:,1),1,nROI-1);
basel=mean(calData(baselTime(1):baselTime(2),:),1);
basel=repmat(basel,numberImage,1);
calData=100*(calData-basel)./basel;
figure;
% plot(t,cal);
cmap = hsv(nROI-1);
for i=1:nROI-1
    plot(t,calData(:,i),'Color',cmap(i,:));
    hold on;
end
% plot(t,calData);
ylabel('\DeltaF/F%');
xlabel('Time/s');
legend;
filePath=handles.filePath;
fileName=handles.fileName;
meanData=mean(calData,2);
semData=std(calData,0,2)/sqrt(nROI-1);
figure;
drawErrorLine(t,meanData,semData,'red',0.2);
ylabel('\DeltaF/F%');
xlabel('Time/s');
figure;
imagesc(t,1:nROI-1,calData');
xlabel('Time/s');
ylabel('Cell#');
save(strrep([filePath,fileName],'.tif','.mat'),'calData','meanData','semData');



% --- Executes on slider movement.
function slider_Callback(hObject, eventdata, handles)
% hObject    handle to slider (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,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider
axes(handles.axes1);
Image=handles.Image;
info=handles.info;
N=length(info);
sliderValue=get(handles.slider,'Value');
index=round(sliderValue*(N-1))+1;
imagesc(Image(:,:,index));
colormap gray;
axis off;


% --- Executes during object creation, after setting all properties.
function slider_CreateFcn(hObject, eventdata, handles)
% hObject    handle to slider (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor',[.9 .9 .9]);
end



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


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


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


% --- Executes during object creation, after setting all properties.
function edit_f_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_f (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_loadROI.
function pb_loadROI_Callback(hObject, eventdata, handles)
% hObject    handle to pb_loadROI (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
uiopen('.mat');
handles.ROI=ROI;
axes(handles.axes2);
Image=handles.Image;
refImage=Image(:,:,1);
imagesc(refImage);
axis off;
colormap gray;
hold on;
nROI=length(ROI);
for i=1:nROI
    boundaryROI=bwboundaries(ROI{i});
    plot(boundaryROI{1}(:,2),boundaryROI{1}(:,1),'r');
    p=regionprops(ROI{i},'centroid');
    text(round(p.Centroid(1)),round(p.Centroid(2)),num2str(i),'Color','green');
%     ROI{i}=createMask(e,hRef);
end
hold off;
guidata(hObject,handles);

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