*! version 0.0.7 jsl 2008-01-30 - cleanup

*   DO: find way to get rid of the comma
*   DO: If command is number, find a way to record that drop was used
*           to drop an option in interactive mode

/*
NOTES:

1) To drop an existing string option, use drop as the entered
        string colvar(drop)
2) To drop number options, enter the default number you want
*/

* global: pvinteractive : 1 if old graph is being modified

capture program drop pvplot3
program define pvplot3
    version 9.2
    local qui "qui"

    syntax , ///                    ** COLORS
            [COLors(string)]            /// colors for categories
            [COLVar(varname)]           /// colors vary by this variable
            [COLRange(string)]          /// start and end value of colvar;
                                        ///     only needed if
                                        /// colvar has gaps
            [COLIntensity(string)]      /// intensities corresponding to colors
                                        ///     such as (1 .2 .5 etc)
///                                 ** INTENSITY
            [INTensity(string)]         /// intensities corresponding to values
                                        ///     of intvar
            [INTVar(varname)]           /// variable controlling path intensity
            [INTRange(string)]          /// start and end value of colvar; only
                                        ///     needed if
                                        /// intvar has gaps
///                                 ** HIDDEN AND SHOWN CASES
            [SHOWIF(string)]            /// conditions for active vars; use a
                                        ///     standard stata if/in statement
            [HIDEIF(string)]            /// conditions for hide vars; use a
                                        ///     standard stata if/in statement
            [HIDEColor(string)]         /// color of hide lines (gs15 default)
            [HIDEINTensity(string)]     /// intensity of hide lines
///                                 ** TITLES
            [CAPtion(passthru)]         /// caption pass through to stata graph
            [TItle(passthru)]           /// title passthrough
            [SUBtitle(passthru)]        /// subtitle passthrough
            [note(passthru)]            /// notepassthrough
///                                 ** GRID, AXES LABELS AND BORDER
            [GRIDColor(string)]         /// color of grid - default is black
            [GRIDWidth(real .3)]        /// width of grid line
            [GRIDYWidth(real .2)]       /// width of vertical grid line
            [GRIDSpace(integer 10)]     /// space from grid to paths
            [BORDER]                    /// add shading around graph
            [YLABOFFset(real .25)]      /// offset for ylabel offset
            [LABELSize(string)]         /// size of axes labels
                                        /// --> tiny vsmall small medsmall medium
                                        /// --> medlarge large vlarge
            [ANGLE]                     /// show labels on an angle
///
            [PATHWidth(real .01)]       /// path width (was line width)
            [EXport(string)]            /// name of export file
            [OPTions(string)]           /// enter graph options here
            [ASPECTratio(real 1)]       /// aspect ratio
            [Delta(real -99)]           /// size of offset between lines
///
            [SAMPLE(integer 100)]       /// sample this percent of cases
            [DEBUG]                     /// test mode
            [PATTERN(string)]           /// experimental: lines pattern
            [intoff]                    /// turn off interactive mode
            [Reset]                     /// reset options (same as intoff)
            [Quietly]                   /// do not show graph
            [EXPAdd]                    /// add number to export

//  set up export increment number (added to name of exported file)

    * if expadd not used, set number to 0 and prior number to 0
    if "`expadd'"=="" {
        local priorexpnum = 0
        global pvexportnum = 0
    }
    * expadd option used
    else {
        * if no prior number, make prior 0 & current 1
        if "$pvexportnum"=="" {
            local priorexpnum = 0
            global pvexportnum = 1
        }
        * global exists so increment by 1
        else {
            local priorexpnum = $pvexportnum
            global pvexportnum = $pvexportnum + 1
        }
    }

//  control interactive mode

    * reset and intoff are the same
    if "`reset'"=="reset" {
        local intoff "intoff"
    }
    * turn off interactive mode
    if "`intoff'"=="intoff" {
        global pvinteractive = 0
    }

