function [] = results_update(Data,Results);
%RESULTS_UPDATE - Update of display the source parameters and residuals while RAP-MUSIC or LS is running.
% function [] = results_update(Data,Results);
%Update of display the source parameters and residuals while RAP-MUSIC or LS is running.
%Associated with the GUI: RESULTS_UPDATE_GUI
% Must have the following fields in the BrainStorm structures Data and Results:
% Data: Structure containing information of the data
% Data.F: Spatio-temporal matrix of the original data
% Data.Time: Vector containing the time instants within the current time window of analysis for source localization    
% Results: Results structure containing the source parameters
% Results.IndepTopo
% Results.TimeSeries
% Results.Time
% Results.SourceOrder
% Results.Comment;
% Results.Subject.Name;
% Results.Study.Name;
% Results.SourceCorrelation
% Results.SourceLoc
%
% Please refer to the BrainStorm ParameterDescription file for details regarding the structure of arguments passed to this function

%<autobegin> ---------------------- 26-May-2004 11:34:16 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Visualization
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\fronorm.m
%
% Figure Files opened by this function:
%   'results_update_gui.fig'
%
%   Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
%   <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure results_update_gui.fig
%   text::Axes1Text1 "" uses ButtonDownFcn for ctlpanel SelectMoveResize
%   text::Axes1Text2 "" uses ButtonDownFcn for ctlpanel SelectMoveResize
%   text::Axes1Text3 "" uses ButtonDownFcn for ctlpanel SelectMoveResize
%   text::Axes1Text4 "" uses ButtonDownFcn for ctlpanel SelectMoveResize
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FilePost')                                                    
%   uimenu::                       "" uses Callback for
%     figure                                                                          
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FileOpen')                                                    
%   uimenu::                       "" uses Callback for
%     close(gcbf)                                                                     
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FileExport')                                                  
%   uimenu::                       "" uses Callback for
%     propedit(gcbf)                                                                  
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FilePreferences')                                             
%   uimenu::                       "" uses Callback for
%     pagesetupdlg(gcbf)                                                              
%   uimenu::                       "" uses Callback for
%     filemenufcn(gcbf,'FilePrintSetup')                                              
%   uimenu::                       "" uses Callback for
%     printpreview(gcbf)                                                              
%   uimenu::                       "" uses Callback for
%     printdlg                                                                        
%   uimenu::                       "" uses Callback for
%     editmenufcn(gcbf,'EditCopyFigure')                                              
%   uimenu::                       "" uses Callback for
%     editmenufcn(gcbf,'EditCopyOptions')                                             
%   uimenu::                       "" uses Callback for
%     domymenu('menubar','toggletoolbar',gcbf)                                        
%   uimenu::                       "" uses Callback for
%     %<noop>                                                                         
%   uimenu::                       "" uses Callback for
%     domymenu menubar addaxes                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar addarrow                                                       
%   uimenu::                       "" uses Callback for
%     domymenu menubar addline                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar addtext                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar zoomin                                                         
%   uimenu::                       "" uses Callback for
%     domymenu menubar zoomout                                                        
%   uimenu::                       "" uses Callback for
%     domymenu menubar rotate3d                                                       
%   uimenu::                       "" uses Callback for
%     winmenu(gcbo)                                                                   
%   uimenu::                       "" uses Callback for
%     %<noop>                                                                         
%   uimenu::                       "" uses Callback for
%     helpview([docroot '/mapfiles/plotedit.map'], 'plot_editor','PlotEditCollection')
%   uimenu::                       "" uses Callback for
%     web([docroot '/techdoc/umg/umg.html']);                                         
%   uimenu::                       "" uses Callback for
%     helpwin                                                                         
%   uimenu::                       "" uses Callback for
%     helpwin helpinfo                                                                
%   uimenu::                       "" uses Callback for
%     helpdesk                                                                        
%   uimenu::                       "" uses Callback for
%     demo                                                                            
%   uimenu::                       "" uses Callback for
%     uimenufcn(gcbf,'HelpAbout')                                                     
%   uimenu::                       "" uses Callback for
%     doc subscribe                                                                   
%   uimenu::figMenuEdit "" uses Callback for
%     editmenufcn(gcbf,'EditPost')                                                    
%   uimenu::figMenuEditClear "" uses Callback for
%     uimenufcn(gcbf,'EditClear')                                                     
%   uimenu::figMenuEditCopy "" uses Callback for
%     uimenufcn(gcbf,'EditCopy')                                                      
%   uimenu::figMenuEditCut "" uses Callback for
%     uimenufcn(gcbf,'EditCut')                                                       
%   uimenu::figMenuEditPaste "" uses Callback for
%     uimenufcn(gcbf,'EditPaste')                                                     
%   uimenu::figMenuEditSelectAll "" uses Callback for
%     uimenufcn(gcbf,'EditSelectAll')                                                 
%   uimenu::figMenuEditUndo "" uses Callback for
%     editmenufcn(gcbf,'EditUndo')                                                    
%   uimenu::figMenuFileSave "" uses Callback for
%     filemenufcn(gcbf,'FileSave')                                                    
%   uimenu::figMenuFileSaveAs "" uses Callback for
%     filemenufcn(gcbf,'FileSaveAs')                                                  
%   uimenu::figMenuTools "" uses Callback for
%     domymenu('menubar','updatetools',gcbf)                                          
%   uimenu::figMenuToolsAxesProps "" uses Callback for
%     domymenu menubar axesprop                                                       
%   uimenu::figMenuToolsLineProps "" uses Callback for
%     domymenu menubar lineprop                                                       
%   uimenu::figMenuToolsLockAxes "" uses Callback for
%     domymenu menubar lockaxes                                                       
%   uimenu::figMenuToolsPlotedit "" uses Callback for
%     plotedit(gcbf)                                                                  
%   uimenu::figMenuToolsShowLegend "" uses Callback for
%     domymenu menubar legend                                                         
%   uimenu::figMenuToolsTextProps "" uses Callback for
%     domymenu menubar textprop                                                       
%   uitoggletool::ScribeSelectToolBtn "" uses DeleteFcn for plotedit(gcbf,'off')
%
% At Check-in: $Author: Mosher $  $Revision: 14 $  $Date: 5/26/04 10:02a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 26-May-2004 11:34:16 -----------------------

