% loadasciidrift_drogueon.m
%
% load a kriged ASCII file (as provided by Mayra
% or Jessica) into Matlab.
% "_drogueon.m" - the file only contains drifters
% with drogues attached, so there is no need to
% compile with the directory file.
%
% First, manually strip the header line, e.g.
%	sed -n '4,$p' filename > destinationname
% MAKE SURE it has the format:
%  ID TIME LAT LON TEMP(dgC) VE(cm/s) VN(cm/s) ...
%       SPD eLAT eLON eTEMP
%     - or -
%  ID MM DD YY LAT LON ...
% 
clear all;
%filename='world.dat';
filename='drogue_apr_jun04.dat';

fprintf('Loading file ... ');
eval(['x=dlmread(''',filename,''');']);
fprintf('done.');

% replace placeholder for bad value:
% 999.99 -> NaN
q=find(x==999.999);
x(q)=NaN;

if (0)  % header: ID T LAT ...
    id=x(:,1);  t=x(:,2);  
    lat=x(:,3);  lon=x(:,4); sst=x(:,5); 
    u=x(:,6)/100; v=x(:,7)/100;
    elat=sqrt(x(:,9)); elon=sqrt(x(:,10)); 
    esst=sqrt(x(:,11));
elseif (1)    % header: ID MM DD YY LAT ...
    id=x(:,1);  
    t=juliand([x(:,4) x(:,2) x(:,3)]);
    lat=x(:,5);  lon=x(:,6);
    sst=x(:,7); u=x(:,8)/100; v=x(:,9)/100;
    elat=sqrt(x(:,11)); elon=sqrt(x(:,12)); 
    esst=sqrt(x(:,13));
end;
clear x;
% make sure lon is defined from -180 to 180.
q=find(lon>180);lon(q)=lon(q)-360;

plot(1,1,'.w');hold on;overlay;
plot(lon,lat,'.k','markersize',4);
hold off;
%keyboard;

% remove values with undefinied position
q=find(isnan(lat+lon));
id(q)=[];t(q)=[];lat(q)=[];lon(q)=[];
sst(q)=[];u(q)=[];v(q)=[];
elat(q)=[];elon(q)=[];esst(q)=[];
clear q;

drogue=ones(size(u));

%%%%%%%%%%%%%%%%%%%%%%%%%%%
%disp('DROPPING ALL DRIFTERS AFTER 8 APRIL 2003');
%q=find(t>juliand([2003 4 8 0 0 0]));
%truncatedrift;
%%%%%%%%%%%%%%%%%%%%%%%%%%%

Tx=NaN*ones(size(u));Ty=Tx;

% run "lowpassdrifters.m".  This script
% runs a 5 day lowpass filter on the wind stresses
% and speeds, the latter to calculate a detided
% and de-inertialized (if that is that a word)
% u, v; it also NaNs the velocities and
% where elon or elat are greater than
% 0.03 degrees (approx. 10 cm/s max error for speed)
% or where esst>0.1 degC.
disp('Lowpassing the velocities.');
lowpassdrifters

% save everything
clear filename
disp(' ');
disp('Saving data as "drift.mat"');
save drift
