function [chiimg w]=chiimg(img,ip,mk,w,range)

if(~exist('range','var'))
  range='full';
end
if(~exist('mk','var') || isempty(mk))
  mk=ip;
end
if(~exist('w','var') || isempty(w))
  bb1=ones(size(img));                          % Blank image;
  w=(conv2(bb1,ip.^2.*mk,range));         % Weighting factor
end
if(~exist('range','var'))
  range='full';
end

ip=ip(end:-1:1,end:-1:1);
mk=mk(end:-1:1,end:-1:1);

chiimg=1+(-2*conv2(img,ip.*mk,range)+conv2(img.^2,mk,range))./w;    % best fit ignoring overlap  
