function fnames = xb_swan_write(fname, sp2, varargin)
%XB_SWAN_WRITE  Write SWAN file from struct
%
%   Write one or more SWAN files from struct. In case of multiple files,
%   the filename is extended with an indexing number.
%
%   Syntax:
%   fnames = xb_swan_write(fname, sp2, varargin)
%
%   Input:
%   fname     = Path to output file
%   sp2       = SWAN struct to write
%   varargin  = none
%
%   Output:
%   fnames    = Path(s) to output file(s)
%
%   Example
%   fnames = xb_swan_write('waves.sp2', sp2)
%
%   See also xb_swan_read, xb_swan_struct

%% Copyright notice
%   --------------------------------------------------------------------
%   Copyright (C) 2011 Deltares
%       Bas Hoonhout
%
%       bas.hoonhout@deltares.nl	
%
%       Rotterdamseweg 185
%       2629HD Delft
%
%   This library is free software: you can redistribute it and/or
%   modify it under the terms of the GNU Lesser General Public
%   License as published by the Free Software Foundation, either
%   version 2.1 of the License, or (at your option) any later version.
%
%   This library is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%   Lesser General Public License for more details.
%
%   You should have received a copy of the GNU Lesser General Public
%   License along with this library. If not, see <http://www.gnu.org/licenses/>.
%   --------------------------------------------------------------------

% This tool is part of <a href="http://OpenEarth.nl">OpenEarthTools</a>.
% OpenEarthTools is an online collaboration to share and manage data and 
% programming tools in an open source, version controlled environment.
% Sign up to recieve regular updates of this function, and to contribute 
% your own tools.

%% Version <http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html>
% Created: 14 Feb 2011
% Created with Matlab version: 7.9.0.529 (R2009b)

% $Id$
% $Date$
% $Author$
% $Revision$
% $HeadURL$
% $Keywords: $

%% read options

OPT = struct( ...
);

OPT = setproperty(OPT, varargin{:});

%% write sp2 file

fnames = '';

for n = 1:length(sp2)
    
    % create spectrum file
    if length(sp2) > 1
        [fd fn fe] = fileparts(fname);
        fnames{n} = sprintf('%s%03d%s', fullfile(fd, fn), n, fe);
        fid = fopen(fnames{n}, 'w');
    else
        fnames = fname;
        fid = fopen(fnames,'w');
    end

    if ~isfield(sp2(n),'run'); sp2(n).run = 1; end;

    % write swan header
    fprintf(fid,'SWAN%4.0d\r\n',sp2(n).run);

    fprintf(fid,'$   Generated by matlab function WRITE_SP2\r\n');
    fprintf(fid,'$   Project:                 ;  run number:     \r\n');

    % write time header, if necessary
    if sp2(n).has_time
        fprintf(fid,'TIME\r\n');
        fprintf(fid,'%6.0d\r\n',1);
    end

    % write location header
    switch lower(sp2(n).location.type)
        case 'xy'
            fprintf(fid,'LOCATIONS\r\n');
        case 'lonlat'
            fprintf(fid,'LONLAT\r\n');
    end

    fprintf(fid,'%6.0d\r\n',sp2(n).location.nr);

    for i = 1:size(sp2(n).location.data,1)
        fprintf(fid,'%12.6f%12.6f\r\n',sp2(n).location.data(i,1),sp2(n).location.data(i,2));
    end

    % write frequency header
    switch lower(sp2(n).frequency.type)
        case 'absolute'
            fprintf(fid,'AFREQ\r\n');
        case 'relative'
            fprintf(fid,'RFREQ\r\n');
    end

    fprintf(fid,'%6.0d\r\n',sp2(n).frequency.nr);

    for i = 1:size(sp2(n).frequency.data,1)
        fprintf(fid,'%10.4f\r\n',sp2(n).frequency.data(i));
    end

    % write direction header
    switch lower(sp2(n).direction.type)
        case 'nautical'
            fprintf(fid,'NDIR\r\n');
        case 'cartesian'
            fprintf(fid,'CDIR\r\n');
    end

    fprintf(fid,'%6.0d\r\n',sp2(n).direction.nr);

    for i = 1:size(sp2(n).direction.data,1)
        fprintf(fid,'%10.4f\r\n',sp2(n).direction.data(i));
    end

    % write spectrum header
    fprintf(fid,'QUANT\r\n');
    fprintf(fid,'%6.0d\r\n',sp2(n).spectrum.nr);
    fprintf(fid,'%s\r\n',sp2(n).spectrum.type);
    fprintf(fid,'%s\r\n',sp2(n).spectrum.unit);
    fprintf(fid,'%14e\r\n',sp2(n).spectrum.exception);

    % write spectra for each timestep and point
    if ~isempty(sp2(n).spectrum.data)
        for i = 1:size(sp2(n).spectrum.data,1)

            % write timestep
            if sp2(n).has_time
                fprintf(fid,'%s\r\n',datestr(sp2(n).time.data(i),'yyyymmdd.HHMMSS'));
            end

            for j = 1:size(sp2(n).spectrum.data,2)
                % crop data to relevant part
                data = reshape(sp2(n).spectrum.data(i,j,:,:),size(sp2(n).spectrum.data,3),size(sp2(n).spectrum.data,4));

                % write NODATA, if no data is available
                if all(all(isnan(data))) || isempty(data)
                    fprintf(fid,'NODATA\r\n');
                    continue;
                end

                % determine multiplication factor
                if ~isfield(sp2(n).spectrum,'factor') || isempty(sp2(n).spectrum.factor) || ...
                        sp2(n).spectrum.factor(i,j) == 1 || sp2(n).spectrum.factor(i,j) == 0
                    factor = max(max(data))/990099;
                else
                    factor = sp2(n).spectrum.factor(i,j);
                end

                data = data./factor;

                % write multiplication factor
                fprintf(fid,'FACTOR\r\n');
                fprintf(fid,'%20.8e\r\n',factor);

                % write data
                for k = 1:size(data,1)
                    fprintf(fid,[repmat('%7d',1,size(data,2)) '\r\n'],round(data(k,:)));
                end
            end
        end
    else
        fprintf(fid,'NODATA\r\n');
    end

    fclose(fid);
end