Update 02_hhchar.do

Update 02_hhchar.do

/*------------------------------------------------------------------------------
# Name:		02_hhchar
# Purpose:	Process household characteristics and education characteristics
# Author:	Tim Essam
# Created:	2015/2/26
# License:	MIT License
# Ado(s):	labutil, labutil2 (ssc install labutil, labutil2)
# Dependencies: copylables, attachlabels, 00_SetupFoldersGlobals.do
#-------------------------------------------------------------------------------
*/

clear
capture log close
log using "$pathlog/02_hhchar", replace
di in yellow "`c(current_date)' `c(current_time)'"

use "$pathraw/GSEC2.dta", replace

* Merge education data to household roster using the force command
merge 1:1 HHID PID using "$pathraw/GSEC4.dta", force
ren _merge gsecMerge
merge 1:1 HHID PID using "$pathraw/GSEC3.dta", force

/* Demographic list to calculate
1. Head of Household Sex
2. Relationship Status
*/

* Create head of household variable based on primary respondent and sex
g byte hoh = h2q4 == 1
la var hoh "Head of household"

g byte femhead = h2q3 == 2 & h2q4 == 1
la var femhead "Female head of household"

g agehead = h2q8 if hoh == 1
la var agehead "Age of head of household"

g ageSpouse = h2q8 if h2q4 == 2
la var ageSpouse "Age of spouse"

g ageheadsq = agehead^2
la var ageheadsq "Squared age of the head (for non-linear life experience)"

* Relationship status variables
g byte marriedHohm = h2q10 == 1 & hoh==1
la var marriedHohm "married HOH monogamous"

g byte marriedHoh = hoh ==1 & inlist(h2q10, 1, 2)
la var marriedHoh "married head of household (any type)"

g byte marriedHohp = h2q10 == 2 & hoh==1
la var marriedHohp "married HOH polygamous"

g byte divorcedHead = (h2q10 == 3 & hoh==1)
la var divorcedHead "divorced HoH"

g byte divorcedFemhead = (h2q10 == 3 & femhead == 1)
la var divorcedFemhead "divorced Female head of household"

g byte widowHead = (h2q10 == 4 & hoh==1)
la var widowHead "widowed HoH"

g byte widowFemhead = (h2q10 == 4 & femhead == 1)
la var widowFemhead "Widowed Female head of household"

g byte singleHead = (h2q10==5 & hoh==1)
la var singleHead "single HoH"

g byte singleFemhead = (h2q10==5 & femhead == 1)
la var singleFemhead "single HoH"

* Calculate household demographics (size, adult equivalent units, dep ratio, etc).

/* Household size - Household size refers to the number of usual members in a
household. Usual members are defined as those who have lived in the household
for at least 6 months in the past 12 months. However, it includes persons who
may have spent less than 6 months during the last 12 months in the household
but have joined the household with intention to live permanently or for an
extended period of time.
* http://www.ubos.org/UNHS0910/chapter2_householdcharacteristics.html */

*Create a flag variable for determining who is a usual member from above.
g byte hhmemb = (inlist(h2q7, 1, 2) & h2q5 >= 6)
la var hhmemb "Usual member of household"
egen hhsize = total(hhmemb), by(HHID)
la var hhsize "household size"

* Create gender ratio for households
g byte male = h2q3 == 1 & hhmemb == 1
g byte female = h2q3 == 2 & hhmemb == 1
la var male "male hh members"
la var female "female hh members"

egen msize = total(male), by(HHID)
la var msize "number of males in hh"

egen fsize = total(female), by(HHID)
la var fsize "number of females in hh"

* Create a gender ratio variable
g gendMix = msize/fsize
recode gendMix (. = 0) if fsize==0
la var gendMix "Ratio of males to females (1 = 1:1 mix)"

