function nwrt = covis_write( file, hdr, data )
% Write Reson R7038 data file.  
% The data matrix is of size [number_samples,number_chans].
% The data matrix is complex with each data column representing the 
% discrete time series of the baseband recieved signal from each element.
% Each data sample is a quadrature pair (I&Q) with 12 bits of resolution.
%
% ----------
% This program is free software distributed in the hope that it will be useful, 
% but WITHOUT ANY WARRANTY. You can redistribute it and/or modify it.
% Any modifications of the original software must be distributed in such a 
% manner as to avoid any confusion with the original work.
% 
% Please acknowledge the use of this software in any publications arising  
% from research that uses it.
% 
% ----------
% Version 1.0 - cjones@apl.washington.edu 06/2010
%
global Verbose

format = 'ieee-le';
fp = fopen(file,'w',format);
if(fp <= 0) 
    error('Error openning f7038 data file');
end

[nsamps, nelems] = size(data);
hdr.nsamps = nsamps;
hdr.neleems = nelems;

reserved1 = 0;
reserved7 = [0,0,0,0,0,0,0];

nwrt = fwrite(fp, hdr.serial_number, 'uint64');
nwrt = nwrt + fwrite(fp, hdr.number, 'uint32');
nwrt = nwrt + fwrite(fp, reserved1, 'uint16'); 
nwrt = nwrt + fwrite(fp, hdr.total_nelems, 'uint16');
nwrt = nwrt + fwrite(fp, hdr.nsamps, 'uint32');
nwrt = nwrt + fwrite(fp, hdr.nelems, 'uint16');
nwrt = nwrt + fwrite(fp, hdr.first_samp, 'uint32');
nwrt = nwrt + fwrite(fp, hdr.last_samp, 'uint32');
nwrt = nwrt + fwrite(fp, hdr.samp_type, 'uint16');
nwrt = nwrt + fwrite(fp, reserved7, 'uint32');

% write element number list
nwrt = nwrt + fwrite(fp, hdr.element, 'uint16');

% reorde
raw = zeros(2*nelems,nsamps);
raw(1:2:end-1,:) = real(data)';
raw(2:2:end,:) = imag(data)';

% write data (I&Q pairs) for all elements 
nwrt = nwrt + fwrite(fp, raw, 'int16');

fclose(fp);

end


