function cp_normalize(FeatureFN,N_features,ImageId,MethodId,NonlinId,SmoothId,NormId)
% CP_NORMALIZE  Normalize the features (using global normalization factors)
%	cp_normalize(FeatureFN,N_features,...
%	  ImageId,MethodId,NonlinId,SmoothId,NormId)
%	One global normalization factor for each feature class

TmpFN=tempnam;

if    idcmp(MethodId,'Eigen') ...
    | idcmp(MethodId,'Fisher') ...
    | idcmp(MethodId,'Singh') ...
    | idcmp(MethodId,'Unser') ...
    | idcmp(MethodId,'Dunn') ...
    | idcmp(MethodId,'Weldon') ...
    | idcmp(MethodId,'Bovik') ...
    | idcmp(MethodId,'LinPred') ...
    | idcmp(MethodId,'NNFilt')
  fprintf(1,':-|\n');
  catframe([],FeatureFN,[],'Final');
  return;
end


fprintf(1,':-(');
% Compute identifier string
N_id=4*40; % 				Max identifier string, 4 substr.
N_nf=100; % 				Max number of nomalization factors
Id=[zeropad(MethodId,1,N_id/4) zeropad(NonlinId,1,N_id/4) ...
    zeropad(SmoothId,1,N_id/4) zeropad(NormId  ,1,N_id/4)];

% Set initial values
DBIds=[];
DBNormFacts=[];
NormFacts=[];

% Load database of normalization factors (variables: Ids and NormFacts)
if exist('NormFacts.mat')==2
  load NormFacts.mat
  for k=1:size(DBIds,1)
    if strcmp(DBIds(k,:),Id)
      NormFacts=DBNormFacts(k,:);
    end
  end
end

% If NormFacts has not yet been determined, compute it based on Nat-5c
if isempty(NormFacts) | isempty(trimend(NormFacts))
  xx=cp_image('Nat-5c');
  cp_feature(xx,TmpFN,ImageId,MethodId,NonlinId,SmoothId,NormId,1);
  for n=0:N_features-1
    v_i=hipsread(sprintf('%s_%03d',TmpFN,n));
    NormFacts(1,n+1)=std(v_i(:));
    eval(sprintf('!rm -f %s_%03d',TmpFN,n));
  end
  DBIds=[DBIds;Id];
  DBNormFacts=[zeropad(DBNormFacts,size(DBNormFacts,1),N_nf)
    zeropad(NormFacts,1,N_nf)];
  save NormFacts.mat DBIds DBNormFacts
end

% Normalize and store
NormFacts=trimend(NormFacts);
for n=0:N_features-1
  eval(sprintf('!scale -l %f < %s_%03d > %s_%03d; mv %s_%03d %s_%03d',...
    1/NormFacts(n+1),FeatureFN,n,TmpFN,n,TmpFN,n,FeatureFN,n));
end
catframe([],FeatureFN,[],'Final');
fprintf(1,'\b)\n');

% Clean up
eval(sprintf('!rm -f %s',TmpFN));

  
