/* Social Security Benefit Function for United States -
Based on Social Security Handbook 2004. Computes benefits given
PIA, Year, Birth Year, Quarters Coverage, and assumes the person
is single, so only worker benefits
---------------------------------------------------- */

program define SsBenefitSimple,
	syntax varlist [if], gen(namelist)
	marksample touse
	tokenize `varlist'
	#delimit;
	tempvar rpia rclyr rbyr rq yr;

	///1. Assign Data to Variables -------------------

	qui gen `rpia'      = `1'  if `touse';
	qui gen `rclyr'    = `2'  if `touse';
	qui gen `rbyr'     = `3'  if `touse';
	qui gen `rq'	     = `4'  if `touse';
	qui gen `yr'    = `rclyr'  if `touse';

	/// 2.A Important Indicators ----------------------
	tempvar ry60 sy60 ry62 sy62 rynra synra ry70 sy70 rage sage;

	  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' = (`rage'>=62)&(`rq'>=`rmin') if `touse';

		/// Get DRC or ARF based on birth year and claiming date
	tempname arf;
	tempvar rdrc rr;
	scalar `arf' = 0.0678;
	qui egen `rdrc' = drc(`rbyr') if `touse';

	qui replace `rdrc' = exp(`arf'*max(min(`rclyr'-`rynra',0),62-`rynra')) if `rclyr'<=`rynra'&`touse';
	qui replace `rdrc' = exp(`rdrc'*min(`rclyr'-`rynra',`ry70'-`rynra')) if `rclyr'>`rynra'&`touse';

	qui gen `rr' = `rclyr'<=`yr' if `touse';
	qui replace `rdrc' = 0 if (`rr'==0|`re'==0)&`touse';
	/// Calculate Admissible Benefits on own account
	tempvar rben_g;
	qui gen `rben_g' = `rdrc'*`rpia' if `touse';



	/// Sep 14, 2008 - adjust to 2004 dollars ;
	tempvar cola_r60 cola_s60 cola_04 ;
	qui egen `cola_r60' = cola(`ry60');
	qui egen `cola_04'  = cola(2004);

	foreach x in rben_g  {;
		qui replace ``x'' = ``x''* (`cola_04'/`cola_r60') if `touse' & !missing(``x'');
	};

	tokenize `gen';
	qui gen `1' = `rben_g' if `touse';
end;