/* Social Security Benefit Function for United States -
Based on Social Security Handbook 2004
---------------------------------------------------- */

program define DiBenefit,
	syntax varlist [if], gen(namelist)
	marksample touse
	tokenize `varlist'
	#delimit;
	tempvar raime rq ry_earn rbyr yr;
	///1. Assign Data to Variables -------------------

	qui gen `raime'    = `1'  if `touse';
	qui gen `rq'	 = `2'  if `touse';
	qui gen `ry_earn'  = `3'  if `touse';
	qui gen `rbyr'     = `4'  if `touse';
	qui gen `yr'       = `5' if `touse';
	/// 2.A Important Indicators ----------------------
	tempvar ry60 ry62 rynra ry70 rage;
	  qui gen `ry60' = `rbyr' + 60 if `touse';
 	  qui gen `ry62' = `rbyr' + 62 if `touse';
	  qui gen `ry70' = `rbyr' + 70 if `touse';
	  qui egen `rynra' = nra(`rbyr') if `touse';
  	  qui replace `rynra' = `rbyr' + `rynra' if `touse';
	  qui gen `rage' = `yr' - `rbyr' if `touse';


	/// Determine Eligibility based on age and quarters or coverage
	tempvar rmin re;
	qui gen `rmin' = 40 if `touse';
	qui replace `rmin' = 40 - (1929-`rbyr') if `rbyr'<1929&`touse';
	qui gen `re' = (`rq'>=`rmin')&(`yr'<`rynra') if `touse';

	/// Get PIA based on AIME, quarters (for minimum PIA) and birth year
	tempvar rpia rl rdthyr;
	qui gen `rl' = 1;
	qui gen `rdthyr' = 2100;
	SsPIA `raime' `rq' `rbyr' `rl' `rdthyr' if `touse', gen(`rpia');
	/// Get DRC or ARF based on birth year and claiming date
	tempvar rdrc;
	qui gen `rdrc' = 1 if `touse';
	qui replace `rdrc' = 0 if (`re'==0)&`touse';
	/// Calculate Admissible Benefits on own account
	tempvar rben_g;
	qui gen `rben_g' = `rdrc'*`rpia' if `touse';
	/// Get Substancial Gainful Activity
	tempvar rea_cap;
	qui egen `rea_cap' =  sga(`yr') if `touse';
	replace `rea_cap' = `ry_earn'<=`rea_cap' if `touse';

	/// Only pay benefit if above SGA

	// Proportional Reduction of All benefits
	qui replace `rben_g' = `rea_cap'*`rben_g' if `touse';
	tokenize `gen';
	qui gen `1' = `rben_g'*12 if `touse';
end;