* Calculate age demographics (Youth)
* Make cuts at 0-5; 6-9; 10-14; 15-17; 18-24; 25-30; 31-35;
* Youth standard definition is 15-24;
* Uganda definition is 18-30 (http://www.ubos.org/onlinefiles/uploads/ubos/pdf%20documents/NCLS%20Report%202011_12.pdf)
egen youthtmp = cut(h2q8), at(0, 6, 10, 15, 18, 25, 31, 36) icodes
table youthtmp, c(min h2q8 max h2q8)
table h2q8 youthtmp

* Create binary variables for demographic categories
g byte under5tmp = inlist(youthtmp, 0) & hhmemb == 1
g byte under15tmp = inlist(youthtmp, 0, 1, 2) & hhmemb == 1
g byte under24tmp = inlist(youthtmp, 0, 1, 2, 3, 4) & hhmemb == 1
g byte youth15to24tmp = inlist(youthtmp, 3, 4) & hhmemb == 1
g byte youth18to30tmp = inlist(youthtmp, 4, 5) & hhmemb == 1

* Create total, male and female totals at the household level of each demographic
local demo under5 under15 under24 youth15to24 youth18to30
foreach x of local demo {
	egen `x'  = total(`x'tmp), by(HHID)
	egen `x'm = total(`x'tmp) if male == 1, by(HHID)
	egen `x'f = total(`x'tmp) if female == 1, by(HHID)

	la var `x' "total hh members `x'"
	la var `x'm "total male hh members `x'"
	la var `x'f "total female hh members `x'"
}
*end

/* Create intl. HH dependency ratio (age ranges appropriate for Bangladesh)
# HH Dependecy Ratio = [(# people 0-14 + those 65+) / # people aged 15-64 ] * 100 #
The dependency ratio is defined as the ratio of the number of members in the age groups
of 0â€“14 years and above 60 years to the number of members of working age (15â€“60 years).
The ratio is normally expressed as a percentage (data below are multiplied by 100 for pcts.*/
g byte numDepRatio = (h2q8 < 15 | h2q8 > 64) & hhmemb == 1
g byte demonDepRatio = numDepRatio != 1 & hhmemb == 1
egen totNumDepRatio = total(numDepRatio), by(HHID)
egen totDenomDepRatio = total(demonDepRatio), by(HHID)

* Check that numbers add to hhsize
assert hhsize == totNumDepRatio+totDenomDepRatio if hhmemb==1
g depRatio = (totNumDepRatio/totDenomDepRatio)*100 if totDenomDepRatio!=.
recode depRatio (. = 0) if totDenomDepRatio==0
la var depRatio "Dependency Ratio"

drop numDepRatio demonDepRatio totNumDepRatio totDenomDepRatio

* Calculate household labor shares (ages 12 - 60)
/* Household Labor Shares */
g byte hhLabort = (h2q8>= 12 & h2q8<60) & hhmemb == 1
egen hhlabor = total(hhLabort), by(HHID)
la var hhlabor "hh labor age>11 & < 60"

g byte mlabort = (h2q8>= 12 & h2q8<60 & male == 1 & hhmemb == 1)
egen mlabor = total(mlabort), by(HHID)
la var mlabor "hh male labor age>11 & <60"

g byte flabort = (h2q8>= 12 & h2q8<60 & female == 1 & hhmemb == 1)
egen flabor = total(flabort), by(HHID)
la var flabor "hh female labor age>11 & <60"
drop hhLabort mlabort flabort

* Male/Female labor share in hh
g mlaborShare = mlabor/hhlabor
recode mlaborShare (. = 0) if hhlabor == 0
la var mlaborShare "share of working age males in hh"

g flaborShare = flabor/hhlabor
recode flaborShare (. = 0) if hhlabor == 0
la var flaborShare "share of working age females in hh"

* Generate adult equivalents in household
g male10 	= 1
g fem10_19 	= 0.84
g fem20		= 0.72
g child10	= 0.60

g ae = .
replace ae = male10 if (h2q8 >=10 ) & male == 1 & hhmemb == 1
replace ae = fem10_19 if (h2q8 >= 10 & h2q8 < 20) & female == 1 & hhmemb == 1
replace ae = fem20 if (h2q8 >= 20) & female == 1 & hhmemb == 1
replace ae = child10 if (h2q8) < 10 & hhmemb == 1 & hhmemb == 1
la var ae "Adult equivalents in household"

egen adultEquiv = total(ae), by(HHID)
la var adultEquiv "Total adult equivalent units"

* Ethnicity codes of household members - create mixed hh codes or homogenous hh
* Codes found in UNPS2010.Household.Woman.Qx.Manual.pdf (pp. 132)
la def eth 11 "Acholi" 12 "Alur" 13 "Baamba" 14 "Babukusu" 15 "Babwisi" /*
*/ 16 "Bafumbira" 17 "Baganda" 18 "Bagisu" 19 "Bagungu" 20 "Bagwe" 21 "Bagwere"  /*
*/ 22 "Bahehe" 23 "Bahororo" 24 "Bakenyi" 25 "Bakiga" 26 "Bakhonzo" /*
*/ 27 "Banyabindi" 28 "Banyakole" 29 "Banyara" 30 "Banyarwanda" 31 "Banyole" /*
*/ 32 "Banyoro" 33 "Baruli" 34 "Basamia" 35 "Basoga" 36 "Basongora" /*
*/ 37 "Batagwenda" 38 "Batoro" 39 "Batuku" 40 "Batwa" 41 "Chope" 42 "Dodoth" /*
*/ 43 "Ethur" 44 "Ik (Teuso)" 45 "Iteso" 46 "Indian" 47 "Japadhola" 48 "Jie" /*
*/ 49 "Jonam" 50 "Kakwa" 51 "Karimojong" 52 "Kebu" 53 "Kuku" 54 "Kumam" /*
*/ 55 "Langi" 56 "Lendu" 57 "Lugbara" 58 "Madi" 59 "Mening" 60 "Mvuba" 61 "Napore"/*
*/ 62 "Nubi" 63 "Nyangia" 64 "Pokot" 65 "Sabiny" 66 "So (Tepeth)" 67 "Vonoma" 68 "Other"
la val h3q9 eth

* Create variable reflectin whether or not husband/wife are same ethnic mix
g ethHeadtmp = h3q9 if h2q4 == 1

egen ethHead = max(ethHeadtmp), by(HHID)
la val ethHead eth
la var ethHead "Ethnicity of head"

g ethSpousetmp = h3q9 if h2q4 == 2
egen ethSpouse = max(ethSpousetmp), by(HHID)
la val ethSpouse eth
la var ethSpouse "Ethnicity of spouse"

g byte mixedEth = (ethHead != ethSpouse) if marriedHoh==1 & ethHead!=. & ethSpouse !=.
replace mixedEth = 0 if mixedEth ==.
la var mixedEth "mixed ethnicity household"

egen mixedEthType = concat(ethHead ethSpouse) if ethHead!=. & ethSpouse !=. & ethHead!=ethSpouse, decode p("-")
encode mixedEthType, gen(mixedEthN)
drop mixedEthType
la var mixedEthN "type of mixed ethinicity household"

***********
* Orphans *
***********
g byte orphan = h3q2a == 3 & h3q5a == 3
egen orphanhh = total(orphan), by(HHID)
la var orphan "hh member is an ophan"
la var orphanhh "total number of orphans in hh"

********************
* Mosquito net use *
********************
* Assuming "don't know == no"
g byte mosqNet = inlist(h3q10, 1, 2) == 1 & hhmemb == 1
la var mosqNet "member slept under net"

* For net to be considered treated, we are requiring it to be dipped
g byte mosqNetT = inlist(h3q10, 2) == 1 & h3q12 == 1 & hhmemb == 1
la var mosqNetT "member slept under dipped net"

g byte mosqNetUt = inlist(h3q10, 1, 2) == 1 & h3q12 != 1 & hhmemb == 1
la var mosqNetUt "member slept under non-dipped net"

g byte mosqNetHead = (mosqNet == 1 & hoh == 1)
la var mosqNetHead "hoh slept under mosquito net"

g byte mosNetSpouse = (mosqNet == 1 & h2q4 == 2 & hhmemb == 1)
la var mosNetSpouse "spouse slept under mosquito net"

g byte mosNetChild = (mosqNet == 1 & h2q4 == 3 & hhmemb == 1 & h2q8<=18)
la var mosNetChild "Child (under 18) slept under mosquito net"

g byte mosNetGchild = (mosqNet == 1 & h2q4 == 4 & hhmemb == 1 & h2q8<=18)
la var mosNetGchild "Grand child (under 18) slept under mosquito net"

* Calculate % of hh member sleeping under net (also check if head slept under net)
egen mosNethh = total(mosqNet), by(HHID)
egen mosNetThh = total(mosqNetT), by(HHID)
la var mosNethh "total mosquito nets used in household"
la var mosNetThh "total treated mosquito nets used in household"

g pctMosNet = mosNethh / hhsize
g pctMosNetT = mosNetThh / hhsize
la var pctMosNet "Share of household using nets"
la var pctMosNetT "Share of household using treated nets"

* Calculate % of children under 18 sleeping under net
g byte chltmp = (h2q4 == 3 & hhmemb == 1 & h2q8<=18)
egen totChild = total(chltmp), by(HHID)

g byte gchltmp = (h2q4 == 4 & hhmemb == 1 & h2q8<=18)
egen totGchild = total(gchltmp), by(HHID)

egen mosNetChildtot = total(mosNetChild), by(HHID)
egen mosNetGchildtot = total(mosNetGchild), by(HHID)
la var mosNetChildtot "Total children using mosquito net"
la var mosNetGchildtot "Total grand-children using mosquito net"

g pctmosNetChild = mosNetChildtot / totChild
g pctmosNetGChild = mosNetGchildtot / totGchild

la var totChild "Total children in hh"
la var totGchild "Total grandchildren in hh"
la var pctmosNetChild "Share of children using nets"
la var pctmosNetGChild "Share of grandchildren using nets"

******************
* Skipping meals *
******************
g byte mealskip = (T6FQ13)==1 & T6FQ16 != 0 & hhmemb == 1
egen totMealSkip = total(mealskip), by(HHID)
g pctMealSkip = totMealSkip / hhsize
la var pctMealSkip "Share of household skipping meals"
la var mealskip "household member skipped meals"
la var totMealSkip "number of household members skipping meals"

******************
* Migration ties *
******************
* (DEFINED AS EVER MIGRATED: (1) Has lived in current village/town for one to five years
g byte hhmig = inlist(h3q15, 1, 2, 3, 4, 5)==1
egen hhmignet = max(hhmig) , by(HHID)
la var hhmignet "household migration network"

**********************
* Education outcomes *
**********************
/* Literacy is defined as oneâ€™s ability to read with understanding and to
 write meaningfully in any language. */
g byte literateHoh = h4q4 == 4 & hoh == 1
g byte literateSpouse = h4q4 == 4 & h2q4 == 2 & hhmemb == 1

la var literateHoh "Hoh is literate"
la var literateSpouse "Spouse is literate"

/* Education level values found in h4q7 defined using the following:
http://microdata.worldbank.org/index.php/catalog/565/datafile/F2/V110
http://www.classbase.com/countries/Uganda/Education-System
	No Education (0)
	Pre-Primary (Less than Primary Year 1)
	Primary Level (Years 1 - 7)
	Post-Primary Specialized Training or Certificate
	Junior Vocational/Technical (Years 8 - 10)
	Lower Secondary (Years 8 - 11)
	Upper Secondary (Years 11 - 13)
	Post-Secondary Specialized Training or Certificate
	Tertiary (Above Secondary other than Post-Secondary Specialized Training or Cer
tificate)
*/
g educ = .
la var educ "Education levels"
* No education (This includes:"Don't Know" and "2" Responses))
replace educ = 0 if inlist(h4q7, 2, 99)
* Pre-primary
replace educ = 1 if inlist(h4q7, 10)
* Primary
replace educ = 2 if inlist(h4q7, 11, 12, 13, 14, 15, 16, 17)
* Post-Primary Specialized Training or Certificate
replace educ = 3 if inlist(h4q7, 41)
* Junior Techincal/Vocational
replace educ = 4 if (inlist(h4q7, 21, 22, 23) | inlist(h4q9, 21, 22, 23))
* Lower Secondary
replace educ = 5 if (inlist(h4q7, 31, 32, 33, 34) | inlist(h4q9, 31, 32, 33, 34))
* Upper Secondary
replace educ = 6 if (inlist(h4q7, 35, 36) | inlist(h4q9, 35, 36))
* Post-Secondary Specialized Training or Certificate
replace educ = 7 if (inlist(h4q7, 51, 50) | inlist(h4q9, 50, 51))
* Tertiary
replace educ = 8 if (inlist(h4q7, 61) | inlist(h4q9, 61))

g educHoh = educ if hoh == 1
g educSpouse = educ if h2q4 == 2 & hhmemb == 1

lab def ed 0 "No education" 1 "Pre-primary" 2 "Primary" 3 "Post-Primary" /*
*/ 4 "Junior Techincal/Vocational " 5 "Lower Secondary" 6 "Upper Secondary" /*
*/ 7 "Post-Secondary Specialized" 8 "Tertiary"
la values educ ed
la values educHoh ed
la values educSpouse ed

* Create variable to reflect the maximum level of education in the household for those 25+
egen educAdult = max(educ) if h2q8>24 & hhmemb ==1, by(HHID)
egen educAdultM = max(educ) if h2q8>24 & hhmemb ==1 & male == 1, by(HHID)
egen educAdultF = max(educ) if h2q8>24 & hhmemb ==1 & female == 1, by(HHID)

* Max youth education in hh
egen educYouth = max(educ) if h2q8>17 & h2q8<31 & hhmemb == 1, by(HHID)
egen educYouthM = max(educ) if h2q8>17 & h2q8<31 & hhmemb == 1 & male == 1, by(HHID)
egen educYouthF = max(educ) if h2q8>17 & h2q8<31 & hhmemb == 1 & female == 1, by(HHID)

* Apply value labels
local edlist educ educHoh educSpouse educAdult educAdultM educAdultF educYouth educYouthM educYouthF
foreach x of local edlist {
	replace `x' = 0 if h4q5 == 1
	la values `x' ed
}
*end

la var educAdult "Highest adult education in household"
la var educAdultM "Highest male adult education in household"
la var educAdultF "Highest female adult education in household"
la var educHoh "Education of Hoh"
la var educSpouse "Education of spouse"
la var educYouth "Max education of youth"
la var educYouthM "Max education of male youth"
la var educYouthF "Max edcuation of female youth"

* Calculate school expenses for all regular household members
egen totSchoolExptmp = rsum2(h4q15a h4q15b h4q15c h4q15d h4q15e h4q15f)
replace totSchoolExptmp = h4q15g if totSchoolExp == 0
egen totSchoolExp = total(totSchoolExptmp), by(HHID)
la var totSchoolExp "Total school expenses for household"

g byte aidSchool = (h4q16 == 1)
la var aidSchool "HH member received school scholarship (all sources)"

* Create variables reflecting school dropouts
g byte quitEduchoh = (h4q8!=.  & hhmemb == 1 & hoh == 1)
la var quitEduc "stopped education early"

g byte quitEduc25  = (h4q8!=. & h2q8<= 25 & hhmemb == 1)
g byte quitEducPreg = (h4q8 == 13 & h2q8<=25 & hhmemb == 1)
la var quitEduc25 "Quit school early"
la var quitEducPreg "Quit school due to pregnancy (under 25)"

* Occupation of mother and father (do not know codes yet, need to get them).
g byte occupFath = h3q4 if hhmemb == 1
g byte oocupMoth = h3q7 if hhmemb == 1
la var occupFath "Father's occupation"
la var oocupMoth "Mother's occupation"

drop youthtmp under5tmp under15tmp under24tmp youth15to24tmp youth18to30tmp /*
*/  male10 fem10_19 fem20 child10 ethHeadtmp ethSpousetmp chltmp gchltmp /*
*/ hhmig totSchoolExptmp

* Retain only derived data for collapsing
qui ds(h2q* h4* T6* T2* LocID PID gsecMerge h3q* _merge educ ae), not
keep `r(varlist)'

preserve
keep if hhmemb == 1
save "$pathout/hhchar_ind.dta", replace
restore

* Collapse everything down to HH-level using max values for all vars
* Copy variable labels to reapply after collapse
qui include "$pathdo/copylabels.do"

qui ds(HHID), not
collapse (max) `r(varlist)', by(HHID)

* Reapply variable lables & value labels
qui include "$pathdo/attachlabels.do"

la val mixedEthN mixedEthN

* Summarize collapsed data and review for potential coding errors
sum

* Check missing values and determine which ones can be replaced with zero
mdesc
replace pctMosNet = 0 if pctMosNet == .
replace pctMosNetT = 0 if pctMosNetT == .
replace pctMealSkip = 0 if pctMealSkip == .

foreach x of varlist youth* under* {
	replace `x' = 0 if `x' == .
}
*end

* label values
foreach x of varlist  educHoh educSpouse educAdult educAdultM educAdultF educHoh educSpouse {
	la values `x' ed
	tab `x'
	}
*end

merge 1:1 HHID using "$pathout/Geovars.dta", gen(geo_merge)

* Save
save "$pathout/hhchar.dta", replace

* Keep a master file of only household id's for missing var checks
use "$pathraw/GSEC2", replace
keep HHID PID
save "$pathout/hhid.dta", replace

* Create an html file of the log for internet sharability
log2html "$pathlog/02_hhchar", replace
log close

/*------------------------------------------------------------------------------
# Name:		02_hhchar
# Purpose:	Process household characteristics and education characteristics
# Author:	Tim Essam
# Created:	2015/2/26
# License:	MIT License
# Ado(s):	labutil, labutil2 (ssc install labutil, labutil2)
# Dependencies: copylables, attachlabels, 00_SetupFoldersGlobals.do
#-------------------------------------------------------------------------------
*/

clear
capture log close
log using "$pathlog/02_hhchar", replace
di in yellow "`c(current_date)' `c(current_time)'"

use "$pathraw/GSEC2.dta", replace

* Merge education data to household roster using the force command
merge 1:1 HHID PID using "$pathraw/GSEC4.dta", force
ren _merge gsecMerge
merge 1:1 HHID PID using "$pathraw/GSEC3.dta", force

/* Demographic list to calculate
1. Head of Household Sex
2. Relationship Status
*/

* Create head of household variable based on primary respondent and sex
g byte hoh = h2q4 == 1
la var hoh "Head of household"

g byte femhead = h2q3 == 2 & h2q4 == 1
la var femhead "Female head of household"

g agehead = h2q8 if hoh == 1
la var agehead "Age of head of household"

g ageSpouse = h2q8 if h2q4 == 2
la var ageSpouse "Age of spouse"

g ageheadsq = agehead^2
la var ageheadsq "Squared age of the head (for non-linear life experience)"

* Relationship status variables
g byte marriedHohm = h2q10 == 1 & hoh==1
la var marriedHohm "married HOH monogamous"

g byte marriedHoh = hoh ==1 & inlist(h2q10, 1, 2)
la var marriedHoh "married head of household (any type)"

g byte marriedHohp = h2q10 == 2 & hoh==1
la var marriedHohp "married HOH polygamous"

g byte divorcedHead = (h2q10 == 3 & hoh==1)
la var divorcedHead "divorced HoH"

g byte divorcedFemhead = (h2q10 == 3 & femhead == 1)
la var divorcedFemhead "divorced Female head of household"

g byte widowHead = (h2q10 == 4 & hoh==1)
la var widowHead "widowed HoH"

g byte widowFemhead = (h2q10 == 4 & femhead == 1)
la var widowFemhead "Widowed Female head of household"

g byte singleHead = (h2q10==5 & hoh==1)
la var singleHead "single HoH"

g byte singleFemhead = (h2q10==5 & femhead)
la var singleFemhead "single HoH"

* Calculate household demographics (size, adult equivalent units, dep ratio, etc).

/* Household size - Household size refers to the number of usual members in a
household. Usual members are defined as those who have lived in the household
for at least 6 months in the past 12 months. However, it includes persons who
may have spent less than 6 months during the last 12 months in the household
but have joined the household with intention to live permanently or for an
extended period of time.
* http://www.ubos.org/UNHS0910/chapter2_householdcharacteristics.html */

*Create a flag variable for determining who is a usual member from above.
g byte hhmemb = (inlist(h2q7, 1, 2) & h2q5 >= 6)
egen hhsize = total(hhmemb), by(HHID)
la var hhsize "household size"

* Create sex ratio for households
g byte male = h2q3 == 1 & hhmemb == 1
g byte female = h2q3 == 2 & hhmemb == 1
la var male "male hh members"
la var female "female hh members"

egen msize = total(male), by(HHID)
la var msize "number of males in hh"

egen fsize = total(female), by(HHID)
la var fsize "number of females in hh"

* Create a gender ratio variable
g sexRatio = msize/fsize
recode sexRatio (. = 0) if fsize==0
la var sexRatio "Ratio of males to females in HH"

* Calculate age demographics (Youth)
* Make cuts at 0-5; 6-9; 10-14; 15-17; 18-24; 25-30; 31-35;
* Youth standard definition is 15-24;
* Uganda definition is 18-30 (http://www.ubos.org/onlinefiles/uploads/ubos/pdf%20documents/NCLS%20Report%202011_12.pdf)
egen youthtmp = cut(h2q8), at(0, 6, 10, 15, 18, 25, 31, 36) icodes
table youthtmp, c(min h2q8 max h2q8)
table h2q8 youthtmp

* Create binary variables for demographic categories
g byte under5tmp = inlist(youthtmp, 0) & hhmemb == 1
g byte under15tmp = inlist(youthtmp, 0, 1, 2) & hhmemb == 1
g byte under24tmp = inlist(youthtmp, 0, 1, 2, 3, 4) & hhmemb == 1
g byte youth15to24tmp = inlist(youthtmp, 3, 4) & hhmemb == 1
g byte youth18to30tmp = inlist(youthtmp, 4, 5) & hhmemb == 1

* Create total, male and female totals at the household level of each demographic
local demo under5 under15 under24 youth15to24 youth18to30
foreach x of local demo {
	egen `x'  = total(`x'tmp), by(HHID)
	egen `x'm = total(`x'tmp) if male == 1, by(HHID)
	egen `x'f = total(`x'tmp) if female == 2, by(HHID)

	la var `x' "total hh members `x'"
	la var `x'm "total male hh members `x'"
	la var `x'f "total female hh members `x'"
}
*end

/* Create intl. HH dependency ratio (age ranges appropriate for Bangladesh)
# HH Dependecy Ratio = [(# people 0-14 + those 65+) / # people aged 15-64 ] * 100 #
The dependency ratio is defined as the ratio of the number of members in the age groups
of 0â€“14 years and above 60 years to the number of members of working age (15â€“60 years).
The ratio is normally expressed as a percentage (data below are multiplied by 100 for pcts.*/
g byte numDepRatio = (h2q8 < 15 | h2q8 > 64) & hhmemb == 1
g byte demonDepRatio = numDepRatio != 1 & hhmemb == 1
egen totNumDepRatio = total(numDepRatio), by(HHID)
egen totDenomDepRatio = total(demonDepRatio), by(HHID)

* Check that numbers add to hhsize
assert hhsize == totNumDepRatio+totDenomDepRatio if hhmemb==1
g depRatio = (totNumDepRatio/totDenomDepRatio)*100 if totDenomDepRatio!=.
recode depRatio (. = 0) if totDenomDepRatio==0
la var depRatio "Dependency Ratio"

* Calculate household labor shares (ages 12 - 60)
/* Household Labor Shares */
g byte hhLabort = (h2q8>= 12 & h2q8<60) & hhmemb == 1
egen hhlabor = total(hhLabort), by(HHID)
la var hhlabor "hh labor age>11 & < 60"

g byte mlabort = (h2q8>= 12 & h2q8<60 & male == 1)
egen mlabor = total(mlabort), by(HHID)
la var mlabor "hh male labor age>11 & <60"

g byte flabort = (h2q8>= 12 & h2q8<60 & female == 1)
egen flabor = total(flabort), by(HHID)
la var flabor "hh female labor age>11 & <60"
drop hhLabort mlabort flabort

* Male/Female labor share in hh
g mlaborShare = mlabor/hhlabor
recode mlaborShare (. = 0) if hhlabor == 0
la var mlaborShare "share of working age males in hh"

g flaborShare = flabor/hhlabor
recode flaborShare (. = 0) if hhlabor == 0
la var flaborShare "share of working age females in hh"

* Generate adult equivalents in household
g male10 	= 1
g fem10_19 	= 0.84
g fem20		= 0.72
g child10	= 0.60

g ae = .
replace ae = male10 if (h2q8 >=10 ) & male == 1
replace ae = fem10_19 if (h2q8 >= 10 & h2q8 < 20) & female == 1
replace ae = fem20 if (h2q8 >= 20) & female == 1
replace ae = child10 if (h2q8) < 10 & hhmemb == 1
la var ae "Adult equivalents in household"

egen adultEquiv = total(ae), by(HHID)
la var adultEquiv "Total adult equivalent units"

* Ethnicity codes of household members - create mixed hh codes or homogenous hh
* Codes found in UNPS2010.Household.Woman.Qx.Manual.pdf (pp. 132)
la def eth 11 "Acholi" 12 "Alur" 13 "Baamba" 14 "Babukusu" 15 "Babwisi" /*
*/ 16 "Bafumbira" 17 "Baganda" 18 "Bagisu" 19 "Bagungu" 20 "Bagwe" 21 "Bagwere"  /*
*/ 22 "Bahehe" 23 "Bahororo" 24 "Bakenyi" 25 "Bakiga" 26 "Bakhonzo" /*
*/ 27 "Banyabindi" 28 "Banyakole" 29 "Banyara" 30 "Banyarwanda" 31 "Banyole" /*
*/ 32 "Banyoro" 33 "Baruli" 34 "Basamia" 35 "Basoga" 36 "Basongora" /*
*/ 37 "Batagwenda" 38 "Batoro" 39 "Batuku" 40 "Batwa" 41 "Chope" 42 "Dodoth" /*
*/ 43 "Ethur" 44 "Ik (Teuso)" 45 "Iteso" 46 "Indian" 47 "Japadhola" 48 "Jie" /*
*/ 49 "Jonam" 50 "Kakwa" 51 "Karimojong" 52 "Kebu" 53 "Kuku" 54 "Kumam" /*
*/ 55 "Langi" 56 "Lendu" 57 "Lugbara" 58 "Madi" 59 "Mening" 60 "Mvuba" 61 "Napore"/*
*/ 62 "Nubi" 63 "Nyangia" 64 "Pokot" 65 "Sabiny" 66 "So (Tepeth)" 67 "Vonoma" 68 "Other"
la val h3q9 eth

* Create variable reflectin whether or not husband/wife are same ethnic mix
g ethHeadtmp = h3q9 if h2q4 == 1

egen ethHead = max(ethHeadtmp), by(HHID)
la val ethHead eth

g ethSpousetmp = h3q9 if h2q4 == 2
egen ethSpouse = max(ethSpousetmp), by(HHID)
la val ethSpouse eth

g byte mixedEth = (ethHead != ethSpouse) if marriedHoh==1 & ethHead!=. & ethSpouse !=.
replace mixedEth = 0 if mixedEth ==.
la var mixedEth "mixed ethnicity household"

egen mixedEthType = concat(ethHead ethSpouse) if ethHead!=. & ethSpouse !=., decode p("-")
la var mixedEthType "type of mixed ethinicity household"

***********
* Orphans *
***********
g byte orphan = h3q2a == 3 & h3q5a == 3

**********************
* Education outcomes *
**********************
/* Literacy is defined as oneâ€™s ability to read with understanding and to
 write meaningfully in any language. */
g byte literateHoh = h4q4 == 4 & hoh == 1
g byte literateSpouse = h4q4 == 4 & h2q4 == 2 & hhmemb == 1

la var literateHoh "Hoh is literate"
la var literateSpouse "Spouse is literate"

/* Education level values found in h4q7 defined using the following:
http://microdata.worldbank.org/index.php/catalog/565/datafile/F2/V110
http://www.classbase.com/countries/Uganda/Education-System
	No Education (0)
	Pre-Primary (Less than Primary Year 1)
	Primary Level (Years 1 - 7)
	Post-Primary Specialized Training or Certificate
	Junior Vocational/Technical (Years 8 - 10)
	Lower Secondary (Years 8 - 11)
	Upper Secondary (Years 11 - 13)
	Post-Secondary Specialized Training or Certificate
	Tertiary (Above Secondary other than Post-Secondary Specialized Training or Cer
tificate)
*/
g educ = .
la var educ "Education levels"
* No education (This includes:"Don't Know" and "2" Responses))
replace educ = 0 if inlist(h4q7, 2, 99)
* Pre-primary
replace educ = 1 if inlist(h4q7, 10)
* Primary
replace educ = 2 if inlist(h4q7, 11, 12, 13, 14, 15, 16, 17)
* Post-Primary Specialized Training or Certificate
replace educ = 3 if inlist(h4q7, 41)
* Junior Techincal/Vocational
replace educ = 4 if inlist(h4q7, 21, 22, 23)
* Lower Secondary
replace educ = 5 if inlist(h4q7, 31, 32, 33, 34)
* Upper Secondary
replace educ = 6 if inlist(h4q7, 35, 36)
* Post-Secondary Specialized Training or Certificate
replace educ = 7 if inlist(h4q7, 51)
* Tertiary
replace educ = 8 if inlist(h4q7, 61)

g educHoh = educ if hoh == 1
g educSpouse = educ if h2q4 == 2 & hhmemb == 1

lab def ed 0 "No education" 1 "Pre-primary" 2 "Primary" 3 "Post-Primary" /*
*/ 4 "Junior Techincal/Vocational " 5 "Lower Secondary" 6 "Upper Secondary" /*
*/ 7 "Post-Secondary Specialized" 8 "Tertiary"
la values educ ed
la values educHoh ed
la values educSpouse ed

* Create variable to reflect the maximum level of education in the household for those 25+
egen educAdult = max(educ) if h2q8>24 & hhmemb ==1, by(HHID)
egen educAdultM = max(educ) if h2q8>24 & hhmemb ==1 & male == 1, by(HHID)
egen educAdultF = max(educ) if h2q8>24 & hhmemb ==1 & female == 1, by(HHID)

la var educAdult "Highest adult education in household"
la var educAdultM "Highest male adult education in household"
la var educAdultF "Highest female adult education in household"
la var educHoh "Education of Hoh"
la var educSpouse "Education of spouse"

* Calculate school expenses for all regular household members
egen totSchoolExptmp = rsum2(h4q15a h4q15b h4q15c h4q15d h4q15e h4q15f)
replace totSchoolExptmp = h4q15g if totSchoolExp == 0
egen totSchoolExp = total(totSchoolExptmp), by(HHID)
la var totSchoolExp "Total school expenses for household"

g byte aidSchool = (h4q16 == 1)
la var aidSchool "HH member received school scholarship (all sources)"

* Household member slept under mosquito net
g byte mosqTreatnet = h3q10 == 2 & hhmemb == 1
g byte mosqNet = (inlist(h3q10, 1, 2) & hhmemb == 1)

* Occupation of mother and father (do not know codes yet, need to get them).
g byte occupFath = h3q4 if hhmemb == 1
g byte oocupMoth = h3q7 if hhmemb == 1

drop totNumDepRatio totDenomDepRatio demonDepRatio numDepRatio male10 fem10_19 fem20 child10 /*
*/ under15tmp under24tmp hhmemb totSchoolExptmp

* Retain only derived data for collapsing
ds(h2q* h4* T6* T2* LocID PID gsecMerge h3q* _merge educ), not
keep `r(varlist)'

* Collapse everything down to HH-level using max values for all vars
* Copy variable labels to reapply after collapse
include "$pathdo/copylabels.do"

ds(HHID), not
collapse (max) `r(varlist)', by(HHID)

* Reapply variable lables & value labels
include "$pathdo/attachlabels.do"

* Summarize collapsed data and review for potential coding errors
sum

foreach x of varlist  educHoh educSpouse educAdult educAdultM educAdultF educHoh educSpouse {
	la values `x' ed
	tab `x'
	}
*end

merge 1:1 HHID using "$pathout/Geovars.dta", gen(geo_merge)

* Save
save "$pathout/hhchar.dta", replace
bob
* Keep a master file of only household id's for missing var checks
use "$pathraw/GSEC2", replace
keep HHID PID
save "$pathout/hhid.dta", replace

* Create an html file of the log for internet sharability
log2html "$pathlog/02_hhchar", replace
log close


Update 04_shocks.do

Update 04_shocks.do

/*-------------------------------------------------------------------------------
# Name:		04_shocks
# Purpose:	Process shock module including coping strategies
# Author:	Tim Essam, Ph.D.
# Created:	01/12/2015
# Owner:	USAID GeoCenter | OakStream Systems, LLC
# License:	MIT License
# Ado(s):	see below
#-------------------------------------------------------------------------------
*/
capture log close
clear
log using "$pathlog/04_shocks", replace
set more off

* Load in shock module to look at different shocks faced by hh
use "$pathraw/GSEC16.dta", clear

* List the label for shocks and their cross-walk codes
label list df_SHOCK df_SHOCKRECOVERY

* Tabulate total shocks reported
tab h16q00 if h16q01 == 1

* Calculate total shocks per household
g byte anyshock = (h16q01 ==1)
egen totShock = total(anyshock), by(HHID)
la var anyshock "household reported at least one shock"
la var totShock "total shocks"

* Quickly get a sense of frequency of shocks at HH-level
bys HHID: gen id = _n
tab totShock if id==1, mi

la var totShock "Total shocks"

* Create shock buckets
/* World Bank classifications
	Prices (inputs, outputs, food)
	Hazards (natural, droughts, floods)
	Employment (jobs, wages)
	Assets (house, land, livestock)
	Health (death, illness)
	Crime & Safety (theft, violence)	*/

* Create detailed shocks just in case they are needed
/*ag 		= other crop damage; input price increase; death of livestock
* aglow		= unusually low prices for ag output
* conflit 	= theft/robbery/violence
* disaster 	= drought, flood, heavy rains, landslides, fire
* drought	= drought/irregular rains
* financial	= loss of non-farm job
* pricedown = price fall of food items
* health	= death of hh member; illness of hh member
* other 	= loss of house; displacement; other
* theft		= theft of money/assets/output/etc.. */
g byte ag 		= inlist(h16q00, 104, 105, 106) &  inlist(h16q01, 1) == 1
g byte aglow	= inlist(h16q00, 107) &  inlist(h16q01, 1) == 1
g byte conflict = inlist(h16q00, 116) &  inlist(h16q01, 1) == 1
g byte drought	= inlist(h16q00, 101) &  inlist(h16q01, 1) == 1
g byte disaster = inlist(h16q00, 102, 103, 117) &  inlist(h16q01, 1) == 1
g byte financial= inlist(h16q00, 108, 109) &  inlist(h16q01, 1) == 1
g byte health 	= inlist(h16q00, 110, 111, 112, 113) &  inlist(h16q01, 1) == 1
g byte other 	= inlist(h16q00, 118, 116) &  inlist(h16q01, 1) == 1
g byte theft	= inlist(h16q00, 114, 115) &  inlist(h16q01, 1) == 1

g byte priceShk = inlist(h16q00, 106, 107) &  inlist(h16q01, 1) == 1
g byte hazardShk = inlist(h16q00, 101, 102, 103, 117) &  inlist(h16q01, 1) == 1
g byte employShk = inlist(h16q00, 108, 109) &  inlist(h16q01, 1) == 1
g byte assetShk = inlist(h16q00, 104, 105) &  inlist(h16q01, 1) == 1
g byte healthShk = inlist(h16q00, 110, 111, 112, 113) &  inlist(h16q01, 1) == 1
g byte crimeShk = inlist(h16q00, 114, 115, 116) &  inlist(h16q01, 1) == 1

la var ag "Agriculture"
la var aglow "Low ag output prices"
la var conflict "Conflict"
la var disaster "Disaster"
la var financial "Financial"
la var health "Health"
la var other "Other"
la var theft "Theft"
la var drought "lack of rainfall or drought"

la var priceShk "price shocks  (inputs, outputs, food)"
la var hazardShk "hazard schock (flood, fire, drought, landslide)"
la var employShk "Employment (jobs, wages)"
la var assetShk "Assets (house, land, livestock)"
la var healthShk "Health (death, illness)"
la var crimeShk "Crime & Safety (theft, violence)"

* How did households cope?
label list df_SHOCKRECOVERY

/* Coping Mechanisms - What are good v. bad coping strategies? From (Heltberg et al., 2013)
	http://siteresources.worldbank.org/EXTNWDR2013/Resources/8258024-1352909193861/
	8936935-1356011448215/8986901-1380568255405/WDR15_bp_What_are_the_Sources_of_Risk_Oviedo.pdf
	Good Coping:: use of savings, credit, asset sales, additional employment,
					migration, and assistance
	Bad Coping : increases vulnerabiliy* compromising health and edudcation
				expenses, productive asset sales, conumsumption reductions
				*/

g byte goodcope = inlist(h16q4a, 1, 2, 4, 5, 6, 7, 8, 9, 10, 12) &  inlist(h16q01, 1) == 1
g byte badcope 	= inlist(h16q4a, 3, 13, 14, 15, 11) &  inlist(h16q01, 1) == 1
g byte incReduction = h16q3a == 1

la var goodcope "Good primary coping strategy"
la var badcope "Bad primary coping strategy"
la var incReduction "Income reduction due to shock"

* Collapse data to househld level and merge back with GIS info
ds (h16* result_code id ), not
keep `r(varlist)'

* Collapse everything down to HH-level using max values for all vars
* Copy variable labels to reapply after collapse
include "$pathdo/copylabels.do"

#delimit ;
	collapse (max) ag aglow conflict drought disaster financial health other theft
	priceShk hazardShk employShk healthShk crimeShk assetShk
	goodcope badcope incReduction anyshock totShock, by(HHID) fast;
#delimit cr

* Reapply variable lables & value labels
include "$pathdo/attachlabels.do"

* Save shock data and merge with geovars
compress
merge 1:1 HHID using "$pathout/Geovars.dta", gen(geo_merge)
drop geo_merge

* Merge in the data with sampling information
merge 1:1 HHID using "$pathraw\GSEC1.dta", gen(_merge)
keep if _merge==3

* Survey set the data to account for complex sampling design in variance calculations
* svyset comm [pweight=mult], strata(stratum) singleunit(centered)

* Export a cut for GIS work
export delimited "$pathexport/shocks.csv", replace

save "$pathout/shocks.dta", replace
log2html "$pathlog/04_shocks", replace
capture log close

/*-------------------------------------------------------------------------------
# Name:		04_shocks
# Purpose:	Create preliminary analysis Uganda
# Author:	Tim Essam, Ph.D.
# Created:	01/12/2015
# Owner:	USAID GeoCenter | OakStream Systems, LLC
# License:	MIT License
# Ado(s):	see below
#-------------------------------------------------------------------------------
*/
capture log close
clear
log using "$pathlog/04_shocks", replace
set more off

* Load in shock module to look at different shocks faced by hh
use "$pathraw/GSEC16.dta", clear

* List the label for shocks and their cross-walk codes
label list df_SHOCK df_SHOCKRECOVERY

* Tabulate total shocks reported
tab h16q00 if h16q01 == 1

* Calculate total shocks per household
g byte anyshock = (h16q01 ==1)
egen totShock = total(anyshock), by(HHID)
la var anyshock "household reported at least one shock"
la var totShock "total shocks"

* Quickly get a sense of frequency of shocks at HH-level
bys HHID: gen id = _n
tab totShock if id==1, mi

la var totShock "Total shocks"

* Create shock buckets
/* World Bank classifications
	Prices (inputs, outputs, food)
	Hazards (natural, droughts, floods)
	Employment (jobs, wages)
	Assets (house, land, livestock)
	Health (death, illness)
	Crime & Safety (theft, violence)	*/

* Create detailed shocks just in case they are needed
/*ag 		= other crop damage; input price increase; death of livestock
* aglow		= unusually low prices for ag output
* conflit 	= theft/robbery/violence
* disaster 	= drought, flood, heavy rains, landslides, fire
* drought	= drought/irregular rains
* financial	= loss of non-farm job
* pricedown = price fall of food items
* health	= death of hh member; illness of hh member
* other 	= loss of house; displacement; other
* theft		= theft of money/assets/output/etc.. */
g byte ag 		= inlist(h16q00, 104, 105, 106) &  inlist(h16q01, 1) == 1
g byte aglow	= inlist(h16q00, 107) &  inlist(h16q01, 1) == 1
g byte conflict = inlist(h16q00, 116) &  inlist(h16q01, 1) == 1
g byte drought	= inlist(h16q00, 101) &  inlist(h16q01, 1) == 1
g byte disaster = inlist(h16q00, 102, 103, 117) &  inlist(h16q01, 1) == 1
g byte financial= inlist(h16q00, 108, 109) &  inlist(h16q01, 1) == 1
g byte health 	= inlist(h16q00, 110, 111, 112, 113) &  inlist(h16q01, 1) == 1
g byte other 	= inlist(h16q00, 118, 116) &  inlist(h16q01, 1) == 1
g byte theft	= inlist(h16q00, 114, 115) &  inlist(h16q01, 1) == 1

g byte priceShk = inlist(h16q00, 106, 107) &  inlist(h16q01, 1) == 1
g byte hazardShk = inlist(h16q00, 101, 102, 103, 117) &  inlist(h16q01, 1) == 1
g byte employShk = inlist(h16q00, 108, 109) &  inlist(h16q01, 1) == 1
g byte assetShk = inlist(h16q00, 104, 105) &  inlist(h16q01, 1) == 1
g byte healthShk = inlist(h16q00, 110, 111, 112, 113) &  inlist(h16q01, 1) == 1
g byte crimeShk = inlist(h16q00, 114, 115, 116) &  inlist(h16q01, 1) == 1

la var ag "Agriculture"
la var aglow "Low ag output prices"
la var conflict "Conflict"
la var disaster "Disaster"
la var financial "Financial"
la var health "Health"
la var other "Other"
la var theft "Theft"
la var drought "lack of rainfall or drought"

la var priceShk "price shocks  (inputs, outputs, food)"
la var hazardShk "hazard schock (flood, fire, drought, landslide)"
la var employShk "Employment (jobs, wages)"
la var assetShk "Assets (house, land, livestock)"
la var healthShk "Health (death, illness)"
la var crimeShk "Crime & Safety (theft, violence)"

* How did households cope?
label list df_SHOCKRECOVERY

/* Coping Mechanisms - What are good v. bad coping strategies? From (Heltberg et al., 2013)
	http://siteresources.worldbank.org/EXTNWDR2013/Resources/8258024-1352909193861/
	8936935-1356011448215/8986901-1380568255405/WDR15_bp_What_are_the_Sources_of_Risk_Oviedo.pdf
	Good Coping:: use of savings, credit, asset sales, additional employment,
					migration, and assistance
	Bad Coping : increases vulnerabiliy* compromising health and edudcation
				expenses, productive asset sales, conumsumption reductions
				*/

g byte goodcope = inlist(h16q4a, 1, 2, 4, 5, 6, 7, 8, 9, 10, 12) &  inlist(h16q01, 1) == 1
g byte badcope 	= inlist(h16q4a, 3, 13, 14, 15, 11) &  inlist(h16q01, 1) == 1
g byte incReduction = h16q3a == 1

la var goodcope "Good primary coping strategy"
la var badcope "Bad primary coping strategy"
la var incReduction "Income reduction due to shock"

* Collapse data to househld level and merge back with GIS info
ds (h16* result_code id ), not
keep `r(varlist)'

* Collapse everything down to HH-level using max values for all vars
* Copy variable labels to reapply after collapse
include "$pathdo2/copylabels.do"

#delimit ;
	collapse (max) ag aglow conflict drought disaster financial health other theft
	priceShk hazardShk employShk healthShk crimeShk assetShk
	goodcope badcope incReduction anyshock totShock, by(HHID) fast;
#delimit cr

* Reapply variable lables & value labels
include "$pathdo2/attachlabels.do"

* Save shock data and merge with geovars
compress
merge 1:1 HHID using "$pathout/Geovars.dta", gen(geo_merge)
drop geo_merge

* Merge in the data with sampling information
merge 1:1 HHID using "$pathraw\GSEC1.dta", gen(_merge)
keep if _merge==3

* Survey set the data to account for complex sampling design in variance calculations
* svyset comm [pweight=mult], strata(stratum) singleunit(centered)

* Export a cut for GIS work
export delimited "$pathexport/shocks.csv", replace

save "$pathout/shocks.dta", replace
log2html "$pathlog/04_shocks", replace
capture log close


iefodler - remove synonym unitofobs

iefodler - remove synonym unitofobs

cap program drop 	iefolder
	program define	iefolder

	syntax anything, PROJectfolder(string) [ABBreviation(string)]

	***Todo
	*Test that a folder called DataWork already exist (unless new project)
	*Test that old master do file exist
	*allow to specifiy other place for master do file

	/***************************************************

		Parse input

	***************************************************/

	*Parse out the sub-command
	gettoken subcommand item : anything

	*Parse out the item type and the item name
	gettoken itemType itemName : item

	*Make sure that the item name is only one word
	gettoken itemName rest : itemName

	*Clean up the input
	local subcomand = trim("`subcommand'")
	local itemType 	= trim("`itemType'")
	local itemName 	= trim("`itemName'")

	di "SubCommand 	`subcommand'"
	di "ItemType 	`itemType'"
	di "ItemName	`itemName'"

	if "`rest'" != "" {

		di as error "You have specified to many words. Spaces are not allowed."
		error 198
	}

	 /***************************************************

		Test input

	***************************************************/

	local sub_commands "new"
	local itemTypes "project round master"

	*Test if subcommand is valid
	if `:list subcommand in sub_commands' == 0 {

		di as error "{phang}You have not used a valid subcommand. See help file for details.{p_end}"
		error 198
	}

	*Test if item type is valid
	if `:list itemType in itemTypes' == 0 {

		di as error "{phang}You have not used a valid item type. See help file for details.{p_end}"
		error 198
	}

	*Test that item name is used when item type is anything but project
	else if ("`itemType'" != "project" & "`itemName'" == "" ) {

		di as error "{phang}You must specify a name of the `itemType'. See help file for details.{p_end}"
		error 198
	}

	di "All tests ok"

	/***************************************************

		Start making updates to the project folder

	***************************************************/

	*Create a temporary textfile
	tempname 	newHandle
	tempfile	newTextFile

	cap file close 	`newHandle'
		file open  	`newHandle' using "`newTextFile'", text write append

	*Create a global pointing to the main data folder
	global dataWorkFolder 	"`projectfolder'/DataWork"
	global encryptFolder 	"$dataWorkFolder/EncryptedData"

	if "`subcommand'" == "new" {

		di "Subcommand: New"

		*Creating a new project
		if "`itemType'" == "project" {

			di "ItemType: Project"
			iefolder_newProject "`projectfolder'" `newHandle'
		}
		*Creating a new round
		else if "`itemType'" == "round" {

			*Use the full item name if abbrevaition was not specified
			if "`abb'" == "" local abb "`itemName'"

			di "ItemType: round"
			iefolder_newRound `newHandle' "`itemName'" "`abb'"
		}
		*Creating a new level of observation for master data set
		else if "`itemType'" == "master" {

			di "ItemType: master/unitofobs"
			di `"iefolder_newMaster	`newHandle' "`itemName'""'
			iefolder_newMaster	`newHandle' "`itemName'"
		}
	}

	*Closing the new main master dofile handle
	file close 		`newHandle'

	*Copy the new master dofile from the tempfile to the original position
	copy "`newTextFile'"  "$dataWorkFolder/Project_MasterDofile.do" , replace

