function[FilterArray]=ImgFilter(ImgSize,BW)

%Filter function
%Arguments ImageSize, Bandwidth of Filter(EVEN)


if rem(BW,1) > 0, 
   disp(sprintf('BW is not an integer and has been rounded to %1.0f',round(BW)))
   BW = round(BW);
end


if BW < 1     % invalid BW
   error('BW must be at least 1');
   
elseif BW < 4 % trivial BW
   Filter = ones(BW);

else
   
   DIAMETER = BW;
   diameter = BW-1;
   RADIUS = DIAMETER/2;
   radius = diameter/2;
   height_45 = round(radius/sqrt(2));
   width = zeros(1,RADIUS);
   semicircle = zeros(DIAMETER,RADIUS);   

   for i  = 1 : height_45
       upward = i - 0.5;
       sine = upward/radius;
       cosine = sqrt(1-sine^2);
       width(i) = ceil(cosine * radius);
   end

   array = width(1:height_45)-height_45;

   for j = max(array):-1:min(array)
       width(height_45 + j) = max(find(array == j));
   end

   if min(width) == 0
      index = find(width == 0);
      width(index) = round(mean([width(index-1) width(index+1)]));
   end

   width = [fliplr(width) width];

   for k  = 1 : DIAMETER
       semicircle(k,1:width(k)) = ones(1,width(k));
   end   

   Filter = [fliplr(semicircle) semicircle];
end

Middle=ImgSize/2;
FilterWidth=BW/2;


FilterStart=Middle-FilterWidth+1;
FilterEnd=Middle+FilterWidth;

FilterArray=zeros(ImgSize,ImgSize);

FilterArray(FilterStart:FilterEnd,FilterStart:FilterEnd)=Filter(1:BW,1:BW);

