capture program drop tabxml
# delimit ;
program define tabxml;
version 10.1;
syntax ,   [dv(namelist) cond(str) subcond(str) ivc(namelist) ivd(namelist) split(str) PERcent(str) TFormat(str) save(str) order(namelist) OPTions(namelist) JUSTify(str) DISplay bold olines otab sp chi2 pval pdec(string) chidec(string) rotate(string) labrown(string) labcoln(string) excelpath(string) calcpath(string) osvy];

*------------------------ svy  dimensions ----------------------;

if "`osvy'"=="osvy" {;
	tempvar osvy;
	gen `osvy'=1;
	quietly svyset [pweight=`osvy'];
};
quietly capture svyset;
if _rc {;
	noisily dis in yellow "need to use osvy option or specify weights";
	exit;
};

quietly return list;
local weight=r(wvar);
local stages=r(stages);

*------------------------ default settings ----------------------;

local options "`options'";
foreach var of local options {;
	local options_`var'="`var'";
};
if "`rotate'"=="" local rotate="0";
if "`rotate'"!="0" local align="Left";
if "`rotate'"=="0" local align="Center";
local pdec "`pdec'";
local chidec "`chidec'";
if "`pdec'"=="" local pdec="2";
if "`chidec'"=="" local chidec="2";
local order "`order'";
local chi2 "`chi2'";
if "`split'"!="" {;
	quietly levelsof `split';
	local multiplier : word count `r(levels)';
};
if "`ivd'"=="" local percent "col";
if "`display'"=="display" local display "noisily";
else local display "quietly";
if "`percent'"=="" local percent "col";
if "`percent'"=="row" local p "c";
if "`percent'"=="col" local p "r";
if "`tformat'"=="" local tformat "2";
if "`justify'"=="" local justify "Left";
if ("`justify'"=="l" | "`justify'"=="L" | "`justify'"=="left") local justify=subinstr("left","l","L",1);
if ("`justify'"=="r" | "`justify'"=="R" | "`justify'"=="right")  local justify=subinstr("right","r","R",1);
if ("`justify'"=="c" | "`justify'"=="C" | "`justify'"=="center")  local justify=subinstr("center","c","C",1);
matrix drop _all;
if "`split'"!="" {;
	quietly levelsof `split';
	local values `r(levels)';
	if "`options_nototal'"=="nototal" local cycle `values';
	if "`options_nototal'"=="" local cycle `values' Total;
};
else {;
	local cycle Total;
};
local format "%9.`tformat'f";

*------------------------ excel/calc paths ----------------------;


if "`excelpath'"!="" local excelpath "`excelpath'/excel.exe";
capture local dirs : dir "C:/Program Files/Microsoft Office" dirs "office*";
foreach d of local dirs {;
	capture confirm file "C:/Program Files/Microsoft Office/`d'/excel.exe";
	if ~_rc {;
		if "`excelpath'"=="" local excelpath="C:/Program Files/Microsoft Office/`d'/excel.exe";
	};
};

if "`calcpath'"!="" local calcpath "`calcpath'/scalc.exe";
capture local dirs : dir "C:/Program Files" dirs "openoffice*";
foreach d of local dirs {;
	capture confirm file "C:/Program Files/`d'/program/scalc.exe";
	if ~_rc {;
		if "`calcpath'"=="" local calcpath="C:/Program Files/`d'/program/scalc.exe";
	};
};

*------------------------ create/change to excel folder ----------------------;

capture cd excel;
tempvar length excel;
gen `length' = strlen("`c(pwd)'");
gen `excel' = substr("`c(pwd)'",`length'-4, `length');
if `excel'!="excel" mkdir excel;

*------------------------ validate model inputs ----------------------;

local iv `ivd' `ivc' ;
if "`ivc'"=="" & "`ivd'"=="" local iv "";
local lengthiv : word count `iv';
local order_l : word count `order';
if "`order_l'"!="0" & "`order_l'"!="`lengthiv'" {;
	noisily dis in yellow "no. variables in 'order' does not match no. of indep variables";
	exit;
};

*------------------------ xml code ----------------------;

tempfile tmpfile;
tempname ofile outfile;
local xmlheader  "<?xml version='1.0'?>
			   <?mso-application progid='Excel.Sheet'?>
          	   <Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet'
					   xmlns:o='urn:schemas-microsoft-com:office:office'
                            xmlns:x='urn:schemas-microsoft-com:office:excel'
                            xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'
                            xmlns:html='http://www.w3.org/TR/REC-html40'>";