end

	/***************************************************

		Here are all functions for combination of
		subcommand and item type

	***************************************************/

cap program drop 	iefolder_newProject
	program define	iefolder_newProject

		args projectfolder newHandle

		*Test if folder where to create new folder exist
		checkFolderExists "`projectfolder'" "parent"

		*Test that the new folder does not already exist
		checkFolderExists "$dataWorkFolder" "new"

		mkdir "$dataWorkFolder"

		******************************
		*Writing master do file header
		******************************

		*Write intro part with description of project,
		mdofle_p0 `newHandle' project

		*Write flolder globals section header and the root folders
		mdofle_p1 `newHandle' "`projectfolder'"

		*Write globals section header and the root folders
		mdofle_p2 `newHandle'

		*Write section that runs sub-master dofiles
		mdofle_p3 `newHandle' project

end

cap program drop 	iefolder_newRound
	program define	iefolder_newRound

	args subHandle rndName rndAbb

	di "new round command"

	*Test if folder where to create new folder exist
	checkFolderExists "$dataWorkFolder" "parent"

	*Test that the new folder does not already exist
	checkFolderExists "$dataWorkFolder/`rndName'" "new"

	*Old file reference
	tempname 	oldHandle
	local 		oldTextFile 	"$dataWorkFolder/Project_MasterDofile.do"

	file open `oldHandle' using `"`oldTextFile'"', read
	file read `oldHandle' line

	*Locals needed for the section devider
	local partNum 		= 0 //Keeps track of the part number

	while r(eof)==0 {

		*Do not interpret macros
		local line : subinstr local line "\$"  "\\$"
		local line : subinstr local line "\`"  "\\`"

		parseReadLine `"`line'"'

		if `r(ief_line)' == 0 {

			*This is a regular line of code. It should be copied as-is. No action needed.
			file write	`subHandle' `"`line'"' _n

		}
		else if `r(ief_line)' == 1 {

			**This is a line of code with a devisor written by
			* iefodler. New additions to a section are always added right before an end of section line.

			*return list

			**This is NOT an end of section line. Nothing will be written here
			* but we test that there is no confict with previous names
			if `r(ief_end)' == 0 {

					*Test if it is an end of globals section as we are writing a new
					if "`r(sectionName)'" == "monitor" {

					*Write devisor for this section
					writeDevisor 			`subHandle' 1 RoundGlobals rounds `rndName' `rndAbb'

					*Write the globals to the master do file and create the folders
					newRndFolderAndGlobals 	`rndName' `rndAbb' "dataWorkFolder" `subHandle'

					*Write an empty line before the end devisor
					file write		`subHandle' "" _n

				}
				else {

					*Test that the folder name about to be used is not already in use
					if "`r(itemName)'" == "`rndName'" {
						di as error "{phang}The new round name `rndName' is already in use. No new folders are creaetd and the master do-files has not been changed.{p_end}"
						error 507
					}

					*Test that the folder name about to be used is not already in use
					if "`r(itemAbb)'" == "`rndAbb'" {
						di as error "{phang}The new round abbreviation `rndAbb' is already in use. No new folders are creaetd and the master do-files has not been changed.{p_end}"
						error 507
					}

				}

				*Copy the line as is
				file write		`subHandle' `"`line'"' _n
			}

			**This is an end of section line. We will add the new content here
			* before writing the end of section line
			else if `r(ief_end)' == 1 {

				*Test if it is an end of globals section as we are writing a new
				if "`r(partName)'" == "End_RunDofiles" {

					*Write devisor for this section
					writeDevisor 			`subHandle' 3 RunDofiles `rndName' `rndAbb'

					*Write the
					file write  `subHandle' ///
						_col(4)"if (0) { //Change the 0 to 1 to run the `rndName' master dofile" _n ///
						_col(8) `"do ""' _char(36) `"`rndAbb'/`rndName'_master_dofile.do" "' _n ///
						_col(4)"}" ///
						_n

					*Write an empty line before the end devisor
					file write		`subHandle' "" _n

				}

				*Write the end of section line
				file write		`subHandle' `"`line'"' _n
			}
		}

		*Read next file and repeat the while loop
		file read `oldHandle' line
	}

	*Close the old file.
	file close `oldHandle'

