function writeSWI(basename,swi)
% writeSWI(basename,swi)
% DHM 24062009
% 0.- Opens a new empty file to write all the data in
% 1.- Types in the new file the name and the date, does not work with this file
% 2.- Types in the command window the file which is being written
% 3.- Types the first line with the four requires values (NPLN ISTRAT ISWIZT
%     NPRN)
% 4.- Types the second line with the four required values (TOESLOPE TIPSLOPE
%     ZETAMIN DELZETA)
% 5.- Types the density values depending of the value given to ISTRAT
% 6.- The interfaces are written by number of plane and, afterwards, by layer
% 7.- Types the value of the effective porosity by layer
% 8.- Types the kind of source at each point by layer
%
% The .swi file is ready to be used

fid=fopen([basename,'.',swi.ext],'wt');                                     
%% 0

%fprintf(fid,'# MATLAB writeSWI %s\n',datestr(now));  % SWI doesn't allow comment lines
fprintf(    '# MATLAB writeSWI %s\n',datestr(now));                         

%% 1

fprintf(fid,'%10d%10d%10d%10d     NPLN ISTRAT ISWIZT NPRN\n',...            
        swi.NPLN,swi.ISTRAT,swi.ISWIZT,swi.NPRN);
    % number of inerfaces, swithc for stratified or interpolated and number
    % of steps between zeta recordings
    
%% 2 

fprintf(fid,'%10f%10f%10f%10f     TOESLOPE TIPSLOPE ZETAMIN DELZETA\n',...  
        swi.TOESLOPE,swi.TIPSLOPE,swi.ZETAMIN,swi.DELZETA);
        % max slop of toecell, of tipcell, minimum zeta before zeta is
        % removed from a cell, delzeta is elevation when it is moved into
        % an adjacent cell
%% 3
% Values for dimensionless density (NPLN+1 if ISTRAT=1, NPLN if ISTRT=0
warray(fid,swi.NU(:)',swi.unit,sprintf('(%dF15.5)',length(swi.NU)),'NU');  

%% 4
% SWI needs all interfaces within all layers. So we intersect each interaces with the top and
% bottom of each layer on the fly and write out the results immediately according to the
% order required by SWI.
for ipln=1:swi.NPLN  % for each surface
    z=swi.ZETA(ipln).values;
    k=1;
    for iLay=1:swi.NLAY % for each layer
        warray(fid,max(min(swi.Z(:,:,k),z(:,:,iLay)),swi.Z(:,:,k+1)),...
            swi.unit,'(10E15.6)',sprintf('Layer(%d), ZETA(%d)',iLay,ipln));
        k=k+1;
        if swi.LAYCBD(iLay), k=k+1; end
    end
end

%% 5
% Types the value of the effective porosity by layer
for iLay=1:swi.NLAY
    warray(fid,swi.SSZ(:,:,iLay)    ,swi.unit,'(12F12.3)',sprintf('SSZ(%d)=effective porosity'    ,iLay)); 
end

%% 6
% Types the kind of source at each point by layer
for iLay=1:swi.NLAY
    warray(fid,swi.ISOURCE(:,:,iLay),swi.unit,'(25I4)',sprintf('ISOURCE(%d)',iLay)); 
end

%% The .swi file is ready to be used
fclose(fid);
