function varargout = ma_search(varargin)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% this function controls searching and displaying database information

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 'new'
  
  if(isfield(ma,'search'))
    ma = rmfield(ma,'search') %% clear old searches
  end

  ma.search.criteria.author = {[]};
  ma.search.criteria.year = [];
  ma.search.criteria.pmid = [];
    
  ma_figure('clear');
  ma_table('clear');
  
  %----------------------------------------------------------
 case 'papers_gui'
  
  ma_search('new');
  
  F = ma_interactive('GetWin');
  ma_interactive('clear');
  set(F,'Name','AMAT: Search Database')
  sz = get(F,'Position');
  
  ma.search.type = 'papers';
  
  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;
  
  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);
  
  %% set up author fields
  for i=1:3
    uicontrol(F,'Style','Text',...
              'String','Author',...
              'Tag',['Label_author',num2str(i)],...
              'UserData','',...
              'HorizontalAlignment','Right',...
              'Position',[px1,lines(i+1),wdth1,hgt], ...
              'BackgroundColor',Colour);
    
    uicontrol(F,'Style','Edit',...
              'String','',...
              'Tag',['Inp_author',num2str(i)],...
              'UserData','',...
              'HorizontalAlignment','Left',...
              'Position',[px2,lines(i+1),wdth2,hgt], ...
              'BackgroundColor',Colour);
  end
  
  %% year
  uicontrol(F,'Style','Text',...
            'String','Year',...
            'Tag',['Label_year'],...
            'UserData','',...
            'HorizontalAlignment','Right',...
            'Position',[px1,lines(5),wdth1,hgt], ...
            'BackgroundColor',Colour);
        
  uicontrol(F,'Style','Edit',...
            'String','',...
            'Tag',['Inp_year'],...
            'UserData','',...
            'HorizontalAlignment','Left',...
            'Position',[px2,lines(5),wdth2,hgt], ...
            'BackgroundColor',Colour);
        
  %% Results box
  uicontrol(F,'Style','Text',...
            'String','',...
            'Tag',['Label_results'],...
            'UserData','',...
            'HorizontalAlignment','Center',...
            'Position',[10,lines(8),wdth2,hgt], ...
            'FontSize',spm('Fontsize',14),...
            'BackgroundColor',Colour,'Visible','off');
        
  %% search button
  uicontrol(F,'String','Search', ...
            'Tag','Search_button', ...
            'TooltipString','Search the database for papers', ...
            'Position',[px1,lines(end),wdth1,30],...
            'CallBack',['ma_search(''do_search_papers'')'],...
            'ForegroundColor',[0 0 1]);
        
  uicontrol(F,'String','Show Papers', ...
            'Tag','Show_button', ...
            'TooltipString','Search the database for papers', ...
            'Position',[px1+wdth1+10,lines(end),wdth1,30],...
            'CallBack','ma_search(''show_results'')',...  
            'ForegroundColor',[0 0 1],'Enable','off');
  
  uicontrol(F,'String','Refine Search', ...
            'Tag','Refine_button', ...
            'TooltipString','Search the database for papers', ...
            'Position',[px1+20+wdth1*2,lines(end),wdth1,30],...
            'CallBack',['ma_search(''refine_search_papers'')'],...
            'ForegroundColor',[0 0 1],'Enable','off');  
        
  %------------------------------------------------------------------
 case 'refine_search_papers'
  
  F = ma_interactive('GetWin');
  %% find useful info
  set(findobj(F,'Style','Edit'),'Enable','On');
  set(findobj(F,'Tag','Search_button'),'Enable','On');
  set(findobj(F,'Tag','Refine_button'),'Enable','Off');
  set(findobj(F,'Tag','Show_button'),'Enable','Off');
  
  
  %------------------------------------------------------------------
 case 'do_search_papers'
  
  F = ma_interactive('GetWin');
  
  %% find useful info
  for i=1:3
    obj = findobj(F,'Tag',['Inp_author',num2str(i)]);
    if(length(obj)>0)
      ma.search.criteria.author{i} = deblank(get(obj,'String'));
    else
      ma.search.criteria.author{i} = [];
    end
  end
  
  obj = findobj(F,'Tag','Inp_year');
  if(length(obj)>0)
    ma.search.criteria.year = deblank(get(obj,'String'));
  else
    ma.search.criteria.year = [];
  end
  set(findobj(F,'Style','Edit'),'Enable','Off');
  
  %% get index for year
  if(length(ma.search.criteria.year)>0)
    myear = strmatch(ma.search.criteria.year,num2str(cat(1,ma.pubmed.year)),'exact');
  else
    myear = 1:length(ma.pubmed);
  end
    
  %% get index for pmid
  if(length(ma.search.criteria.pmid)>0)
    mpmid = strmatch(ma.search.criteria.pmid,num2str(cat(1,ma.pubmed.id)),'exact');
  else
    mpmid = 1:length(ma.pubmed);
  end
  
  %% get index for authors
  w = 1;
  for j=1:length(ma.search.criteria.author)
    if(length(ma.search.criteria.author{j})>0)
      for i=1:length(ma.pubmed)
        mm = strmatch(lower(ma.search.criteria.author{j}),lower(strvcat(ma.pubmed(i).authors)));
        mauth(i,w) = length(mm);
      end
      w = w+1;
    end
  end
  if(w==1) %% i.e. if no authors specified
    mauthor = 1:length(ma.pubmed);
  else
    mauthor = find(all(mauth>0,2));
  end
  
  ma.search.results.dbid=intersect(myear,mpmid);
  ma.search.results.dbid=intersect(ma.search.results.dbid,mauthor);
  ma.search.results.pmid=cat(1,ma.pubmed(ma.search.results.dbid).id);
  ma.search.results.n = length(ma.search.results.dbid);
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%
  %% show buttons etc
  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;
  
  set(findobj(F,'Tag','Search_button'),'Enable','Off');
  set(findobj(F,'Tag','Refine_button'),'Enable','On');
  set(findobj(F,'Tag','Show_button'),'Enable','On');
  set(findobj(F,'Tag','Label_results'),'Visible','On', ...
                    'String',[num2str(ma.search.results.n),' papers found']);
  
  %------------------------------------------------------------------
 case 'show_results'
  
  if(isfield(ma,'search')~=1)
    disp('There are no results to search')
    return;
  end
  
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %% put results into a nice table
  clear tab
  
  tab.ttl = ['Search Criteria  =   Authors: ',ma.search.criteria.author{1}, ...
             ma.search.criteria.author{3},ma.search.criteria.author{3}, ...
             '  |  Year: ',ma.search.criteria.year];
  
  tab.cols.header = {'Authors','Year','Title','Journal','PMID'};
  tab.cols.width = {30,5,45,15,10};
  for i=1:ma.search.results.n
    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,1} = aut;
    tab.cols.data{i,2} = num2str(ma.pubmed(ind).year);
    tab.cols.data{i,3} = ma.pubmed(ind).title;
    tab.cols.data{i,4} = ma.pubmed(ind).journal;
    tab.cols.data{i,5} = num2str(ma.pubmed(ind).id);
  end
  
  ma_table('show',tab);
  
 otherwise
  %=======================================================================
  warning(['Illegal Action string: ',action])
end
return;
%=======================================================================

