function tracknuc
%% help
% comments
%% Parameters for positions and colors of figures and some handles
% The position of the game figure will be [figX1,figX2,figY1,figY2]
figX1 = 0;
figX2 = 1000;
figY1 = 0;
figY2 = 1000;
%% sets initial variables
FileName = '';
PathName = '';
FilterIndex = '';
frame = 1;
frameinit = 1;
framefin = 150;
Nf = 150;
Img = [];
lines.xx1 = [];
lines.yy1 = [];
lines.xx2 = [];
lines.yy2 = [];
boo = [];
%% Create and hide the GUI figure as it is being constructed.
segfigure = figure('Visible','on','Tag','segfigure','Position',[figX1,figY1,figX2,figY2]);
set ( gcf, 'Color', [0 0 0] )

% To capture mouse and keyboard
set(segfigure,'WindowKeyPressFcn',@keypress);
set(segfigure,'WindowScrollWheelFcn',@scroll);
set(segfigure,'WindowButtonUpFcn',@click);
%% Create buttons and others
hmessages = uicontrol('Style','text','String','Please load a movie',...
    'Position',[50,930,350,50],'FontSize',14, ...
    'ForegroundColor','white','BackgroundColor','black'); % Display instructions

hquitbutton = uicontrol('Style','pushbutton',...
    'String','Quit','Callback',@hquitbutton_Callback,...
    'Position',[950,950,50,50]); % Quit seg
%20.6628 -446.1809  144.5822   52.1283

hloadbutton = uicontrol('Style','pushbutton',...
    'String','Load','Callback',@hloadbutton_Callback,...
    'Position',[400,930,100,50]); % load file

hpath = uicontrol('Style','text','String','Path',...
    'Position',[510,930,400,50],'FontSize',10);

hframe = uicontrol('Style','slider',...
    'Min',1,'Max',Nf, 'value',frame,...
    'Position',[20,10,950,20],...
    'SliderStep',[1/150 0.2],'Callback',@hframe_Callback);

hsave = uicontrol('Style','pushbutton','String', 'Save ROIs',...
    'Position',[10,950,100,50],...
    'Callback',@hsave_Callback);
%% Create axes and display image
canvas = 870;
ImgOp = imread('DIC1_c21_s7175.tif',1);
sI = size(ImgOp);
panelI_X1 = 40;
%panelI_X2 = panelI_X1+sI(2);
panelI_X2 = canvas;
panelI_Y1 = 40;
%panelI_Y2 = panelI_Y1+sI(1);
panelI_Y2 = canvas;
ha = axes('Units','Pixels','Position',[panelI_X1,panelI_Y1,panelI_X2,panelI_Y2]);
imshow(ImgOp,[]);
% Change units to normalized so components resize automatically.
set([segfigure,ha,hmessages...
    hpath,hloadbutton,hquitbutton,...
    hframe,hsave],...
    'Units','normalized');
%% Final settings
% Assign the GUI a name to appear in the window title.
set(segfigure,'Name','Segment NUP V1')
% Move the GUI to the center of the screen.
movegui(segfigure,'north')
% Make the GUI visible.
set(segfigure,'Visible','on')