if "`bold'"=="bold" local bold "<Font x:Family='Swiss' ss:Bold='1'/>";
if "`otab'"!="otab" local otab "ss:Indent='1'";
if "`otab'"=="otab" local otab "";
if "`olines'"!="olines" local olines2 "<Borders><Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/><Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1'/></Borders>";
if "`olines'"!="olines" local olines "<Borders><Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/></Borders>";
local digit=0;
forval q=2/`tformat' {;
	local digit="`digit'0";
};
local fmt_per="#,##0.`digit';-#,##0.`digit'";
if "`tformat'"=="0" local fmt_per="#,##0;-#,##0";
if "`dv'"=="" local dv="dummy";
if "`save'"=="" {;
	local filename="`c(pwd)'/tab_out.xml";
};
foreach dep of local dv {;
	if "`save'"=="" {;
		file open  `outfile' using "tab_out.xml", write replace;
	};
	if "`save'"!="" {;
		file open  `outfile' using "`save'.xml", write replace;
	};
	file write `outfile' `"`xmlheader'"' _n;
	file write `outfile' "<Styles>";
	file write `outfile' "<Style ss:ID='s1'><Alignment ss:Vertical='Bottom'/><NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s2'><Alignment ss:Vertical='Bottom'/>'`bold''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s3'><Alignment ss:Vertical='Bottom' `otab'/><NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s4'><Alignment ss:Horizontal='`align'' ss:Vertical='Bottom' ss:Rotate='`rotate''/>'`olines''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s5'>'`olines''</Style>";
	file write `outfile' "<Style ss:ID='s6'><Alignment ss:Horizontal='Center' ss:Vertical='Bottom'/><NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s7'><Alignment `otab' ss:Vertical='Bottom'/>'`olines''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s8'><Alignment ss:Horizontal='`justify'' ss:Vertical='Bottom'/>'`olines''</Style>";
	file write `outfile' "<Style ss:ID='s9'><Alignment  ss:Horizontal='`justify'' ss:Vertical='Bottom'/>'`olines''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s10'><Alignment ss:Vertical='Bottom'/>'`bold'''`olines2''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s11'><Alignment ss:Vertical='Bottom'/>'`olines2''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s12'><Alignment ss:Vertical='Bottom'  `otab'/>'`olines''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s13'><Alignment ss:Vertical='Bottom'/>'`olines''<NumberFormat ss:Format='`digit''/></Style>";
	file write `outfile' "<Style ss:ID='s14'><Alignment ss:Horizontal='`justify'' ss:Vertical='Bottom'/><NumberFormat ss:Format='`fmt_per'' /></Style>";
	file write `outfile' "<Style ss:ID='s15'><Alignment ss:Horizontal='`justify'' ss:Vertical='Bottom'/>'`olines''<NumberFormat ss:Format='`fmt_per'' /></Style>";
	file write `outfile' "<Style ss:ID='s16'><Alignment ss:Horizontal='`justify'' ss:Vertical='Bottom'/></Style>";
	file write `outfile' "</Styles>" _n;
	file write `outfile' "<Worksheet ss:Name='Sheet1'>" _n;
	file write `outfile' "<Table ss:DefaultRowHeight='13.2'>";
	file write `outfile' "<Column ss:AutoFitWidth='0' ss:Width='67.2' ss:Span='100'/>";
	file write `outfile' "<ss:Row>";
	if "`dep'"=="dummy" file write `outfile' "<Cell ss:Index='1' ss:StyleID='s5'/>";
	if "`dep'"!="dummy" {;
		quietly levelsof `dep';
		local cnt : word count `r(levels)';
	};
	local cnt=`cnt'-1;
	if "`dep'"=="dummy" local cnt=0;
	local index=2;
	foreach sub of local cycle {;
		if "`sub'"!="Total" local sub : label `split' `sub';
		if "`split'"=="" {;
			if "`dep'"=="dummy" file write `outfile' "<Cell ss:MergeAcross='`cnt'' ss:Index='`index'' ss:StyleID='s4'><Data ss:Type='String'>`sub'</Data></Cell>";
			if "`dep'"!="dummy" file write `outfile' "<Cell ss:MergeAcross='`cnt'' ss:Index='`index'' ss:StyleID='s6'><Data ss:Type='String'>`dep'</Data></Cell>";
		};
		if "`split'"!="" {;
			if "`dep'"=="dummy" file write `outfile' "<Cell ss:MergeAcross='`cnt'' ss:Index='`index'' ss:StyleID='s4'><Data ss:Type='String'>`sub'</Data></Cell>";
			if "`dep'"!="dummy" file write `outfile' "<Cell ss:MergeAcross='`cnt'' ss:Index='`index'' ss:StyleID='s6'><Data ss:Type='String'>`sub'</Data></Cell>";
		};
		local index=`index'+`cnt'+1;
	};
	file write `outfile' "</ss:Row>";
	if "`dep'"!="dummy" {;
		file write `outfile' "<ss:Row>";
		file write `outfile' "<Cell ss:Index='1' ss:StyleID='s5'/>";
		local countdv=2;
		foreach sub of local cycle {;
			if "`sub'"!="Total" local subpop "if `split'==`sub'";
			if "`dep'"=="dummy" quietly capture svy, subpop(`subpop' `subcond'): tab `dep' `cond', count per miss;
			if "`dep'"!="dummy" quietly capture svy, subpop(`subpop' `subcond'): tab `dep' `cond', `percent' per miss;
			mat colcount_`sub'=e(Prop)*e(N_pop);
			local colcount=1;
			quietly levelsof `dep';
			foreach var in `r(levels)' {;
				local row : label (`dep') `var';
				local coltotal=el(colcount_`sub',`colcount',1);
				local coltotal=round(`coltotal',1);
				if "`labcoln'"=="" file write `outfile' "<Cell ss:Index='`countdv'' ss:StyleID='s4'><Data ss:Type='String'>`row'</Data></Cell>";
				if "`labcoln'"!="" file write `outfile' "<Cell ss:Index='`countdv'' ss:StyleID='s4'><Data ss:Type='String'>`row' (`labcoln'`coltotal')</Data></Cell>";
				local `colcount++';
				local `countdv++';
			};
			local subpop "";
		};
		file write `outfile' "</ss:Row>";
	};
	if "`order'"=="" local order=1;
	local ivd_store="`ivd'";
	local ivc_store="`ivc'";
	foreach ord of local order {;
		if "`order'"!="1" local index_ivd =  indexnot("`ord'", "`ivd'");
		if "`index_ivd'"=="0" local ivd="`ord'";
		if "`index_ivd'"=="1" local ivd="";
		if "`order'"!="1" local index_ivc =  indexnot("`ord'", "`ivc'");
		if "`index_ivc'"=="0" local ivc="`ord'";
		if "`index_ivc'"=="0" local ivd="";
		if "`index_ivd'"=="0" local ivc="";
		foreach indep of local ivd {;
			quietly levelsof `indep';
			local totcnt : word count `r(levels)';
			local total1=_N+1;
			foreach sub of local cycle {;
				if "`sub'"!="Total" local subpop "if `split'==`sub'";
				if "`sub'"=="Total" local subpop "";
				if "`sub'"=="Total" & "`subcond'"!="" local subcond="if `subcond'";
				if "`sub'"!="Total" & "`subcond'"!="" local subcond="& `subcond'";
				if ("`subpop'"!="" | "`subcond'"!="") & "`cond'"!="" quietly levelsof `indep' `subpop' `subcond' & `cond';
				if ("`subpop'"=="" & "`subcond'"=="" & "`cond'"!="") quietly levelsof `indep' if `cond';
				if ("`cond'"=="") quietly levelsof `indep' `subpop' `subcond';
				local cnt : word count `r(levels)';
				if "`cnt'"!="`totcnt'" {;
					quietly levelsof `indep', local(totval);
					if ("`subpop'"!="" | "`subcond'"!="") & "`cond'"!="" quietly levelsof `indep' `subpop' `subcond' & `cond', local(subval);
					if ("`subpop'"=="" & "`subcond'"=="" & "`cond'"!="") quietly levelsof `indep' if `cond', local(subval);
					if ("`cond'"=="") quietly levelsof `indep' `subpop' `subcond';
					local addvals : list totval - subval;
					local obs=`c(N)'+1;
					foreach var in `addvals' {;
						quietly set obs `obs';
						quietly svyset;
						quietly replace `weight' = 0 in `obs';
						forval id=1/`stages' {;
							quietly replace `r(su`id')' = 1 in `obs';
						};
						quietly replace `indep' = `var' in `obs';
						if "`split'"!="" & "`sub'"!="Total" quietly replace `split' = `sub' in `obs';
						local `obs++';
					};
				};
				if "`cond'"!="" local cond="if `cond'";
				if "`dep'"!="dummy" {;
					`display' dis in yellow "svy, subpop(`subpop' `subcond'): tab `indep' `dep' `cond', `percent' per";
					capture `display' svy, subpop(`subpop' `subcond'): tab `indep' `dep' `cond', `percent' per;
					quietly svy, subpop(`subpop' `subcond'): tab `indep' `dep' `cond', per miss;
				};
				if "`dep'"=="dummy" {;
					`display' dis in yellow "svy, subpop(`subpop' `subcond'): tab `indep' `cond', count `percent' per";
					capture `display' svy, subpop(`subpop' `subcond'): tab `indep' `cond', count per;
					quietly capture svy, subpop(`subpop' `subcond'): tab `indep' `cond', co miss;
				};
				if "`e(N_subpop)'"=="" mat matrix_`sub'=e(Prop)*e(N_pop);
				if "`e(N_subpop)'"!="" mat matrix_`sub'=e(Prop)*e(N_subpop);
				if "`dep'"!="dummy" quietly levelsof `dep' `cond';
				local cntdep : word count `r(levels)';
				if "`dep'"=="dummy" local cntdep=1;
				quietly levelsof `indep' `cond';
				capture local cond=subinstr("`cond'","if ","",.);
				capture local cond=subinstr("`cond'","if","",.);
				local cntindep : word count `r(levels)';
				mat matrix_`sub'=matrix_`sub'[1..`cntindep',1..`cntdep'];
				matsum matrix_`sub', col(ctotal_`sub');
				matsum matrix_`sub', row(rtotal_`sub');
				local rows=rowsof(matrix_`sub');
				local cols=colsof(matrix_`sub')+1;
				if "`dep'"=="dummy" local cols=2;
				capture local subpop=subinstr("`subpop'","if ","",.);
				capture local subcond=subinstr("`subcond'","if ","",.);
				capture local subcond=subinstr("`subcond'","&","",.);
				capture local cond=subinstr("`cond'","if ","",.);
			};
			local total2=_N;
			forval x=`total2'(-1)`total1' {;
				quietly drop if _n==`x';
			};
			file write `outfile' "<ss:Row>";
			local title : variable label `indep';
			file write `outfile' "<Cell ss:Index='1' ss:StyleID='s2'><Data ss:Type='String'>`title'</Data></Cell>";
			if "`dep'"!="dummy" quietly levelsof `dep';
			local dep_c : word count `r(levels)';
			if "`multiplier'"=="" local multiplier="1";
			local position=(`multiplier'*`dep_c')+2;
			if "`subcond'"!="" local subcond "if `subcond'";
			if "`chi2'"=="chi2" & "`pval'"!="pval" {;
				if "`dep'"!="dummy" quietly capture  svy, subpop(`subcond'): tab `indep' `dep' `cond', `percent' per;
				if "`dep'"=="dummy" quietly capture  svy, subpop(`subcond'): tab `indep' `cond', count per;
				local chi=string(`e(cun_Penl)',"%9.`chidec'f");
				if "`options_nototal'"!="nototal" & "`split'"!="" local position=`position'+`dep_c';
				file write `outfile' "<Cell ss:Index='`position''><ss:Data ss:Type='String' xmlns='http://www.w3.org/TR/REC-html40'>&chi;<Sup>2</Sup>=`chi'</ss:Data></Cell>";
			};
			if "`chi2'"!="chi2" & "`pval'"=="pval" {;
				if "`dep'"!="dummy" quietly capture  svy, subpop(`subcond'): tab `indep' `dep' `cond', `percent' per;
				if "`dep'"=="dummy" quietly capture  svy, subpop(`subcond'): tab `indep' `cond', count per;
				local pv=string(`e(p_Pear)',"%9.`pdec'f");
				if `pv'>=0.01 local pv2="p=`pv'";
				if `pv'<0.01 local pv2="p<0.01";
				if `pv'<0.05 local pv2="p<0.05";
				if `pv'<0.001 local pv2="p<0.001";
				if "`options_nototal'"!="nototal" & "`split'"!="" local position=`position'+`dep_c';
				file write `outfile' "<Cell ss:Index='`position''><Data ss:Type='String'>`pv2'</Data></Cell>";
			};
			if "`chi2'"=="chi2" & "`pval'"=="pval" {;
				if "`dep'"!="dummy" quietly capture  svy, subpop(`subcond'): tab `indep' `dep' `cond', `percent' per;
				if "`dep'"=="dummy" quietly capture  svy, subpop(`subcond'): tab `indep' `cond', count per;
				local chi=string(`e(cun_Penl)',"%9.`chidec'f");
				local pv=string(`e(p_Pear)',"%9.`pdec'f");
				if `pv'>=0.01 local pv2="p=`pv'";
				if `pv'<0.01 local pv2="p<0.01";
				if `pv'<0.05 local pv2="p<0.05";
				if `pv'<0.001 local pv2="p<0.001";
				if "`psig'"!="" if `pv'<`psig' local pv2="p<0.`psig'";
				if "`options_nototal'"!="nototal" & "`split'"!="" local position=`position'+`dep_c';
				file write `outfile' "<Cell ss:Index='`position''><ss:Data ss:Type='String' xmlns='http://www.w3.org/TR/REC-html40'>&chi;<Sup>2</Sup>=`chi'; `pv2'</ss:Data></Cell>";
			};
			file write `outfile' "</ss:Row>";
			if "`cond'"!="" local cond "if `cond'";
			quietly levelsof `indep' `cond';
			capture local cond=subinstr("`cond'","if ","",.);
			local matcount=1;
			local borders : word count `r(levels)';
			local row=1;
			foreach var in `r(levels)' {;
				file write `outfile' "<ss:Row>";
				local countiv=2;
				local col : label (`indep') `var';
				local countmat=1;
				local total =0;
				local cond="if `cond'";
				if "`dep'"!="dummy" quietly capture svy, subpop(`subcond'): tab `indep' `cond', count per miss;
				if "`dep'"=="dummy" quietly capture svy, subpop(`subcond'): tab `indep' `cond', count per miss;
				capture local cond=subinstr("`cond'","if ","",.);
				if "`e(N_subpop)'"=="" mat matrix_labrown=e(Prop)*e(N_pop);
				if "`e(N_subpop)'"!="" mat matrix_labrown=e(Prop)*e(N_subpop);
				local total = round(el(matrix_labrown,`row',1),1);
				if "`labrown'"!="" {;
					if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='1' ss:StyleID='s3'><Data ss:Type='String'>`col' (`labrown'`total')</Data></Cell>";
					if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='1' ss:StyleID='s12'><Data ss:Type='String'>`col' (`labrown'`total')</Data></Cell>";
				};
				else {;
					if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='1' ss:StyleID='s3'><Data ss:Type='String'>`col'</Data></Cell>";
					if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='1' ss:StyleID='s12'><Data ss:Type='String'>`col'</Data></Cell>";
				};
				foreach sub of local cycle {;
					forval j=2/`cols' {;
						local n = round(el(matrix_`sub',`matcount',`j'-1),1);
						if "`n'"=="" local n="0";
						if "`percent'"=="row" local p = 100*el(matrix_`sub',`matcount',`j'-1)/el(rtotal_`sub',`matcount',1);
						if "`percent'"=="col" local p = 100*el(matrix_`sub',`matcount',`j'-1)/el(ctotal_`sub',1,`j'-1);
						local p=string(`p',"`format'");
						if `n'==0 {;
							if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='Number'>0</Data></Cell>";
							if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='Number'>0</Data></Cell>";
						};
						else if `p'==100 {;
							if "`options_n'"=="n" {;
								if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='Number'>`n'</Data></Cell>";
								if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='Number'>`n'</Data></Cell>";
							};
							else if "`options_per'"=="per" {;
								if "`sp'"!="sp" {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='Number'>100</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='Number'>100</Data></Cell>";
								};
								else {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='Number'>100%</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='Number'>100%</Data></Cell>";
								};
							};
							else {;
								if "`sp'"!="sp" {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='String'>`n' (100)</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='String'>`n' (100)</Data></Cell>";
								};
								else {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='String'>`n' (100%)</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='String'>`n' (100%)</Data></Cell>";
								};
							};
						};
						else {;
							if "`options_n'"=="n" {;
								if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='Number'>`n'</Data></Cell>";
								if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='Number'>`n'</Data></Cell>";
							};
							else if "`options_per'"=="per" {;
								if "`sp'"!="sp" {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s14'><Data ss:Type='Number'>`p'</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s15'><Data ss:Type='Number'>`p'</Data></Cell>";
								};
								else {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s14'><Data ss:Type='String'>`p'%</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s15'><Data ss:Type='String'>`p'%</Data></Cell>";
								};
							};
							else {;
								if "`sp'"!="sp" {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='String'>`n' (`p')</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='String'>`n' (`p')</Data></Cell>";
								};
								else {;
									if "`matcount'"!="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s16'><Data ss:Type='String'>`n' (`p'%)</Data></Cell>";
									if "`matcount'"=="`borders'" file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='String'>`n' (`p'%)</Data></Cell>";
								};
							};
						};
						local `countiv++';
					};
				};
				file write `outfile' "</ss:Row>";
				local `matcount++';
				local row=`row'+1;
			};
			capture local subcond=subinstr("`subcond'","if ","",.);
		};
		local ivd="`ivd_store'";
		foreach indep of local ivc {;
			local countiv=2;
			file write `outfile' "<ss:Row>";
			local title : variable label `indep';
			file write `outfile' "<Cell ss:Index='1' ss:StyleID='s10'><Data ss:Type='String'>`title'</Data></Cell>";
			local countiv=2;
			local matcount2=1;
			if "`dv'"!="dummy" quietly levelsof `dv';
			local borders2 : word count `r(levels)';
			if "`dv'"=="dummy" local borders2=1;
			local k="`r(levels)'";
			if "`dv'"=="dummy" local k=1;
			foreach var in `k' {;
				if "`dv'"!="dummy" local col : label (`dv') `var';
				foreach sub of local cycle {;
					if "`dv'"!="dummy" {;
						if "`sub'"!="Total" local subpop "if `split'==`sub' & `dv'==`var'";
						if "`sub'"=="Total" local subpop "if `dv'==`var'";
						if "`subcond'"!="" local subcond="& `subcond'";
						if "`cond'"!="" local cond="if `cond'";
						`display' dis in yellow "svy, subpop(`subpop' `subcond'): mean `indep' `cond'";
						capture `display' svy, subpop(`subpop' `subcond'): mean `indep' `cond';
					};
					if "`dv'"=="dummy" {;
						if "`sub'"!="Total" local subpop "if `split'==`sub'";
						if "`sub'"=="Total" local subpop "";
						if "`subcond'"!="" & "`sub'"=="Total" local subcond="if `subcond'";
						if "`cond'"!="" local cond="if `cond'";
						`display' dis in yellow "svy, subpop(`subpop' `subcond'): mean `indep' `cond'";
						capture `display' svy, subpop(`subpop' `subcond'): mean `indep' `cond';
					};
					if _rc==2000 {;
						local mean="";
						local stderr="";
					};
					else {;
						mat mean=e(b);
						local mean = el(mean,1,1);
						local mean = string(`mean',"`format'");
						mat stderr=e(V);
						local stderr = el(stderr,1,1);
						local stderr="sqrt(`stderr')";
						local stderr = string(`stderr',"`format'");
						local ci_l="`mean'-`stderr'";
						local ci_l = string(`ci_l',"`format'");
						local ci_u="`mean'+`stderr'";
						local ci_u = string(`ci_u',"`format'");
					};
					if "`options_mean'"=="mean" & "`options_ci'"=="" {;
						file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='Number'>`mean'</Data></Cell>";
					};
					else if "`options_ci'"=="ci" {;
						file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s8'><Data ss:Type='String'>`mean' (`ci_l', `ci_u')</Data></Cell>";
					};
					else {;
						file write `outfile' "<Cell ss:Index='`countiv'' ss:StyleID='s9'><Data ss:Type='String'>`mean' (`stderr')</Data></Cell>";
					};
					local `countiv++';
					capture local subcond=subinstr("`subcond'","if ","",.);
					capture local cond=subinstr("`cond'","if ","",.);
					capture local subcond=subinstr("`subcond'","&","",.);
				};
				local `matcount2++';
			};
			file write `outfile' "</ss:Row>";
		};
		local ivc="`ivc_store'";
		local ivd="`ivd_store'";
	};
	file write `outfile' "</Table>" _n;
	file write `outfile' "</Worksheet>" _n;
	file write `outfile' "</Workbook>" _n;
};

if "`save'"!="" local filename="`c(pwd)'/`save'.xml";
display as text "";
display as text "note: results saved to `filename'";
if "`excelpath'" !="" {;
	display `"{ stata `"winexec "`excelpath'" "`filename'" "': click here}"' _c;
	display as text " to open with Excel";
};
if "`calcpath'" !="" {;
	display `"{ stata `"winexec "`calcpath'" "`filename'" "': click here}"' _c;
	display as text " to open with Calc";
};


quietly cd ..;
end;