program define tab2file
    syntax varname, saving(string) [replace] [fmt(string)] [*]

	tempname R F P C fh

	if (missing(`"`fmt'"')) local fmt="%-12.4f"


	capture confirm numeric variable `varlist'
	if !_rc {
	  local isnum=1
	  local vlbl `"`:value label `varlist''"'
      quietly tab1 `varlist', matrow(`R') matcell(`F') `options'
	}
	else {
	  local isnum=0
	  local vlbl ""

	  capture assert missing(`"`options'"')
	  if _rc {
	    display as error "Extended options not possible with string variables"
		error 101
	  }

	  quietly tab1 `varlist', matcell(`F')
	  quietly levelsof `varlist' , local(slev)
	}

	local s=0
	local n=rowsof(`F')
	forvalues i = 1/`n' {
	  local s=`s' + `=`F'[`i',1]'
	}

	matrix `P'=`F'/`s'*100.0
	matrix `C'=`F'
	forvalues i = 1/`n' {
	  matrix `C'[`i',1]=`P'[`i',1]
	  if (`i'>1) matrix `C'[`i',1]=`C'[`i',1]+`C'[`i'-1,1]
	}

	local t1 `"Tabulation of `varlist'"'
	if !missing(`"`: variable label `varlist''"') local t1 `"`t1': `: variable label `varlist''"'

	file open `fh' using `"`saving'"', write text `replace'
    file write `fh' `"`t1'"' _n
	file write `fh' "Value" _tab "Freq." _tab "Percent" _tab "Cum."
	if !missing(`"`vlbl'"') file write `fh' _tab "Label"
	file write `fh' _n

	forvalues i = 1/`n' {
       if (`isnum') {
		   local rr=`R'[`i',1]
		   file write `fh' "`=`R'[`i',1]'" _tab ///
		    "`=string(`F'[`i',1])'" _tab ///
			"`=string(`P'[`i',1],"`fmt'")'" _tab ///
			"`=string(`C'[`i',1],"`fmt'")'"

		   if !missing("`vlbl'") {
			 local rf `"`:label `vlbl' `rr''"'
			 file write `fh' _tab `"`rf'"'
		   }

		   file write `fh' _n
	   }
	   else {
         local rf `"`:word `i' of `slev''"'
		 file write `fh' "`rf'" _tab ///
		   "`=string(`F'[`i',1])'" _tab ///
		   "`=string(`P'[`i',1],"`fmt'")'" _tab ///
		   "`=string(`C'[`i',1],"`fmt'")'" _n
	   }
	}

	file write `fh' "Total" _tab "`s'" _tab "`=string(100,"`fmt'")'" _n
	file close `fh'
end

// eof