function blend_sm(navmaskfile, deepreffile, shallowreffile, blendreffile)
% function blend_sm(navmaskfile, deepreffile, shallowreffile, blendreffile)
%
% Make a new .sm file by using a deep ref layer
% where possible, and a shallow one elsewhere.
%
% EF 2000/09/27
%

% navmaskfile = '35_40_80.nav'
% deepreffile = '20_40.sm'
% shallowreffile = '05_10.sm'
% blendreffile = 'blend.sm'

[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(deepreffile));
shallow = tonan(read_asc(shallowreffile));

% 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(blendreffile, '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);