//  NOTATION used in code
/*

HIDE/SHOW
    hideC   hide color
    hideI   hide intensity

ITEMS
    itemNM - item names
    itemK - item # of items
    itemC - # of categoreis

    itemSTx - name of variable with start x-coord of item
    itemENx - name of variable with end x-coord of item

CATEGORIES
    catK - # of categories
    catMAX
    catMIN
    catSTy      - name of variable with start y-coord for category
    catENy      - name of variable with end y-coord for category
    catSTyoff   - name of variable with start y-coord offset for category
    catENyoff   - name of variable with end y-coord offset for category

INTENSITY
    intNM   - name of intensity variable
    intV    - intensity values
    intON   - intensity is being used
    intMAX  - max of intensity variable
    intMIN  - min ...
    intK    - # of categories
    intSET  - set of intensities

COLORS
    clrNM   - name of color variable
    clrI    - color intensity
    clrISET - set of color intensity
    clrV    - color values
    clrVSET - set of color values
    clrK    - # of categories in clrNM
    clrMIN  - min cat of color var
    clrMAX

DELTA
    delta

GRID
    gridC color
    gridW width
    gridS space
    gridX x locations of grid
    gridY y locations of grid
    gridYMAX max location of y
    gridXMAX
    gridYMIN
    gridXMIN

PLOT COMMANDS ARE BUILD USING THESE LOCALS

    Pgrid
    Pxyline
    Pxaxis
    Pyaxis

*/

//  grab globals to specify options if in interative mode
//      - only done if option has not been set with command

    if $pvinteractive==1 { // if modification model

        if "`angle'"=="" {
            local angle "$pvangle"
        }
        if "`intrange'"=="" {
            local intrange "$pvintrange"
        }
        if "`colrange'"=="" {
            local colrange "$pvcolrange"
        }
        if "`hidecolor'"=="" {
            local hidecolor "$pvhideC"
        }
        if "`colors'" == "" {
            local colors "$pvcolors"
        }
        if "`colvar'" == "" {
            local colvar "$pvcolvar"
        }
        if "`colintensity'" == "" {
            local colintensity "$pvcolintensity"
        }
        if "`intensity'" == "" {
            local intensity "$pvintensity"
        }
        if "`intvar'" == "" {
            local intvar "$pvintvar"
        }
        if "`showif'" == "" {
            local showif "$pvshowif"
        }
        if "`hideif'" == "" {
            local hideif "$pvhideif"
        }
        if "`hidecolor'" == "" {
            local hidecolor "$pvhidecolor"
        }
        if "`hideintensity'" == "" {
            local hideintensity "$pvhideintensity"
        }
        if "`caption'" == "" {
            local caption "$pvcaption"
        }
        if `"`title'"' == "" {
            local title `"$pvtitle"'
        }
        if "`subtitle'" == "" {
            local subtitle "$pvsubtitle"
        }
        if "`note'" == "" {
            local note "$pvnote"
        }
        if "`gridcolor'" == "" {
            local gridcolor "$pvgridcolor"
        }
        if `gridywidth'==.2 {
            local gridywidth = $pvgridywidth
        }
        if `gridwidth'==.3 {
            local gridwidth = $pvgridwidth
        }
        if `gridspace'==10 {
            local gridspace = $pvgridspace
        }
        if "`border'" == "" {
            local border "$pvborder"
        }
        if `ylaboffset'==.25 {
            local ylaboffset = $pvylaboffset
        }
        if "`labelsize'" == "" {
            local labelsize "$pvlabelsize"
        }
        if `pathwidth'==.01 {
            local pathwidth = $pvpathwidth
        }
        if "`export'" == "" {
            local export "$pvexport"
        }
        if "`options'" == "" {
            local options "$pvoptions"
        }
        if `aspectratio'==1 {
            local aspectratio = $pvaspectratio
        }
        if `delta'==-99 {
            local delta = $pvdelta
        }
        if `sample'==100 {
            local sample = $pvsample
        }
        if "`debug'" == "" {
            local debug "$pvdebug"
        }
        if "`pattern'" == "" {
            local pattern "$pvpattern"
        }

    //  drop options that were set before

        if "`angle'"=="drop" {
            local angle ""
        }
        if "`intrange'"=="drop" {
            local intrange ""
        }
        if "`colrange'"=="drop" {
            local colrange ""
        }
        if "`hidecolor'"=="drop" {
            local hidecolor ""
        }
        if "`colors'" == "drop" {
            local colors ""
        }
        if "`colvar'" == "drop" {
            local colvar ""
        }
        if "`colintensity'" == "drop" {
            local colintensity ""
        }
        if "`intensity'" == "drop" {
            local intensity ""
        }
        if "`intvar'" == "drop" {
            local intvar ""
        }
        if "`showif'" == "drop" {
            local showif ""
        }
        if "`hideif'" == "drop" {
            local hideif ""
        }
        if "`hidecolor'" == "drop" {
            local hidecolor ""
        }
        if "`hideintensity'" == "drop" {
            local hideintensity ""
        }
        * Note: use `"`xx'"' not "`xx'"
        if `"`caption'"' == "drop" {
            local caption ""
        }
        if `"`title'"' == "drop" {
            local title ""
        }
        if `"`subtitle'"' == "drop" {
            local subtitle ""
        }
        if `"`note'"' == "drop" {
            local note ""
        }
        if "`gridcolor'" == "drop" {
            local gridcolor ""
        }
        if "`border'" == "drop" {
            local border ""
        }
        if "`labelsize'" == "drop" {
            local labelsize "$pvlabelsize"
        }
        if "`export'" == "drop" {
            local export "$pvexport"
        }
        if "`options'" == "drop" {
            local options "$pvoptions"
        }
        if "`debug'" == "drop" {
            local debug "$pvdebug"
        }
        if "`pattern'" == "drop" {
            local pattern "$pvpattern"
        }

        *? How to drop numeric input? Use -99?
        *DO   if `gridspace'==10 {
        *DO   if `ylaboffset'==.25 {
        *DO    if `pathwidth'==.01 {
        *DO    if `aspectratio'==1 {
        *DO    if `delta'==-99 {
        *DO    if `sample'==100 {
    }


