function [face_norms, flags]=calc_mesh_norm(vertex,face,options)

% plot_mesh - plot a 3D mesh.
%
%   plot_mesh(vertex,face, options);
%
%   'options' is a structure that may contains:
%       - 'normal' : a (nvertx x 3) array specifying the normals at each vertex.
%       - 'edge_color' : a float specifying the color of the edges.
%       - 'face_color' : a float specifying the color of the faces.
%       - 'face_vertex_color' : a color per vertex or face.
%       - 'vertex'
%
%   See also: mesh_previewer.
%
%   Copyright (c) 2004 Gabriel Peyr?

if nargin<3
   if size(vertex,1)==3,
      options.center = mean(vertex');
   else
      options.center = mean(vertex);
   end
   options.check_norm = 1;
end
if isfield(options,'check_norm')==0,
    options.check_norm = 1;
end
if isfield(options,'center')==0,
   if size(vertex,1)==3,
      options.center = mean(vertex');
   else
      options.center = mean(vertex);
   end

end
% can flip to accept data in correct ordering
if (size(vertex,1)==3 | size(vertex,1)==2) & size(vertex,2)~=3
    vertex = vertex';
end
if size(face,1)==3 & size(face,2)~=3
    face = face';
end

if size(face,2)~=3 | (size(vertex,2)~=3 & size(vertex,2)~=2)
    error('face or vertex does not have correct format.');
end
%axis ij;
hold on;
face_norms=zeros([size(face,1) size(vertex,2)]);
flags=(1:1:size(face,1))*0;
for i=1:size(face,1),
   xx=vertex(face(i,2),:)-vertex(face(i,1),:);
   xx1=vertex(face(i,3),:)-vertex(face(i,1),:);
   face_norms(i,:)=cross(xx,xx1);
   face_norms(i,:)=face_norms(i,:)/norm(face_norms(i,:));
   displace=0-dot(face_norms(i,:),vertex(face(i,1),:));
   if dot(face_norms(i,:),options.center)+displace < 0,
      flags(i)=1;
   else
      flags(i)=-1;
      end
   if flags(i) < 0,
      if options.check_norm==1,
         face_norms(i,:)=0-face_norms(i,:);
      end
   end
end

return
