%% bin_missionNST.m : called from process_auvmissionNST.m
function [P1,P2,T1,T2,C1,C2,S1,S2,D1,D2,OBSbin,O2,FLOW1,FLOW2,depthnav,depth1,depth2,pitch,roll,yaw,Xpos,Ypos, N2, N2Qual, N2Depth] = ...
    bin_mission2NST(p1,p2,t1,t2,c1,c2,s1,s2,d1,d2,obs,o2,flw1,flw2,dpth1,dpth2, ...
           ndepth,npitch,nroll,nyaw,nposx,nposy,...
	   n2, n2qual, n2depth, n2time,...
           mtime,c1time,c2time,navtime);

buf=median(diff(mtime))/2;

for N=1:length(mtime)
 %%------
 %% CTD1
 %%------
 idx = find(c1time >= mtime(N)-buf & c1time < mtime(N)+buf);
if (isempty(idx) == 0)
  P1(N,1)=median(p1(idx));
  T1(N,1)=median(t1(idx));
  C1(N,1)=median(c1(idx));
  S1(N,1)=median(s1(idx));
  D1(N,1)=median(d1(idx));
  OBSbin(N,1)=median(obs(idx));
  O2(N,1)=median(o2(idx));
  FLOW1(N,1)=median(flw1(idx));
  depth1(N,1)=median(dpth1(idx));
end
  
 %%------
 %% CTD2
 %%------
 idxi = find(c2time >= mtime(N)-buf & c2time < mtime(N)+buf);
if (isempty(idxi) == 0)
  P2(N,1)=median(p2(idxi));
  T2(N,1)=median(t2(idxi));
  C2(N,1)=median(c2(idxi));
  S2(N,1)=median(s2(idxi));
  D2(N,1)=median(d2(idxi));
  FLOW2(N,1)=median(flw2(idxi));
  depth2(N,1)=median(dpth2(idxi));
end

 %%----------
 %% Spatial 
 %%----------
 idx = find(navtime >= mtime(N)-buf & navtime < mtime(N)+buf);
if (isempty(idx) == 0)
  depthnav(N,1)=median(ndepth(idx));
  pitch(N,1)=median(npitch(idx));
  roll(N,1)=median(nroll(idx));
  yaw(N,1)=median(nyaw(idx));
  Xpos(N,1)=median(nposx(idx));
  Ypos(N,1)=median(nposy(idx));
else
  depthnav(N,1)=0;
  pitch(N,1)=0;
  roll(N,1)=0;
  yaw(N,1)=0;
% Xpos(N,1)=Xpos(1,1);
% Ypos(N,1)=Ypos(1,1);
  Xpos(N,1)=0;
  Ypos(N,1)=0;
end
  
 %%------
 %% ISUS
 %%------
 idxi = find(n2time >= mtime(N)-buf & n2time < mtime(N)+buf);
if (isempty(idxi) == 0)
  N2(N,1)      = median(n2(idxi));
  N2Qual(N,1)  = median(n2qual(idxi));
  N2Depth(N,1) = median(n2depth(idxi));
end


end %for