%% Callbacks
    function keypress(~,~)
        % Not used...
    end
    function click(~,~)
        % Not used...
    end
    function hquitbutton_Callback(~,~)
        close(segfigure);
    end

    function hloadbutton_Callback(~,~)
        frame = 1;
        set(hframe,'Value',frame);
        [FileName,PathName,FilterIndex] = uigetfile('*.tif','Select the tif file');
        set(hpath,'String',[PathName,FileName]);
        info = imfinfo([PathName,FileName]);
        Nf = length(info);
        lines.xx1 = repmat([10 100],Nf,1);
        lines.yy1 = repmat([10 100],Nf,1);
        lines.xx2 = repmat([10 100],Nf,1);
        lines.yy2 = repmat([100 10],Nf,1);
        boo = zeros(Nf,1);
        Wd = info(1).Width;
        Hg = info(1).Height;
        sI = [Hg,Wd];
        Img = [];
        for i=1:Nf
            Img = cat(3,Img,imread([PathName,FileName],i));
        end
        showI
        %showI(Img(:,:,1),lines);
        set(hframe,'max',Nf,'SliderStep',[1/(Nf-1) 0.4])
        set(hmessages,'String',['Loaded. Frame ',num2str(frame)]);
        %hl(1) = imline(gca,xx1(1,:), yy1(1,:));
        %hl(2) = imline(gca,xx2(1,:), yy2(1,:));
    end

    function hframe_Callback(~,~)
        frame = get(hframe,'Value');
        frame = round(frame);
        set(hframe,'Value',frame);
        showI
        set(hmessages,'String',['Frame ',num2str(frame)]);
    end

    function scroll(src,evnt)
        deltaframe = evnt.VerticalScrollCount;
        frame = frame + deltaframe;
        if frame<1
            frame=1;
        end
        if frame>Nf
            frame = Nf;
        end
        set(hframe,'Value',frame);
        showI
        set(hmessages,'String',['Frame ',num2str(frame)]);
    end

    function hsave_Callback(~,~)
        for i=1:Nf
            if boo(i)==1
                bx = [lines.xx1(i,1),lines.xx1(i,2),lines.xx2(i,1),lines.xx2(i,2)];
                by = [lines.yy1(i,1),lines.yy1(i,2),lines.yy2(i,1),lines.yy2(i,2)];
                BW = zeros(sI);
                BW(round(bx(1)),round(by(1)))=1;
                BW(round(bx(2)),round(by(2)))=1;
                BW(round(bx(3)),round(by(3)))=1;
                BW(round(bx(4)),round(by(4)))=1;
                stats(i)  = regionprops(BW,'centroid','Eccentricity','Orientation');
            else
                if i>1
                    locb = 0;
                    k=i-1;
                    while locb==0
                        if boo(k)==1
                            locb = 1;
                        else
                            k = k-1;
                        end
                    end
                    bx = [lines.xx1(k,1),lines.xx1(k,2),lines.xx2(k,1),lines.xx2(k,2)];
                    by = [lines.yy1(k,1),lines.yy1(k,2),lines.yy2(k,1),lines.yy2(k,2)];
                    BW = zeros(sI);
                    BW(round(bx(1)),round(by(1)))=1;
                    BW(round(bx(2)),round(by(2)))=1;
                    BW(round(bx(3)),round(by(3)))=1;
                    BW(round(bx(4)),round(by(4)))=1;
                    stats(i)  = regionprops(BW,'centroid','Eccentricity','Orientation');
                end
            end
        end
        k = strfind(FileName,'.');
        save([PathName,FileName(1:k-1),'_nuc.mat'],'stats');
    end
%% Functions
    function showI
        axes(ha);
        imshow(Img(:,:,frame),[]);
        if boo(frame)==1
            hl(1) = imline(gca,lines.xx1(frame,:), lines.yy1(frame,:));
            hl(2) = imline(gca,lines.xx2(frame,:), lines.yy2(frame,:));
            addNewPositionCallback(hl(1),@my1);
            addNewPositionCallback(hl(2),@my2);
        else
            if frame>1
                locb = 0;
                k=frame-1;
                while locb==0
                    if boo(k)==1
                        locb = 1;                       
                    else
                        k = k-1;
                    end
                end
                hl(1) = imline(gca,lines.xx1(k,:), lines.yy1(k,:));
                hl(2) = imline(gca,lines.xx2(k,:), lines.yy2(k,:));
                lines.xx1(frame,:) = lines.xx1(k,:);
                lines.yy1(frame,:) = lines.yy1(k,:);
                lines.xx2(frame,:) = lines.xx2(k,:);
                lines.yy2(frame,:) = lines.yy2(k,:);
                addNewPositionCallback(hl(1),@my1);
                addNewPositionCallback(hl(2),@my2);
                boo(frame)=1;
            else
                hl(1) = imline(gca,lines.xx1(frame,:), lines.yy1(frame,:));
                hl(2) = imline(gca,lines.xx2(frame,:), lines.yy2(frame,:));
                addNewPositionCallback(hl(1),@my1);
                addNewPositionCallback(hl(2),@my2);
            end
        end
    end

    function my1(pos)
        % imroi callback function, first input is handle of calling imroi object,
        % second is the updated position of the object, third is the point number
        % an integer identifying which point called this callback
        % ... insert your code here, using the handle, position, or id number
        lines.xx1(frame,:) = [pos(1,1),pos(2,1)];
        lines.yy1(frame,:) = [pos(1,2),pos(2,2)];
                boo(frame)=1;
    end % end of callback function

    function my2(pos)
        % imroi callback function, first input is handle of calling imroi object,
        % second is the updated position of the object, third is the point number
        % an integer identifying which point called this callback
        % ... insert your code here, using the handle, position, or id number
        lines.xx2(frame,:) = [pos(1,1),pos(2,1)];
        lines.yy2(frame,:) = [pos(1,2),pos(2,2)];
                boo(frame)=1;
    end % end of callback function
end