program def avplot2, sort
*! avplot2  1.0.0  cfb  2315
*! from regplot 1.2.0 NJC 19 Sept 2001
	version 7.0

* use notion that SEP(varname) will be e.g. cat, with dummies labelled cat1,...
* and interactions with VARLIST(varname) being cat1xVAR; assume constant in
* regression

	syntax varlist(max=1 numeric default=none ts), SEParate(varname) /*
	*/ [ Connect(str) L1title(str) Symbol(str) XLAbel XLAbel(str) /*
	*/ YLAbel YLabel(str) TItle(str)  * /*
	*/ ]

	* initial checking and picking up what -regress- type command
	* leaves behind

	if "`e(cmd)'" == "anova" {
		di as err "avplot2 not allowed after anova"
		exit 498
	}

	if "`e(depvar)'" == "" {
		di as err "estimates not found"
		exit 301
	}

	local ndepvar : word count `e(depvar)'
	if `ndepvar' > 1 {
		di as err "avplot2 not allowed after `e(cmd)'"
		exit 498
	}

* place interaction variable into xxx
	local xxx `varlist'
* get regressor list
	tempname b
	mat `b' = e(b)
	local x : colnames `b'
* find all that start with SEPname
	local lsep = length("`separate'")
	foreach v of local x {
		local imatch = match(substr("`v'",1,`lsep'),"`separate'")
		if `imatch' {
* determine whether they are interactions
			local jmatch = index("`v'","`xxx'")
			if `jmatch' {
				local xlist "`xlist' `v'"
				}
			if `imatch'+`jmatch'==1 {
						local seplist "`seplist' `v'"
						}
			}
	}
* create partial predictions: first for interaction terms
	local i 0
	foreach v of local xlist {
		local i = `i'+1
		tempvar yhat`i'
* get pre-interaction component for conditional generate
		local base = subinstr("`v'","x`xxx'","",1)
		qui g `yhat`i'' = _b[_cons] + _b[`v']*`v' if (`base')
		label var `yhat`i'' "`v'"
		local graphlist "`graphlist' `yhat`i''"
		local ell "`ell'l"
		local dot "`dot'."
* look for associated element in seplist to pick up constant
		foreach c of local seplist {
			local cmatch = index("`v'","`c'")
			if `cmatch' {
				qui replace `yhat`i'' = `yhat`i'' + _b[`c'] if (`base')
				}
			}
		}
* turn off dashing, rely on keyplot symbols
	local connect `ell'
	local ny `i'
* logic swiped from tsgraph
    if "`connect'" == "" {
        if `ny' == 1 { local connect "L" }
            else if `ny' == 2 { local connect "LL[_]" }
            else if `ny' == 3 { local connect "LL[_]L[-]" }
            else if `ny' == 4 { local connect "LL[_]L[-]L[.]" }
            else local connect : di _dup(`ny') "L"
    }

* graph the yhats versus the interaction variable
	local y "`e(depvar)'"
	keyplot `graphlist' `xxx', c(`connect')  varlbl ti("Predictions of `y' for categories of `xxx'") `options'
	exit
end