end

cap program drop 	iefolder_newMaster
	program define	iefolder_newMaster

	args subHandle obsName

	di "new master command"

	*************
	*create folder in encrypred ID key master

	*Test if folder where to create new folder exist
	checkFolderExists "$dataWorkFolder/EncryptedData/IDMasterKey" "parent"

	*Test that the new folder does not already exist
	checkFolderExists "$dataWorkFolder/EncryptedData/IDMasterKey/`obsName'" "new"

	*Create the folder
	mkdir "$dataWorkFolder/EncryptedData/IDMasterKey/`obsName'"

	*************
	*create folder in masterdata
	global mastData 	"$dataWorkFolder/MasterData"

	*Old file reference
	tempname 	oldHandle
	local 		oldTextFile 	"$dataWorkFolder/Project_MasterDofile.do"

	file open `oldHandle' using `"`oldTextFile'"', read
	file read `oldHandle' line

	*Locals needed for the section devider
	local partNum 		= 0 //Keeps track of the part number

	while r(eof)==0 {

		*Do not interpret macros
		local line : subinstr local line "\$"  "\\$"
		local line : subinstr local line "\`"  "\\`"

		parseReadLine `"`line'"'

		if `r(ief_line)' == 1 & `r(ief_line)' == 1 & `r(ief_end)' == 0  & "`r(sectionName)'" == "rawData" {

			*Create master data folder and add global to folder in master do file
			cap createFolderWriteGlobal "`obsName'"  "mastData"  	mastData_`obsName'	`subHandle'

			if _rc == 693 {

				*Test if folder where to create new fodler exist
				checkFolderExists "$mastData" "parent"

				*Test that the new folder does not already exist
				checkFolderExists "$mastData\`obsName'" "new"

				*If that folder exist, problem
				di as error "{phang}could not create new folder, folder name might already exist "
				error _rc

			}
			else if _rc != 0 {

				*Unexpected error, run the exact command name again and throw the error to user
				createFolderWriteGlobal "`obsName'"  "mastData"  	mastData_`obsName'	`subHandle'
			}

			file write		`subHandle' `"`line'"' _n

		}
		else {

			*Copy the line as is
			file write		`subHandle' `"`line'"' _n

		}

		*Read next file and repeat the while loop
		file read `oldHandle' line
	}

	*Close the old file.
	file close `oldHandle'

	*Create master data subfolders
	createFolderWriteGlobal "MasterDataSets"  	"mastData_`obsName'"  masterDataSets
	createFolderWriteGlobal "Dofiles"  			"mastData_`obsName'"  mastDataDo
	createFolderWriteGlobal "Sampling"  		"mastData_`obsName'"  mastDataSamp
	createFolderWriteGlobal "Treatment"  		"mastData_`obsName'"  mastDataTreat

