% Process raw merger file (*.mer)
% apply AC9 calibration offset, TS corr, lag.
% compute bb from BB9 with attenuation correction
% type: dis-dissolved, tot-totals

clear all

path='/Users/emmanuelboss/Desktop/Rivet/IOP_pack/day1/IOP';

[file_list,n_file]=list_file(path);

fprintf('\r\n %d file(s) selected \r\n',n_file-2)

for i=4:n_file
   fclose all; close all;
   file_name_current_in=file_list(i,:);
   
   % get file name, remove empty characters
   fname_length=size(file_name_current_in,2);
   j=0;
   while file_name_current_in(1,fname_length-j)==' '
      file_name_current_in=file_name_current_in(1,1:fname_length-j-1);
   	j=j+1;   
   end
   fname_length=size(file_name_current_in,2);
      
   % load selected file
   disp('loading input file...')
   disp(file_name_current_in);
   [hdr_in,data_in]=rdctd([path,'/',file_name_current_in]);
   
   %find variables that need to be corrected
   hdr_in=lower(hdr_in);
   ind_time=strmatch('time(s)',hdr_in);
   ind_a412=strmatch('a412',hdr_in);
   ind_a715=strmatch('a715',hdr_in);
   ind_c412=strmatch('c412',hdr_in);
   ind_c715=strmatch('c715',hdr_in);
   ind_press=strmatch('pressure(db)',hdr_in);
   ind_temp=strmatch('temperature(c)',hdr_in);
   ind_sal=strmatch('salinity(psu) ',hdr_in);
   [m n]=size(data_in);    
   
   % Median-binning data in 0.5db bins- using both up and down data. 
   %Current was so strong that there is no difference between up and down.
   %crappy data at begining and end was edited by hand.
   
  
  [data_out,prr2]=binpre(data_in,data_in(ind_press,:),floor(min(data_in(ind_press,:))),floor(max(data_in(ind_press,:))),0.5,1);
            
   file_name_current_out=[path,'/',file_name_current_in(1:fname_length-4),'.prof'];
   fprintf('\nwriting to file: %s\n',file_name_current_out);
   wrtmerg(file_name_current_out,data_out,hdr_in);
   fprintf('done\n');
   clear data_out data_in
end

   fprintf('\nALL DONE\n');  

   