//  rename syntax locals to make later code easier to read

    local intNM "`intvar'"
    local intR  "`intrange'"
    local intV "`intensity'"
    local clrNM "`colvar'"
    local clrV "`colors'"
    local clrR  "`colrange'"
    local clrI "`colintensity'"
    local hideI "`hideintensity'"
    local hideC "`hidecolor'"
    local gridC "`gridcolor'"
    local gridW "`gridwidth'"
    local gridYW "`gridywidth'"
    local gridS "`gridspace'"

//  increment number for export file so you don't have to
//      keep renaming them...

    * if increment export name
    if "`expadd'"=="expadd" & "`export'"!="" {

        * if no prior export number
        if `priorexpnum'==0 {
            * nothing was added to the export name before
            local priorlabel ""
        }

        * if prior export number
        else {
            * export name had - and number added
            local priorlabel "-`priorexpnum'"
        }
        * increment within export
        local export = subinstr("`export'","`priorlabel'.","-$pvexportnum.",1)
    }

//  indicates that interactive mode has begun

    global pvinteractive = 1

//  SAMPLE CASES for testing

    if `sample'<100 {
        set seed 11
        tempvar r
        gen `r' = uniform()
        keep if `r'<.`sample'
        drop `r'
    }

//  SET DEFAULTS

    * default hide line color
    if "`hideC'"=="" {
        local hideC "gs13"
    }
    * default labelsize
    if "`labelsize'"=="" {
        local labelsize "vsmall"
    }

