function [lattice, crystal, herm] = gtReadSpaceGroup(sg)
% GTREADSPACEGROUP  Read the spacegroup and give the hermann_mauguin symbol
%     [lattice, crystal, herm] = gtReadSpaceGroup(sg)
%     -----------------------------------------------
%
%     INPUT:
%       sg = spacegroup to look at <double>
%
%     OUTPUT:
%       lattice = lattice system for this spacegroup
%       crystal = crystal system for this spacegroup
%       herm    = hermann-mauguin symbol
%
%     Version 007 25-09-2012 by LNervo
%       Improve speed and use cellfun (back to version 005)
%
%     Version 006 24/09/2012 by AKing
%       Remove the unused hashtable, fix the logic for trigonal
%       spacegroups, return harmann-mauguin symbol
%
%     Version 005 21-09-2012 by LNervo
%       Removed mhashtable
%                 
%     Version 004 20-09-2012 by YGuilhem
%       Now using GT_MATLAB_HOME to determine path to spacegroups.dat
%
%     Version 003 14-05-2012 by LNervo
%       Add lattice system calculation

global GT_MATLAB_HOME

fid = fopen( fullfile(GT_MATLAB_HOME, 'zUtil_Cryst', 'spacegroups.dat' ),'r');
C = textscan(fid,'%s %*d','delimiter','\t','commentstyle','matlab');
fclose(fid);

% clean the cell structure
index = cellfun(@(num) ~isempty(strfind(num, '%')), C{:});
C{:}(index) = [];

% get the hermann-mauguin symbol list, by removing the space at the end of each cell string
hermann = cellfun(@(num) strtrim(num), C{:},'UniformOutput', false);

if between(sg,1,2)
    crystal = 'triclinic'; % a ~= b ~= c;  alpha ~= beta ~= gamma ~= 90
    lattice = 'triclinic';
end

if between(sg,3,15)
    crystal = 'monoclinic'; % a ~= b ~= c;  alpha = gamma = 90 ~= beta
    lattice = 'monoclinic';
end

if between(sg,16,74)
    crystal = 'orthorhombic'; % a ~= b ~= c;  alpha = beta = gamma = 90
    lattice = 'orthorhombic';
end

if between(sg,75,142)
    crystal = 'tetragonal'; % a = b ~= c;  alpha = beta = gamma = 90
    lattice = 'tetragonal';
end

if between(sg,143,167)
    crystal = 'trigonal';

    if ~isempty(strfind(hermann{sg},'P')) % hexagonal lattice 
        % a1 = a2 = a3 ~= c;  alpha = beta = 90; gamma = 120
        lattice = 'hexagonal';
    elseif ~isempty(strfind(hermann{sg},'R')) % rhombohedral lattice
        % a = b = c;  alpha = beta = gamma ~= 90
        lattice = 'rhombohedral';
    end
end

if between(sg,168,194) || sg==663 % snow case
    crystal = 'hexagonal'; % a1 = a2 = a3 ~= c;  alpha = beta = 90; gamma = 120
    lattice = 'hexagonal';
end

if between(sg,195,230)
    crystal = 'cubic'; % a = b = c;  alpha = beta = gamma = 90
    lattice = 'cubic';
end        
        
if nargout == 3
    herm = hermann{sg};
end

end % end of function
