function varargout=ma_figure(varargin)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this does the figure with a clickable brain
%% it is based on spm_figure
%-Condition arguments
%-----------------------------------------------------------------------
if (nargin==0), Action = 'Create'; else, Action = varargin{1}; end

switch lower(Action),
    
    case 'findwin'
        F = findobj(get(0,'Children'),'Flat','Tag','Graphics');
        if length(F) > 1
            % Multiple Graphics windows - close all but most recent
            close(F(2:end))
            F = F(1);
        end
        if isempty(F)
            F = ma_figure('Create');
        end
        % F is supposed to be a figure number - check it
        if ~any(F==get(0,'Children')), F=[]; end
        varargout = {F};
        
    case 'getwin'
        %=======================================================================
        % F=ma_figure('GetWin',Tag)
        F = ma_figure('FindWin');
        
        if isempty(F)
            F = ma_figure('Create');
        end
        varargout = {F};
        
    case 'clear'
        %=======================================================================
        % ma_figure('Clear',F,Tags)
        
        F = ma_figure('FindWin');
        
        %-Clear figure
        %-----------------------------------------------------------------------
        pos = get(F,'Position');
        delete(findobj(get(F,'Children'),'flat','HandleVisibility','on'));
        drawnow
        set(F,'Position',pos);
        
        %-Reset figures callback functions
        set(F,'KeyPressFcn','',...
            'WindowButtonDownFcn','',...
            'WindowButtonMotionFcn','',...
            'WindowButtonUpFcn','')
        
        set(F,'Name','AMAT: Graphics','UserData',[])
        set(F,'Pointer','Arrow')    
        
    case {'create','createwin'}
        %=======================================================================
        % F=ma_figure('CreateWin',Tag,Name,Visible)
        
        %% close any previous graphics windows;
        F = findobj(get(0,'Children'),'Flat','Tag','Graphics');
        close(F);
        
        S0   = get(0,'ScreenSize');
        WS = [S0(3)/1152 (S0(4)-50)/900 S0(3)/1152 (S0(4)-50)/900];  % window scale
        FS = ceil( (1:36)* (1 + 0.85*(min(WS)-1)) );  %% font size
        Rect = [155   465   435   465].*WS;
        PF   = spm_platform('fonts');			%-Font names (for this platform)
        Rect =  [602   465   547   465].*WS;
        
        F    = figure(...
            'Tag','Graphics',...
            'Position',Rect,...
            'Resize','off',...
            'Color','w',...
            'ColorMap',gray(64),...
            'DefaultTextColor','k',...
            'DefaultTextInterpreter','none',...
            'DefaultTextFontName',PF.helvetica,...
            'DefaultTextFontSize',FS(10),...
            'DefaultAxesColor','w',...
            'DefaultAxesXColor','k',...
            'DefaultAxesYColor','k',...
            'DefaultAxesZColor','k',...
            'DefaultAxesFontName',PF.helvetica,...
            'DefaultPatchFaceColor','k',...
            'DefaultPatchEdgeColor','k',...
            'DefaultSurfaceEdgeColor','k',...
            'DefaultLineColor','k',...
            'DefaultUicontrolFontName',PF.helvetica,...
            'DefaultUicontrolFontSize',FS(10),...
            'DefaultUicontrolInterruptible','on',...
            'MenuBar','none',...
            'PaperType','A4',...
            'PaperUnits','normalized',...
            'PaperPosition',[.0726 .0644 .854 .870],...
            'InvertHardcopy','off',...
            'Renderer','zbuffer',...
            'Visible','off');
                
        set(F,'Name','AMAT: Graphics','NumberTitle','off')
        set(F,'Visible','on')
        
        set(F,'Units','Normalized');
        uicontrol(F,'Style','Text',...
            'String','',...
            'Tag',['Label_coords'],...
            'UserData','',...
            'HorizontalAlignment','Right',...
            'Position',[300,10,100,30], ...
            'BackgroundColor',[1,1,1]);

        varargout = {F};
        
    case 'draw_brain'

        F = ma_figure('getwin')
        set(F,'Units','Normalized');
        
        global st
        bb      = [ [-78 78]' [-112 76]' [-50 85]' ];
        st      = struct('n', 0, 'vols',[], 'bb',bb,'Space',eye(4),'centre',[0 0 0],...
            'callback',';','xhairs',1,'hld',1,'fig',F,'mode',1,'plugins',[]);
        st.vols = cell(24,1);
        st.callback = ['ma_figure(''show_coords'',st.centre);'];
        
        %% show hires
        hname = 'single_subj_T1.mnc';
        H = spm_vol(hname);
        hBrain =spm_orthviews('Image',H,[0.01,0.05,0.95,0.9]);
        
        ma_figure('show_coords',st.centre);
        
    case 'add_points'
        
        %% read inputs 
        pts = varargin{2};
        sz = varargin{3};
        col = varargin{4};  %% colors must all be the same
        if(size(pts,2)~=3)
            disp('Points matrix is not n x 3')
            return
        end
        if(~all(size(col)==[1,3]))
            disp('Color must be 1x3 RGB vector')
            return
        end
        if(size(sz,1)~=size(pts,2))
            sz = repmat(sz(1),size(pts,1),1);
        end
        
        F = ma_figure('getwin');
        hname = 'single_subj_T1.mnc';
        H = spm_vol(hname);

        cci = [];
        for i=1:size(pts,1)  %% for each point
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            %% generate sphere
            [x,y,z] = ndgrid(-10:10,-10:10,-10:10);
            sph = [x(:),y(:),z(:)];
            d = sqrt(sum(sph.^2,2));
            sph = sph(d<=sz(i),:);
            
            brain_point = ( pts(i,:)-H.mat(1:3,4)' )/2;

            %% plot database points
            cci = [cci;sph+repmat(brain_point,size(sph,1),1)];
        
        end

        %% add only unique points
        cci = round(cci);
        cci = unique(cci,'rows');
                
        spm_orthviews('AddColouredBlobs',F,cci',1*ones(length(cci),1),H.mat,col)

    case 'show_coords'
        %% this should mainly be called by clicking on the figure
        %% and is shows the current coordinates in a text box
        centre = varargin{2};
        
        centre = centre(:);
        if(~all(size(centre)==[3,1]));
            disp('cannot show coords')
        end
        
        F = ma_figure('getwin');
        hCoord = findobj(F,'Tag','Label_coords');
        set(hCoord,'String',num2str(round(centre')));
        
%         axhires = get(F,'Children')
%         
%         for i=1:3
%             set(axhires(i),'Tag',['Brain',num2str(i)])
%         end
%             
%         
        
        
    otherwise
        %=======================================================================
        warning(['Illegal Action string: ',Action])
    end
    return;
    %=======================================================================
    
    
    %=======================================================================
    function copy_menu(F,G)
    %=======================================================================
    handles = findobj(get(F,'Children'),'Flat','Type','uimenu','Visible','on');
    if length(handles)==0, return; end;
    for F1=handles',
        if ~strcmp(get(F1,'Label'),'&Window'),
            G1 = uimenu(G,'Label',get(F1,'Label'),...
                'CallBack',get(F1,'CallBack'),...
                'Position',get(F1,'Position'),...
                'Separator',get(F1,'Separator'));
            copy_menu(F1,G1);
        end;
    end;
    return;
    %=======================================================================
    
    
    %=======================================================================
    function PRINTSTR = clean_PRINTSTR(PRINTSTR)
    %=======================================================================
    % Matlab 6.5 printing doesn't like the -append option if the file does
    % not already exist
    %-----------------------------------------------------------------------
    off = findstr('-append',PRINTSTR);
    if ~isempty(off),
        bl = [0 find(isspace(PRINTSTR)) (length(PRINTSTR)+1)];
        for i=1:(length(bl)-1),
            ca{i} = PRINTSTR((bl(i)+1):(bl(i+1)-1));
        end;
        ca = strvcat(ca);
        off1 = find(ca(:,1)~='-'); % either 'print' or a filename
        if length(off1)>1,
            fname = deblank(ca(off1(end),:));
            
            % If there is no path to the file, then make it the
            % current directory
            [pth,nam,ext] = fileparts(fname);
            if isempty(pth), fname = ['.' filesep nam ext]; end;
            
            fd = fopen(fname,'r');
            if fd~=-1,
                % File exists, so -append can be used
                fclose(fd);
            else,
                % File does not exist, so remove -append option
                PRINTSTR(off:(off+7))='';
            end;
        end;
    end;