//  CREATE VARIABLE INDICATING IF PATH IS SHOWN/HIDDEN

    capture drop _pv_showif
    if "`showif'"=="" {
        gen _pv_showif = 1
        label var _pv_showif "Line is active?"
    }
    * showif specified
    else {
        gen _pv_showif = 0
        label var _pv_showif "Line is active?"
        replace _pv_showif = 1 if `showif'
    }
    * hideif specified
    if "`hideif'"!="" {
        replace _pv_showif = 0 if `hideif'
    }
    * locals used to select active and hide cases
    local activeyes "& _pv_showif==1"
    local activeno "_pv_showif==0"

//  INFORMATION ON DATA BEING PLOTTED

    * names of items
    local i = 0
    local itemNM ""
    `qui' sum itemSTx
    local itemK = r(max) + 1
    forvalues k = 1(1)`itemK' {
        * get variable names from value label
        local tmplbl : label itemlbl `k'
        local itemNM "`itemNM' `tmplbl'"
    }

    * if no color variable specified, use first item
    if "`clrNM'"=="" {
        local clrNM : word 1 of `itemNM'
    }

//  check ranges for intvar and colvar to avoid problem
//  when the smallest category is missing in the current
//  dataset. Without a range check, the first color will
//  be used for the first occuring category.

    * find min and max for intensity variable; if intrange
    * is specified, use that
    if "`intNM'"!="" {
        sum `intNM'
        local intMIN = r(min)
        local intMAX = r(max)
        if "`intR'"!="" {
            local intMIN : word 1 of `intR'
            local intMAX : word 2 of `intR'
        }
    }
    * ditto for color variable
    if "`clrNM'"!="" {
        sum `clrNM'
        local clrMIN = r(min)
        local clrMAX = r(max)
        if "`clrR'"!="" {
            local clrMIN : word 1 of `clrR'
            local clrMAX : word 2 of `clrR'
        }
    }

    * determine number of categories in data being plotted
    local catK = 0
    local catMAX = -9999
    local catMIN =  9999
    forvalues itemnum = 1(1)`itemK' { // check all items
        local tmpvar : word `itemnum' of `itemNM'
        `qui' tab `tmpvar'
        local tmpcats = r(r)
        if `tmpcats'>`catK' {
            local catK = r(r)
        }
        `qui' sum `tmpvar'
        local tmpmax = r(max)
        if `tmpmax'>`catMAX' {
            local catMAX = r(max)
        }
        local tmpmin = r(min)
        if `tmpmin'<`catMIN' {
            local catMIN = r(min)
        }
    } // through items

    * check number of categories a second way
    local tmpncat = `catMAX' - `catMIN' + 1
    if `catK'!=`tmpncat' {
        di in red "ERROR: category values are not sequential"
        tab `tmpvar'
        exit
    }

//  INTENSITY - by default no variation in intensity

    * is intensity on?
    local intON = 0
    if "`intNM'"!="" {
        local intON = 1
    }
    if `intON' {
        * get range of intNM
        local intK = `intMAX' - `intMIN' + 1

        * if no intensity, make it all 1's
        if "`intV'"=="" {
            local intV "1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
        }

        * create set of intensity values - change abbrev to values
        local intSET ""
        foreach i in `intV' {
            if "`i'"=="hi" {
                local intSET "`intSET' 1"
            }
            else if "`i'"=="med" {
                local intSET "`intSET' .6"
            }
            else if "`i'"=="low" {
                local intSET "`intSET' .2"
            }
            else if "`i'"=="lo" {
                local intSET "`intSET' .2"
            }
            else {
                local intSET "`intSET' `i'"
            }
        }
        local tmpn : word count `intSET'
        while `tmpn'<`intK' {
            * if too few values, duplicate what we have
            local intSET "`intSET' `intSET'"
            local tmpn : word count `intSET'
        }

    } // intensity on

//  COLORS for COLOR VARIABLE - by default vary colors by values of first variable

    * if no colors indicated, use these as defaults
    if "`clrV'"=="" {
        local clrV "red green blue cyan magenta yellow"
    }
    else if "`clrV'"=="2cat" {
        local clrV "red blue"
    }
    else if "`clrV'"=="3cat" {
        local clrV "red blue green"
    }
    else if "`clrV'"=="4cat" {
        local clrV "red blue green gold"
    }
    else if "`clrV'"=="5cat" {
        local clrV "red blue green gold purple"
    }
    else if "`clrV'"=="bw" {

    }
    * make sure there are enough colors
    `qui' tab `clrNM'
    local clrK = r(r)
    local clrK = r(max) - r(min) + 1
    local clrK = `clrMAX' - `clrMIN' + 1

    if "`debug'"=="debug" {
        di _new "! color max min and ncats are: "
        di _new "max:   `clrMAX'"
        di "min:   `clrMIN'"
        di "ncats: `clrK'"
    }

    * ? is this needed now?
    local clrVSET `clrV'
    local tmpn : word count `clrVSET'
    while `tmpn'<`clrK' {
        local clrVSET "`clrVSET' `clrV'"
        local tmpn : word count `clrVSET'
    }

//  intensity of color

    * dummy up intensity if it isn't defined
    if "`clrI'"=="" {
        local clrI "1.0"
    }
    local clrISET
    * translate hi med low to colors
    foreach i in `clrI' {
        if "`i'"=="hi" {
            local clrISET "`clrISET' 1"
        }
        else if "`i'"=="med" {
            local clrISET "`clrISET' .6"
        }
        else if "`i'"=="low" {
            local clrISET "`clrISET' .2"
        }
        else if "`i'"=="lo" {
            local clrISET "`clrISET' .2"
        }
        else {
            local clrISET "`clrISET' `i'"
        }
    }

    * make sure there are enough color intensity
    local tmpn : word count `clrISET'
    while `tmpn'<`clrK' {
        local clrISET "`clrISET' `clrISET'"
        local tmpn : word count `clrISET'
    }

//  HIDDEN LINES (unselected)

    * intensity for hide lines
    if "`hideI'"=="" {
        local hideI = 1
    }
    else if "`hideI'"=="hi" {
        local hideI = 1
    }
    else if "`hideI'"=="med" {
        local hideI = .6
    }
    else if "`hideI'"=="low" {
        local hideI = .2
    }
    else if "`hideI'"=="lo" {
        local hideI = .2
    }