end

cap program drop 	iefolder
	program define	iefolder

	syntax anything, PROJectfolder(string) [ABBreviation(string)]

	***Todo
	*Test that a folder called DataWork already exist (unless new project)
	*Test that old master do file exist
	*allow to specifiy other place for master do file

	/***************************************************

		Parse input

	***************************************************/

	*Parse out the sub-command
	gettoken subcommand item : anything

	*Parse out the item type and the item name
	gettoken itemType itemName : item

	*Make sure that the item name is only one word
	gettoken itemName rest : itemName

	*Clean up the input
	local subcomand = trim("`subcommand'")
	local itemType 	= trim("`itemType'")
	local itemName 	= trim("`itemName'")

	di "SubCommand 	`subcommand'"
	di "ItemType 	`itemType'"
	di "ItemName	`itemName'"

	if "`rest'" != "" {

		di as error "You have specified to many words. Spaces are not allowed."
		error 198
	}

	 /***************************************************

		Test input

	***************************************************/

	local sub_commands "new"
	local itemTypes "project round master unitofobs"

	*Test if subcommand is valid
	if `:list subcommand in sub_commands' == 0 {

		di as error "{phang}You have not used a valid subcommand. See help file for details.{p_end}"
		error 198
	}

	*Test if item type is valid
	if `:list itemType in itemTypes' == 0 {

		di as error "{phang}You have not used a valid item type. See help file for details.{p_end}"
		error 198
	}

	*Test that item name is used when item type is anything but project
	else if ("`itemType'" != "project" & "`itemName'" == "" ) {

		di as error "{phang}You must specify a name of the `itemType'. See help file for details.{p_end}"
		error 198
	}

	di "All tests ok"

	/***************************************************

		Start making updates to the project folder

	***************************************************/

	*Create a temporary textfile
	tempname 	newHandle
	tempfile	newTextFile

	cap file close 	`newHandle'
		file open  	`newHandle' using "`newTextFile'", text write append

	*Create a global pointing to the main data folder
	global dataWorkFolder 	"`projectfolder'/DataWork"
	global encryptFolder 	"$dataWorkFolder/EncryptedData"

	if "`subcommand'" == "new" {

		di "Subcommand: New"

		*Creating a new project
		if "`itemType'" == "project" {

			di "ItemType: Project"
			iefolder_newProject "`projectfolder'" `newHandle'
		}
		*Creating a new round
		else if "`itemType'" == "round" {

			*Use the full item name if abbrevaition was not specified
			if "`abb'" == "" local abb "`itemName'"

			di "ItemType: round"
			iefolder_newRound `newHandle' "`itemName'" "`abb'"
		}
		*Creating a new level of observation for master data set
		else if "`itemType'" == "master" | "`itemType'" == "unitofobs" {

			di "ItemType: master/unitofobs"
			di `"iefolder_newMaster	`newHandle' "`itemName'""'
			iefolder_newMaster	`newHandle' "`itemName'"
		}
	}

	*Closing the new main master dofile handle
	file close 		`newHandle'

	*Copy the new master dofile from the tempfile to the original position
	copy "`newTextFile'"  "$dataWorkFolder/Project_MasterDofile.do" , replace

