% 
% An attempt to write a script to warn if a mooring has broken loose.
%
mond=[0,31,59,90,120,151,181,212,243,273,304,334];
monc=['jan',
      'feb',
      'mar',
      'apr',
      'may',
      'jun',
      'jul',
      'aug',
      'sep',
      'oct',
      'nov',
      'dec'];

%fpath=['/data/span9/bahr/perlprogs/'];
fpath=[];
eval(['load ',fpath,'mooringid.dat']);
eval(['mid=mooringid;']);
eval(['load ',fpath,'time.dat']);
eval(['gtime=time;']);
year=gtime(1);
month=gtime(2);
day=gtime(3);
hour=gtime(4);
minu=gtime(5);
sec=0;
yday=gtime(6);
yearo=year;
pathm1=[];
%pathm1=['/data/span9/bahr/m',num2str(mid),'/adcp/',num2str(year),'/'];
patho=pathm1;
fnm1=['m',num2str(mid),'_gps_',monc(month,:),'_',num2str(year)];
%
fid=fopen([pathm1,fnm1,'.mat'],'r+');
if fid > 2,
	fclose(fid);
	eval(['load ',pathm1,fnm1,'.mat']);
	eval(['b=gpsn;']);
	eval(['bf=gpsf;']);
	b(:,1)=ydtostr(year,b(:,1));
else,
	b=[];
	bf=[];
end
if day > 8,
	a=[];
	af=[];
else,
	if month==1,
		yearo=year-1;
		patho=['/data/span9/bahr/m',num2str(mid),'/adcp/',num2str(yearo),'/'];
	fnm10=['m',num2str(mid),'_gps_dec_',num2str(yearo)];
	else,
		yearo=year;
		patho=pathm1;
		fnm1o=['m',num2str(mid),'_gps_',monc(month-1,:),'_',num2str(year)];
	end
	fido=fopen([patho,fnm1o,'.mat'],'r+');
	if fido > 2,
		fclose(fido);
		eval(['load ',patho,fnm1o,'.mat']);
		eval(['a=gpsn;']);
		eval(['af=gpsf;']);
		a(:,1)=ydtostr(yearo,a(:,1));
	else,
		a=[];
		af=[];
	end
end
gps=[a
     b];
flag=[af
      bf];
dnow=datenum(year,month,day,hour,minu,00);
switch mid,
	case 1,
		x=-122-0.921/60;
		y=36+44.714/60;
		dmax=1.01;
	case 2,
		x=-122.3948
		y=36.6974
		dmax=1.63;
end
% look at last 5 gps positions.
oc=0;
if size(gps,1) >=5,
	last5=gps(end-4:end,:);
	ic=5;
else,
	if size(gps,1) > 0,
		last5=gps(:,:);
		ic=size(gps,1);
	else,
		ic=0;
		dist=[];
		oc=0;
	end
end
for i=1:ic,
	 dist(i)=gdist(y,x,last5(i,2),last5(i,3));
	 if dist(i) > dmax,
		oc=oc+1;
	end
end
if (oc==ic)&(oc > 0),
	ffff=fopen('gps_message.txt','w+');
	fprintf(ffff,'Mooring M%d\n',mid);
	fprintf(ffff,'Distance from Anchor point exceded\n');
	fprintf(ffff,'Last Distance was %f km at %f f\n',dist(end),gps(end,2),gps(end,3));
	fprintf(ffff,'Check mooring positions\n');
	fclose(ffff);
ms=['Mail -s "M',num2str(mid),'" oasis@mbari.org < gps_message.txt'];
	unix(ms);
end
quit
