*! gcsetup 0.5.1 2009-05-25 scott long

//  setup group and variables for group comparisons

capture program drop gcsetup
program define gcsetup, rclass
    version 9

    syntax varlist ,        /// RHS variables
        GRPVar(varname)     /// group variable
        gr0var(string)     /// name of variable equal to 1 for group 0
        gr1var(string)     /// name of variable equal to 1 for group 1
        [                   ///
        gr0label(string)    /// label for group 0
        gr1label(string)    /// label for group 1
        Details             /// list details
        Matrix(string)      /// create empty matrix to hold results
        ]

//  RESET GLOBALS BEFORE PROCEEDING

    gcreset, gcsetup

//  CREATE GLOBALS

    * name of group variable
    if "`grpvar'"=="" { // if no group variable, quit
        exit
    }
    else {
        global grpvar "`grpvar'"
    }
    foreach gnum in 0 1 {
        * group vars
        if "`gr`gnum'var'"!="" {
            global gr`gnum'var "`gr`gnum'var'"
        }
        * labels for each group
        if "gr`gnum'label'"!="" {
            global gr`gnum'label "`gr`gnum'label'"
        }
    } // foreach gnum

//  GENERATE INTERACTIONS

    * create variables defining group 1 and 0
    foreach gnum in 0 1 {
        capture gen `gr`gnum'var' = (`grpvar'==`gnum') & `grpvar'!=.
        if _rc {
            di as error `"Variable "`gr`gnum'var'" exists. Pick different name with gr`gnum'var()."'
            exit
        }
        label var `gr`gnum'var' "(`grpvar'==`gnum')"
    }

    * collect names of interaction varibles created
    if "`details'"=="details" {
        local newvarlist "`grp1var' `grp0var'"
    }

    * create rhs interactions
    foreach v in `varlist' {

        foreach gnum in 0 1 {

            local newvarnm "`gr`gnum'var'`v'"
            capture gen `newvarnm' = ($grpvar==`gnum')*`v'
            if _rc {
                di as error `"Variable "`newvarnm'" already exists. Pick a different name with gr`gnum'var()."'
                exit
            }
            label var `newvarnm' "(`grpvar'==`gnum')*`v'"
            * collect names of variables created
            if "`details'"=="details" {
                local newvarlist "`newvarlist' `newvarnm'"
            }

        } // foreach gnum

    } // foreach v

//  DETAILS

    if "`details'"=="details" {

        gcglobals, gcsetup
        di _new "These interaction variables were created:"
        codebook `newvarlist', compact

    }

//  Reset matrix

    if "`matrix'"!="" {
        gcresults, matrix(`matrix') reset
    }

end
exit

//  History

Started by combining:

* gdgen3 0.3.0 2008-04-10 > Report error if variables already exist.
* gdset3 0.3.0 2008-04-10 > No changes.
* gcsetup 0.1.0 2008-06-18 add matrix
* gcsetup 0.0.2 2008-06-18 add matrix
* gcsetup 0.0.1 2008-06-18
* gcsetup 0.5.0a 2009-05-22 #1pass