function c = genimg(p,kappa,pts,extrema)
%
% genimg: generate a camera image given a camera model, 3D points and range
% On input:
%     p: persective camera transform (3x4)
% kappa: radial distortion coefficients (6 of them)
%   pts: set of 3D points (4xn)
% extrema: camera image u,v extrema
% On output:
%     c: set of points in the image (3xm)
% Call:
%     c = genimg(p,kappa,pts,extrema)
%

[m,n] = size(pts);
p2 = p*pts;
for pt = 1:n
  p2(:,pt) = p2(:,pt)/p2(3,pt);
end;
c = zeros(3,n);
for i1 = 1:n
  theta = atan2(p2(1,i1),p2(2,i1));
  len = sqrt(p2(1,i1).^2 + p2(2,i1).^2);
  r = zeros(1,6);  
  if len>0
    r(1) = 1/len;
    r(2) = 1/(len*len);
    r(3) = 1/(len*len*len);
  end
  r(4) = len;
  r(5) = len*len;
  r(6) = len*len*len;
  rprime = sum(r*kappa');
  u = rprime*sin(theta);
  v = rprime*cos(theta);
  s = p2(3,i1);
%  if (u>extrema(1)) & (u<extrema(2)) & (v>extrema(3)) & (v<extrema(4))
    c(1,i1) = u;
    c(2,i1) = v;
    c(3,i1) = s;
%  end;
end
