clear all
close all


ind_start = 1; % SOD and nutrient fluxes from bottom
ind_end = 20;

% SOD and sediment nutrient fluxes
% b_flux_name = {'SOD','JNH4','JNO3','JPO4','JSi'};
% file_dir = 'F:\01ROMS_HJT\03Roms_RCA_SFM\MERL_datasheet_scans\01_MERL_data\from_robin';
% filename = fullfile(file_dir,'MERLdataTabDelimited.txt');
% readMERLraw(filename);  
% for ii = 1:length(b_flux_name)
% %     create_rca_bottom_flux(fid,data(ind_start:ind_end,1+ii),data(ind_start:ind_end),startday,b_flux_name{ii}); 
% end
% fclose(fid);

flux_dir = 'bottom_flux_process/';
meso_name = {'C0','C5','C8','1X','2X','4X','8X','16X','32X'};
if ~exist(flux_dir,'dir')
    mkdir(flux_dir);
end
bf_name = {'O2','NH4','NO23','PO4','Si'};
% unit conversion
bf_conv = [ -24/1000  24/1000*14   24/1000*14  24/1000*31   24/1000*28];

bfnum = length(bf_name);
bf_dir = 'F:\01ROMS_HJT\03Roms_RCA_SFM\MERL_datasheet_scans\01_MERL_data';
% assume saturated DO for the bay (calculated by T and S)
for ii = 1:length(bf_name)
    filename = ['Sed_Flux_' bf_name{ii} '.txt'];
    filename = fullfile(bf_dir,filename);
    readMERL(filename);
    for imeso = 1:9
        ind = imeso;
        if imeso >= 4
            ind = imeso+1;
        end
        outfile = ['Sed_Flux_' bf_name{ii} '_' meso_name{imeso} '.dat'];
        outfile = fullfile(flux_dir,outfile);
        fid2 = fopen(outfile,'w');
        datestring = textdata(:,1);
        icn = 0;
        for id = 1:length(datestring)
            dates(1) = str2num(datestring{id}(1:5));
            yr = str2num(datestring{id}(1:2));
            dates(2) = yr*1000+str2num(datestring{id}(7:9));  
            cycle = 2;
            if dates(2) == dates(1)
                cycle = 1;
            end
            for kk = 1:cycle
                icn = icn+1;
                time(icn) = dates(kk);
                value(icn) = data(id,ind)*bf_conv(ii);
                addup_day = (yr-81)*365;
                julianday = dates(kk)-yr*1000+addup_day;
                fprintf(fid2,'%3s%10d%10.4f \n','Day',julianday,value(icn));
            end
        end
        fclose(fid2);
    end
end