%---------------------------------------------------------------------
% General:  Generate .rdi and .mat files with instrument data given a file
%           in database 
% Output:   .mat, .rdi
% Modify Date/Author:  20101207, R.Jenkyns
%---------------------------------------------------------------------

close all; clear all;

% Get reference for processing time
tic

% Device ID or RDI ADCP: If you do not know your device IDs
% refer to the Device Listing at http://dmas.uvic.ca/DeviceListing, and
% select the device to get a list of sensors and their ids
% For example:
deviceid=12108;

% Enter time range for data search
startdate=datenum([2010 1 5 0 0 0]);
enddate=datenum([2010 1 6 0 0 0]);

% Divide time range into deployment segments (one per instrument deployment)
[startdate,enddate]=getStartDates(deviceid,startdate,enddate);

% Path to log files
files='http://dmas.uvic.ca/AdFile?filename=';   

for j=1:length(startdate)
  % Retrieve raw log filenames within time range
  adfiles=getADfiles(deviceid,startdate(j),enddate(j));

  % convert raw log data into rdi and  mat files
  for i=1:length(adfiles)
     filename = adfiles{i,1}; 
     rdifiles=[];   
     currtime=datenum(filename(end-23:end-9),'yyyymmddTHHMMSS');
     sp=getSamplePeriod(deviceid,currtime);
    
     % subdivide data file depending on sample period (to avoid memory problems)
     sst(1)=currtime; %subset start time     
     if sp<2, ss=8; deltat=datenum([0 0 0 3 0 0]);
     elseif sp<15, ss=4; deltat=datenum([0 0 0 6 0 0]);
     else, ss=1; deltat=datenum([0 0 1 0 0 0]);
     end  
     for k=1:ss, sst(k+1)=currtime+k*deltat; end

     % convert ADCP raw log fileinto .rdi binary files
     for k=1:ss
         rdifiles1=adcphex2bin([files,filename],[filename(1:end-9),'.rdi'],sst(k:k+1)); 
         rdifiles=[rdifiles;rdifiles1];   
     end
     % make mat file of rdi data
     if ~isempty(rdifiles) 
        for j=1:size(rdifiles)
            t=datenum(rdifiles(j,end-18:end-4),'yyyymmddTHHMMSS');
            meta=getDeviceMeta(deviceid,t);               
            [adcp,config,units]=adcpRDItoMat([rdifiles(j,1:end-4),'.rdi'],meta);  
            units.deviceHeading='Beam 3 degrees relative to true N';
            units.lat='degrees N';
            units.lon='degrees E';
            units.samplingPeriod='sec';
            ofile=[rdifiles(j,1:end-4),'.mat'];
            save(ofile, 'adcp','config','units','meta','-v7')  
            clear meta config adcp units
        end
     end
  end  
end

toc