function aout = symmetrize (ain,SG)
% aout = symmetrize (ain,SG)
% 
% This symmetrizes ain by averaging over the group action
% (no normalization by the number of group elements)
%
% SG must be either 229 or 230 (space group number)

sz=(size(ain));
K=(sz(1)-1)/2;
[kx,ky,kz]=ndgrid(-K:K);
flp=(2*K+1:-1:1);

if SG==230
    atmp=ain;
    atmp=atmp + permute(atmp,[2 3 1])+permute(atmp,[3 1 2]);    
    atmp=atmp + (-1).^(-(kx+ky+kz)/2).*permute(atmp,[2 1 3]);
    atmp=atmp + (-1).^(kz).*atmp(flp,:,:);
    atmp=atmp + (-1).^(kx).*atmp(:,flp,:);
    atmp=atmp + (-1).^(ky).*atmp(:,:,flp);
    atmp=atmp + atmp(flp,flp,flp);
    aout=atmp;
elseif SG==229
    atmp = ain;
    atmp = atmp + permute(atmp,[2 3 1])+permute(atmp,[3 1 2]);
    atmp = atmp + permute(atmp,[2 1 3]);
    atmp = atmp + atmp(flp,:,:); 
    atmp = atmp + atmp(:,flp,:); 
    atmp = atmp + atmp(:,:,flp);  
    atmp = atmp + (-1).^(-(kx+ky+kz)).*atmp; 
    aout = atmp;
else
    disp('Error, only Space Groups 229 and 230 coded');
end;

end