*! recocl: Recodes municipality's codes for Chile (CL)
*! Version 1.0.0 January 6, 2021
*! Author: Daniel Pailañir Vargas
*! daniel.pailanir@gmail.com

cap program drop recocl
program recocl
version 13.0

#delimit ;
    syntax varlist(min=1 max=1 numeric)
    , Year(integer)
    [
    GENerate(string)
    ]
    ;
#delimit cr

*-------------------------------------------------------------------------------
*check year of change
*-------------------------------------------------------------------------------
if ("`year'"!="2017") + ("`year'"!="2007")>1 {
    di as err "choose only a year with code change {bf:2017} or {bf:2007}"
    exit 198
}
*-------------------------------------------------------------------------------
*'recode' for municipalities of 'Bio Bio' and 'Tarapaca'
*-------------------------------------------------------------------------------
if "`year'"=="2017" {
    if "`generate'"!="" {
        #delimit ;
        gen `generate'=`varlist';
        recode `generate' (8401=16101) (8402=16102) (8406=16103) (8407=16104)
                          (8410=16105) (8411=16106) (8413=16107) (8418=16108)
                          (8421=16109) (8414=16201) (8403=16202) (8404=16203)
                          (8408=16204) (8412=16205) (8415=16206) (8420=16207)
                          (8416=16301) (8405=16302) (8409=16303) (8417=16304)
                          (8419=16305);
        #delimit cr
    }
    else {
        #delimit ;
        recode `varlist' (8401=16101) (8402=16102) (8406=16103) (8407=16104)
                         (8410=16105) (8411=16106) (8413=16107) (8418=16108)
                         (8421=16109) (8414=16201) (8403=16202) (8404=16203)
                         (8408=16204) (8412=16205) (8415=16206) (8420=16207)
                         (8416=16301) (8405=16302) (8409=16303) (8417=16304)
                         (8419=16305);
        #delimit cr
    }
}
if "`year'"=="2007" {
    if "`generate'"!="" {
        #delimit ;
        gen `generate'=`varlist';
        recode `generate' (1201=15101) (1202=15102) (1301=15201) (1302=15202)
                          (10501=14101) (10502=14102) (10506=14103) (10507=14104)
                          (10508=14105) (10509=14106) (10510=14107) (10511=14108)
                          (10504=14201) (10503=14202) (10505=14203) (10512=14204);
        #delimit cr
    }
    else {
        #delimit ;
	    recode `varlist' (1201=15101) (1202=15102) (1301=15201) (1302=15202)
                         (10501=14101) (10502=14102) (10506=14103) (10507=14104)
                         (10508=14105) (10509=14106) (10510=14107) (10511=14108)
                         (10504=14201) (10503=14202) (10505=14203) (10512=14204);
        #delimit cr
    }
}

end