function saMat = SSDB_correlationsrightanddown_Stan(X,options);
%
%function saMat = SSDB_correlationsrightanddown_Stan(X,options);

 d.PoolRepDist = 1;
 d.PoolSize = 7;
 d.nPoolReps = 20;
 d.imSize = [128 128];
 d.UseLinearVersionOfParallelism = 0;
 if(not(exist('options')))
   options = [];
 end
 options = ResolveMissingOptions(options,d);
 range = generaterange(options);
 nEx = size(X,2);
 for i = 1:nEx
   stim = reshape(X(:,i),options.imSize);
   stim = histeq(stim/256);
   stim4 = FourWayFilter(stim);
   [M,I] = correlationsrightanddown(stim4,range,options.PoolSize,options);
   if(i == 1);
     saMat.X = zeros(length(M(:)),nEx);
   end
   saMat.X(:,i) = M(:);
 end

function [Z,I] = correlationsrightanddown(I,range,patchsize,options);
% function M = correlationsrightanddown(I,range,patchsize);
 numranges = size(range,1);
 M = zeros(size(I,1),size(I,2),numranges);
 s = size(I);
 for iOri = 1:4
   for i = 1:numranges,
    leftout = s(1:2)-range(i,:);
    SHIFTI = [zeros(size(I,1),range(i,2)),[zeros(range(i,1),leftout(2)); I(1:leftout(1),1:leftout(2),iOri)]];
    Do{iOri}(:,:,i) = conv2(ones(patchsize,1),ones(1,patchsize),(I(:,:,iOri)-SHIFTI).^2,'same');
   end
 end
 D = Do{1};
 for i = 2:4
   D = D + Do{i};
 end
 S = sum(D,3) / numranges;
 [m,Idx] = max(-D,[],3);
 m = -m;
 M = max(D,[],3);
 IdxLR = mod(Idx,sqrt(numranges));
 IdxUD = Idx / sqrt(numranges);
 keyboard
 if(options.UseLinearVersionOfParallelism)
   M = sum(M,3);
   Idx = M;
 else
   M = (max(M,[],3)./(min(M,[],3)+.5));
 end
 Mstat = zeros(size(M,1), size(M,2), 4);
 Mstat(:,:,1) = -maxfilter(-M,12);
 Mstat(:,:,2) = sumfilter(M,12)/625;
 Mstat(:,:,3) = modefilter(M,12);
 Mstat(:,:,4) = maxfilter(M,12);
 Z = Mstat(1:8:end, 1:8:end,:);
 
function range = generaterange(options)
range = (ceil((options.PoolSize / 2)+options.PoolRepDist)):options.PoolRepDist:(ceil((options.PoolSize / 2)+options.nPoolReps*options.PoolRepDist));
mrange = ones(length(range),1)*(range(:)');
mrange2 = mrange';
range = [mrange(:), mrange2(:)];

function outim = FourWayFilter(inim)
filters{1} = [ 1  1  1; 0  0  0;-1 -1 -1];
filters{2} = [-1  0  1;-1  0  1;-1  0  1];
filters{3} = [ 0  1  1;-1  0  1;-1 -1  0];
filters{4} = [ 1  1  0; 1  0 -1; 0 -1 -1];
outim = abs(ApplyFilterBank(inim,filters));
