function X = SampleCtxFeaturesAtLocations(Template, Locations,PositionImage)
%

[depth, sxy] = GetTemplateSize(Template);
nLocs = length(Locations);
X = zeros(depth, nLocs);
if(nargin > 2)
   X2 = zeros(size(PositionImage,3),nLocs);
end
load CAfilelist_FilterSS
prvidx = -1;
tic
for i = 1:nLocs
%for i = 1:10
   idx = Locations(i).CAidx;
   dopause = 0;
   %if(idx ~= prvidx)
   %  if(prvidx ~= -1), pause, end;
   %  clf
   %  imshow(imread(CAfilelist{idx}.imagename));
   %  prvidx = idx;
   %end  
   if(mod(i,10) == 0);
    fprintf('%d of %d\n',i,nLocs);
    toc
   end
   bbox = Locations(i).bbox;
   bbox_cxy = [bbox(1) + bbox(3)/2, bbox(2) + bbox(4)/2];
   rxy = CoordReal2Relative(bbox_cxy, [960,1280]);
   xy = CoordRelative2Real(rxy,sxy([2,1]),1);
   xy = round(xy);
   if(idx ~= prvidx)
     load(sprintf(Template,idx));%-->LayerImg;
     LayerImg = LayerImg800;
     prvidx = idx;
   end
   %xy_full = CoordRelative2Real(rxy,[960 1280],1)
   %if(Locations(i).y == 1)
   %   rectangle('Position',bbox,'EdgeColor', [1,1,0]);
   %   plot(xy_full(1), xy_full(2), 'y+');
   %   plot(bbox_cxy(1), bbox_cxy(2), 'yo');
   %else
   %   rectangle('Position',bbox,'EdgeColor', [1,0,0]);
   %   plot(xy_full(1), xy_full(2), 'r+');
   %   plot(bbox_cxy(1), bbox_cxy(2), 'ro');
   %end
   r = LayerImg(xy(2), xy(1), :);
   X(:,i) = permute(r,[3,1,2]);
   if(nargin > 2)
      r2 = PositionImage(xy(2), xy(1), :);
      X2(:,i) = permute(r2,[3,1,2]);
   end
end
if(nargin > 2)
  X = [X;X2];
end

function [depth,sxy] = GetTemplateSize(Template);
load(sprintf(Template,1));%-->LayerImg
LayerImg = LayerImg800;
s = size(LayerImg);
depth = (s(3));
sxy = s([2,1]);
