
function [data] = fixFaulty( data, badChannel )

%FIXFAULTY	Replace faulty channels in data by average of neighbors.	
%
%	[data] = FIXFAULTY( data, badChannel ) replaces the channel
%	defined by 'badChannel' by the average of the neighbors. 
%	Appropiate averaging rules are used depending of the position 
%	of the channel in an assumed 8x8 array. 



%--- Parameters ---

N_CHANNELS = 64;  % this script was developed for 64 channels


%--- Test the data for correct number of channels ---

if( size( data, 2 ) ~= N_CHANNELS + 1 )
   error( ['The data does not have the expected ', num2str( N_CHANNELS ),' channels.'] )
end


%--- Test that bad channel numbers is legal ---

if( badChannel < 1 | badChannel > N_CHANNELS )
   error( ['Bad channel ', num2str( badChannel ),', is out of valid [1,' , num2str( N_CHANNELS ), '] range.'] )
end


%===== Fix bad channel =====

switch badChannel
   
case 1		% Top left corner
   data(:,2) = data(:,3);
   
case 8		% Top right corner
   data(:,9) = data(:,8);
   
case 57		% Bottom left corner
   data(:,58) = data(:,59);
   
case 64		% Bottom right corner
   data(:,65) = data(:,64);
   
case { 2, 3, 4, 5, 6, 7 }											% Top edge
   data( :, badChannel + 1 ) = ( ...
      data( :, badChannel + 1 - 1 ) + ...
      data( :, badChannel + 1 + 1 ) ) / 2;
   
case { 58, 59, 60, 61, 62, 63 }									% Bottom edge
   data( :, badChannel + 1 ) = ( ...
      data( :, badChannel + 1 - 1 ) + ...
      data( :, badChannel + 1 + 1 ) ) / 2;
   
case { 9, 17, 25, 33, 41, 49 }									% Left edge
   data( :, badChannel + 1 ) = ...
      data( :, badChannel + 1 + 1 );
   
case { 16, 24, 32, 40, 48, 56 }									% Right edge
   data( :, badChannel + 1 ) = ...
      data( :, badChannel + 1 - 1 );
   
otherwise																% Somewhere in middle
   data( :, badChannel + 1 ) = ( ...
      data( :, badChannel + 1 - 1 ) + ...
      data( :, badChannel + 1 + 1 ) ) / 2;
   
end

