*! v 1.1.0 PR 08Oct98.
program define _fracord
version 5.0
local varlist "req ex min(2)"
local if "opt"
local in "opt"
local weight "aweight fweight"
local options "CMd(string) MACro(string) ORDer(string) FP01 *"
parse "`*'"
if "`cmd'"=="" { local cmd "regress" }
if "`order'"=="" {
	di in red "order() must be specified"
	exit 198
}
local order=substr("`order'",1,1)
if "`order'"!="+" &"`order'"!="-" &"`order'"!="r" &"`order'"!="n" {
	di in red "invalid order()"
	exit 198
}
parse "`varlist'", parse(" ")
local lhs `1'
mac shift
local rhs `*'
quietly {
	local Rhs
	parse "`rhs'", parse(" ")
	local i 1
	while "``i''"!="" {
		local x`i' ``i''
		if "`order'"=="+" | "`order'"=="-" {
			if "`fp01'"!="" {
/*
	Allow log transformation if >2 distinct values
*/
				distinct ``i'' `if' `in'
				if $S_1>2 {
					tempvar lx`i'
					fracgen ``i'' 0 `if' `in'
					rename $S_1 `lx`i''
					local x`i' `x`i'' `lx`i''

				}
			}
		}
		local Rhs `Rhs' `x`i'' /* `x`i'' has 1-2 vars */
		local i=`i'+1
	}
	if "`order'"=="+" | "`order'"=="-" {
		`cmd' `lhs' `Rhs' `if' `in' [`weight' `exp'], `options'
	}
	tempvar c n
	tempname p dfnum dfres stat
	gen `c'=.
	gen str8 `n'=""
	parse "`rhs'", parse(" ")
	local nx 0
	while "`1'"!="" {
		local nx=`nx'+1
		if "`order'"=="+" | "`order'"=="-" {
			capture test `x`nx'' /* linear or FP (0,1) */
			local rc=_rc
			capture local se=_se[`1']
			if `rc'!=0 | "`se'"=="0" { noi di in red /*
				 */ "`1' not fitted so could not be tested" /*
				 */ "---collinearity?"
				exit 1001
			}
			scalar `dfnum'=_result(3)
			scalar `dfres'=_result(5)
			scalar `stat'=_result(6)
			if `dfres'==. {
				scalar `p'=chiprob(`dfnum',`stat')
			}
			else scalar `p' = fprob(`dfnum',`dfres',`stat')
			if "`order'"=="-" { /* reducing P-value */
				replace `c'=-`p' in `nx'
			}
			else replace `c'=`p' in `nx'
		}
		replace `n'="`1'" in `nx'
		local n`nx' `1'
		mac shift
	}
	if "`order'"=="r" {
		replace `c'=uniform() in 1/`nx'
	}
}
if "`order'"!="n" { sort `c' }
global S_1 "`lhs'"
local i 0
while `i'<`nx' {
	local i=`i'+1
	local v=`n'[`i']
	global S_1 "$S_1 `v'"
/*
	Store original position of variable i in list of RHS variables
*/
	local j 0
	while `j'<`nx' {
		local j=`j'+1
		if "`v'"=="`n`j''" {
			local o`j' `i'
			local j `nx'
		}
	}
}
if "`macro'"!="" { global `macro' $S_1 }
/*
	Store original positions of variables in $S_2...
*/
local i 1
while `i'<=`nx' {
	local j=`i'+1
	global S_`j' `o`i''
	local i `j'
}
end