function [err, errmsg, Info] = writesourcebrik(source, vol, brikname)
%
%       [err, errmsg, Info] = writesourcebrik(source, vol, brikname)
%
% Write the volume given by vol, which must be part of the source structure,
% as an AFNI brik.  For example, writesourcebrik(source, source.avg.pow, 'moo')

funcname = 'writesourcebrik';

% Reshape it into a 3D matrix.

M = reshape(vol, source.dim);

% Get rid of the NaNs.

M(isnan(M)) = 0.;

% Set AFNI header fields.

Info.DATASET_RANK = [3 1];
Info.DATASET_DIMENSIONS = source.dim;
Info.TYPESTRING = '3DIM_HEAD_FUNC';
Info.SCENE_DATA = [0 0 1];
Info.ORIENT_SPECIFIC = [2 0 4]; % PRI

% Convert to mm.  The X axis needs to be flipped for some reason?
% Should perhaps check source.vol.unit?

mm = 10.;
Info.ORIGIN = [source.xgrid(1) source.ygrid(1) source.zgrid(1)];
Info.ORIGIN = Info.ORIGIN .* [-mm mm mm];
Info.DELTA = [source.xgrid(2) source.ygrid(2) source.zgrid(2)] - ...
	     [source.xgrid(1) source.ygrid(1) source.zgrid(1)];
Info.DELTA = Info.DELTA .* [-mm mm mm];

Info.BRICK_TYPES = 3;
Info.BRICK_FLOAT_FACS = 1.;
Info.BRICK_STATS = [min(vol) max(vol)];

% Write the brik.

Opt.Prefix = brikname;
Opt.verbose = 0;
Opt.Slices = [];

[err, errmsg, Info] = WriteBrik(M, Info, Opt);
