%SHMOVIE	Show 2D array movie of data as it evolves trough time.
%	shMovie( filename, resolution [20], frameStep [10, that is 1 frame/ms] )
%

function shMovie( data, resolution, frameStep )


%--- Parameters ---

if( nargin <= 2 ), frameStep = 10;, end
if( nargin == 1 ), resolution= 20;, end


dataCSD = data;


%--- Adjust color scale ---

dataMax =  max( max( data(:, 2:65) ) );
dataMin =  min( min( data(:, 2:65) ) );
saturation = 0.3; % values above this fraction of the color scale are saturated
colorMax =  saturation * max( abs(dataMax), abs(dataMin) );
disp( ['[shMovieV] Automatically adjusted max. color scale value: ', num2str( colorMax, 3 )] )

maxV = colorMax;

%maxV = 0.025; % hand picked color limit


%--- Seed graph ---

steps = 8 * resolution;
[XI, YI] = meshgrid(1:(8-1)/(steps-1):8,1:(8-1)/(steps-1):8);
[X, Y] = meshgrid(1:8,1:8);

figure(1)
subplot(111)
imageSize = [size( XI, 1 ) + 7, size( XI, 2 )];
h1 = image( rand( imageSize(1), imageSize(2) ) );
%hTitle1 = title('*');
%set( hTitle1, 'EraseMode', 'xor' )
set( h1, 'EraseMode', 'none' )
colormap( [obMap; [1 1 1]] )
%colormap( [ycMap; [1 1 1]] )
brighten( 0.3 )
axis('image')
axis('off')


%--- Animation loop ---

gridX = (meshgrid( 1:8 ) - 1) * (8 / 7) / 8 * (resolution*8 - 1) + 1;
gridX = round(gridX);
gridY = gridX';

sliceX = [1 46];   %These lines can supply an anatomical sketch, 
sliceY = [1 46];    %now placed in upper left and 3rd diagonal point.

for frame = 1:frameStep:size(data, 1)
   
   %--- interpolate array ---
   
   Z1 =  toMatrix( data(frame, 2:65), 8 );
   ZI1 = interp2( X, Y, Z1, XI, YI, 'spline' );    
   
      
   %--- Update data in plot ---
   
   ZI1 = 255 * ( 0.5 * ZI1 / maxV + 0.5);
   %ZI1 = trunc( ZI1, 1, 255 );
   ZI1(ZI1>255)=255; ZI1(ZI1<1)=1;
   
   %--- Electrode positions ---
   
   ZI1(gridX(1:64), gridY(1:64)) = 256;
   
   %--- Slice layout --
   
   ZI1(sliceX(1),sliceY(1))=256;
   ZI1(sliceX(2),sliceY(2))=256;
   
   %--- Time stamp ---
   
   %ZI1 = [ZI1; timeImg( data(frame, 1), 130, 256, imageSize(2) )];
   
   
   %--- Display image ---
   
   set( h1, 'cdata', ZI1 )
%   set( hTitle1, 'String', ['Potential. Time: ', num2str( data(frame, 1), '%04.1f' ), ' [ms]'] );
   drawnow
   
   
   
end