end

	/***************************************************

		Here are all functions for combination of
		subcommand and item type

	***************************************************/

cap program drop 	iefolder_newProject
	program define	iefolder_newProject

		args projectfolder newHandle

		*Test if folder where to create new folder exist
		checkFolderExists "`projectfolder'" "parent"

		*Test that the new folder does not already exist
		checkFolderExists "$dataWorkFolder" "new"

		mkdir "$dataWorkFolder"

		******************************
		*Writing master do file header
		******************************

		*Write intro part with description of project,
		mdofle_p0 `newHandle' project

		*Write flolder globals section header and the root folders
		mdofle_p1 `newHandle' "`projectfolder'"

		*Write globals section header and the root folders
		mdofle_p2 `newHandle'

		*Write section that runs sub-master dofiles
		mdofle_p3 `newHandle' project

end

cap program drop 	iefolder_newRound
	program define	iefolder_newRound

	args subHandle rndName rndAbb

	di "new round command"

	*Test if folder where to create new folder exist
	checkFolderExists "$dataWorkFolder" "parent"

	*Test that the new folder does not already exist
	checkFolderExists "$dataWorkFolder/`rndName'" "new"

	*Old file reference
	tempname 	oldHandle
	local 		oldTextFile 	"$dataWorkFolder/Project_MasterDofile.do"

	file open `oldHandle' using `"`oldTextFile'"', read
	file read `oldHandle' line

	*Locals needed for the section devider
	local partNum 		= 0 //Keeps track of the part number

	while r(eof)==0 {

		*Do not interpret macros
		local line : subinstr local line "\$"  "\\$"
		local line : subinstr local line "\`"  "\\`"

		parseReadLine `"`line'"'

		if `r(ief_line)' == 0 {

			*This is a regular line of code. It should be copied as-is. No action needed.
			file write	`subHandle' `"`line'"' _n

		}
		else if `r(ief_line)' == 1 {

			**This is a line of code with a devisor written by
			* iefodler. New additions to a section are always added right before an end of section line.

			*return list

			**This is NOT an end of section line. Nothing will be written here
			* but we test that there is no confict with previous names
			if `r(ief_end)' == 0 {

					*Test if it is an end of globals section as we are writing a new
					if "`r(sectionName)'" == "monitor" {

					*Write devisor for this section
					writeDevisor 			`subHandle' 1 RoundGlobals rounds `rndName' `rndAbb'

					*Write the globals to the master do file and create the folders
					newRndFolderAndGlobals 	`rndName' `rndAbb' "dataWorkFolder" `subHandle'

					*Write an empty line before the end devisor
					file write		`subHandle' "" _n

				}
				else {

					*Test that the folder name about to be used is not already in use
					if "`r(itemName)'" == "`rndName'" {
						di as error "{phang}The new round name `rndName' is already in use. No new folders are creaetd and the master do-files has not been changed.{p_end}"
						error 507
					}

					*Test that the folder name about to be used is not already in use
					if "`r(itemAbb)'" == "`rndAbb'" {
						di as error "{phang}The new round abbreviation `rndAbb' is already in use. No new folders are creaetd and the master do-files has not been changed.{p_end}"
						error 507
					}

				}

				*Copy the line as is
				file write		`subHandle' `"`line'"' _n
			}

			**This is an end of section line. We will add the new content here
			* before writing the end of section line
			else if `r(ief_end)' == 1 {

				*Test if it is an end of globals section as we are writing a new
				if "`r(partName)'" == "End_RunDofiles" {

					*Write devisor for this section
					writeDevisor 			`subHandle' 3 RunDofiles `rndName' `rndAbb'

					*Write the
					file write  `subHandle' ///
						_col(4)"if (0) { //Change the 0 to 1 to run the `rndName' master dofile" _n ///
						_col(8) `"do ""' _char(36) `"`rndAbb'/`rndName'_master_dofile.do" "' _n ///
						_col(4)"}" ///
						_n

					*Write an empty line before the end devisor
					file write		`subHandle' "" _n

				}

				*Write the end of section line
				file write		`subHandle' `"`line'"' _n
			}
		}

		*Read next file and repeat the while loop
		file read `oldHandle' line
	}

	*Close the old file.
	file close `oldHandle'

end

cap program drop 	iefolder_newMaster
	program define	iefolder_newMaster

	args subHandle obsName

	di "new master command"

	*************
	*create folder in encrypred ID key master

	*Test if folder where to create new folder exist
	checkFolderExists "$dataWorkFolder/EncryptedData/IDMasterKey" "parent"

	*Test that the new folder does not already exist
	checkFolderExists "$dataWorkFolder/EncryptedData/IDMasterKey/`obsName'" "new"

	*Create the folder
	mkdir "$dataWorkFolder/EncryptedData/IDMasterKey/`obsName'"

	*************
	*create folder in masterdata
	global mastData 	"$dataWorkFolder/MasterData"

	*Old file reference
	tempname 	oldHandle
	local 		oldTextFile 	"$dataWorkFolder/Project_MasterDofile.do"

	file open `oldHandle' using `"`oldTextFile'"', read
	file read `oldHandle' line

	*Locals needed for the section devider
	local partNum 		= 0 //Keeps track of the part number

	while r(eof)==0 {

		*Do not interpret macros
		local line : subinstr local line "\$"  "\\$"
		local line : subinstr local line "\`"  "\\`"

		parseReadLine `"`line'"'

		if `r(ief_line)' == 1 & `r(ief_line)' == 1 & `r(ief_end)' == 0  & "`r(sectionName)'" == "rawData" {

			*Create master data folder and add global to folder in master do file
			cap createFolderWriteGlobal "`obsName'"  "mastData"  	mastData_`obsName'	`subHandle'

			if _rc == 693 {

				*Test if folder where to create new fodler exist
				checkFolderExists "$mastData" "parent"

				*Test that the new folder does not already exist
				checkFolderExists "$mastData\`obsName'" "new"

				*If that folder exist, problem
				di as error "{phang}could not create new folder, folder name might already exist "
				error _rc

			}
			else if _rc != 0 {

				*Unexpected error, run the exact command name again and throw the error to user
				createFolderWriteGlobal "`obsName'"  "mastData"  	mastData_`obsName'	`subHandle'
			}

			file write		`subHandle' `"`line'"' _n

		}
		else {

			*Copy the line as is
			file write		`subHandle' `"`line'"' _n

		}

		*Read next file and repeat the while loop
		file read `oldHandle' line
	}

	*Close the old file.
	file close `oldHandle'

	*Create master data subfolders
	createFolderWriteGlobal "MasterDataSets"  	"mastData_`obsName'"  masterDataSets
	createFolderWriteGlobal "Dofiles"  			"mastData_`obsName'"  mastDataDo
	createFolderWriteGlobal "Sampling"  		"mastData_`obsName'"  mastDataSamp
	createFolderWriteGlobal "Treatment"  		"mastData_`obsName'"  mastDataTreat

end


ieboilstart -set more off PERM

ieboilstart -set more off PERM

