function match_scale(P,T)

% FORMAT match_scale(P,T)
% Matches image intensities to some standard image
% which can help normalisation
% where T is name of template to which to match scalefactors  
% and P is filename(s) for which to match scalefactors

% If you select first the image you want to alter the scaling for, then 
%the image you want to match the first image to, it will alter the scale 
%factor of the first image in a fairly sensible way, and store the old 
%scale factor in the description field of the image header, as text.

% Works only for analyze format images
% Matthew Brett 7/99
  
if nargin < 1
  P = [];
end
if nargin < 2
  T = [];
end

if isempty(P)
  P = spm_get(Inf, 'img', 'Select images for scaling to template');
end

if isempty(T)
  T = spm_get(1, 'img', 'Select template to scale to');
end

PV = spm_vol(P);
TV = spm_vol(T);
Tg = spm_global(TV);
for i=1:size(P, 1)
  scf = Tg / spm_global(PV(i));
  [DIM VOX SCALE TYPE OFFSET ORIGIN DESCRIP] = spm_hread(P(i, :));
  DESCRIP = spm_str_manip(...
      sprintf('%s (old scf %0.8f)', DESCRIP, SCALE),...
      'l80');
  spm_hwrite(P(i,:),DIM,VOX,SCALE*scf,TYPE,OFFSET,ORIGIN,DESCRIP);
end