//  DETERMINE DELTA FOR DISTANCE BETWEEN LINES

    if `delta'==-99 { // if -99 pvplot computes delta

        * find max N in any category of any item
        local maxcatn = 0
        foreach v in `itemNM' { // loop over items
            forvalues c = `catMIN'(1)`catMAX' { // loop through categories
                `qui' count if `v'==`c' & itemSTx==1
                if r(N)>`maxcatn' {
                    local maxcatn = r(N)
                }
            }
        }
        * delta divides axis by max number of cases - accordingly, largest N fills space
        local delta = 1/(`gridS'+`maxcatn')
    }

//  AXES

    * set color of grid lines
    if "`gridC'"=="" {
        local gridC "black"
    }
    * determine locations for gridlines
    local gridX ""
    local gridY ""
    * place vertical lines at locations 1 2 3 ...
    forvalue i = 1(1)`itemK' {
        local gridX "`gridX' `i'"
    }
    * place horizontal lines at values of categories
    forvalue i = `catMIN'(1)`catMAX' {
        local gridY "`gridY' `i'"
    }
    * add grid line at top - add extra space for white space between paths and line
    local gridYMAX = `catMAX' + 1 + (`gridS'*`delta')
    local gridY "`gridY' `gridYMAX'"
    * y scale matches minimum category and maxlocation
    local yscale "yscale(range(`catMIN' `gridYMAX'))"
    * mins and maxs for using with -pci-
    local gridYMIN = `catMIN'
    local gridXMIN = 1
    local gridXMAX = `itemK'

