% function bytes = dmapwr(DMAP, gehead, filename)
%
% Shift and scale a DMAP, then write it out to a 16-bit GE 5.x-format
% image file.
%
% DMAP - a double-precision image; values may even be negative.  The
%        image scale and shift constants are stored in the GE header.
%
% gehead - a GE-format header structure, of the kind expected by gewrite.m.
%        If gehead=[], a header will be created, but then you can't specify
%        the image corners, can you?
%
% filename - name of the image file to write
%
function bytes = dmapwrite(DMAP, gehead, filename)

% First, create gehead if it's not defined
%
if ~isstruct(gehead),
  gehead = struct('mri', struct('user', zeros(1,27)));
elseif ~isfield(gehead,'mri'),
  gehead.mri = struct('user', zeros(1,27));
elseif ~isfield(gehead.mri,'user'),
  gehead.mri.user = zeros(1,27);
end
  
% Since pixel values are defined from 0 to 2^15, we shift the data so its lowest value is zero,
% scale it so that it uses the whole range, and store the constants in h.mri.user(1:2).
%
gehead.mri.user(1) = -min(DMAP(:));
gehead.mri.user(2) = 2^15 / (max(DMAP(:)) + gehead.mri.user(1));

% Finally, we write out the image
%
bytes = gewrite(gehead.mri.user(2) * (DMAP + gehead.mri.user(1)), filename, gehead);


