% routine to convert Coast Guard Instrument log file to 
% and ascii column formatted file for JGOFS posting


clf;

% loop for multiple drifters
hm=input('How many? ');
for mm=1:hm;
disp(' ');

fn=input('input filename (w/out direc or extension): ','s');
direc='/data5/jmanning/drift/oc301/';
disp(' ');
disp(['Hardcoded to look in ',direc,fn,'.log'])
inext='.log';
outext='.dat';
%fn='d21a';
fid=fopen([direc,fn,inext]);



eval(['load ',direc,fn,inext]);
eval(['d=',fn,';']);
ydi=d(:,3)-1;
yr=d(:,2)-1900;
hr=floor(d(:,4)/10000);
mn=(d(:,4)-hr*10000)/100;
sec=(d(:,4)-(hr*10000+mn*100))/100;
y=d(:,5);
x=d(:,6);

%  now generate julian day
yd=ydi+(hr+mn/60+sec/3600)/24;

% determine the mth & day
for i=1:length(yd);
 datee=calday(yr(i),yd(i));
 mth(i)=datee(2);
 day(i)=datee(3);
end;


%pltdrft(y,x,2,1,day,-1);


minyd=input('Enter minimum yearday to save: ');
maxyd=input('Enter maximum yearday to save: ');
ids=find(yd>=minyd&yd<=maxyd);
mth=mth(ids)';
day=day(ids)';
hr=hr(ids);
mn=mn(ids);
sec=sec(ids);
yr=yr(ids);
x=x(ids);
y=y(ids);
yd=yd(ids);

temp=99.9*ones(length(ids),1);

yy=[yd x y temp mth day yr hr*100+mn];
eval(['save ',direc,fn,outext,' yy -ascii']);

% throwout any time problems or bad fixes
idgood=find(diff(yy(:,1))>0);
idg2=find(y(idgood)<50&y(idgood)>38);

% save file for JGOFS
yyy=yy(idgood(idg2),1:4);
eval(['save ',direc,fn,'.jgf yyy -ascii']);

yy=yy(idgood(idg2),:);

% Now, make final plot with good data
if mm==1;
  georbat;
end;
pltdrft(yy(:,3),yy(:,2),-1*mm,1,yy(:,6),-1);
axis([min(yy(:,2)) max(yy(:,2)) min(yy(:,3)) max(yy(:,3))]);
lllabel;
title([fn,' ',num2str(mth(1)),'/',num2str(day(1)),' ',num2str(hr(1)*100+mn(1)),'GMT to ',...
 num2str(mth(length(mth))),'/',num2str(day(length(day))),' ',num2str(hr(length(hr))*100+mn(length(mn))),'GMT']);

hold on;

clear yd x y yy yyy temp mth day yr hr mn

% end loop for mulitple drifters
end;
orient tall;
