function [spaceimage,varargout] = ImagePos(object,H,V,T,nodal,focalength)
% function [spaceimage,varargout] = ImagePos(object,H,V,T,nodal,focalength)
% Calculates the position of the image of an object, both in space and in retinal coordianates.
% The eye has nodal position stated (nodal is a vector, eg [-I;0;0]) and "object" is an array containing the space coordinates of the object.
% H,V,T are the HH coordinates of the eye

% NB this is in coordinates where X = right-to-left interocular, Y = up, Z = straight-ahead

% Rotation matrix for this retina
RotMatrix = RotationMatrix3(V,[1 0 0]) * RotationMatrix3(H,[0 1 0]) * RotationMatrix3(T,[0 0 1]);
invRotMat = RotationMatrix3(-T,[0 0 1]) * RotationMatrix3(-H,[0 1 0]) * RotationMatrix3(-V,[1 0 0]);

% Normal vector to this retina
norm = RotMatrix * [0;0;1];
% Fovea of this retina
fovea = nodal + RotMatrix * [0;0;-focalength];
% Position of the image on this retina in space:
spaceimage = nodal + (object-nodal) * dot(fovea-nodal,norm) / dot(object-nodal,norm);
if nargout>1
    % Position of the image on this retina in retinal coordinates (x,z)
    retimage = invRotMat * (spaceimage - fovea);
    varargout{1} = [retimage(1) retimage(2)];
end


