function ECoG_View(ChNy,ChNx,EEGData,EEGFrequency,Analyzer,FileName)      %jrn/28.02.2017

%% ECOG View	Create a 2D View of ECoG data (electrode grid)
% ==============================================================
% ChNy: number of rows in ECoG-electrode grid
% ChNx: number of columns in ECoG-electrode grid
% 
% ChN = ChNx * ChNy;  Number of channels in the grid 
% Sensors in grid are horizontally arranged as [1,2,...,ChNx] ; [ChNx+1,
% ChNx+2,...,2*ChNx] ; [...,ChN]   
% 
% This function expects average across segments of FFT Power.
%
% =============================================
% Author: Jose R Naranjo
% Scientific Consultant
% Software and Scientific Support Department
% Brain Products GmbH
% =============================================
%
% this MATLAB script is intended to work only for this application

%% Check grid dimensions 

% Check if grid dimensions are positive integers

if (isnumeric(ChNy) && (ChNy > 0) && (mod(ChNy,1) == 0)) && (isnumeric(ChNx) && (ChNx > 0) && (mod(ChNx,1) == 0))
    ChN = ChNx * ChNy;
else
    disp('ECoG_View(ChNy,ChNx,EEGData,EEGFrequency,Analyzer,FileName)')
    error('ChNy and ChNx shall be possitive integers')
end

% Check if ChN match number of channels in grid
 
if (ChN ~= size(EEGData,2))
    disp('ECoG_View(ChNy,ChNx,EEGData,EEGFrequency,Analyzer,FileName)')
    error(['Grid size (',num2str(ChN),') does not match the number of data channels(',num2str(size(EEGData,2)),')']);
end

%% Define Frequency Bands here!

Freqband(1).name='Delta';   Freqband(1).range=[0.5 3.5];
Freqband(2).name='Theta';   Freqband(2).range=[3.5 7.5];
Freqband(3).name='Alpha';   Freqband(3).range=[7.5 12.5];
Freqband(4).name='Beta';    Freqband(4).range=[12.5 30];

% NOTES:
% 1- The four frequency bands are defined as the Analyzer default bands,
% but can be modified or extended.
% 2- Each band is displayed in a subplot pane. 

%% ECOG VIEW

figure('position', [400, 300, 800, 600])
annotation('textbox', [0 0.9 1 0.1],'String','ECoG Power (\muV^2)','EdgeColor','none','HorizontalAlignment','center','fontweight','bold','fontsize',12);

% for each band
NBands=length(Freqband);

for i=1:NBands
    
    fmin=find(EEGFrequency<=min(Freqband(i).range), 1, 'last' );
    fmax=max(find(EEGFrequency<=max(Freqband(i).range))-1);
    
    meanPOW=mean(EEGData(fmin:fmax,:),1);
    ECOG=reshape(meanPOW,ChNx,ChNy)';
    maxECOG=ceil(max(meanPOW));
    
    subplot(2,2,i);     % adapt the number of panes according to the nunmber of bands
    imagesc(ECOG,[0 maxECOG]);title(Freqband(i).name);colorbar;
    set(gca, 'YTick', 1:ChNy); set(gca, 'xTick', 1:ChNx);
    axis square;
end

%% Save and open ECoG Power figure in Analyzer Export Folder 

fig_name=[Analyzer.ExportFileFolder,'\',FileName,'_ECoG Power.tif'];

saveas(gcf,fig_name);
winopen(fig_name);

end