add permanently option to ieboilstart

	*! version 4.0 18APR2017  Kristoffer Bjarkefur kbjarkefur@worldbank.org

	capture program drop ieboilstart
	program ieboilstart , rclass

	qui {

		syntax ,  Versionnumber(string) [noclear maxvar(numlist) matsize(numlist) Quietly veryquietly Custom(string) setmem(string) ]

		version 11.0

		/*********************************

			Check user specifed version
			and apply it is valid

		*********************************/

		local stata_versions "11.0 11.1 11.2 12.0 12.1 13.0 13.1 14.0 14.1"

		if `:list versionnumber in stata_versions' == 0 {

			di as error "{phang}Only recent major releases are allowed. One decimal must always be included. The releases currently allowed are:{break}`stata_versions'{p_end}"
			di ""
			error 198
			exit
		}

		*Return the value
		return local version "version `versionnumber'"

		*Set the version specfied in the command
		version `versionnumber'

		/*********************************

			Check settings related to older
			versions and Stata IC

		*********************************/

		*Test that maxvar is not set in combination when using Stata IC
		if 	!(c(MP) == 1 | c(SE) == 1) & "`maxvar'" != "" {

			di as error "{phang}In Stata IC the maximum number of variables allowed is fixed at 2,047 and maxvar() is therefore not allowed.{p_end}"
			error 198
		}

		if 	"`setmem'" != ""	{

			if `versionnumber' >= 12  {

				di as error "{phang}Option setmem() is only allowed when setting the version number to 11. Setmem() is only applicable in Stata 11 or eralier, but those versions wont be able to run this file as the version number is set to 12 or higher.{p_end}"
				error 198
			}

			*Split the memory setting string into value and byte unit
			local mem_strlen 	= strlen("`setmem'") -1
			local mem_number	= substr("`setmem'",  1 , `mem_strlen')
			local mem_bytetype	= substr("`setmem'", -1 , 1)

			*Test that the number part is a number and a integer
			cap confirm integer number `mem_number'
			if _rc {

				di as error "{phang}The value in setmem(`setmem') must be a number (followed by either b, k, m or g). See {help memory} for details.{p_end}"
				error _rc
			}

			*Test that the byte type is not anything else than b, k, m or g
			if !`=inlist(lower("`mem_bytetype'"), "b", "k", "m", "g")' {

				di as error "{phang}The last character in setmem(`setmem') must be either b, k, m or g. See {help memory} for details.{p_end}""
				error 7

			}
		}
		else {

			*Default value is 50M. This is probably too little, but
			*it will safely work. And users can manually increase this
			local setmem "50M"

		}

		/*********************************

			Check input for maxvar and matsize
			if specified, other wise set
			maximum value allowed.

		*********************************/

		*Setting maxvar requires a cleared memory. Therefore
		*maxvar() and noclear cannot be used at the same time.
		if "`maxvar'" != "" & "`clear'" != "" {

			di as error "{phang}It is not possible to set allowed maximum numbers of variables without clearing the data. noclear and maxvar() can therefore not be specified at the same time{p_end}"
			di ""
			error 198
			exit
		}

		foreach maxlocal in maxvar matsize {

			*Set locals with the max and min values fox maxvar and matsize
			if "`maxlocal'" == "maxvar" {
				local max 32767
				local min 2048
			}
			if "`maxlocal'" == "matsize" {
				local max 11000
				local min 10
			}

			*Test if user set a value for this value
			if "``maxlocal''" != "" {

				*If user specified a value, test that it is between the min and the max
				if !(``maxlocal'' >= `min' & ``maxlocal'' <= `max') {

					di as error "{phang}`maxlocal' must be between `min' and `max' (inclusive) if you are using Stata SE and Stata MP. You entered ``maxlocal''.{p_end}"
					di ""
					*Throw appropriate error if below or above error
					if ``maxlocal'' < `min' error 910
					if ``maxlocal'' > `max' error 912
					exit
				}
			}

			else {
				*User did not specify value, use ieboilstart's defaults:

				if "`maxlocal'" == "maxvar" {
					*Set maxvar to max value allowed as this is often an issue when working with large survey data
					local `maxlocal' `max'
				}
				if "`maxlocal'" == "matsize" {
					*Set to the default as the maximum is rarely requered.
					local `maxlocal' 400
				}
			}
		}

		/*********************************

			Set the settings

		*********************************/

		local setDispLocal "{col 5}{ul:Settings set by this command:}"

		*Set basic memory limits
		if "`clear'" == "" {

			*Setting
			clear all
			local setDispLocal "`setDispLocal'{break}{col 5}clear all"

			**Setting maxvar not allowed in Stata IC.
			if 	(c(MP) == 1 | c(SE) == 1) {

				*Setting
				set maxvar `maxvar'
				local setDispLocal "`setDispLocal'{break}{col 5}set maxvar {col 22}`maxvar'"
			}
		}

		*Setting
		set matsize `matsize'
		local setDispLocal "`setDispLocal'{break}{col 5}set matsize {col 22}`matsize'"

		****************
		*Memory	settings

		*For compatibility with Stata 11 the do file includes and if/else
		*condition testing version number. The memoroy settings introduced
		*in Stata 12 will be applied to Stata version more recent than
		*Stata 11, and set memory will be applied to Stata 11.
		if c(stata_version) >= 12 {

			*Setting
			set niceness 5
			local setDispLocal "`setDispLocal'{break}{col 5}set niceness{col 22}5"

			*These settings cannot be modified with data in memory
			if "`clear'" == "" {

				*Settings
				set min_memory 0
				set max_memory .
				local setDispLocal "`setDispLocal'{break}{col 5}set min_memory {col 22}0{break}{col 5}set max_memory {col 22}."

				*Set segment size to the largest value allowed by the operative system
				if c(bit) == 64 {
					*Setting
					set segmentsize	32m
					local setDispLocal "`setDispLocal'{break}{col 5}set segmentsize	{col 22}32m"
				}
				else {
					*Setting
					set segmentsize	16m
					local setDispLocal "`setDispLocal'{break}{col 5}set segmentsize	{col 22}16m"
				}
			}
		}
		else {

			*If this dofile is generated in Stata 11 then only the old
			*way of setting memory is included. This will be ignored by
			*more recent versios of Stata

			*Setting
			set memory `setmem'
			local setDispLocal "`setDispLocal'{break}{col 5}set memory {col 22}`setmem'"

		}

		*********************
		*Set default settings
		set more 		off , perm
		pause 			on
		set varabbrev 	off
		local setDispLocal "`setDispLocal'{break}{col 5}set more {col 22}off {col 28}, perm"
		local setDispLocal "`setDispLocal'{break}{col 5}pause {col 22}on"
		local setDispLocal "`setDispLocal'{break}{col 5}set varabbrev {col 22}off"

		/*********************************

			Add custom lines of code

		*********************************/

		if `"`custom'"' != "" {

			local setDispLocal `"`setDispLocal'{break} {break}{col 5}{ul:User specified settings:}"'

			*Create a local with the rowlabel input to be tokenized
			local custom_code_lines `custom'

			while `"`custom_code_lines'"' != "" {

				*Parsing name and label pair
				gettoken code_line custom_code_lines : custom_code_lines, parse("@")

				*Removing leadning or trailing spaces
				local code_line = trim(`"`code_line'"')

				*Set custom setting
				local setDispLocal `"`setDispLocal'{break}{col 5}`code_line'"'
				`code_line'

				*Parse char is not removed by gettoken
				local custom_code_lines = subinstr(`"`custom_code_lines'"' ,"@","",1)
			}
		}

		/*********************************

			Create return value and output message

		*********************************/

		if "`quietly'" == "" & "`veryquietly'" == "" {

			noi di ""
			noi di "{phang}{err:DISCLAIMER:} Due to how settings works in Stata, this command can only attempt to harmonize settings as much as possible across users, but no guarantee can be given that all commands will always behave identical unless the exact same version and type of Stata is used.{p_end}"
			noi di ""
			noi di `"`setDispLocal'"'
		}

		if  "`veryquietly'" == "" {

			noi di ""
			noi di "{phang}{err:IMPORTANT:} The most important setting of this command cannot be set inside the command due to technical reasons. The setting has been prepared by this command, and you only need to write \`r(version)' after this command (include the apostrophes).{p_end}"

		}

	}
	end

	*! version 4.0 18APR2017  Kristoffer Bjarkefur kbjarkefur@worldbank.org

	capture program drop ieboilstart
	program ieboilstart , rclass

	qui {

		syntax ,  Versionnumber(string) [noclear maxvar(numlist) matsize(numlist) Quietly veryquietly Custom(string) setmem(string) ]

		version 11.0

		/*********************************

			Check user specifed version
			and apply it is valid

		*********************************/

		local stata_versions "11.0 11.1 11.2 12.0 12.1 13.0 13.1 14.0 14.1"

		if `:list versionnumber in stata_versions' == 0 {

			di as error "{phang}Only recent major releases are allowed. One decimal must always be included. The releases currently allowed are:{break}`stata_versions'{p_end}"
			di ""
			error 198
			exit
		}

		*Return the value
		return local version "version `versionnumber'"

		*Set the version specfied in the command
		version `versionnumber'

		/*********************************

			Check settings related to older
			versions and Stata IC

		*********************************/

		*Test that maxvar is not set in combination when using Stata IC
		if 	!(c(MP) == 1 | c(SE) == 1) & "`maxvar'" != "" {

			di as error "{phang}In Stata IC the maximum number of variables allowed is fixed at 2,047 and maxvar() is therefore not allowed.{p_end}"
			error 198
		}

		if 	"`setmem'" != ""	{

			if `versionnumber' >= 12  {

				di as error "{phang}Option setmem() is only allowed when setting the version number to 11. Setmem() is only applicable in Stata 11 or eralier, but those versions wont be able to run this file as the version number is set to 12 or higher.{p_end}"
				error 198
			}

			*Split the memory setting string into value and byte unit
			local mem_strlen 	= strlen("`setmem'") -1
			local mem_number	= substr("`setmem'",  1 , `mem_strlen')
			local mem_bytetype	= substr("`setmem'", -1 , 1)

			*Test that the number part is a number and a integer
			cap confirm integer number `mem_number'
			if _rc {

				di as error "{phang}The value in setmem(`setmem') must be a number (followed by either b, k, m or g). See {help memory} for details.{p_end}"
				error _rc
			}

			*Test that the byte type is not anything else than b, k, m or g
			if !`=inlist(lower("`mem_bytetype'"), "b", "k", "m", "g")' {

				di as error "{phang}The last character in setmem(`setmem') must be either b, k, m or g. See {help memory} for details.{p_end}""
				error 7

			}
		}
		else {

			*Default value is 50M. This is probably too little, but
			*it will safely work. And users can manually increase this
			local setmem "50M"

		}

		/*********************************

			Check input for maxvar and matsize
			if specified, other wise set
			maximum value allowed.

		*********************************/

		*Setting maxvar requires a cleared memory. Therefore
		*maxvar() and noclear cannot be used at the same time.
		if "`maxvar'" != "" & "`clear'" != "" {

			di as error "{phang}It is not possible to set allowed maximum numbers of variables without clearing the data. noclear and maxvar() can therefore not be specified at the same time{p_end}"
			di ""
			error 198
			exit
		}

		foreach maxlocal in maxvar matsize {

			*Set locals with the max and min values fox maxvar and matsize
			if "`maxlocal'" == "maxvar" {
				local max 32767
				local min 2048
			}
			if "`maxlocal'" == "matsize" {
				local max 11000
				local min 10
			}

			*Test if user set a value for this value
			if "``maxlocal''" != "" {

				*If user specified a value, test that it is between the min and the max
				if !(``maxlocal'' >= `min' & ``maxlocal'' <= `max') {

					di as error "{phang}`maxlocal' must be between `min' and `max' (inclusive) if you are using Stata SE and Stata MP. You entered ``maxlocal''.{p_end}"
					di ""
					*Throw appropriate error if below or above error
					if ``maxlocal'' < `min' error 910
					if ``maxlocal'' > `max' error 912
					exit
				}
			}

			else {
				*User did not specify value, use ieboilstart's defaults:

				if "`maxlocal'" == "maxvar" {
					*Set maxvar to max value allowed as this is often an issue when working with large survey data
					local `maxlocal' `max'
				}
				if "`maxlocal'" == "matsize" {
					*Set to the default as the maximum is rarely requered.
					local `maxlocal' 400
				}
			}
		}

		/*********************************

			Set the settings

		*********************************/

		local setDispLocal "{col 5}{ul:Settings set by this command:}"

		*Set basic memory limits
		if "`clear'" == "" {

			*Setting
			clear all
			local setDispLocal "`setDispLocal'{break}{col 5}clear all"

			**Setting maxvar not allowed in Stata IC.
			if 	(c(MP) == 1 | c(SE) == 1) {

				*Setting
				set maxvar `maxvar'
				local setDispLocal "`setDispLocal'{break}{col 5}set maxvar {col 22}`maxvar'"
			}
		}

		*Setting
		set matsize `matsize'
		local setDispLocal "`setDispLocal'{break}{col 5}set matsize {col 22}`matsize'"

		****************
		*Memory	settings

		*For compatibility with Stata 11 the do file includes and if/else
		*condition testing version number. The memoroy settings introduced
		*in Stata 12 will be applied to Stata version more recent than
		*Stata 11, and set memory will be applied to Stata 11.
		if c(stata_version) >= 12 {

			*Setting
			set niceness 5
			local setDispLocal "`setDispLocal'{break}{col 5}set niceness{col 22}5"

			*These settings cannot be modified with data in memory
			if "`clear'" == "" {

				*Settings
				set min_memory 0
				set max_memory .
				local setDispLocal "`setDispLocal'{break}{col 5}set min_memory {col 22}0{break}{col 5}set max_memory {col 22}."

				*Set segment size to the largest value allowed by the operative system
				if c(bit) == 64 {
					*Setting
					set segmentsize	32m
					local setDispLocal "`setDispLocal'{break}{col 5}set segmentsize	{col 22}32m"
				}
				else {
					*Setting
					set segmentsize	16m
					local setDispLocal "`setDispLocal'{break}{col 5}set segmentsize	{col 22}16m"
				}
			}
		}
		else {

			*If this dofile is generated in Stata 11 then only the old
			*way of setting memory is included. This will be ignored by
			*more recent versios of Stata

			*Setting
			set memory `setmem'
			local setDispLocal "`setDispLocal'{break}{col 5}set memory {col 22}`setmem'"

		}

		*********************
		*Set default settings
		set more 		off
		pause 			on
		set varabbrev 	off
		local setDispLocal "`setDispLocal'{break}{col 5}set more {col 22}off"
		local setDispLocal "`setDispLocal'{break}{col 5}pause {col 22}on"
		local setDispLocal "`setDispLocal'{break}{col 5}set varabbrev {col 22}off"

		/*********************************

			Add custom lines of code

		*********************************/

		if `"`custom'"' != "" {

			local setDispLocal `"`setDispLocal'{break} {break}{col 5}{ul:User specified settings:}"'

			*Create a local with the rowlabel input to be tokenized
			local custom_code_lines `custom'

			while `"`custom_code_lines'"' != "" {

				*Parsing name and label pair
				gettoken code_line custom_code_lines : custom_code_lines, parse("@")

				*Removing leadning or trailing spaces
				local code_line = trim(`"`code_line'"')

				*Set custom setting
				local setDispLocal `"`setDispLocal'{break}{col 5}`code_line'"'
				`code_line'

				*Parse char is not removed by gettoken
				local custom_code_lines = subinstr(`"`custom_code_lines'"' ,"@","",1)
			}
		}

		/*********************************

			Create return value and output message

		*********************************/

		if "`quietly'" == "" & "`veryquietly'" == "" {

			noi di ""
			noi di "{phang}{err:DISCLAIMER:} Due to how settings works in Stata, this command can only attempt to harmonize settings as much as possible across users, but no guarantee can be given that all commands will always behave identical unless the exact same version and type of Stata is used.{p_end}"
			noi di ""
			noi di `"`setDispLocal'"'
		}

		if  "`veryquietly'" == "" {

			noi di ""
			noi di "{phang}{err:IMPORTANT:} The most important setting of this command cannot be set inside the command due to technical reasons. The setting has been prepared by this command, and you only need to write \`r(version)' after this command (include the apostrophes).{p_end}"

		}

	}
	end


redo: turn off overaggressive -flto

redo: turn off overaggressive -flto

# jgfs2
# (c) 2013 Justin Gottula
# The source code of this project is distributed under the terms of the
# simplified BSD license. See the LICENSE file for details.

exec >&2

TARGET=$1
TARGET_BASE=$2
OUTPUT=$3

export CC="ccache gcc"
export CXX="ccache g++"
export AR=ar

