*********************************************************************************************
* Pseudosurv.
*
* The pseudo value approach for the survival function.
*
* Author: Erik Parner, Department of Biostatistics, University of Aarhus.
*         Email: parner@biostat.au.dk
*
*********************************************************************************************

program pseudosurv
	version 9
	st_is 2 analysis

	syntax anything [, Generate(string) Failure ]

	tokenize `anything'
	local tmax `1'
	mac shift
	local rest `*'

	* Checking the number of time points.
	if(`"`rest'"'!="") {
		display as error "The procedure only supports one time points at this moment!"
		exit
	}

	* Checking the tmax.
	quietly sum _t if(_st==1)
	local max=r(max)
	if(`tmax'>`max') {
		display as error "The time point is greater than the largest observation time."
		exit
	}

	* The number of observation in the survival analysis.
	quietly count if(_st==1)
	local noobs=r(N)


	tempvar pseudo

	* Generating the pseudo values.
        forvalues i=1(1)1 {
		* Computing the KM value at tmax.
		sts gen kmfit=s
		quietly summarize kmfit if(_t<=`tmax')
		local SofTmax=r(min)
		drop kmfit

		* Computing the pseudo values.
		quietly gen `pseudo'=.
		local ntotal=_N
		forvalues i=1(1)`ntotal' {
			if(_st[`i']==1) {
				quietly replace _st=0 if(_n==`i')
				sts gen kmfit=s
				quietly summarize kmfit if(_t<=`tmax')
				local SofTmaxj=r(min)
				quietly replace _st=1 if(_n==`i')
				if (`"`failure'"'=="" ) {
					quietly replace `pseudo'= `noobs'*`SofTmax' - (`noobs'-1)*`SofTmaxj'  if(_n==`i')
				}
				if (`"`failure'"'!="" ) {
					quietly replace `pseudo'= `noobs'*(1-`SofTmax') - (`noobs'-1)*(1-`SofTmaxj') if(_n==`i')
				}
				drop kmfit
			}
		}
	}
	* Generating final variables.
	if(`"`generate'"'=="" ) {
		quietly gen pseudo=`pseudo'
		disp as result "Generating pseudo values: pseudo"
	}
	if(`"`generate'"'!="" ) {
		quietly gen `generate'=`pseudo'
		disp as result "Generating pseudo values: `generate'"
	}

end