% function to save in sun binary format data for the mit model.
% data format is REAL *4 binary dumps of the arrays.
% data format is such that the matrix is packed with the row
% corresponding to the y-index, and the column to the x-index.
% the first NY rows are from the bottom layer of the model, and
% so on.
%
% x = savemodel(pname, fname, dummy)
%
% input variables
%   pname path name
%   fname file name
%   dummy dummy fortran header and tail, obtained from readmodel
%                                      defaults to global gcm size
%
% required global variables
%   DATA     input data matrix created with readmodel
%   NX       zonal model dimension
%   NY       meridional model dimension
%   NZ       vertical model dimension
%
% modified from tom haine's routine readmodel.m

function array = savemodel(pname, fname, dummy)

global NX NY NZ DATA

if nargin < 3
  dummy=6.780042489789195e-39;       % default for global gcm
end

if nargin < 2
  fname=pname; pname='';
end

[fid, message] = fopen([pname fname],'w'); % open file
if fid < 2, error(message); end
disp('writing to ...'); disp([pname fname]);

% Currently data files have 2 extra entries, at the beginning
% and end, for some obscure reason. so add these two values at
% the beginning and the end of the file.

cnt = fwrite (fid,dummy,'float32'); % write dummy header

ix = find(isnan(DATA));
DATA(ix)=zeros(size(ix));

cnt = fwrite (fid,DATA','float32'); % write data
if cnt ~= NX*NY*NZ
  error('problem writing file: file length is not NX*NY*NZ')
end

DATA(ix) = nan*ones(size(ix));

cnt = fwrite (fid,dummy,'float32'); % write dummy tail
