clear
set more off

* Load "find_synth3" program
do "$do\12_0_SCM_individual_level_program_define.do"

set seed 250 // Random integer between 0 and 3000 from https://www.random.org
set sortseed 2955 // Random integer between 0 and 3000 from https://www.random.org

* Set number of placebo groups
local nb_placebo = 1000 // Test command
*local nb_placebo = 1000

local dis = int(0.05*`nb_placebo')

use "$temp/final_data", clear

* Size of original treated group (number of individuals)
distinct id_ind if connect == 1
local target_ind = r(ndistinct)
local target_obs = r(N)

* Delete Sarkozy affiliates from data
drop if connect == 1

tempfile tmpB
save `tmpB', replace

* Draw random placebo connected groups
********************************************************************************

forvalues j = 1(1)`nb_placebo'{

if  mod(`j',`dis') == 0{
noisily : di "Placebo group `j' / `nb_placebo'"
}

local check_2 = 0
while `check_2' == 0{

use `tmpB', clear

local check = 0
quietly{
while `check' == 0{
replace connect = runiform()
bys id_ind: replace connect = connect[1]
egen a = group(connect id_ind)
local cut = int(runiform(0.75,1.25) * `target_ind')
replace connect = (a <= `cut')
drop a
quietly : count if connect == 1
if r(N) >= `target_obs'*0.30{ // Check that there are enough observations in this group (minimize the risk of subsequent failure)
   local check = 1
   }
} // End of while `check' == 0{

replace inter = after * connect

tempfile tmpA
save `tmpA', replace
} // End of quietly{
********************************************************************************
 

capture{
foreach dep in abret comply dist{

use `tmpA', clear

* Select dependent variable
if "`dep'" == "abret"{
local var an_abret_index_SBF120_30_1
keep  if  type == "Purchase"
}
if "`dep'" == "comply"{
local var diff_comply
}
if "`dep'" == "dist"{
local var dist_next_res_all
}

* SCM estimation
********************************************************************************
find_synth3 `var' after connect id_ind 5000 10
********************************************************************************


local pre_gap_`dep' = pre_gap[1]
local post_gap_`dep' = post_gap[1]

} // End of foreach dep in abret comply dist{

} // End of capture
if _rc{ // If crash (any reason)
di "Placebo `j': SCM estimation failed, try again with different group"
}
if !_rc{ // If no crash
local check_2  = 1
*di "Success!"
}
} // End of while `check_2' == 0{

quietly{
clear
set obs 3
foreach x in pre_gap post_gap{
gen `x' = .
}
gen dep = ""

local a = 0
foreach dep in abret comply dist{
local a = `a' + 1
replace dep = "`dep'" if _n == `a'
foreach x in pre_gap post_gap{
replace `x' = ``x'_`dep'' if _n == `a'
}

}

gen draw = `j'
tempfile tmp_scm3_placebo_`j'
save `tmp_scm3_placebo_`j'', replace
} // End of quietly{
}

* Append individual output files
clear
forvalues j = 1(1)`nb_placebo'{
append using `tmp_scm3_placebo_`j''
}
save "$temp/scm_individual_placebo", replace
