function [Mil,varargout] = form2face(f,varargin)
%FORM2FACE gives miller indices of all faces of a form.
%   [Mil]=FORM2FACE(f,pg,hf) gives 
%
%   [Mil,mult]=FORM2FACE(f,pg,hf) gives 
%
%   [Mil,mult,ftype]=FORM2FACE(f,pg,hf) gives 
%
%   [Mil,mult,ftype,h]=FORM2FACE(f,pg,hf) gives 
%
%
%   References:
%   [1] C. Borchert, On Multidimensional Population Balance Modeling for
%   Faceted Crystals, Diploma Thesis, The University of Magdeburg, 2007.
%   FORM2FACE is part of the ... package.
%
%   $Revision: 1.0 $  $Date: 2009/07/13 $

% The following licence is added according to the email stored as
%   agreement.eml.

% Christian Borchert, Copyright 2009, 
%   Max Planck Institute for Dynamics of Complex Technical Systems, 
%   Magdeburg, Germany
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU General Public License as published by the 
%   Free Software Foundation, either version 3 of the License, or (at your 
%   option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   General Public License for more details.
%
% You should have received a copy of the GNU General Public License along 
%   with this program.  If not, see <http://www.gnu.org/licenses/>.

if nargin<4
    if nargin==3;
        pg = varargin{1};
        hf = varargin{2};
    elseif nargin==2
        if nargout==4
            error('specify hf to obtain h');
        else
            hf = zeros(1,size(f,1));
        end
        pg = varargin{1};
    end
    if nargin<2
        error('MATLAB:form2face:NotEnoughInputs',...
              'Not enough input arguments. FORM2FACE.');
    end
else
    error('MATLAB:form2face:TooManyInputs',...
          'Too many input arguments. FORM2FACE.');        
end


P=pointgroup(pg,'HM');

Mil = [];
h = [];
ftype = [];

Mil_add = f*cell2mat(P.M_inv);
for j=1:size(f,1)
    Mil_add_j = unique(reshape(Mil_add(j,:),3,numel(Mil_add(j,:))/3)','rows');
    [trash,I]=sortrows([sum(Mil_add_j,2),Mil_add_j],[1 2 3 4]);
    Mil = [Mil; Mil_add_j(I,:)];
    mult(j) = size(Mil_add_j,1);
    h = [h, hf(j)*ones(1,mult(j))];
    ftype = [ftype, j*ones(1,mult(j))];
end

varargout(1) = {mult};
varargout(2) = {ftype};
varargout(3) = {h};