//  OFFSETS - translate catSTyoff and catENyoff into delta units

    gen _pv_catSTyoff = catSTy + (catSTyoff*`delta') + (`gridS'*`delta')
    gen _pv_catENyoff = catENy + (catENyoff*`delta') + (`gridS'*`delta')

//  TITLES

/*
    if "`title'"!="" {
        local title "title(`title')"
    }
    if "`subtitle'"!="" {
        local subtitle "subtitle(`subtitle')"
    }
    if "`note'"!="" {
        local note "note(`note')"
    }
    if "`caption'"!="" {
        local caption "caption(`caption')"
    }
*/

//  P locals

    * variables to plot by -pcspike-
    local plotVARS "_pv_catSTyoff itemSTx _pv_catENyoff itemENx"

    * parameters for x-grid and y-grid lines
    local Pxyline "xline(`gridX', lwidth(`gridW') lcolor(`gridC'))"
    local Pxyline "`Pxyline' yline(`gridY', lwidth(`gridYW') lcolor(`gridC'))"

    * y-axis labels for categories
    local ylabeltext ""
    local itemlabels : value label catSTy

    * loop through values and find names of variables associated with values
    forvalues itemnum = `catMIN'(1)`catMAX' {
        local itemlabel : label `itemlabels' `itemnum'
        local textyloc = `itemnum' + .5
        local textxloc = 1 - `ylaboffset'
        local tmptxt `"text(`textyloc' `textxloc' "`itemlabel'",place(w) size(`labelsize'))"'
        local ylabeltext `" `ylabeltext' `tmptxt' "'
    }

* 2008-01-30 - problem when too many items...
local lblrng "1(1)`itemK'"
local lblang ""
if "`angle'"=="angle" {
    local lblang "angle(forty_five)"
}
    * x-axis and y-axis commands
*    local Pxaxis "xtitle("") xlabel(,valuelabel nogrid noticks labsize(`labelsize')) legend(off)"
local Pxaxis "xtitle("") xlabel(`lblrng', `lblang' valuelabel nogrid noticks labsize(`labelsize')) legend(off)"
    local Pyaxis "ytitle("") ylabel(,nolabel nogrid tstyle(none))"
    local Paxis "yscale(off) xscale(noline)"

    * aspect ratio and path width
    local Pratio "aspectratio(`aspectratio') lwidth(`pathwidth')"

    * set up various default options for graph
    local Pborder "color(white)" // i.e., no shading
    if "`border'"!="" {
        local Pborder "color(`border')"
    }
    local Pregion "graphregion(lstyle(none) `Pborder')"

    * defaults for general plot characateristics
    local Pdefaults `"`Pregion' `Paxis' `Pxaxis' `Pyaxis' `ylabeltext' "'
    *local Pdefaults `"`Pdefaults' `Pratio' caption(`caption') title(`title') "'
    local Pdefaults `"`Pdefaults' `Pratio' `caption' `title' "'
    local Pdefaults `"`Pdefaults' `subtitle' `note' `options'"'

    * plot of hidden lines
    local Phide "(pcspike `plotVARS' if `activeno', "
    local Phide "`Phide' lcolor(`hideC'*`hideI') lwidth(`pathwidth')"
    local Phide `"`Phide' `Pdefaults' `grid' `yscale')"'
    *local PLOT  `"twoway `Phide'"'
local PLOT ""

/** plot commands for plot 1
* get color for 1st category
local color1 : word 1 of `clrVSET'
local inten1 : word 1 of `clrIset'
    local P1 "(pcspike `plotVARS' if `clrNM'==1 `activeyes',"
    local P1 "`P1' lpat(`pattern') lcolor(`color1'*`inten1') "
    local P1 "`P1' `pathwidth')"
*/

/*
//  loop through colorvar categories to create plot

    local icolor = `clrK' + 1
    * loop through categories to create plot commands
    forvalues cat = `clrMAX'(-1)`clrMIN' {
        local icolor = `icolor' - 1
        local clr : word `icolor' of `clrVSET'
        local inten : word `icolor' of `clrIset'
        local plot`cat' "(pcspike `plotVARS' if `clrNM'==`cat' "
        local plot`cat' "`plot`cat'' `activeyes', lpat(`pattern') "
        local plot`cat' "lcolor(`clr'*`inten') `pathwidth' )"
        * stack with rest of plots
        local PLOT "`PLOT' `plot`cat''"
    }
*/

//  loop through intensity var and color var to create plot sets

*di "XXXX forvalues cat = `clrMAX'(-1)`clrMIN' "
*di "clriset: `clrISET'"
*di "clrvset: `clrVSET'"
    local icolor = `clrK' + 1 // start with 1 more than # of colors, then decrement
    forvalues cat = `clrMAX'(-1)`clrMIN' {
        local icolor = `icolor' - 1
        * get current color and intensity
        local clr : word `icolor' of `clrVSET'
*di "clrISET `clrISET'"
        local clrinten : word `icolor' of `clrISET'
        * is there an intensity variable
        if `intON' {
            local iint = `intK' + 1
            forvalues icat = `intMAX'(-1)`intMIN' {
                local iint = `iint' - 1
                local inten: word `iint' of `intSET'
                local P`cat'`icat' "(pcspike `plotVARS' if `clrNM'==`cat' & `intNM'==`icat' "
                local P`cat'`icat' "`P`cat'`icat'' `activeyes', lpat(`pattern') "
                * combined the intensities
*di "clrinten `clrinten'"
*di "inten `inten'"
                local intis = `clrinten'*`inten'
                local P`cat'`icat' "`P`cat'`icat'' lcolor(`clr'*`intis') lwidth(`pathwidth') )"
                local PLOT "`PLOT' `P`cat'`icat''"
            }
        } // intON
        else { // no intensity variable

            local P`cat' "(pcspike `plotVARS' if `clrNM'==`cat' "
            local P`cat' "`P`cat'' `activeyes', lpat(`pattern') "
            local P`cat' "`P`cat'' lcolor(`clr'*`clrinten') lwidth(`pathwidth') )"
            * stack with rest of plots
            local PLOT "`PLOT' `P`cat''"
        }
    } // if intON

