************************************************************************************************************
* based on the command "detect" by Jean-Benoit Hardouin 
************************************************************************************************************
program define detect2 , rclass
version 7.0
syntax varlist(min=2 numeric), PARTition(numlist integer >0) [noSCOres noRESTscores]

local nbitemstest=0
tokenize `partition'
local Q:word count `partition'
local firstitem=0
local dim0=1
forvalues i=1/`Q' {
	local dim`i'=``i''
	local firstitem`i'=`firstitem`=`i'-1''+`dim`=`i'-1''
	local nbitemstest=`nbitemstest'+`dim`i''
	tempvar score`i'
	qui gen `score`i''=0
	forvalues j=`firstitem`i''/`=`firstitem`i''+`dim`i''-1' {
		local item`j': word `j' of `varlist'
		qui replace `score`i''=`score`i''+`item`j''
	}
}



local nbitems:word count `varlist'
tokenize `varlist'

if `nbitems'!=`nbitemstest' {
	di in red "The sum of the numbers of items in all the dimensions is different of the total number of items precised in varlist"
exit
}


tempname Corrscores Corrrestscores

matrix define `Corrscores'=J(`nbitems',`Q',0)
matrix define `Corrrestscores'=J(`nbitems',`Q',0)


forvalues i=1/`nbitems' {
	forvalues j=1/`Q' {
		tempvar restscore`i's`j'
		qui gen `restscore`i's`j''=`score`j''-``i''
		qui corr ``i'' `score`j''
		local corr`i's`j'=r(rho)
		qui corr ``i'' `restscore`i's`j''
		local corr`i'rs`j'=r(rho)
		matrix `Corrscores'[`i',`j']=`corr`i's`j''
		matrix `Corrrestscores'[`i',`j']=`corr`i'rs`j''
	}
}



local namesdim
forvalues q=1/`Q' {
	local namesdim "`namesdim' dim`q'"
}

matrix colnames `Corrscores'= `namesdim'
matrix colnames `Corrrestscores'= `namesdim'
return matrix Corrscores `Corrscores'
return matrix Corrrestscores `Corrrestscores'


end