% Sylvain Baillet, Ph.D.
% John C. Mosher, Ph.D.

% History -----------------------------------------------------------------
% 2/22/00 JCM     altering minor window features
% 2/23/00 JCM     adding time series display as well
% JCM 3/20/00     added orientation string, made sure was compatible with least-squares
% JCM 3/20/00     Each run now gets its own update window. Makes for easier comparison between
%                 solutions. Tag is based on output filename
% JCM 3/21/00     Switchable phrase between "correlation" and "variance explained", dependent on
%                 Results.Function. Also set listbox to black text on white background in the 
%                 program code, so that hardcopy looks better.
% JCM 08-Sep-2003 Commenting
% -------------------------------------------------------------------------

TAG = sprintf('RESULTS_UPDATE: %s',Results.GUI.Results); % filename being written

RESULTS_UPDATE_GUI = findobj(0,'Tag',TAG);
if isempty(RESULTS_UPDATE_GUI), % this tag has not yet been created
   open('results_update_gui.fig');
   RESULTS_UPDATE_GUI = findobj(0,'Tag','RESULTS_UPDATE'); % preset tag on generic window
   set(RESULTS_UPDATE_GUI,'Tag',TAG); % set tag to results name
end

figure(RESULTS_UPDATE_GUI)
set(gcf,'Name',sprintf('Intermediate Results %s %s %s',...
   Results.Subject.Name, Results.Study.Name, Results.GUI.Results));

% for plot niceties, lets flip polarity of time series as needed.
FLIP = zeros(1,length(Results.SourceOrientation)); % should be one per topo column
for i=  1:length(FLIP),
   [mx,mxi] = max(abs(Results.SourceOrientation{i}(:)));
   FLIP(i) = sign(Results.SourceOrientation{i}(mxi));
end

Results.IndepTopo = Results.IndepTopo .* FLIP(ones(1,size(Results.IndepTopo,1)),:);
Results.TimeSeries = Results.TimeSeries .* FLIP(ones(1,size(Results.TimeSeries,1)),:);

