MODULE mod_globvar
  USE UTILITIES, ONLY : DP
  IMPLICIT NONE
  !Separator
  CHARACTER(LEN=1) :: sep="/" ! If unix or mac ="/", if windows ="\"

  INTEGER :: use_steady_guess
  !------------------------------------------------
  !Parameters/Calibration - Quarterly Model
  !------------------------------------------------
  !Cash at hand
  INTEGER :: ny_neg				!Negative cash at hand values
  INTEGER :: ny_pos				!Positive cash at hand values
  INTEGER :: ny					!Total number of cash at hand values
  REAL(8) :: min_y				!Minimum
  REAL(8) :: max_y				!Maximum
  REAL(8) :: curv_yneg			!Curvature of grid for negative points
  REAL(8) :: curv_ypos			!Curvature of grid for positive points
  REAL(8) :: dy_neg				!Increments for negative points
  REAL(8) :: dy_pos				!Increments for positive points

  REAL(8) :: haircut    !Loss in first period of transition
  REAL(8) :: Agg_MPC    !Average MPC
  REAL(8) :: Rent_MPC    !Average MPC
  REAL(8) :: Own_MPC    !Average MPC

  REAL(8) :: bankFC
  INTEGER :: DoBankFC

  REAL(8) :: firmFC     !Fixed cost of operating for firm
  REAL(8) :: StockMarketValue     !Fixed cost of operating for firm
  REAL(8) :: ss_debtlevel !Debt level as a fraction of annual GDP
  REAL(8) :: ss_spendlevel  !Spending as a fraction of GDP
  REAL(8) :: MBS          !Mortgage Backed Securities
  REAL(8) :: ChinaDemand !Asset demand from China
  REAL(8) :: ChinaLevel
  REAL(8) :: mortstock
  !Cash at hand (extra fine grid for computing model moments)
  INTEGER :: nyfine_neg
  INTEGER :: nyfine_pos
  INTEGER :: nyfine
  REAL(8) :: min_yfine
  REAL(8) :: max_yfine
  REAL(8) :: curv_yfineneg
  REAL(8) :: curv_yfinepos
  REAL(8) :: dyfine_neg
  REAL(8) :: dyfine_pos

  !Bonds
  INTEGER :: nb
  REAL(8) :: max_b
  REAL(8) :: curv_b
  REAL(8) :: db

  !Housing and apartment parameters
  INTEGER :: napt       !Number of apartment sizes
  INTEGER :: inf_taylor  !Use inflation (vs pricelevel) targeting taylor rule
  INTEGER :: shoot_pi  !Shoot on inflation or pricelevel
  INTEGER :: smooth_guess

  INTEGER :: nh					!Number of house sizes
  REAL(8) :: min_h				!Minimum house size
  REAL(8) :: max_h				!Maximum house size
  REAL(8) :: hincrement			!House size increments with constant proportion h/h_1
  INTEGER :: nu					!Housing match-specific shocks (1 or 2)
  INTEGER :: ng					!Total number of housing states
  REAL(8) :: useparate			!Utility of housing when "separated"
  REAL(8) :: pseparate			!Probability of housing separation
  REAL(8) :: utilown				!Utility benefit of homeownership
  REAL(8) :: max_a				!Maximum apartment size
  REAL(8) :: rentratio			!Rent to price ratio
  REAL(8) :: pa					!Price of apartment space (rentratio*ph)

  !Housing search
  INTEGER :: nx					!Number of normalized housing submarkets
  REAL(8) :: curv_x
  REAL(8) :: min_xs				!Minimum selling price relative to ph (maximum seller discount)
  REAL(8) :: max_xs				!Maximum selling price relative to ph (minimum seller discount)
  REAL(8) :: min_xb				!Minimum buying price relative to ph (minimum buying premium)
  REAL(8) :: max_xb				!Maximum buying price relative to ph (maximum buying premium)
  REAL(8) :: dx
  REAL(8) :: curv_ms				!Curvature of seller's market matching function (< 1/2 for concavity)
  REAL(8) :: curv_mb				!Curvature of buyer's market matching function (< 1/2 for concavity)
  REAL(8) :: searchcost			!Price posting utility cost in selling market

  !Mortgage parameters
  INTEGER :: nm					!Number of pseudo-leverage points
  REAL(8) :: max_ltv				!Maximum leverage at origination
  REAL(8) :: minpay
  REAL(8) :: max_m				!Maximum pseudo-leverage -- make sure max_m >= max_ltv*max_ph
  REAL(8) :: curv_m
  REAL(8) :: dm

  !Foreclosure and REO parameters
  REAL(8) :: fpenalty				!Foreclosure utility penalty
  REAL(8) :: fdiscount			!REO sale discount
  REAL(8) :: psearch				!Relative search efficiency of REO's
  REAL(8) :: pforeclose			!Probability of repossession in the event of default

  !Preference parameters (CRRA specification)
  REAL(8) :: psurvive				!Probability of survival (stochastic lifecycle)
  REAL(8) :: beta					!Discount factor
  REAL(8) :: beta_min					!Discount factor
  REAL(8) :: beta_max					!Discount factor
  REAL(8) :: gamma				!Coefficient of relative risk aversion
  REAL(8) :: ies					!Intratemporal elasticity of substitution (CES)
  REAL(8) :: disutil_scale		!Labor disutility = disutil_scale*s**disutil_exp*l**(1.d0 + 1.d0/frisch)/(1.d0 + 1.d0/frisch)
  REAL(8) :: disutil_exp			!disutil_exp = 1 or 0 (= 1 --> labor supply doesn't depend on s)
  REAL(8) :: labor_steady			!Steady state labor
  REAL(8) :: frisch				!Frisch elasticity
  REAL(8) :: invfrisch			!1.0d0+1.0d0/frisch
  REAL(8) :: cshare				!Utility weight on non-housing consumption
  REAL(8) :: min_spend

  !Idiosyncratic labor productivity parameters (see Storesletten et al (2004))
  INTEGER :: ns					!Number of permanent shocks (AR(1) process)
  REAL(8) :: mean_s				!Mean of permanent shock
  REAL(8) :: rho_s				!Persistence of permanent shock
  REAL(8) :: sig_s				!Standard deviation of permanent shock
  REAL(8) :: cover_s				!Tauchen coverage of permanent shocks
  REAL(8) :: s_luck				!Average labor efficiency for ns relative to the average of labor effiency for all other s
  REAL(8) :: p_luckstart			!Probability of transitioning from ns - 1 to ns
  REAL(8) :: p_luckstay			!Probability of staying in state ns
  INTEGER :: ne					!Number of transitory shocks
  REAL(8) :: sig_e				!Standard deviation of transitory shock
  REAL(8) :: cover_e				!Tauchen coverage of transitory shocks

  !Interest rates
  REAL(8) :: rf					!Risk-free rate
  REAL(8) :: pi					!Inflation rate
  REAL(8) :: price				!Price level
  REAL(8) :: rf_steady			!Steady state risk-free rate
  REAL(8) :: pi_steady			!Steady state inflation rate
  REAL(8) :: rocost				!Mortgage origination cost
  REAL(8) :: rscost				!Mortgage servicing cost
  REAL(8) :: rmspread				!Mortgage interest rate spread
  REAL(8) :: qm					!Inverse of mortgage interest rate

  !Housing construction parameters
  REAL(8) :: hstock				!Exogenous housing stock in the case of no construction
  REAL(8) :: deprec_h				!Quarterly depreciation rate of housing
  REAL(8) :: deprec_h_death		!Probability of stochastic depreciation conditional on death
  REAL(8) :: deprec_h_survive		!Probability of stochastic depreciation conditional on survival
  REAL(8) :: landshare			!Land's share in housing construction
  REAL(8) :: zh					!TFP of housing construction

  !Production
  REAL(8) :: markup_elas			!Production elasticity (markup = production_elas/(production_elas - 1)
  REAL(8) :: elas_w		 	!Production elasticity (markup = production_elas/(production_elas - 1)
  REAL(8) :: tfp					!TFP in the non-housing sector

  !Government policy
  REAL(8) :: usercost             !Property taxes, maintenance costs, etc.
  REAL(8) :: labortax				!Proportional labor income tax rate
  REAL(8) :: lumpsum				!Lump sum transfer
  REAL(8) :: govspend				!Government consumption
  REAL(8) :: govdebt				!Government debt
  INTEGER :: debt_nominal   ! Whether we keep nominal (1) or real debt constant (0)
  INTEGER :: period_by_period ! Use transfers to keep debt constant period by period
  !Nominal rigidities
  REAL(8) :: taylor_pi			!Taylor rule inflation coefficient
  REAL(8) :: rho_taylor
  REAL(8) :: adjust_theta			!Price adjustment cost parameter
  REAL(8) :: as_if_rigid                  !If we don't want to count adjustment cost in resource constraint

  !Transition path
  REAL(8) :: phbase
  REAL(8) :: max_ph

  !------------------------------------------------
  !Other prices, trade probabilities, etc.
  !------------------------------------------------
  REAL(8) :: dividends												!Intermediate firm profits
  REAL(8) :: w                                                        !Wage
  REAL(8) :: qb														!Bond price
  REAL(8) :: qb_annuity												!Annuity-adjusted bond price
  REAL(8) :: ph			                                            !Shadow price of housing
  REAL(8), DIMENSION(:,:,:,:), ALLOCATABLE :: qm0                     !Mortgage prices (includes closing costs, points, etc.)
  REAL(8) :: aggsupply, aggdemand, yh		                            !Non-housing output, housing construction, and structures
  REAL(8), DIMENSION(:), ALLOCATABLE :: prob_xs, prob_xb              !Submarket trade probabilities
  REAL(8), DIMENSION(:,:), ALLOCATABLE :: labor						!Earnings

  !------------------------------------------------
  !Grids
  !------------------------------------------------
  REAL(8), DIMENSION(:), ALLOCATABLE :: mm							!Leverage
  REAL(8), DIMENSION(:), ALLOCATABLE :: yy							!Cash at hand
  REAL(8), DIMENSION(:), ALLOCATABLE :: yyfine						!Cash at hand (extra fine grid)
  REAL(8), DIMENSION(:), ALLOCATABLE :: bb							!Bonds
  REAL(8), DIMENSION(:), ALLOCATABLE :: hh							!House sizes
  REAL(8), DIMENSION(:), ALLOCATABLE :: aptgrid					!Apartment sizes
  REAL(8), DIMENSION(:), ALLOCATABLE :: uu							!Housing preference shock
  REAL(8), DIMENSION(:), ALLOCATABLE :: xx							!Submarkets
  REAL(8), DIMENSION(:), ALLOCATABLE :: ss							!Permanent labor productivity shocks
  REAL(8), DIMENSION(:), ALLOCATABLE :: ee							!Transitory labor productivity shocks

  !------------------------------------------------
  !Transition probabilities and state variable correspondences
  !------------------------------------------------
  INTEGER, DIMENSION(:), ALLOCATABLE :: hfun, ufun					!g --> (h,u) correspondence
  INTEGER, DIMENSION(:,:), ALLOCATABLE :: gfun						!(h,u) --> g correspondence
  REAL(8), DIMENSION(:,:), ALLOCATABLE :: prob_ss						!Prob(s,s'), ie prob(s'|s)
  REAL(8), DIMENSION(:), ALLOCATABLE :: stationary_s, mu_s			!Stationary distribution of persistent shocks
  REAL(8), DIMENSION(:), ALLOCATABLE :: emeas							!Pdf of transitory labor shock
  REAL(8) :: eavg														!Average labor productivity

  !------------------------------------------------
  !Endogenous objects for optimization
  !------------------------------------------------
  !Banks:
  REAL(8), DIMENSION(:), ALLOCATABLE :: Jreo, psell_reo, xs_reo

  !Continuation utilities
  REAL(8), DIMENSION(:,:,:,:), ALLOCATABLE :: Vcont_own
  REAL(8), DIMENSION(:,:), ALLOCATABLE :: Vcont_rent

  !Households -- Subperiod 3:
  REAL(8), DIMENSION(:,:,:,:), ALLOCATABLE :: Vown, mown, bown, bown_temp, cown, mpcown, hcown, bown_sp1, bown_sp1_weight, bown_weight
  REAL(8), DIMENSION(:,:), ALLOCATABLE :: Vrent, brent, crent, hcrent, mpcrent
  INTEGER, DIMENSION(:,:,:,:), ALLOCATABLE :: locmown, locbown_sp1_low, locbown_sp1_upp, locbown_low, locbown_upp

  !Households -- Subperiods 1/2:
  REAL(8), DIMENSION(:,:,:,:), ALLOCATABLE :: Wown, default, xsell, xsratio, psell
  REAL(8), DIMENSION(:,:), ALLOCATABLE :: Wrent, hbuy, pbuy, xbuy, xbratio
  INTEGER, DIMENSION(:,:,:,:), ALLOCATABLE :: locxsell
  INTEGER, DIMENSION(:,:), ALLOCATABLE :: lochbuy, locxbuy, arent

  !------------------------------------------------
  !Stationary distributions (format: subperiod, owner/renter) and REO housing stock
  !------------------------------------------------
  REAL(8), DIMENSION(:,:,:,:), ALLOCATABLE :: mu1own, mu2own, mu3own
  REAL(8), DIMENSION(:,:), ALLOCATABLE :: mu1rent, mu2rent, mu3rent
  REAL(8), DIMENSION(:), ALLOCATABLE :: htot_reo, htot_reo_new, htot_reo_death

  !------------------------------------------------
  !Other
  !------------------------------------------------
  REAL(8), DIMENSION(:,:), ALLOCATABLE :: ylb		                    !Lower bound of y at mortgage origination
  INTEGER :: equil_num, matchfunction, monthly_quarterly, convertinc_quarterly, num_threads, num_threads_simul, load_data, print_input, print_output, luck_shock, input_tfp, &
       algorithm_ph, genseries, load_panel, load_stochastic, fwdguide, algorithm, pareto

  INTEGER :: load_data_1st_time

  !Variables used for VFI, iterating on mortgage prices, and simulating the distribution
  REAL(8) :: diff_q, diff_j, diff_val, diff_mu, vftol

  !Helper variables
  INTEGER :: gis, gim, gih, giu, gig
  REAL(8) :: gliq, glabor, glabordisutil, gAggC

  !"Global" variables on each thread
  !$OMP THREADPRIVATE(gis, gliq, gim, gih, gig, giu)

  ! ESTIMATION
  INTEGER, PARAMETER :: ntargets = 47
  REAL(8), DIMENSION(ntargets,2) :: mom_tar

END MODULE mod_globvar
