function merged = merge_profiles(instr1, instr2, crit);
%MERGE_PROFILES merge data from two instruments according to the dates
%   both instrument must be structures with a Julian Day field jd 
%
% Inputs: 
%    Required:
%        instr1 struct with field jd
%        instr2 struct with field jd
%    Optional:
%        crit double is a criterion specifying the period of the first
%          instrument in Julian Day, it's used to average the second instr
%
% Outputs:
%   merged struct containing the two instruments variables except wl and scat_angle
%     the data are average arround the first instrument time scale if the
%     instrument are run at different frequencies
%
% Example:
%   iop = merge_profiles(ctd, acs);
%
% Tested with: Matlab R2015a
%
% Author: Nils Haentjens, Ms, University of Maine
% Email: nils.haentjens@maine.edu
% Created: 21th July 2015
% Last update: 22th July 2015
  
% Check input
if nargin > 3
   error('Too many input arguments')
elseif nargin < 1
   error('Not enough input arguments')
end
if nargin < 3;
  crit = 0.000008;
end;


  merged = instr1;
  for j=1:size(instr1.jd,1);
    % Get range to average
%     m = find(instr1.jd(j) == instr2.jd);
%     if j ~= 1;
%       m_b = m_a;
%     else
%       m_b = m(1);
%     end;
%     if j ~= size(instr1.jd,1);
%       m_a = find(instr1.jd(j+1) == instr2.jd);
%       if isempty(m_a)
%         if ~isempty(m); m_a = m(end);
%         else m_a = m_b; m = m_b; end;
%       end;
%     else
%       if ~isempty(m); m_a = m(end);
%       else m_a = m_b; m = m_b; end;
%     end;
%     if size(m_b,1) > 1; m_b = m_b(1); end; 
%     if isempty(m); m = floor(abs((m_a - m_b)/2)); end;
%     foo = floor((m+m_b)/2):floor((m+m_a)/2);
    foo = find(abs(instr1.jd(j) - instr2.jd) < crit);
    
    % Average range for every field
    fields = fieldnames(instr2);
    for f=1:size(fields,1);
      if ~strcmp(fields{f}, 'jd') && ~strcmp(fields{f}, 'wl') && ~strcmp(fields{f}, 'scat_angle');
        if size(foo,1) > 1;
          merged.(fields{f})(j,:) = median(instr2.(fields{f})(foo, :));
        elseif size(foo,1) == 1
          merged.(fields{f})(j,:) = instr2.(fields{f})(foo, :);
        else
          merged.(fields{f})(j,:) = NaN;
        end;
      end;
    end;
  end;

end