% Plotting Solution Time Series
TIMESERIES = findobj(RESULTS_UPDATE_GUI,'Tag','TIMESERIES');
axes(TIMESERIES)
plot(Data.Time(Results.Time),Results.TimeSeries);
set(gca,'YGrid','on');
title('Solution Time Series Scaled by Model Contribution','color','w')
set(gca,'Tag','TIMESERIES','Xcolor','w','Ycolor','w','color','k')
axis tight;
% give it a legend
legstr = cell(1,size(Results.TimeSeries,2)); % number of solutions
for i = 1:length(legstr),
   legstr{i} = sprintf('Source %.0f',i);
end
hleg = legend(legstr,0);
hstr= findobj(hleg,'Type','Text'); % find the text strings
set(hstr,'color','w');

% Plotting Modelled Sensor Time Series
MODEL = findobj(RESULTS_UPDATE_GUI,'Tag','MODEL');
model = Results.IndepTopo*Results.TimeSeries';
axes(MODEL)
plot(Data.Time(Results.Time),model');
set(gca,'YGrid','on');
set(gca,'Tag','MODEL','Xcolor','w','Ycolor','w','color','k')
axis tight;
title(sprintf('Modeled Data: %.1f%% Variance Explained',...
   (fronorm(model)/fronorm(Data.F))^2*100),'color','w');
Vaxis = axis; % so what are the axis settings?

% Plotting Residuals 
RESIDUALS = findobj(RESULTS_UPDATE_GUI,'Tag','RESIDUALS');
res = Data.F - model;
axes(RESIDUALS)
plot(Data.Time(Results.Time),res');
set(gca,'YGrid','on');
set(gca,'Tag','RESIDUALS','Xcolor','w','Ycolor','w','Ylim',get(MODEL,'Ylim'),'color','k')
axis(Vaxis); % set to the same as the Model data
% RMS = 100*mean(norlig(res))/mean(norlig(model)); % this is not a power. -JCM
MS = 100 * (res(:)'*res(:)) / fronorm(Data.F)^2; % percent var not explained
RESIDUALS_STR = findobj(0,'Tag','RESIDUALS_STR');
title(sprintf('Residuals: %.1f%% Variance Unexplained',MS),'color','w');

%Update the listbox display
SOURCE_PARAM =  findobj(RESULTS_UPDATE_GUI,'Tag','SOURCE_PARAM');
% since there is no "inverthardcopy" for list boxes, make black text
%  on white background, for better hardcopies
set(SOURCE_PARAM,'BackgroundColor','w');
set(SOURCE_PARAM,'ForegroundColor','k');
String{1} = Results.Comment;
String{2} = Results.Subject.Name;
String{3} = Results.Study.Name;
String{end+1} = ' ';

for k = 1:size(Results.IndepTopo,2)
   String{end+1} = ['Source ',int2str(k),' :'];
   switch(Results.SourceOrder(k))
   case -1
      Type = 'Current Dipole';
   case 0
      Type = 'Magnetic Dipole';
   case 1
      Type = '1st-Order Multipole';
   case 2
      Type = 'Dipole Synchronous Pair';
   case 3
      Type = 'Magnetic Dipole Synchronous Pair';
   case 4
      Type = '1st-Order Multipole Synchronous Pair';
   otherwise
      Type = 'Unknown??';
   end
   String{end+1} = Type;
   if ~isempty(Results.SourceCorrelation(k))
      switch lower(deblank(Results.Function))
      case 'least_squares_fit'
         String{end+1} = sprintf('%.1f%% variance explained',...
            100*Results.SourceCorrelation(k));
      case 'rapmusic_gui'         
         String{end+1} = sprintf('%.1f%% correlation',...
            100*Results.SourceCorrelation(k));
      otherwise
         String{end+1} = sprintf('%.1f%% unknown units',...
            100*Results.SourceCorrelation(k));         
      end
   end
   
   Locs = Results.SourceLoc{k};
   Orients = Results.SourceOrientation{k};
   Orients = reshape(Orients,length(Orients)/size(Locs,2),size(Locs,2)); % one column per source
   for j = 1:size(Locs,2)
      String{end+1} = ['Location: ',num2str(Locs(:,j)'*1000,'%6.1f %6.1f %6.1f')];
      String{end+1} = ['Orientation: ',num2str(FLIP(k)*Orients(:,j)','%5.2f %5.2f %5.2f')];
   end
   
      String{end+1} = ' ';
end

set(SOURCE_PARAM,'String',String)
