capture program drop _graph
program _graph
syntax varlist, PARTition(numlist integer >0) [SCOrename(string)] calcmethod(string)

qui set autotabgraphs on

local P:word count `partition'

if "`scorename'" == "" {
	local nname
	forvalues i = 1/`P' {
		local name "Dim`i'"
		local scorename `scorename' `name'
	}
}

local i = 1 
foreach x in `varlist' {
	local var`i' = "`x'"
	local `++i'
}

*capture calcscore `varlist', partition(`partition') scorename(`scorename') calcmethod(`calcmethod')


if "`calcmethod'" == "stand" local w = 10
if "`calcmethod'" == "sum" local b = 10
if "`calcmethod'" == "mean" local w = 0.5

set graphics off
foreach s in `scorename' {
	qui hist `s', name("`s'",replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b')
}
set graphics on

gr combine `scorename', name("Histograms_scores",replace)  

qui biplot `scorename', name("Biplot_dimensions",replace) norow std title("") xtitle("") ytitle("")

qui biplot `varlist', name("temp",replace) norow std nograph

mat a = r(V)

tempvar a1 a2
mat colnames a = `a1' `a2'
svmat a, names(col)

tempvar mina1 mina2 maxa1 maxa2
egen `mina1' = min(`a1')
egen `mina2' = min(`a2')
egen `maxa1' = max(`a1')
egen `maxa2' = max(`a2')
local mina1 = `mina1'
local mina2 = `mina2'
local maxa1 = `maxa1'+1.4
local maxa1x = `maxa1'+0.3
local maxa2 = `maxa2'

local colors = "red blue black green ebblue mint erose orange maroon magenta mint gray teal navy olive sienna"
local i = 1
foreach c in `colors' {
	local col`i' = "`c'"
	local `++i'
}

local i = 1
local y = 1
local c = 1
local bas = `maxa2'+0.2
local droite = max(`maxa1',0.2)

foreach x in `partition' {
	tokenize `scorename'
	if `i' == 1 local s = `x'
	else local s = `s' +`x'
	
	*local r = round(runiform()*255)
	*local g = round(runiform()*255)
	*local b = round(runiform()*255)
	
	forvalues j=`y'/`s' {
		local a = `a1'[`j']
		local b = `a2'[`j']	
		local call `call' || pcarrowi 0 0 `b' `a' "`var`j''", mlabcolor(`col`i'') color(`col`i'') head   
	}
	local bas = `bas'-0.2
	*local droite = `droite'
	local call `call' text(`bas' `droite' "``i''", size(3) color(`col`i'')) /*`bas' `droite' "``i''", mlabcolor("`r' `g' `b'")*/
	local `++i' 
	local y = `s'+1	
	local `++c' 
}

qui twoway `call' name("Biplot_items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) xtitle("") ytitle("")


end

*_graph x1-x40, partition(5 5 5 5 5 5 5 5) scorename(HAaaaaa PSE W BCC AC AE LI MOC)
*_graph ioc1-ioc37, partition(4 4 7 3 3 4 7 5) scorename(HA PSE W BCC AC AE LI MOC) calcmethod(stand)
