function varargout = ma_coords(varargin)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this function searchs for coordinates and displays them

global ma

if(nargin>0)
    action = varargin{1};
else
    disp('must specify an action')
    spm('beep')
    return;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Colour = [0.8,0.8,1];

switch lower(action)
  
  %==============================================================
 case 'neighbours_gui'
  
  if(isfield(ma,'search'))
    ma = rmfield(ma,'search') %% clear old searches
  end
  
  F = ma_interactive('GetWin');
  ma_interactive('clear');
  set(F,'Name','AMAT: Search Neighbours')
  sz = get(F,'Position');
  
  ma.search.type = 'neighbours'
  
  lines = fliplr(linspace(sz(4)*0.05,sz(4)*0.90,10));
  px1 = 10;
  px2 = sz(3)*0.5;
  wdth1 = (px2-px1)*0.9;
  wdth2 = (sz(4)-px2)*0.9;
  hgt = 20;
  
  uicontrol(F,'Style','Text',...
            'String','Enter the Search Terms',...
            'Tag',['Label_title'],...
            'UserData','',...
            'HorizontalAlignment','Center',...
            'Position',[px1,lines(1),wdth2,hgt], ...
            'FontSize',spm('Fontsize',14),...
            'BackgroundColor',Colour);
  
  %% coordinates
  uicontrol(F,'Style','Text',...
            'String','Coordinates',...
            'Tag',['Label_year'],...
            'UserData','',...
            'HorizontalAlignment','Right',...
            'Position',[px1,lines(2),wdth1,hgt], ...
            'BackgroundColor',Colour);
  
  uicontrol(F,'Style','Edit',...
            'String','',...
            'Tag',['Inp_coords'],...
            'UserData','',...
            'HorizontalAlignment','Left',...
            'Position',[px2,lines(2),wdth2,hgt], ...
            'BackgroundColor',Colour);
  
  %% neighbours
  uicontrol(F,'Style','Text',...
            'String','Number of points',...
            'Tag',['Label_nbour'],...
            'UserData','',...
            'HorizontalAlignment','Right',...
            'Position',[px1,lines(3),wdth1,hgt], ...
            'BackgroundColor',Colour);
  
  uicontrol(F,'Style','Edit',...
            'String',num2str(ma.defaults.nbours),...
            'Tag',['Inp_nbours'],...
            'UserData','',...
            'HorizontalAlignment','Left',...
            'Position',[px2,lines(3),wdth2,hgt], ...
            'BackgroundColor',Colour);
  
  %% Coord system
  hRadio(1) = uicontrol(F,'Style','Radiobutton',...
                        'String','MNI',...
                        'Tag',['radio_mni'],...
                        'UserData','',...
                        'HorizontalAlignment','Left',...
                        'Position',[px1+20,lines(4),wdth1,hgt], ...
                        'BackgroundColor',Colour, ...
                        'Value',1);
  
  hRadio(2) = uicontrol(F,'Style','Radiobutton',...
                        'String','Talairach',...
                        'Tag',['radio_tal'],...
                        'UserData','',...
                        'HorizontalAlignment','Left',...
                        'Position',[px2,lines(4),wdth2,hgt], ...
                        'BackgroundColor',Colour, ...
                        'Value',0);  
  
  set(hRadio(1),'Callback','set(hRadio(2),''Value'',0)');
  set(hRadio(2),'Callback','set(hRadio(1),''Value'',0)');
  
  %% search button
  uicontrol(F,'String','Search', ...
            'Tag','Search_button', ...
            'TooltipString','Search the database for neighbours', ...
            'Position',[px1,lines(end),wdth1,30],...
            'CallBack',['ma_coords(''read_coords'')'],...
            'ForegroundColor',[0 0 1]);
  
  %------------------------------------------------------------------
 case 'read_coords'
  %% read values from uicontrols
  F = ma_interactive('GetWin');
  %% find useful info
  
  coord_str = get(findobj(F,'Tag','Inp_coords'),'String');
  nbour = str2num(get(findobj(F,'Tag','Inp_nbours'),'String'));
  coord_sys = get(findobj(F,'Tag','radio_mni'),'Value');
  
  try
    [coords,n,err] = sscanf(coord_str,'%d');
  catch
    spm('beep')
    disp(['Could not read Coordinates: ',coord_str])
    return
  end
  if(n~=3)
    spm('beep')
    disp(['Could not read Coordinates: ',coord_str])
    return
  end 
  coords = coords';
  %% convert to MNI
  if(coord_sys==0)
    coords = tal2mni(coords);
  end
  
  ma.search.criteria.coords = coords;
  ma.search.criteria.nbour = nbour;
  
  ma_coords('do_search')
  
 case 'load_coords'
  %% read values from ma
  ma.search.criteria.coords = ma.search.currentcoord;
  ma.search.criteria.nbour = 30;
     
  ma_coords('do_search');
  
  %------------------------------------------------------------
 case 'do_search'
  
  coords = ma.search.criteria.coords;
  nbour = ma.search.criteria.nbour;
  
  %% find nearest neighbours
  %%% get points and convert to mni
  dbpts = ma.ba.mxyz;
  dist = sqrt( (coords(1)-dbpts(:,1)).^2 + (coords(2)-dbpts(:,2)).^2 ...
               + (coords(3)-dbpts(:,3)).^2 );
  [d,ord] = sort(dist);
  
  ma.search.results.dist = dist(ord(1:nbour));
  ma.search.results.dbpts = dbpts(ord(1:nbour),:);
  ma.search.results.area = ma.ba.area(ord(1:nbour));
  ma.search.results.brod = ma.ba.brod(ord(1:nbour));
  ma.search.results.descrip = ma.ba.descrip(ord(1:nbour));
  ma.search.results.pmid = ma.ba.pmid(ord(1:nbour));
  
  pid = cat(1,ma.pubmed.id);
  for i=1:length(ma.search.results.pmid)
    pind(i) = find(pid==ma.search.results.pmid(i));
    ma.search.results.year{i} = ma.pubmed(pind(i)).year;
    ma.search.results.journal{i} = ma.pubmed(pind(i)).journal;
    ma.search.results.authors{i} = ma.pubmed(pind(i)).authors;
    ma.search.results.dbid(i,:) = pind(i);
  end
        
  ma_coords('make_table')
  
  %---------------------------------------------------------
 case 'pmid_search'
  %% search for points based on an id or series of ids
  
  pmid = ma.search.currentpmid;
  
  baind = find(pmid==ma.ba.pmid);
  
  ma.search.results.dbpts = ma.ba.mxyz(baind,:);
  ma.search.results.area = ma.ba.area(baind);
  ma.search.results.brod = ma.ba.brod(baind);
  ma.search.results.descrip = ma.ba.descrip(baind);
  ma.search.results.pmid = ma.ba.pmid(baind);
  ma.search.results.dist = zeros(size(baind));
  
  pid = cat(1,ma.pubmed.id);
  for i=1:length(ma.search.results.pmid)
    pind(i) = find(pid==ma.search.results.pmid(i));
    ma.search.results.year{i} = ma.pubmed(pind(i)).year;
    ma.search.results.journal{i} = ma.pubmed(pind(i)).journal;
    ma.search.results.authors{i} = ma.pubmed(pind(i)).authors;
    ma.search.results.dbid(i,:) = pind(i);
  end
        
  ma_coords('make_table')
    
  %-----------------------------------------------------------
 case 'make_table'
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %% put results into a nice table
  clear tab
  if(isfield(ma.search.criteria,'nbour'))
    nbour =  length(ma.search.results.dist);
    coords = ma.search.criteria.coords;
    tab.ttl = ['Search Criteria  =   Nearest ',num2str(nbour),...
               ' neighbours to ',num2str(coords,3),' (MNI) '];
  else
    pmid = ma.search.currentpmid;
    coords = [0,0,0];
    nbour = length(ma.search.results.dist);
    tab.ttl = ['Search Criteria = Paper ID ',num2str(pmid)];
  end
  
  
  tab.cols.header = {'Distance','X','Y','Z','Area','Descrip','Authors','Year','PMID'};
  tab.cols.width = {12,8,8,8,50,75,75,10,20};
  for i=1:nbour
    %% sort out coords stuff first
    tab.cols.data{i,1} = num2str(ma.search.results.dist(i),3);
    tab.cols.data{i,2} = num2str(round(ma.search.results.dbpts(i,1)));
    tab.cols.data{i,3} = num2str(round(ma.search.results.dbpts(i,2)));
    tab.cols.data{i,4} = num2str(round(ma.search.results.dbpts(i,3)));
    tab.cols.data{i,5} = ma.search.results.area{i};
    tab.cols.data{i,6} = ma.search.results.descrip{i};
    %% sort out authors etc
    
    pmid = ma.search.results.pmid(i);
    ind = find(pmid==cat(1,ma.pubmed.id));
    aut = [];
    for j=1:length(ma.pubmed(ind).authors)
      aut = [aut,' ',ma.pubmed(ind).authors{j}];
    end
    tab.cols.data{i,7} = aut;
    tab.cols.data{i,8} = num2str(ma.pubmed(ind).year);
    tab.cols.data{i,9} = num2str(ma.pubmed(ind).id);
  end
  
  ma_table('show',tab);
  
  %% and plot in the figure
  ma_figure('create')  %% this closes old ones and makes a new one
  ma_figure('draw_brain')
  ma_figure('add_points',ma.search.results.dbpts,3,[1 0 0]);
  if(isfield(ma.search.criteria,'coords'))
    ma_figure('add_points',ma.search.criteria.coords,3,[0 1 0]);
  end
  spm_orthviews('Reposition',coords)
  ma_figure('show_coords',coords)
  
  
 otherwise
  %=======================================================================
  warning(['Illegal Action string: ',action])
end
return;
%=======================================================================