//  AXES PLOTTED ON TOP OF OTHER LINES

    local i = 0
    local Pgrid ""
    foreach y in `gridY' {
        local yis "`y' `gridXMIN' `y' `gridXMAX', lwidth(`gridYW') lcolor(`gridC')"
        local Pgrid "`Pgrid' (pci `yis')"
    }
    foreach x in `gridX' {
        local xis "`gridYMIN' `x' `gridYMAX' `x', lwidth(`gridW') lcolor(`gridC')"
        local Pgrid "`Pgrid' (pci `xis')"
    }
    * tack this on to end of plot commands (last so lines are on top)
    local PLOT "`PLOT' `Pgrid'"

//  TEST results

if "`test'"=="test" {

di "showif      : `showif'"
di "hideif      : `hideif'"
di "hideC       : `hideC'"
di "hideI       : `hideI'"

di "itemNM      : `itemNM'"
di "itemK       : `itemK'"
di "itemC       : `itemC'"

di "catK        : `catK'"
di "catMAX      : `catMAX'"
di "catMIN      : `catMIN'"

di "intNM       : `intNM'"
di "intV        : `intV'"
di "intON       : `intON'"
di "intMAX      : `intMAX'"
di "intMIN      : `intMIN'"
di "intK        : `intK'"
di "intSET      : `intSET'"

di "clrNM       : `clrNM'"
di "clrI        : `clrI'"
di "clrISET     : `clrISET'"
di "clrV        : `clrV'"
di "clrVSET     : `clrVSET'"
di "clrK        : `clrK'"
di "clrMIN      : `clrMIN'"
di "clrMAX      : `clrMAX'"

di "max N in any cell   : `maxcatn'"
di "delta               : `delta'"

di "gridC       : `gridC'"
di "gridW       : `gridW'"
di "gridS       : `gridS'"
di "gridX       : `gridX'"
di "gridY       : `gridY'"
di "gridYMAX    : `gridYMAX'"
di "gridXMAX    : `gridXMAX'"
di "gridYMIN    : `gridYMIN'"
di "gridXMIN    : `gridXMIN'"

}

