function varargout=ma_table(varargin)
%% these are all the functions for the table window
%_______________________________________________________________________

global ma

%-Condition arguments
%-----------------------------------------------------------------------
if (nargin==0), Action = 'Create'; else, Action = varargin{1}; end

switch lower(Action), 
    
    case 'findwin'
        %=======================================================================
        % F=ma_table('FindWin')        
        F = findobj(get(0,'Children'),'Flat','Tag','Table');
        if length(F) > 1
            % Multiple Graphics windows - close all but most recent
            close(F(2:end))
            F = F(1);
        end
        varargout = {F};
        
    case 'getwin'
        %=======================================================================
        % F=ma_table('GetWin',Tag)
        
        F = ma_table('FindWin');
        
        if isempty(F)
            F = ma_table('Create');
        end
        varargout = {F};
        
    case 'clear'
        %=======================================================================
        % ma_table('Clear',F,Tags)
        
        F = ma_table('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: Table','UserData',[])
        set(F,'Pointer','Arrow')    
        
    case {'create','createwin'}
        %=======================================================================
        % F=ma_table('CreateWin')
        
        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
        PF   = spm_platform('fonts');			%-Font names (for this platform)
        
        Rect = [155    18   992   415].*WS;
        
        F    = figure(...
            'Tag','Table',...
            '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,'PaperOrientation','landscape', ...
            'Name','AMAT: Table','NumberTitle','off')
        set(F,'Visible','on')
        ma_table('set_axes');
        varargout = {F};

    case 'set_axes'
        
        F = ma_table('GetWin');
        ma_table('clear')

        %% set up axes
        hHead = axes('Parent',F,'Tag','Header_axis', ...
            'Units','Normalized',...
            'Position',[0.03,0.91,0.9,0.08],...
            'Visible','off');
        
        hTab = axes('Parent',F,'Tag','Table_axis', ...
            'Units','Normalized',...
            'Position',[0.03,0.03,0.9,0.8],...
            'Visible','off', ...
            'ButtonDownFcn','ma_table(''click'')');
        
        %% set up scroll bar
        hScroll = uicontrol('Parent',F,'Tag','Scroll', ...
            'Style','Slider',...
            'Units','Normalized',...
            'Position',[0.93,0.03,0.02,0.8],...
            'Max',0,'Min',-100,'Value',0, ...
            'Callback','ma_table(''scroll'')');
        
    case 'scroll'
        if(nargin<2)
            F = ma_table('GetWin');
            hScroll = findobj(F,'Tag','Scroll');
            pos = get(hScroll,'Value');
        else
            pos = varargin{2};
            set(hScroll,'Value',pos)
        end
        
        hTab = findobj(F,'Tag','Table_axis');
        ylines = get(hTab,'UserData');
        showlines = ma.defaults.tablelines;
        ylim = [0,showlines]+(ylines-showlines+2)*(-pos)/100;
        set(hTab,'YLim',ylim)
        
    case 'show'
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %% show results in a table
        
        if(nargin<2)
            disp('no data to show')
            return
        else
            tab = varargin{2};
        end
       
        F = ma_table('GetWin');
        ma_table('clear')
        ma_table('set_axes');
        hHead = findobj(F,'Tag','Header_axis');
        hTab = findobj(F,'Tag','Table_axis');
        
        %% set up columns
        cols = cat(2,tab.cols.width{:});
        cwidth = cols./sum(cols);
        cstart = [0,cumsum(cwidth)];
        
        %% write headers
        axes(hHead);
        set(hHead,'XLim',[0,1],'YLim',[0,3]);
        text(0,2.2,tab.ttl,'FontSize',spm('FontSize',11),'FontWeight','Bold')
        for i=1:length(cols)
            if(cols(i)>0)
                hColHead(i) = text(cstart(i),0.75,tab.cols.header{i});
            end
        end
        set(hColHead,'FontSize',spm('FontSize',10))
        hold on
        plot([0,1],[0,0],'k-')
        
        %% write table
        axes(hTab);
        set(hTab,'XLim',[0,1],'YLim',[0,20],'YDir','Reverse')
        set(hTab,'UserData',size(tab.cols.data,1));  %% this is max no of lines
        for i=1:length(cols)
            if(cols(i)>0)
                for j=1:size(tab.cols.data,1)
                    txt = deblank(tab.cols.data{j,i});
                    done = 0;
                    cloop = 0;
                    while(~done)
                        htmp = text(cstart(i),j,txt); ...
                            %  'ButtonDownFcn',disp(num2str([i,j])));
                        %%decide if text is too long
                        bb = get(htmp,'Extent');
                        ylen = bb(1)+bb(3);
                        if(ylen>cstart(i+1))
                            %% fix it
                            over = length(txt)*(1-(ylen-cstart(i+1))./ylen);
                            sp = strfind(txt,' ');
                            sp = sp(sp<over);
                            txt = [txt(1:sp(end-cloop)),' ...'];
                            delete(htmp);
                            cloop = cloop+1;
                        else
                            done = 1;
                        end
                    end
                    set(htmp,'Clipping','on','ButtonDownFcn','ma_table(''click'')')
                end
            end
        end
                    
    case 'click'
        %% work out where the person clicked on the table and do stuff
        
        obj = gco;
      %  disp(['you clicked on ',num2str(obj)])
        F = ma_table('GetWin');
        hHead = findobj(F,'Tag','Header_axis');
        hTab = findobj(F,'Tag','Table_axis');
        pos = get(obj,'Position');
        line = pos(2);
        
        %% show full details of paper in interactive window
        id = ma.search.results.dbid(line);
        nline = 1;
        info = {};
        
        if(isfield(ma.search.results,'dbpts'))
         %% store current coordinate
          ma.search.currentcoord = ma.search.results.dbpts(line,:);

          %% display location info
          info{1} = ['MNI Location:      ',num2str(ma.search.results.dbpts(line,:),3)];
          info{2} = [ma.search.results.area{line},'     BA ',ma.search.results.brod{line}];
          info{3} = ['--------- Stimulus: --------------'];
           nline = 4;
           tmp = ma.search.results.descrip{line};
           while(length(tmp)>70)
             sp = strfind(tmp,' ');
             bk = max(sp(sp<70));
             info{nline} = tmp(1:bk);
             tmp = tmp(bk+1:end);
             nline = nline+1;
           end
           info{nline} = tmp;
           nline = nline+1;
        end
        
        %% store the current paper number
        ma.search.currentpmid = ma.pubmed(id).id;
             
        %% display paper info
        info{nline} = '----------  Paper: ----------------';
        nline = nline+1;
        info{nline} = [];
        for i=1:length(ma.pubmed(id).authors)
          info{nline} = [info{nline},ma.pubmed(id).authors{i},' '];
        end
        nline = nline+1;
        tmp = ma.pubmed(id).title;
        while(length(tmp)>70)
          sp = strfind(tmp,' ');
          bk = max(sp(sp<70));
          info{nline} = tmp(1:bk);
          tmp = tmp(bk+1:end);
          nline = nline+1;
        end
        info{nline} = tmp;
        nline = nline+1;
        
        info{nline} = [ma.pubmed(id).journal,'  ',num2str(ma.pubmed(id).year)];
        
        %% if the table has coords, move to the coords
        if(isfield(ma.search.results,'dbpts'))
            currpoint = ma.search.results.dbpts(line,:);
            spm_orthviews('Reposition',currpoint)
            ma_figure('show_coords',currpoint)
        end
        
        ma_interactive('disp_text',info)

        %% add a 'show' button
        Finter = ma_interactive('GetWin');
        sz = get(F,'Position');
        lines = fliplr(linspace(sz(4)*0.05,sz(4)*0.90,10));
        px1 = 10;
        px2 = sz(3)*0.25;
        wdth1 = (px2-px1)*0.9;
        wdth2 = (sz(4)-px2)*0.9;
        hgt = 20;
        
        %% search button        
        uicontrol(Finter,'String','Show Coordinates of this paper', ...
                  'Tag','Show_coords', ...
                  'TooltipString','Show coordinates of the current paper', ...
                  'Position',[px1+wdth1+10,lines(end),wdth1,30],...
                  'CallBack','ma_coords(''pmid_search'')',...  
                  'ForegroundColor',[0 0 1],'Enable','on');
                         
        %% add a 'search neighbours' button
        uicontrol(Finter,'String','Show Neighbours of this point', ...
                  'Tag','Show_neighbours', ...
                  'TooltipString','Show neighours of the current point',...
                  'Position',[px1,lines(end),wdth1,30],...
                  'CallBack','ma_coords(''load_coords'')',...  
                  'ForegroundColor',[0 0 1],'Enable','on');
         
    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;
