clear all
version 14.1
set matsize 5000

program main
    import_data
    calc_weights
end

program import_data
    syntax, [maxrun(int 100)]
    import delimited "../datastore/analysis/release_large/simulation/BaselineV.csv"
    drop if run > `maxrun'
    foreach var of varlist * {
        if strpos("`:type `var''", "str") replace `var' = "." if lower(trim(`var')) == "nan"
    }
    destring, replace

    gen cohort=time-eventtime
end

program calc_weights
    qui levelsof run, loc(runs)
    tempfile data
    save "`data'"

    local vars z_lead5_1minus     ///
               deltaz_lead5_lead4 ///
               deltaz_lead4_lead3 ///
               deltaz_lead3_lead2 ///
               deltaz_lead2_lead1 ///
               deltaz_lag0_lag1   ///
               deltaz_lag1_lag2   ///
               deltaz_lag2_lag3   ///
               deltaz_lag3_lag4   ///
               deltaz_lag4_lag5   ///
               z_lag5

    disp "Estimating weights for `:list sizeof runs' runs"

    timer clear 1
    mata weights = J(0, `:list sizeof vars' + 3, .)
    local options absorb(i.index i.time) cohort(cohort) rel_time(eventtime)
    foreach run of local runs {
        qui timer on 1
        use "`data'" if run == `run', clear
        eventstudyweights `vars', `options'
        mata e_weights = st_matrix("e(weights)")
        mata weights = weights \ (J(rows(e_weights), 1, `run'), e_weights)
        timer off 1
        timer list
    }

    clear
    mata stata(sprintf("set obs %g", rows(weights)))
    mata vars = "run", st_matrixcolstripe("e(weights)")[., 2]'
    mata (void) st_addvar(J(1, cols(vars), "`:set type'"), vars)
    mata st_store(., vars, weights)
	export delimited "../datastore/analysis/release_large/weights/weights.txt", delimiter(",") replace
end


main