//  RUN THE PLOT


    * summarize how the data was ordered
    local pvdata      : char _dta[pvdata]
    local pvsortorder : char _dta[pvsortorder]
    local pvsortvars  : char _dta[pvsortvars]
    local pvmethod    : char _dta[pvmethod]
    *char define _dta[pvitemncats] "`itemNCATS'" // number of categories
    *char define _dta[pvitemmincats] "`itemMINCATS'" // minimum category value
    *char define _dta[pvitemmaxcats] "`itemMAXCATS'" // maximum category value

    di
    di "Data contructed by `pvdata'.ado:"
    di
    di "   Sorted `pvsortorder' by:`pvsortvars'"
    di "   Paths arranged with `pvmethod' method"
    di

    * echo the command and run the plot

* 2008-01-29
if "`quietly'"== "" {
    di _newline ". twoway " `"`Phide'"' " `PLOT'"
    local PLOT `"twoway `Phide' `PLOT'"'
    `PLOT'
    if "`export'"!="" {
        di ". graph export `export'"
        graph export `export'
    }
} // quietly
else {
    di "Note: no graph created due to quietly option being used."
}

    drop _pv_catSTyoff _pv_catENyoff

//  move things to globals

    global pvhideC "`hideC'"
    global pvhideC "`hideC'"
    global pvcolors "`colors'"
    global pvcolvar "`colvar'"
    global pvcolintensity "`colintensity'"
    global pvintensity "`intensity'"
    global pvintvar "`intvar'"
    global pvshowif "`showif'"
    global pvhideif "`hideif'"
    global pvhidecolor "`hidecolor'"
    global pvhideintensity "`hideintensity'"
    global pvcaption "`caption'"
    global pvtitle "`title'"
    global pvsubtitle "`subtitle'"
    global pvnote "`note'"
    global pvgridcolor "`gridcolor'"
    global pvgridwidth = `gridwidth'
    global pvgridywidth = `gridywidth'
    global pvgridspace = `gridspace'
    global pvborder "`border'"
    global pvylaboffset = `ylaboffset'
    global pvlabelsize "`labelsize'"
    global pvpathwidth = `pathwidth'
    global pvexport "`export'"
    global pvoptions "`options'"
    global pvaspectratio = `aspectratio'
    global pvdelta = `delta'
    global pvsample = `sample'
    global pvtest "`test'"
    global pvpattern "`pattern'"

global pvangle "`angle'"
global pvintrange "`intrange'"
global pvcolrange "`colrange'"

end
exit

//  DROPPED DID NOT WORK LINETYPES
*DROP            [LINEVar(varname)]          /// line type varies by this variable
*DROP            [lines(string)]            /// lines used by linevar

    * if blank, use these as defaults
    if "`lines'"=="" {
        local lines "solid"
    }
    if "`linevar'"!="" {
        * number of categories in linevar
        `qui' tab `linevar'
        local nlinecats = r(r)
        * make sure there are enough lines
        local lineset `lines'
        local nlines : word count `lineset'
        while `nlines'<`nlinecats' {
            local lineset "`lineset' `lines'"
            local nlines : word count `lineset'
        }
    } // if linevar

HISTORY

* version 0.0.1 - 2007-12-21 pvplot3
* version 0.0.2 - 2008-01-24 try passthrough
* version 0.0.3 jsl 2008-01-27
* version 0.0.6 jsl 2008-01-30 - range for colors and intensity
* version 0.0.5 jsl 2008-01-30 - labels with more items...
* version 0.0.4 jsl 2008-01-29 - add some options, fix some bugs