%will update the access table in the bog_link mdb file, so that the Spec_Chl asp page is up to date.
moor = {'M1','M2'};
for mlab = 1:2
    moor_name = char(moor(mlab));
    %database retrieval
    RS = actxserver('ADODB.Recordset');
    CONN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=\\Tornado\Diatom\BOG\bog_link.mdb;';
    SQL = sprintf('SELECT Max(locl_morelchl.Date_Time)');
    SQL = [SQL, sprintf(' FROM locl_morelchl Where locl_morelchl.Mooring = "%s";'...
            ,moor_name)];
    invoke(RS, 'Open', SQL, CONN);
    
    try
        data = invoke(RS, 'getrows');
        invoke(RS,'Close');
        max_time = datenum(data);
        %max_time = datenum('Jan 01 2000') %spec start date (10/7/2000 M1, 5/18/2000 M2)
        
        nc_name = lower(char(moor(mlab)));
        ncpath = sprintf('\\\\Tornado\\Oasis\\%s\\netcdf\\%s_specprr.nc',nc_name,nc_name);
        in = netcdf(ncpath);
        
        %variables to calculate local noon - Not exact but close enough
        TimeLim = 2;
        epoch = datenum('01 Jan 1970 00:00:00');% Look for data +/- 2 hours from Noon
        lat = 36.5;
        lon = -122.5;
        Z = 10;
        t    = nctime(in); 	 		 		% Get the GMT time of the data
        
        ind =   find(t>ceil(max_time)&t<floor(now)); %get the time specified
        
        if isempty(ind)
            %fprintf('No data found!! Please confirm that you chose the right netcdf file for this time period.');
            ncquit(in);
            clear all; close all;
            moor = {'M1','M2'};
        else
            
            t   = t(ind);
            Es490 = in{'Ed490_0_3'}(:);
            Ed490 = in{'Ed490_2_3'}(:);
            Es490 = Es490(ind);
            Ed490 = Ed490(ind);
            ncquit(in);
            
            [Year, Month, Day, Hour, Minute, Second] = datevec(t);  % Get the year 
            Hour = Hour + (Minute + Second./60)./60;			  		  % Get the decimal hour of the day 	   		 						  % Get the longitude (degrees)
            Day  = date2jul(t); 										        % Get the day of the year													  % Get the variable list from the netcdf file
            index = 0;
            %WB = waitbar(0,'Calculating Daily Averages...');
            %n = length(Es490)/144;
            for y = min(Year):max(Year)		 	 % Loop thorugh each year
                id = find(Year == y);
                
                for d = min(Day(id)):max(Day(id)) % Loop from the earliest to the lastest day found in each year
                    
                    LAN = noon(jul2date(d,y),lon,1);								  % Local Area Noon in GMT
                    StartTime = (LAN - abs(TimeLim));       				  	  % in hours
                    EndTime   = (LAN + abs(TimeLim));       				  	  % in hours
                    i = find(Year == y & Day == d & Hour >= StartTime & Hour <= EndTime ); % Find all points on the desired day
                    
                    if ~isempty(i)
                        index = index + 1;
                        mTime(index) = mean(t(i));
                        %waitbar(index/n,WB);
                        dat = Es490(i);
                        bad = find(dat==-999);
                        dat(bad) = NaN;
                        bad = find(dat<2&dat>-999);
                        dat(bad) = NaN;
                        dat = nanmean(dat);
                        if (isnan(dat) | isempty(dat))
                            Es(index) = NaN;
                        else
                            Es(index) = dat;
                        end
                        
                        dat = Ed490(i);
                        bad = find(dat==-999);
                        dat(bad) = NaN;
                        dat = nanmean(dat);
                        if (isnan(dat) | isempty(dat))
                            Ed(index) = NaN;
                        else
                            Ed(index) = dat;
                        end
                        
                    end %isempty(i)
                    
                end  % for d    
            end %for y
            %close(WB);
            
            %calculate attenuation
            solZen = solarzenith(mTime, lat, lon);
            bad = find(solZen > 85); 
            R = 1 - fresnel_(solZen);
            R(bad) = NaN;      
            R(find(R < 0)) = NaN;
            %R = 0.98
            K = calc_k(Es.*R, Ed, Z); 
            
            %calculate morel chlorphyll   
            load morel.coef;
            
            % Get the correct coefficients for the wavelength
            A = interp1(morel(:,1), morel(:,2), 490);
            B = interp1(morel(:,1), morel(:,3), 490);
            C = interp1(morel(:,1), morel(:,4), 490);
            
            % Calculate the CHL
            mCHL = ((K - A)./B).^(1./C);
            
            %crude error check
            bad = find(isnan(Ed));
            Ed(bad)=-999;
            bad = find(isnan(Es));
            Es(bad)=-999;
            bad = find(isnan(K));
            K(bad)=-999;
            bad = find(isnan(mCHL));
            mCHL(bad)=-999;
            bad = find(mCHL<0&mCHL>-999);
            Ed(bad)=-999;Es(bad)=-999;K(bad)=-999;mCHL(bad)=-999;
            jday=date2jul(mTime);
            year=str2num(datestr(mTime,10))';
            
            
            %database entry
            constring = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=\\Tornado\Diatom\BOG\bog_link.mdb;';
            CONN = actxserver('ADODB.Connection'); % Connection not recordset(RS)
            invoke(CONN,'Open',constring);
            for k = 1:length(mCHL)
                SQL = sprintf('INSERT INTO locl_morelchl ( Date_Time, JDay, [Year], Es490, Ed490, K490, Morel_Chl, Z, Mooring )');
                SQL = [SQL ,sprintf(' SELECT %7.6f AS Expr1, %d AS Expr2, %d AS Expr3, %3.2f AS Expr4, %3.2f AS Expr5, %1.4f AS Expr6, %1.4f AS Expr7, 10 AS Expr8, "%s" AS Expr9;'...
                        ,sdn2xl(mTime(k)),jday(k),year(k),Es(k),Ed(k),K(k),mCHL(k),moor_name)];
                rs = invoke(CONN,'Execute',SQL);
            end
            invoke(CONN,'Close');
            clear all; close all;
            moor = {'M1','M2'};
        end %if isempty(ind)

    catch
        %fprintf('Can not contact database. Will try later.\n');
        invoke(RS,'Close');
        clear all; close all;
        moor = {'M1','M2'};
    end % try-catch
end % for mlab

exit %for batch

