function data=blend_sm(navmaskfile, deepsmfile, shallowsmfile, blendsmfile)
% data = blend_sm(navmaskfile, deepsmfile, shallowsmfile, blendsmfile);
% data is [deepsm, shallowsm, blendsm]
%
% Make a new .sm file by using a deep ref layer
% where possible, and a shallow one elsewhere.
%
% example:
% navmaskfile = '35_40_80.nav'
% deepsmfile = '20_40.sm'
% shallowsmfile = '05_10.sm'
% blendsmfile = 'blend.sm'
% eg: data = blend_sm('35_40_80.nav', '20_40.sm', '05_10.sm', 'blend.sm');
%
% EF 2000/09/27
%

[t, u, v] = read_asc(navmaskfile);

goodmask = (u < 1000);

goodmask = goodmask & [1; goodmask(1:(end-1))] & [goodmask(2:end); 1] ...
                    & [1; 1; goodmask(1:(end-2))] & [goodmask(3:end); 1; 1];


deep_weight = bl_filt(goodmask, 2);
shallow_weight = 1 - deep_weight;

deep = tonan(read_asc(deepsmfile));
shallow = tonan(read_asc(shallowsmfile));

% We have to be careful how we fill blend; the simplest
% way, by using the sum of the weighted deep and shallow,
% doesn't work correctly, because the NaNs in the deep come
% through even when their weight is zero.
%

blend = shallow;
ideep = find(deep_weight > 0);

blend(ideep,:) = deep(ideep,:) .* deep_weight(ideep, ones(1,8)) ...
          + shallow(ideep,:) .* shallow_weight(ideep, ones(1,8));
      % We could exclude the time column from this; it doesn't matter.


fid = fopen(blendsmfile, 'w');
ff = '%12.6f  %7.3f %7.3f  %7.3f %7.3f %12.6f %12.6f %4.2f\n';
bigstring = sprintf(ff, blend.');
newstring = strrep(bigstring, ' NaN', '1e38');
fprintf(fid, '%s', newstring);
fclose(fid);

data.deep = deep;
data.shallow = shallow;
data.blend = blend;
data.ideep  = ideep;
