cap program drop latout
program define latout
syntax [namelist] [if]  [, title(string) /// Title of document, also used to generate name of document
						PAth(string) /// Where to save output default is current working directory
						FOOTer(string) /// Text to place at bottom of each page with page number, default Return to top
						BYVars(varlist max=2) /// variables to split results by up to two
						Holes(numlist max=1) /// Used to pick where hole is for histograms if odd number of categories of by variable
						COLumns(numlist max=1) /// Number of columns for by variable histograms
						CUToff(integer 5) ///  Cutoff between categorical and continuous coding
						Strings(string) ///How to handle strings, list, sample, or skip, default is sample
						PReserve ///Perserve dataset to make sure no changes to data
						VARNames] //show variable names in output

	local resetcd `"`c(pwd)'"'
	if `"`namelist'"'!=`""' local varlist `namelist'
	if `"`namelist'"'==`""' {
		qui ds *
		local varlist `"`r(varlist)'"'
		di `"`varlist'"'
	}
	global vlist `"`varlist'"'
	di `"$vlist"'
	if `"`preserve'"'!=`""' {
		tempfile latoutsave
		sa `latoutsave'
	}

	if `"`if'"'!=`""' {
		keep `if'
	}
	if `"`path'"'==`""' local path `"`=subinstr(`"`c(pwd)'"',"\","/",.)'"'
	if `"`strings'"'==`""' local strings `"sample"'
	if inlist(`"`strings'"',`"skip"',`"list"') global skiplist ""
	/** Saved in ado path
	cap program drop fixtex
	program define fixtex, rclass
	syntax anything [, Name(string)]
		local output `anything'
		foreach i in "&" "_" "#" "%"{
			local output=subinstr(`"`output'"',"`i'","\\`i'",.)
		}
		local output = subinstr(`"`output'"', `">"', `"\textgreater"', .)
		local output = subinstr(`"`output'"', `"<"', `"\textless"', .)
		local output = subinstr(`"`output'"', `"'"', `"`=char(39)'"', .)
		local output = subinstr(`"`output'"', `","', `"`=char(44)'"', .)
		local output = subinstr(`"`output'"', `"."', `"`=char(46)'"', .)
		local output=subinstr(`"`output'"',"\$","\\\\$",.)
		if `"`name'"'=="" return local output `"`output'"'
		if `"`name'"'!="" return local `name' `"`output'"'
	end
	*/
	***Set data file here
	global docname=subinstr(`"`title'"'," ","_",.)
	global foot "Return to top" //Text at foot of page
	if `"`footer'"'!="" global foot "`footer'"
	global udate=subinstr(`"`c(current_date)'"'," ","_",.)
	global date `c(current_date)'
	**graphs
	global ext "pdf" //or pdf or eps
		if `"${ext}"' != "eps" set graphics on
		if `"${ext}"' == "pdf" set graphics off //dont need to draw graph if eps
	set rmsg on

	************************************#************************************#
	************************************#************************************#
	******Settings for command
	global bylabl
	global byvar1
	global byv
	global byv "`byvars'"
	foreach i of global byv {
		qui count if mi(`i')
		if `r(N)'>0 {
			drop if mi(`i')
			di in red `"Warning!! `r(N)' observations dropped because missing on by variable (`i')"'
		}
	}
	cap drop byvar
	if `:word count $byv'==2 {
		local vct=0
		foreach v of global byv {
			local ++vct
			if regexm(`"`:type `v''"',"str") {
				gen b`vct'=`v'

			}
			if !regexm(`"`:type `v''"',"str") {
				if `"`:value label `v''"'!="" {
					decode `v', gen(b`vct')
				}
				if `"`:value label `v''"'=="" {
					tostring `v', gen(b`vct')

				}
			}
			label variable b`vct' `"`:variable label `v''"'
			levelsof b`vct', local(vv`vct')
			global byvar`vct' "b`vct'"
		}
		gen byvar=""
		foreach v1 of local vv1 {
			foreach v2 of local vv2 {
				qui replace byvar="`v1' `v2'" if ${byvar1}=="`v1'"&${byvar2}=="`v2'"
			}
		}
		label variable byvar "`:variable label ${byvar1}'/`:variable label ${byvar2}'"
	}
	if `:word count ${byv}'==1 {
		if regexm(`"`:type ${byv}'"',"str") {
			gen byvar=$byv
		}
		if !regexm(`"`:type ${byv}'"',"str") {
			if `"`:value label ${byv}'"'!="" {
				decode $byv, gen(byvar)
			}
			if `"`:value label ${byv}'"'=="" {
				tostring $byv, gen(byvar)
			}
		}
		if `"`byvars'"'=="" global byvar1
		if `"`byvars'"'!="" global byvar1 "$byv"
		if `"`byvars'"'=="" global bylabl
		if `"`byvars'"'!="" global bylabl `"`: variable label ${byv}'"'
	}
	if !inlist(`:word count $byv',0,1,2) {
		di in red "Can only handle 2 way split"
		exit
	}

	**********************Checking for existance of all vars
	global vlist2 ""
	global nplist ""
	foreach vl of global vlist {
		cap confirm variable `vl'
		if _rc!=0 {
			di in red `"`vl' not present in dataset"'
			global nplist "${nplist} `vl'"
		}
		if _rc==0 {
			global vlist2 "${vlist2} `vl'"
		}
	}
	*di `"OLV : ${vlist}"'
	*di `"NLV : ${vlist2}"'
	global vlist "${vlist2}"
	****DEFINING REPORT COLORS
	global teal2 "69 156 227"
	global lblue "9 157 227" //used in latex for headers
	global mustard "200 174 71"  // or "218 152 53"
	global lyellow "235 194 130"
	global dkblue "42 90 118"
	global red2 "173 38 90"
	global purple2 "114 48 124"
	global silver "166 169 170"


	global dotz `"marker(1, mcolor(gs2) msize(medlarge) msymbol(circle)) marker(2, mcolor("${teal2}") msize(medlarge) msymbol(circle)) marker(3, mcolor("${mustard}") msize(medlarge) msymbol(circle)) marker(4, mcolor(gs10) msize(medlarge) msymbol(circle)) marker(5, mcolor(orange) msize(medlarge) msymbol(circle)) marker(6, mcolor("${red2}") msize(medlarge) msymbol(circle)) marker(7, mcolor("${lyellow}") msize(medlarge) msymbol(circle)) marker(8, mcolor("${purple2}") msize(medlarge) msymbol(circle)) marker(9, mcolor(orange) msize(medlarge) msymbol(circle)) "'

	global ygrid `"ylabel(, grid glwidth(medium) glcolor(gs4) glpattern(dot))"'
	global xgrid `"xlabel(, grid glwidth(medium) glcolor(gs4) glpattern(dot))"'


	global barz `"bar(1, fcolor(gs2) lcolor(gs2)) bar(2, fcolor("${teal2}") lcolor("${teal2}"))  bar(3, fcolor("${mustard}") lcolor("${mustard}")) bar(4, fcolor(gs10) lcolor(gs10)) bar(5, fcolor("${dkblue}") lcolor("${dkblue}"))   bar(6, fcolor("${red2}") lcolor("${red2}"))  bar(7, fcolor("${lyellow}") lcolor("${lyellow}")) bar(8, fcolor("${purple2}") lcolor("${purple2}")) "'

	global ygrid `"ylabel(, grid glwidth(medium) glcolor(gs4) glpattern(dot))"'
	global xgrid `"xlabel(, grid glwidth(medium) glcolor(gs4) glpattern(dot))"'

	global blabel `"blabel(bar, format(%3.0f) color("${teal2}") size(small))"' //For counts where no decimals desired
	global blabel2 `"blabel(bar, format(%3.0f) color("${teal2}") size(tiny))"' //For counts where no decimals desired, smaller text




	set scheme burd4

	************************************#
	************************************#
	**2. LATEX DOC
		cap log close _all
		cap texdoc stlog close
		set linesize 89
		set rmsg off

	*===============WRITE LATEX DOC
	cap mkdir `"`path'/ltx_output/"'
	global tex_results `"`path'/ltx_output/"'
	cap rm `"${tex_results}/${docname}.tex"'
	cap copy `"C:/ado/personal/stata.sty"' `"${tex_results}stata.sty"'
	qui cd `"${tex_results}"'
	texdoc init `"${tex_results}/${docname}.tex"', replace force

	qui do `"C:/ado/personal/99_latexpreamble.do"', nostop

	tex	\fancypagestyle{mypagestyle}{
	tex	\fancyhf{}
	tex	\fancyfoot[C]{\hyperref[toc]{${foot}} \thepage}  %% change [C] to either [L] or [R] if needed.
	tex	\renewcommand{\headrulewidth}{0pt}
	tex	\renewcommand{\footrulewidth}{0pt}
	tex	}
	tex \usepackage{subfigure}
	tex \usepackage[subfigure]{tocloft}
	tex \renewcommand\cftsecfont{\small}
	tex \renewcommand\cftsecpagefont{\small}
	tex \renewcommand\cftsubsecfont{\small}
	tex \renewcommand\cftsubsecpagefont{\small}
	tex \renewcommand\cftsubsubsecfont{\small}
	tex \renewcommand\cftsubsubsecpagefont{\small}
	tex \newcolumntype{Y}{>{\centering\arraybackslash}X}
	tex \renewcommand*\familydefault{\sfdefault}
	tex	\makeatletter
	tex	\let\ps@plain\ps@mypagestyle%% comment this to keep chapter page style
	tex	%\let\ps@empty\ps@mypagestyle
	tex	\makeatother
	tex	\pagestyle{mypagestyle}

	tex \begin{document}
	 tex  \pagestyle{plain}
	tex
	tex
	tex   \begin{center}
	tex  {\huge{\color{lightblue}{`title'}}} \\[.2cm]
	tex
	tex  \large{Generated: $date} \\
	tex  \end{center}
	tex
	tex \vspace{1cm}
	tex
	tex  \tableofcontents\label{toc}
	tex  \noindent\hrulefill
	tex  \addtocontents{toc}{~\hrule\vspace{.2cm}\par}
	tex  \addtocontents{toc}{~\hfill\textbf{Pg.}\par}
	tex
	tex
	tex
	tex   \vspace{.25in}
	tex
	tex
	if `"`holes'"' !="" global hs "holes(`holes')"
	if `"`columns'"' !="" global cols "col(`columns')"
	global bhist ""
	if `"`byvars'"'!="" global bhist `"by(${byvar1} ${byvar2}, ${hs} ${cols})"'
	global bstatp ""
	if `:word count ${byv}'==1 global bstatp `"over(${byvar1}, label(labsize(vsmall)))"'
	if `:word count ${byv}'==2 global bstatp `"over(${byvar2}, label(labsize(vsmall))) over(${byvar1}, label(labsize(vsmall)))"'
	local ct=0
	tex \newpage
	local totalct `:word count $vlist'
	global allmilist ""
	foreach var of global vlist {
		local typ ""
		local typ: type `var'
		qui distinct `var'
		local encdist=`r(ndistinct)'
		if regexm(`"`typ'"',"str")&`encdist'<10 {
			encode `var', gen(`var'2)
			cap drop temp
			rename `var' temp
			rename `var'2 `var'
			label variable `var'  `"`: variable label temp'"'
		}
		local ++ct
		qui count if !mi(`var')
		if `r(N)'==0 global allmilist "${allmilist} `var'"
		if `r(N)'>0 {
			qui distinct `var'
			local ntosort=`r(ndistinct)'
			***IF Continuous***IF Continuous***IF Continuous***IF Continuous***IF Continuous***IF Continuous***IF Continuous***IF Continuous***IF Continuous
			if `ntosort'>=10&!regexm(`"`: type `var''"',`"str"')&!regexm("`byvars'","`var'") {
				fixtex `"`: variable label `var''"'
				local divar=subinstr(`"`var'"',"_","\_",.)
				if `"`varnames'"' !=`""' tex \section{`r(output)' (`divar')}
				if `"`varnames'"' ==`""' tex \section{`r(output)'}
				hist `var', ${bhist} xtitle(,size(small)) xsize(5) ysize(6) percent
				qui graph export `"${tex_results}fig`var'.$ext"', replace as(${ext})
				di as smcl `"CLICK TO OPEN: {browse `"${tex_results}fig`var'.$ext"'}"'
				tex \begin{figure}[ht]
				tex \centering
				tex  \includegraphics{fig`var'}
				tex \label{fig:fig`var'}
				tex \end{figure}
				tex \begin{center}
				tex \begin{tabular}{ l c c c c c c c}
				tex ${bylabl}  & Mean & SD & Min & Max & N & Missing & Percent missing \\	\hline
				if `"`byvars'"'!="" {
					qui levelsof byvar, local(lvl)
					foreach l of local lvl {
						qui count if mi(`var')& byvar=="`l'"
						local mis `:display %4.0fc `r(N)''
						qui sum `var' if byvar=="`l'"
						if `mis'>0 {
							local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
						}
						if `mis'>0&`r(N)'==0 {
							local mp "100\%"
						}
						if `mis'==0 {
							local mp "0.00\%"
						}
						qui sum `var' if byvar=="`l'"
						tex `l' & `:display %7.2f `r(mean)'' & `:display %7.2f `r(sd)'' & `:display %7.2f `r(min)'' & `:display %7.2f `r(max)'' & `:display %4.0fc `r(N)'' & `mis' & `mp' 	\\
					}
				}
				if `"`byvars'"'=="" {
					qui count if mi(`var')
					local mis `:display %4.0fc `r(N)''
					qui sum `var'
					if `mis'>0 {
						local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
					}
					if `mis'>0&`r(N)'==0 {
						local mp "100\%"
					}
					if `mis'==0 {
						local mp "0.00\%"
					}
					qui sum `var'
					tex `l' & `:display %7.2f `r(mean)'' & `:display %7.2f `r(sd)'' & `:display %7.2f `r(min)'' & `:display %7.2f `r(max)'' & `:display %4.0fc `r(N)'' & `mis' & `mp' 	\\
				}
				tex \end{tabular}
				tex \end{center}

			}
			****IF Many category string****IF Many category string****IF Many category string****IF Many category string****IF Many category string****IF Many category string
			if `ntosort'>=10&regexm(`"`: type `var''"',`"str"')&`"`strings'"'==`"sample"' {
				fixtex `"`: variable label `var''"'
				local divar=subinstr(`"`var'"',"_","\_",.)
				if `"`varnames'"' !=`""' tex \section{`r(output)' (`divar')}
				if `"`varnames'"' ==`""' tex \section{`r(output)'}
				tex `r(output)' is a string variable with more than `cutoff' distinct values. \\
				tex \begin{center}
				tex \begin{tabular}{ l c c c c c c}
				tex ${bylabl}  & N & Distinct &Max length & Min length & Missing & Percent missing \\	\hline
				qui distinct `var'
				local en `:display %6.0fc `r(N)''
				local dist `:display %6.0fc `r(ndistinct)''
				qui count if mi(`var')
				local mis `:display %4.0fc `r(N)''
				qui count if !mi(`var')
				local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
				cap drop lenlatout
				gen lenlatout=length(`var')
				qui sum lenlatout
				loca minl `:display %4.0fc `r(min)''
				loca maxl `:display %4.0fc `r(max)''
				tex Overall  & `en' & `dist' & `maxl' & `minl' & `mis' & `mp' \\
				if `"`byvars'"'!="" {
					qui levelsof byvar, local(lvl)
					foreach l of local lvl {
						qui distinct `var' if byvar=="`l'"
						local en `:display %6.0fc `r(N)''
						local dist `:display %6.0fc `r(ndistinct)''
						qui count if mi(`var') & byvar=="`l'"
						local mis `:display %4.0fc `r(N)''
						qui count if !mi(`var') & byvar=="`l'"
						local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
						qui sum lenlatout if byvar=="`l'"
						loca minl `:display %4.0fc `r(min)''
						loca maxl `:display %4.0fc `r(max)''
						tex `l'  & `en' & `dist' & `maxl' & `minl' & `mis' & `mp' \\
					}
					drop lenlatout
				}
				tex \end{tabular}
				tex \end{center}
				****************************************
				tex \begin{center}
				tex \begin{tabularx}{\linewidth}{@{}|Y |Y| Y| Y|@{}}
				if `"`byvars'"'!=""|`"`byvars'"'=="" {
					tex \hline
					tex  \multicolumn{4}{|c|}{Sample Values} \\	\hline
					qui count
					local mxn=`r(N)'
					forvalues i=1/10 {
						local tclin
						forvalues j=1/4 {
							local wct=0
							while `"`holder'"'==`""'|`wct'<15 {
								local ++wct
								local test=trunc(runiform()*`mxn')
								if `test'==0 local test "1"
								if `test'>`=_N' local test "`=_N'"
								local holder `"`=`var'[`test']'"'
							}
							fixtex `"`holder'"', n(inp)
							if `j'==1 local tclin "`r(inp)'"
							if `j'>1 local tclin "`tclin' & `r(inp)'"
						}
						tex `tclin' \\ \hline
					}
					tex \end{tabularx}
					tex \end{center}
				}

				****************************************
			}
			if `ntosort'>10&regexm(`"`: type `var''"',`"str"')&inlist(`"`strings'"',`"skip"',`"list"') {
				global skiplist "$skiplist `var'"
			}

			*****IF Categorical and less then 5 categories 			*****IF Categorical and less then 5 categories 			*****IF Categorical and less then 5 categories 			*****IF Categorical and less then 5 categories 			*****IF Categorical and less then 5 categories
			if `ntosort'>2&`ntosort'<=`cutoff'&!regexm("`byvars'","`var'") {
				fixtex `"`: variable label `var''"'
				local divar=subinstr(`"`var'"',"_","\_",.)
				if `"`varnames'"' ==`""' tex \section{`r(output)'}
				if `"`varnames'"' !=`""' tex \section{`r(output)' (`divar')}
				cap drop vtsp?
				qui ta `var', g(vtsp)
				foreach vtsp of varlist vtsp? {
					qui replace `vtsp'=`vtsp'*100
					local bulls	=subinstr(`"`:variable label `vtsp''"',"`var'==","",.)
					label variable `vtsp' `"`bulls'"'
				}
				statplot vtsp?, $bstatp xpose s(mean) xsize(5) ysize(5) ytitle(Percent of responses) varopts(label(labsize(vsmall)))
				cap drop vtsp?
				qui graph export `"${tex_results}fig`var'.$ext"', replace as(${ext})
				di as smcl `"CLICK TO OPEN: {browse `"${tex_results}fig`var'.$ext"'}"'
				tex \begin{figure}[ht]
				tex \centering
				tex  \includegraphics{fig`var'}
				tex \label{fig:fig`var'}
				tex \end{figure}
				if `"`byvars'"'!="" {
					tex \begin{center}
					global texhed " l"
					global texline "${bylabl}"
					qui levelsof `var', local(tlevs)
						foreach tl of local tlevs {
							global texhed "${texhed} Y"
							fixtex `"`: label (`var') `tl''"', n(llbl)
							global texline `"$texline & `r(llbl)'"'
					}
					local shrink=0
					local len =length(`"$texline"')
					if `len'>90 local shrink=1
					if `"`shrink'"'=="1" tex \begin{footnotesize}
					global texhed `"${texhed} Y Y Y "'
					global texline `"$texline & N & Missing & \% Missing "'
					tex \begin{tabularx}{\linewidth}{@{}${texhed}@{}}
					tex ${texline} \\	\hline
					qui levelsof byvar, local(lvl)
					foreach l of local lvl {
						global texline "`l'"
						qui count if byvar=="`l'"&!mi(`var')
						local totl=`r(N)'
						qui levelsof `var', local(tlevs)
						foreach tl of local tlevs {
							qui count if byvar=="`l'"&`var'==`tl'
							if `totl'>0 local perc: display %5.2f `=`r(N)'/`totl'*100'
							if `totl'==0 local perc  "MI"
							if `totl'>0 global texline "$texline & `perc'\%"
							if `totl'==0 global texline "$texline & `perc'"
						}
						qui count if mi(`var')& byvar=="`l'"
						local mis `:display %4.0fc `r(N)''
						qui sum `var' if byvar=="`l'"
						if `mis'>0 {
							local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
						}
						if `mis'>0&`r(N)'==0 {
							local mp "100\%"
						}
						if `mis'==0 {
							local mp "0.00\%"
						}
						global texline "$texline & `:display %4.0fc `totl'' & `mis' & `mp'"

							tex $texline \\
					}
					tex \end{tabularx}
					if `"`shrink'"'=="1" tex \end{footnotesize}

				}
				if `"`byvars'"'=="" {
					tex \begin{center}
					global texhed " l c c "
					qui count if !mi(`var')
					local tbtot=`r(N)'
					local shrink=0
					if `"`shrink'"'=="1" tex \begin{footnotesize}
					tex \begin{tabular}{${texhed}}
					qui levelsof `var', local(tlevs)
					tex `: variable label `var'' & N & Percent \\	\hline
					foreach tl of local tlevs {
						qui count if `var'==`tl'
						local tbn `:display %8.0fc `r(N)''
						local tbperc `:display %8.2fc `=`r(N)'/`tbtot'*100''
						global texline "`: label (`var') `tl'' & `tbn' & `tbperc'\%"
						tex ${texline} \\

					}
					qui count if !mi(`var')
					tex Total non-missing & `r(N)' & 100.00 \% \\ \hline
					qui count if mi(`var')
					local tbn `:display %8.0fc `r(N)''
					local tbperc `:display %8.2fc `=`r(N)'/(`tbtot'+`r(N)')*100''
					tex Missing & `tbn' & `tbperc' \% \\ \hline
					tex \end{tabular}
				}
				tex
				tex
				tex \end{center}
			} //End of fewer than 6 values and not a by variable loop
			*****IF Categorical and more then 5 categories 			*****IF Categorical and less then 5 categories 			*****IF Categorical and less then 5 categories 			*****IF Categorical and less then 5 categories 			*****IF Categorical and less then 5 categories
			if `ntosort'>`cutoff'&`ntosort'<10&!regexm("`byvars'","`var'") {
				fixtex `"`: variable label `var''"'
				local divar=subinstr(`"`var'"',"_","\_",.)
				if `"`varnames'"' !=`""' tex \section{`r(output)' (`divar')}
				if `"`varnames'"' ==`""' tex \section{`r(output)'}
				cap drop vtsp?
				qui ta `var', g(vtsp)
				global leglab ""
				local lgct=0
				foreach vtsp of varlist vtsp? {
					local ++lgct
					qui replace `vtsp'=`vtsp'*100
					local bulls	=subinstr(`"`:variable label `vtsp''"',"`var'==","",.)
					label variable `vtsp' `"`bulls'"'
					global leglab `"$leglab label(`lgct' "`:variable  label `vtsp''")"'
				}
				graph hbar vtsp?, by(byvar) legend(${leglab}) xsize(5) ysize(6)
				cap drop vtsp?
				qui graph export `"${tex_results}fig`var'.$ext"', replace as(${ext})
				di as smcl `"CLICK TO OPEN: {browse `"${tex_results}fig`var'.$ext"'}"'
				tex \begin{figure}[ht]
				tex \centering
				tex  \includegraphics{fig`var'}
				tex \label{fig:fig`var'}
				tex \end{figure}
				if `"`byvars'"'!="" {
					tex \begin{center}
					global texhed " l"
					global texline "${bylabl}"
					qui levelsof `var', local(tlevs)
						foreach tl of local tlevs {
							global texhed "${texhed} Y"
							fixtex `"`: label (`var') `tl''"', n(llbl)
							global texline `"$texline & `r(llbl)'"'
					}
					local shrink=0
					local len =length(`"$texline"')
					if `len'>90 local shrink=1
					if `"`shrink'"'=="1" tex \begin{footnotesize}
					global texhed `"${texhed} Y Y Y "'
					global texline `"$texline & N & Missing & \% Missing "'
					tex \begin{tabularx}{\linewidth}{@{}${texhed}@{}}
					tex ${texline} \\	\hline
					qui levelsof byvar, local(lvl)
					foreach l of local lvl {
						global texline "`l'"
						qui count if byvar=="`l'"&!mi(`var')
						local totl=`r(N)'
						qui levelsof `var', local(tlevs)
						foreach tl of local tlevs {
							qui count if byvar=="`l'"&`var'==`tl'
							if `totl'>0 local perc: display %5.2f `=`r(N)'/`totl'*100'
							if `totl'==0 local perc  "MI"
							if `totl'>0 global texline "$texline & `perc'\%"
							if `totl'==0 global texline "$texline & `perc'"
						}
						qui count if mi(`var')& byvar=="`l'"
						local mis `:display %4.0fc `r(N)''
						qui sum `var' if byvar=="`l'"
						if `mis'>0 {
							local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
						}
						if `mis'>0&`r(N)'==0 {
							local mp "100\%"
						}
						if `mis'==0 {
							local mp "0.00\%"
						}
						global texline "$texline & `:display %4.0fc `totl'' & `mis' & `mp'"

							tex $texline \\
					}
					tex \end{tabularx}
					if `"`shrink'"'=="1" tex \end{footnotesize}
				}
				if `"`byvars'"'=="" {
					tex \begin{center}
					global texhed " l c c "
					qui count if !mi(`var')
					local tbtot=`r(N)'
					local shrink=0
					if `"`shrink'"'=="1" tex \begin{footnotesize}
					tex \begin{tabular}{${texhed}}
					qui levelsof `var', local(tlevs)
					tex `: variable label `var'' & N & Percent \\	\hline
					foreach tl of local tlevs {
						qui count if `var'==`tl'
						local tbn `:display %8.0fc `r(N)''
						local tbperc `:display %8.2fc `=`r(N)'/`tbtot'*100''
						global texline "`: label (`var') `tl'' & `tbn' & `tbperc'\%"
						tex ${texline} \\

					}
					qui count if !mi(`var')
					tex Total non-missing & `r(N)' & 100.00 \% \\ \hline
					qui count if mi(`var')
					local tbn `:display %8.0fc `r(N)''
					local tbperc `:display %8.2fc `=`r(N)'/(`tbtot'+`r(N)')*100''
					tex Missing & `tbn' & `tbperc' \% \\ \hline
					tex \end{tabular}
				}
				tex
				tex
				tex \end{center}
			} //End of more than 6 values but fewer than 10 and not a by variable loop

			*****IF Dichotomous			*****IF Dichotomous			*****IF Dichotomous			*****IF Dichotomous			*****IF Dichotomous			*****IF Dichotomous
			if `ntosort'==2&!regexm("`byvars'","`var'") {
				fixtex `"`: variable label `var''"'
				local divar=subinstr(`"`var'"',"_","\_",.)
				if `"`varnames'"' !=`""' tex \section{`r(output)' (`divar')}
				if `"`varnames'"' ==`""' tex \section{`r(output)'}
				cap drop vtsp?
				qui ta `var', g(vtsp)
				foreach vtsp of varlist vtsp? {
					qui replace `vtsp'=`vtsp'*100
					local bulls	=subinstr(`"`:variable label `vtsp''"',"`var'==","",.)
					label variable `vtsp' `"`bulls'"'
				}
				statplot vtsp?, $bstatp s(mean) xsize(5) ysize(5) ytitle(Percent of responses) varopts(label(labsize(vsmall)))
				cap drop vtsp?
				qui graph export `"${tex_results}fig`var'.$ext"', replace as(${ext})
				di as smcl `"CLICK TO OPEN: {browse `"${tex_results}fig`var'.$ext"'}"'
				tex \begin{figure}[ht]
				tex \centering
				tex  \includegraphics{fig`var'}
				tex \label{fig:fig`var'}
				tex \end{figure}

				if `"`byvars'"'!="" {
					tex \begin{center}
					global texhed " l"
					global texline "${bylabl}"
					qui levelsof `var', local(tlevs)
						foreach tl of local tlevs {
							global texhed "${texhed} Y"
							fixtex `"`: label (`var') `tl''"', n(llbl)
							global texline `"$texline & `r(llbl)'"'
					}
					local shrink=0
					local len =length(`"$texline"')
					if `len'>90 local shrink=1
					if `"`shrink'"'=="1" tex \begin{footnotesize}
					global texhed `"${texhed} Y Y Y "'
					global texline `"$texline & N & Missing & \% Missing "'
					tex \begin{tabularx}{\linewidth}{@{}${texhed}@{}}
					tex ${texline} \\	\hline
					qui levelsof byvar, local(lvl)
					foreach l of local lvl {
						global texline "`l'"
						qui count if byvar=="`l'"&!mi(`var')
						local totl=`r(N)'
						qui levelsof `var', local(tlevs)
						foreach tl of local tlevs {
							qui count if byvar=="`l'"&`var'==`tl'
							if `totl'>0 local perc: display %5.2f `=`r(N)'/`totl'*100'
							if `totl'==0 local perc  "MI"
							if `totl'>0 global texline "$texline & `perc'\%"
							if `totl'==0 global texline "$texline & `perc'"
						}
						qui count if mi(`var')& byvar=="`l'"
						local mis `:display %4.0fc `r(N)''
						qui sum `var' if byvar=="`l'"
						if `mis'>0 {
							local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
						}
						if `mis'>0&`r(N)'==0 {
							local mp "100\%"
						}
						if `mis'==0 {
							local mp "0.00\%"
						}
						global texline "$texline & `:display %4.0fc `totl'' & `mis' & `mp'"

							tex $texline \\
					}
					tex \end{tabularx}
					if `"`shrink'"'=="1" tex \end{footnotesize}

				}
				if `"`byvars'"'=="" {
					tex \begin{center}
					global texhed " l c c "
					qui count if !mi(`var')
					local tbtot=`r(N)'
					local shrink=0
					if `"`shrink'"'=="1" tex \begin{footnotesize}
					tex \begin{tabular}{${texhed}}
					qui levelsof `var', local(tlevs)
					tex `: variable label `var'' & N & Percent \\	\hline
					foreach tl of local tlevs {
						qui count if `var'==`tl'
						local tbn `:display %8.0fc `r(N)''
						local tbperc `:display %8.2fc `=`r(N)'/`tbtot'*100''
						global texline "`: label (`var') `tl'' & `tbn' & `tbperc'\%"
						tex ${texline} \\

					}
					qui count if !mi(`var')
					tex Total non-missing & `r(N)' & 100.00 \% \\ \hline
					qui count if mi(`var')
					local tbn `:display %8.0fc `r(N)''
					local tbperc `:display %8.2fc `=`r(N)'/(`tbtot'+`r(N)')*100''
					tex Missing & `tbn' & `tbperc' \% \\ \hline
					tex \end{tabular}
				}
				tex
				tex
				tex \end{center}
			} //End of dichotomous
			*****By variables*****By variables*****By variables*****By variables*****By variables*****By variables*****By variables*****By variables*****By variables
			if regexm("`byvars'","`var'") {
				fixtex `"`: variable label `var''"'
				local divar=subinstr(`"`var'"',"_","\_",.)
				if `"`varnames'"' !=`""' tex \section{`r(output)' (`divar')}
				if `"`varnames'"' ==`""' tex \section{`r(output)'}
				cap drop vtsp?
				qui ta `var', g(vtsp)
				foreach vtsp of varlist vtsp? {
					qui replace `vtsp'=`vtsp'*100
					local bulls	=subinstr(`"`:variable label `vtsp''"',"`var'==","",.)
					label variable `vtsp' `"`bulls'"'
				}
				statplot vtsp?, s(mean) xsize(5) ysize(5) ytitle(Percent of responses) varopts(label(labsize(vsmall)))
				cap drop vtsp?
				qui graph export `"${tex_results}fig`var'.$ext"', replace as(${ext})
				di as smcl `"CLICK TO OPEN: {browse `"${tex_results}fig`var'.$ext"'}"'
				tex \begin{figure}[ht]
				tex \centering
				tex  \includegraphics{fig`var'}
				tex \label{fig:fig`var'}
				tex \end{figure}
				tex \begin{center}
				global texhed " l"
				global texline "${bylabl}"
				qui levelsof `var', local(tlevs)
					foreach tl of local tlevs {
						global texhed "${texhed} Y"
						fixtex `"`: label (`var') `tl''"', n(llbl)
						global texline `"$texline & `r(llbl)'"'
				}
				local shrink=0
				local len =length(`"$texline"')
				if `len'>90 local shrink=1
				if `"`shrink'"'=="1" tex \begin{footnotesize}
				global texhed `"${texhed} Y Y Y "'
				global texline `"$texline & N & Missing & \% Missing "'
				tex \begin{tabularx}{\linewidth}{@{}${texhed}@{}}
				tex ${texline} \\	\hline
				global texline "`divar'"
				qui count if !mi(`var')
				local totl=`r(N)'
				qui levelsof `var', local(tlevs)
				foreach tl of local tlevs {
					qui count if `var'==`tl'
					if `totl'>0 local perc: display %5.2f `=`r(N)'/`totl'*100'
					if `totl'==0 local perc  "MI"
					if `totl'>0 global texline "$texline & `perc'\%"
					if `totl'==0 global texline "$texline & `perc'"
				}
				qui count if mi(`var')
				local mis `:display %4.0fc `r(N)''
				qui sum `var'
				if `mis'>0 {
					local mp "`:display %5.2f `=`mis'/(`r(N)'+`mis')*100''\%"
				}
				if `mis'>0&`r(N)'==0 {
					local mp "100\%"
				}
				if `mis'==0 {
					local mp "0.00\%"
				}
				global texline "$texline & `:display %4.0fc `totl'' & `mis' & `mp'"
				tex $texline \\
				tex \end{tabularx}
				if `"`shrink'"'=="1" tex \end{footnotesize}
				tex
				tex
				tex \end{center}
			} //End of by variable loop
		} //End of if not zero loop

		tex \newpage
		di as smcl `"`var' `ct' of `totalct' complete for `title' "'
		if regexm(`"`typ'"',"str")&`encdist'<10 {
			drop `var'
			rename temp `var'
		}

	} //End of variables loop
	*******If many cateogry string and list selected			*******If many cateogry string and list selected			*******If many cateogry string and list selected
		if `"$skiplist"'!=""&`"`strings'"'==`"list"' {
		tex \section{Open Ended Responses}
		foreach var of global skiplist {
			fixtex `"`: variable label `var''"'
			local divar=subinstr(`"`var'"',"_","\_",.)
			if `"`varnames'"' !=`""' tex \subsection{`r(output)' (`divar')}
			if `"`varnames'"' ==`""' tex \subsection{`r(output)'}
			qui replace `var'=trim(`var')
			tex \vspace{.15cm}
			if `"`byvars'"'==`""' {
				qui count
				local oect=0
				forvalues obs=1/`r(N)' {
					if `"`=`var'[`obs']'"'!=`""' {
						local ++oect
						tex
						tex \vspace{.05cm}
						tex Text from observation `obs': \\
						fixtex `"`=`var'[`obs']'"'
						tex `r(output)' \\
						tex \vspace{.05cm}
						tex \hrule
					}
				}
			}
			if `"`byvars'"'!=`""' {
				qui count
				local totn `r(N)'
				local oect=0
				qui levelsof byvar, local(bylev)
				foreach bl of local bylev {
					tex \subsubsection{`bl'}
					tex \vspace{1cm}
					tex \hrule
					forvalues obs=1/`totn' {
						if `"`=`var'[`obs']'"'!=`""'&`"`=byvar[`obs']'"'==`"`bl'"' {
							local ++oect
							tex
							tex \vspace{.05cm}
							fixtex `"`=`var'[`obs']'"'
							tex `r(output)' \\
							tex \vspace{.05cm}
							tex \hrule
						}
					}
					tex \newpage
				}
			}
		}
		di in red `"`oect' Open-ended responses output for `divar'"'
	}
	if `"$skiplist"'!=""&`"`strings'"'==`"skip"' {
		tex \section{Skipped String Variables}
		tex The following variables are string variables with many categories and were skipped: \\
		tex \begin{itemize}
		foreach mi of global skiplist {
			local lab: variable label `mi'
			fixtex `"`lab' (`mi')"'
			tex \item  `r(output)'
		}
		tex \end{itemize}

	}
	if "${allmilist}"!=""|"${nplist}"!="" {
		tex \section{Missing Variables}
		if "${allmilist}"!="" {
			tex The following variables are missing for all observations: \\
			tex \begin{itemize}
			foreach mi of global allmilist {
				local lab: variable label `mi'
				fixtex `"`lab' (`mi')"'
				tex \item  `r(output)'
			}
			tex \end{itemize}
		}
		if "${nplist}"!="" {
			tex The following variables are not present in the dataset: \\
			tex \begin{itemize}
			foreach mi of global nplist {
				local mi2=subinstr(`"`mi'"',"_","\_",.)
				tex \item `mi2'
			}
			tex \end{itemize}
		}

	}
	*=========================END DOCUMENT============================*
	tex \end{document}
	texdoc close
	*=================================================================*

	*---------------------Typeset LaTeX Document----------------------*
	local gg "${docname}"
	foreach fff in  `gg'   {
				**first**
		if "`c(os)'" == "Windows"{
			cap rm "${tex_results}/`fff'.pdf"
			!taskkill /f /im "Acrobat.exe"   /t
			!pdflatex "${tex_results}/`fff'.tex"
			**need bibtex command**
			!pdflatex "${tex_results}/`fff'.tex"
			di as smcl `"Click to open directory: {browse `"${tex_results}"'}"'
			di as smcl `"CLICK TO OPEN: {browse `"${tex_results}/`fff'.pdf"'}"'
			****!"C:\Program Files (x86)\Adobe\Acrobat 9.0\Acrobat\Acrobat.exe"  "${sf}/`fff'.pdf"
			} //end windows loop

		if "`c(os)'" == "MacOSX" {
			cap rm "${tex_results}/`fff'.pdf"
			**test:  !/usr/texbin/bibtex	   "${sf}/aisdreport_year1"
			!/Library/TeX/texbin/pdflatex --shell-escape   "${tex_results}/`fff'.tex"  "${tex_results}/`fff'"
			!/Library/TeX/texbin/bibtex	   "${latex}/`f'"
			!/Library/TeX/texbin/pdflatex --shell-escape   "${tex_results}/`fff'.tex"  "${tex_results}/`fff'"
			**!/usr/texbin/makeindex  --shell-escape   "${latex}/`fff'.idx"  "${latex}/`fff'"
			!/Library/TeX/texbin/pdflatex --shell-escape   "${tex_results}/`fff'.tex"  "${tex_results}/`fff'"
			*copy pdf file to subdirectory
				cap copy   "${tex_results}/`fff'.pdf"  "${tex_results}/`fff'.pdf", ///
					replace public
			!open "${results_tex}/`fff'.pdf"
				di as smcl `"Click to open directory: {browse `"${tex_results}"'}"'
				di as smcl `"CLICK TO OPEN: {browse `"${tex_results}/`fff'.pdf"'}"'

			*clean up adjunct files  [[b/c not updating new pdf files properly]]
				foreach clean in pdf log aux tex ind idx {
				*	cap rm  "${latex}/`fff'.`clean'"
					}


				}  //end mac loop
	copy `"`path'/ltx_output/`fff'.pdf"' `"`path'/`fff'.pdf"', replace
	} //end fff loop for compiling
	if `"`preserve'"'!=`""' {
		use `latoutsave', clear
	}

	qui cd `resetcd'
	set graphics on
end