classdef RungekuttaExteriorRV < time.Timestepper
    properties
        F       % RHS of the ODE
        k       % Time step
        t       % Time point
        v       % Solution vector
        n       % Time level
        coeffs  % The coefficents used for the RK time integration
        RV      % Residual Viscosity
        bdfOrder
        v_prev  % Solution vector at previous time levels, used for the RV update
        DvDt    % Function for computing the time deriative used for the RV update


        dudt
    end
    methods

        function obj = RungekuttaExteriorRV(F, k, t0, v0, RV, rkOrder, bdfOrder, dudt)
            obj.F = F;
            obj.k = k;
            obj.t = t0;
            obj.v = v0;
            obj.n = 0;
            % Extract the coefficients for the specified rkOrder
            % used for the RK updates from the Butcher tableua.
            [s,a,b,c] = time.rk.butcherTableau(rkOrder);
            obj.coeffs = struct('s',s,'a',a,'b',b,'c',c);
        
            obj.RV = RV;
            %  TBD: For cases where h~k we could probably use rkOrder-2 here.
            %  TBD: Decide on if the initialization of the previous stages used by
            %       the BDF should be done here, or if it should be checked for each
            %       step taken.
            assert((bdfOrder >= 1) && (bdfOrder <= 6));
            obj.bdfOrder = bdfOrder;
            obj.v_prev = [];
            obj.DvDt = rv.time.BDFDerivative();

            obj.dudt = dudt;
        end

        function [v, t] = getV(obj)
            v = obj.v;
            t = obj.t;
        end

        function state = getState(obj)
            [residual, u_t, grad_f] = obj.RV.getResidual();
            state = struct('v', obj.v, 'residual', residual, 'u_t', u_t, 'grad_f', grad_f, 'viscosity', obj.RV.getViscosity(), 't', obj.t);
        end

        function obj = step(obj)
            % Store current time level
            if (size(obj.v_prev,2) < obj.bdfOrder)
                obj.v_prev = [obj.v, obj.v_prev];
            else
                obj.v_prev(:,2:end) = obj.v_prev(:,1:end-1);
                obj.v_prev(:,1) = obj.v;
            end    
            % Fix the viscosity of the RHS function F
            F_visc = @(v,t) obj.F(v,t,obj.RV.getViscosity()); %TBD: Remove state in RV?
            obj.v = time.rk.rungekutta(obj.v, obj.t, obj.k, F_visc, obj.coeffs);
            obj.t = obj.t + obj.k;
            obj.n = obj.n + 1;
            % Calculate dvdt and update RV for the new time level
            dvdt = obj.DvDt.evaluate(obj.v, obj.v_prev, obj.k);
            if ((size(obj.v_prev,2) >= 4) && (size(obj.v_prev,2) <= obj.bdfOrder))
                obj.RV.update(obj.v,dvdt);
            end
            %obj.RV.update(obj.v,obj.dudt(obj.t));
        end
    end
end