export CFLAGS="-std=gnu11 -O1 -ggdb -Wall -Wextra -Wno-unused-parameter \
-Wno-unused-function -include stddef.h -include stdbool.h -include stdint.h \
-Isrc"
export CXXFLAGS="-std=c++11 -O1 -ggdb -Wall -Wextra -Wno-unused-parameter \
-Wno-unused-function -include cstddef -include cstdint -Isrc"

DEFINES="-D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -DFUSE_USE_VERSION=26 \
-DDEBUG_FATAL"

LIB_OUT="bin/libjgfs2.a"
LIB_SRC=$(find lib -type f -iname '*.c')
LIB_OBJS=${LIB_SRC[@]//.c/.o}
LIB_LIBS=(-lm -lbsd -luuid)

FUSE_OUT="bin/fuse.jgfs2"
FUSE_SRC=$(find src/fuse -type f -iname '*.c')
FUSE_OBJS=${FUSE_SRC[@]//.c/.o}
FUSE_LIBS=(-lfuse)

TEST_OUT="bin/test.jgfs2"
TEST_SRC=$(find src/test -type f -iname '*.c')
TEST_OBJS=${TEST_SRC[@]//.c/.o}
TEST_LIBS=()

VIEW_OUT="bin/view.jgfs2"
VIEW_SRC=$(find src/view -type f -iname '*.c')
VIEW_OBJS=${VIEW_SRC[@]//.c/.o}
VIEW_LIBS=()

MKFS_OUT="bin/mkfs.jgfs2"
MKFS_SRC=$(find src/mkfs -type f -iname '*.c')
MKFS_OBJS=${MKFS_SRC[@]//.c/.o}
MKFS_LIBS=()

FSCK_OUT="bin/fsck.jgfs2"
FSCK_SRC=$(find src/fsck -type f -iname '*.c')
FSCK_OBJS=${FSCK_SRC[@]//.c/.o}
FSCK_LIBS=()

DEFRAG_OUT="bin/defrag.jgfs2"
DEFRAG_SRC=$(find src/defrag -type f -iname '*.c')
DEFRAG_OBJS=${DEFRAG_SRC[@]//.c/.o}
DEFRAG_LIBS=()

FSCTL_OUT="bin/fsctl.jgfs2"
FSCTL_SRC=$(find src/fsctl -type f -iname '*.c')
FSCTL_OBJS=${FSCTL_SRC[@]//.c/.o}
FSCTL_LIBS=()

ATTR_OUT="bin/attr.jgfs2"
ATTR_SRC=$(find src/attr -type f -iname '*.c')
ATTR_OBJS=${ATTR_SRC[@]//.c/.o}
ATTR_LIBS=()

function target_cxx_dep {
	$CXX $CXXFLAGS $DEFINES -o${TARGET//.o/.dep} -MM -MG ${TARGET//.o/.cxx}
}

function target_cxx {
	target_cxx_dep
	read DEPS <${TARGET//.o/.dep}
	redo-ifchange ${DEPS#*:}

	$CXX $CXXFLAGS $DEFINES -o$OUTPUT -c ${TARGET//.o/.cxx}
}

function target_cxx_link {
	redo-ifchange $OBJS

	$CXX $CFXXLAGS $LIBS -o$OUTPUT $OBJS
}

function target_c_dep {
	$CC $CFLAGS $DEFINES -o${TARGET//.o/.dep} -MM -MG ${TARGET//.o/.c}
}

function target_c {
	target_c_dep
	read DEPS <${TARGET//.o/.dep}
	redo-ifchange ${DEPS#*:}

	$CC $CFLAGS $DEFINES -o$OUTPUT -c ${TARGET//.o/.c}
}

function target_c_link {
	redo-ifchange $OBJS

	$CC $CFLAGS $LIBS -o$OUTPUT $OBJS
}

function target_lib {
	redo-ifchange $OBJS

	$AR rcs $OUTPUT $OBJS
}

case "$TARGET" in
all)
	redo lib fuse test view mkfs fsck defrag fsctl attr ;;
lib)
	redo-ifchange $LIB_OUT ;;
fuse)
	redo-ifchange $FUSE_OUT ;;
test)
	redo-ifchange $TEST_OUT ;;
view)
	redo-ifchange $VIEW_OUT ;;
mkfs)
	redo-ifchange $MKFS_OUT ;;
fsck)
	redo-ifchange $FSCK_OUT ;;
defrag)
	redo-ifchange $DEFRAG_OUT ;;
fsctl)
	redo-ifchange $FSCTL_OUT ;;
attr)
	redo-ifchange $ATTR_OUT ;;
$LIB_OUT)
	LIBS=""
	OBJS="${LIB_OBJS[@]}"
	target_lib
	;;
$FUSE_OUT)
	LIBS="${FUSE_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${FUSE_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$TEST_OUT)
	LIBS="${TEST_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${TEST_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$VIEW_OUT)
	LIBS="${VIEW_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${VIEW_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$MKFS_OUT)
	LIBS="${MKFS_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${MKFS_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$FSCK_OUT)
	LIBS="${FSCK_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${FSCK_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$DEFRAG_OUT)
	LIBS="${DEFRAG_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${DEFRAG_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$FSCTL_OUT)
	LIBS="${FSCTL_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${FSCTL_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$ATTR_OUT)
	LIBS="${ATTR_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${ATTR_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
*.o)
	if [[ -e "${TARGET//.o/.cxx}" ]]; then
		target_cxx
	elif [[ -e "${TARGET//.o/.c}" ]]; then
		target_c
	else
		echo "cannot find source file for '$TARGET'"
		exit 1
	fi
	;;
clean)
	rm -rf $(find bin/ -type f)
	rm -rf $(find src/ lib/ -type f -iname *.o)
	rm -rf $(find src/ lib/ -type f -iname *.dep)
	;;
backup)
	cd .. && tar -acvf backup/jgfs2-$(date +'%Y%m%d-%H%M').tar.xz jgfs2/
	;;
*)
	echo "unknown target '$TARGET'"
	exit 1
	;;
esac

# jgfs2
# (c) 2013 Justin Gottula
# The source code of this project is distributed under the terms of the
# simplified BSD license. See the LICENSE file for details.

exec >&2

TARGET=$1
TARGET_BASE=$2
OUTPUT=$3

export CC="ccache gcc"
export CXX="ccache g++"
export AR=ar

export CFLAGS="-std=gnu11 -O1 -flto -ggdb -Wall -Wextra -Wno-unused-parameter \
-Wno-unused-function -include stddef.h -include stdbool.h -include stdint.h \
-Isrc"
export CXXFLAGS="-std=c++11 -O1 -flto -ggdb -Wall -Wextra \
-Wno-unused-parameter -Wno-unused-function -include cstddef -include cstdint \
-Isrc"

DEFINES="-D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -DFUSE_USE_VERSION=26 \
-DDEBUG_FATAL"

LIB_OUT="bin/libjgfs2.a"
LIB_SRC=$(find lib -type f -iname '*.c')
LIB_OBJS=${LIB_SRC[@]//.c/.o}
LIB_LIBS=(-lm -lbsd -luuid)

FUSE_OUT="bin/fuse.jgfs2"
FUSE_SRC=$(find src/fuse -type f -iname '*.c')
FUSE_OBJS=${FUSE_SRC[@]//.c/.o}
FUSE_LIBS=(-lfuse)

TEST_OUT="bin/test.jgfs2"
TEST_SRC=$(find src/test -type f -iname '*.c')
TEST_OBJS=${TEST_SRC[@]//.c/.o}
TEST_LIBS=()

VIEW_OUT="bin/view.jgfs2"
VIEW_SRC=$(find src/view -type f -iname '*.c')
VIEW_OBJS=${VIEW_SRC[@]//.c/.o}
VIEW_LIBS=()

MKFS_OUT="bin/mkfs.jgfs2"
MKFS_SRC=$(find src/mkfs -type f -iname '*.c')
MKFS_OBJS=${MKFS_SRC[@]//.c/.o}
MKFS_LIBS=()

FSCK_OUT="bin/fsck.jgfs2"
FSCK_SRC=$(find src/fsck -type f -iname '*.c')
FSCK_OBJS=${FSCK_SRC[@]//.c/.o}
FSCK_LIBS=()

DEFRAG_OUT="bin/defrag.jgfs2"
DEFRAG_SRC=$(find src/defrag -type f -iname '*.c')
DEFRAG_OBJS=${DEFRAG_SRC[@]//.c/.o}
DEFRAG_LIBS=()

FSCTL_OUT="bin/fsctl.jgfs2"
FSCTL_SRC=$(find src/fsctl -type f -iname '*.c')
FSCTL_OBJS=${FSCTL_SRC[@]//.c/.o}
FSCTL_LIBS=()

ATTR_OUT="bin/attr.jgfs2"
ATTR_SRC=$(find src/attr -type f -iname '*.c')
ATTR_OBJS=${ATTR_SRC[@]//.c/.o}
ATTR_LIBS=()

function target_cxx_dep {
	$CXX $CXXFLAGS $DEFINES -o${TARGET//.o/.dep} -MM -MG ${TARGET//.o/.cxx}
}

function target_cxx {
	target_cxx_dep
	read DEPS <${TARGET//.o/.dep}
	redo-ifchange ${DEPS#*:}

	$CXX $CXXFLAGS $DEFINES -o$OUTPUT -c ${TARGET//.o/.cxx}
}

function target_cxx_link {
	redo-ifchange $OBJS

	$CXX $CFXXLAGS $LIBS -o$OUTPUT $OBJS
}

function target_c_dep {
	$CC $CFLAGS $DEFINES -o${TARGET//.o/.dep} -MM -MG ${TARGET//.o/.c}
}

function target_c {
	target_c_dep
	read DEPS <${TARGET//.o/.dep}
	redo-ifchange ${DEPS#*:}

	$CC $CFLAGS $DEFINES -o$OUTPUT -c ${TARGET//.o/.c}
}

function target_c_link {
	redo-ifchange $OBJS

	$CC $CFLAGS $LIBS -o$OUTPUT $OBJS
}

function target_lib {
	redo-ifchange $OBJS

	$AR rcs $OUTPUT $OBJS
}

case "$TARGET" in
all)
	redo lib fuse test view mkfs fsck defrag fsctl attr ;;
lib)
	redo-ifchange $LIB_OUT ;;
fuse)
	redo-ifchange $FUSE_OUT ;;
test)
	redo-ifchange $TEST_OUT ;;
view)
	redo-ifchange $VIEW_OUT ;;
mkfs)
	redo-ifchange $MKFS_OUT ;;
fsck)
	redo-ifchange $FSCK_OUT ;;
defrag)
	redo-ifchange $DEFRAG_OUT ;;
fsctl)
	redo-ifchange $FSCTL_OUT ;;
attr)
	redo-ifchange $ATTR_OUT ;;
$LIB_OUT)
	LIBS=""
	OBJS="${LIB_OBJS[@]}"
	target_lib
	;;
$FUSE_OUT)
	LIBS="${FUSE_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${FUSE_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$TEST_OUT)
	LIBS="${TEST_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${TEST_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$VIEW_OUT)
	LIBS="${VIEW_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${VIEW_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$MKFS_OUT)
	LIBS="${MKFS_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${MKFS_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$FSCK_OUT)
	LIBS="${FSCK_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${FSCK_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$DEFRAG_OUT)
	LIBS="${DEFRAG_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${DEFRAG_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$FSCTL_OUT)
	LIBS="${FSCTL_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${FSCTL_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
$ATTR_OUT)
	LIBS="${ATTR_LIBS[@]} ${LIB_LIBS[@]}"
	OBJS="${ATTR_OBJS[@]} $LIB_OUT"
	target_c_link
	;;
*.o)
	if [[ -e "${TARGET//.o/.cxx}" ]]; then
		target_cxx
	elif [[ -e "${TARGET//.o/.c}" ]]; then
		target_c
	else
		echo "cannot find source file for '$TARGET'"
		exit 1
	fi
	;;
clean)
	rm -rf $(find bin/ -type f)
	rm -rf $(find src/ lib/ -type f -iname *.o)
	rm -rf $(find src/ lib/ -type f -iname *.dep)
	;;
backup)
	cd .. && tar -acvf backup/jgfs2-$(date +'%Y%m%d-%H%M').tar.xz jgfs2/
	;;
*)
	echo "unknown target '$TARGET'"
	exit 1
	;;
esac