% CASA (Carnegie, Ames, Stanford Approach) terrestrial biogeochemical model
% designed to simulate the terrestrial carbon cycle using satellite data
% 
% Original program written by Potter and Randerson
% See: Potter, C. S., J. T. Randerson, C. B. Field, P. A. Matson, P. M. Vitousek, 
% H. A. Mooney, and S. A. Klooster, 1993.  Terrestrial ecosystem production: 
% A process model based on global satellite and surface data. 
% Global Biogeochemical Cycles (7) 811-841. 
%
% Translated into Matlab and accounted for fires by Guido van der Werf
% email: guido@ltpmailx.gsfc.nasa.gov
% See: Van der Werf, G.R., J.T. Randerson, G. J. Collatz, and L. Giglio, 2003. 
% Carbon emissions from fires in tropical and subtropical ecosystems.
% Global Change Biology 9(4) 547-562

defineConstants
loadCASAinput
defineArrays
getSoilParams
getSoilMoistureParams
doLatitude
getFuelWood

% to run NPP in equilibrium
for year = 1:NPPequilibriumYear
    tic
    for month = 1:12
        doPET
        doSoilMoisture
        doFPARandLAI   
        doOptimumTemperature        
        doNPP      
        doHerbivory
        doLeafRootShedding
        getFireParams
        if numberOfAgeClasses==1    % when running without age classes
            doTreeCarbon
            doHerbCarbon
        else                        % when running with age classes the age classes have to be assigned and sorted
            for ageClass = 1:numberOfAgeClasses
                getAgeClassBF
                assignAgeClassToRunningPool
                doTreeCarbon
                doHerbCarbon
                assignRanPoolToAgeClass
            end
            organizeAgeClasses    
        end
        processData
        if year==1 & month==1, disp(' running...'), end
    end
    disp([' Year ',int2str(year),' of ',int2str(POOLSequilibriumYear),'. Time used = ',num2str(toc),' seconds'])
end

% to run carbon pools (stocks) in equilibrium
for year = (NPPequilibriumYear+1):POOLSequilibriumYear
    tic
    for month = 1:12
        if numberOfAgeClasses==1    % when running without age classes
            doTreeCarbon
            doHerbCarbon
        else                        % when running with age classes the age classes have to be assigned and sorted
            for ageClass = 1:numberOfAgeClasses
                getAgeClassBF
                assignAgeClassToRunningPool
                doTreeCarbon
                doHerbCarbon
                assignRanPoolToAgeClass
            end
            organizeAgeClasses    
        end
        processData
    end
    disp([' Year ',int2str(year),' of ',int2str(POOLSequilibriumYear),'. Time used = ',num2str(toc),' seconds'])
end

