*! version 1.4  29January2014
*! Jean-Benoit Hardouin
************************************************************************************************************
* rsoort: Response Shift detection with the Oort procedure
*
* Historic:
* Version 1 (2013-02-25): Jean-Benoit Hardouin
* Version 1.1 (2013-06-03): Jean-Benoit Hardouin /*some improvements*/
* Version 1.2 (2013-06-03): Jean-Benoit Hardouin /*model1 model2 model3 and covariances options*/
* Version 1.3 (2013-06-03): Jean-Benoit Hardouin /**/
* Version 1.4 (2014-01-29): Jean-Benoit Hardouin /*add an iterate option on model 1*/
*
*
* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
* jean-benoit.hardouin@univ-nantes.fr
*
* Copyright 2013-2014 Jean-Benoit Hardouin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
************************************************************************************************************/


/***************************************************************************
MODIFICATIONS ALICE 
- précedemment, boucles pour les différents cas THA, qui permettent le test général, la hiérarchie et l'ajustement.
- avant l'été 2015, modification pour l'amélioration du fit des modèles 1 et 4
- (22/09/2015): modification dans l'ajout pour l'amélioration du fit avec le fichier déposé en temporaire
-(12/2015): modification, dans les cas sans hierarchie, programme recodé pour la boucle typeRS=2 car pb dans les contraintes
-(01/2016) : modification de l'étape 4, lorsque la procédure entre dans la boucle pour les covariances, M4 modifié (car il était équivalent au M1 donc faux) + réinitialisation de arret_covfit avant modele 4

*****************************************************************************************/


/***********************************************************************************************************
INTRODUCTION
***********************************************************************************************************/


program define Multirsoort_indicefit,rclass

syntax varlist(min=2 numeric) [if] [in] [,METHod(string) nocov12 UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPrioritization(varlist) noSearch html(string) model1 model2 model4 COVariances(string) MATrixrs(string) Cas(string)]
tempfile saveMultirsoort_indicefit
qui save `saveMultirsoort_indicefit',replace
preserve

if "`matrixrs'"!="" {
   if "`uniformrecalibration'"!="" {
      di in red "You cannot use the {bf:matrixrs} and the {bf:uniformrecalibration} options in the same time"
	  error 
   }
   if "`nonuniformrecalibration'"!="" {
      di in red "You cannot use the {bf:matrixrs} and the {bf:nonuniformrecalibration} options in the same time"
	  error 
   }
   if "`reprioritization'"!="" {
      di in red "You cannot use the {bf:matrixrs} and the {bf:reprioritization} options in the same time"
	  error 
   }
}


if "`html'" != "" {
   di "<!-- SphereCalc start of response -->"
}


if "`if'"!=""|"`in'"!="" {
    qui keep `if' `in'
}

tokenize `varlist'
local nbitems:word count `varlist'
local mod=mod(`nbitems',2)
if `mod'!=0 {
  di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
  error
}

if "`method'"=="" {
   local method "ml"
}
local nbitems=`nbitems'/2

if "`html'"== "" {
    di _col(20) "{hline 30}"
    di  _col(20) in gr "Time 1" _col(40) "Time 2"
    di _col(20) "{hline 30}"
    forvalues i=1/`nbitems' {
        di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
    }
    di _col(20) "{hline 30}"
}
else {
    di "<table id=" _char(34) "rsoorttimetable" _char(34) "class=" _char(34) "restable" _char(34) ">"
    di "<caption></caption>"
    di "<thead><tr><th>Time 1</th><th>Time2</th></tr></thead>"
    di "<tbody>"
    forvalues i=1/`nbitems' {
       di "<tr><td>``i''</td><td>``=`i'+`nbitems'''</td></tr>"
    }
    di "</tbody></table>"
}

/**************************************************************************************************************
Model 1
***************************************************************************************************************/

if "`model1'"=="" {
   local qui qui
}
else {
   local qui
}
local cov12b
forvalues i=1/`nbitems' {
   local cov12b `cov12b' e.``i''*e.``=`i'+`nbitems'''
}
if "`cov12'"!="" {
   local cov12b
}

/*if ("`cas'"=="cas3" | "`cas'"=="cas4" | "`cas'"=="cas5" | "`cas'"=="cas6" ) {*/

`qui' sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0)  method(`method') cov(`cov12b' `covariances') iterate(100)
tempname b 
matrix `b'=r(table)

estat gof
local rmsea1=r(rmsea)


local covfit
local r =999
local arret_covfit=999 

while `rmsea1' >0.08 {

di"`rmsea1'"
tempfile data
save `data', replace 
di "`data'"
/*on récupère les indices de modifs*/
estat mindice
matrix indice = r(mindices)
clear
/* on ajoute dans une colonne le nom des items concernés*/
svmat2 indice , r(nomcol) full

/*on controle l'ajout de covariances uniquement sur un même temps*/
gen tmp=substr(nomcol,1,3)
drop if tmp!="cov"

gen tmp1=substr(nomcol,11,1)
gen tmp2=substr(nomcol,20,1)
drop if tmp1 != tmp2

matrix list indice

/*On vérifie qu'il reste des lignes de covariances à ajouter*/
local vide = indice1[1]
if "`vide'" == "." {
local covfit= "`covfit'"
local arret_covfit=1
local rmsea1=0
use "`data'",clear

}
else {
/*on trie par ordre croissant pour ajouter les covariances les plus influentes*/
local arret_covfit=0
gsort - indice1

local tmp3=nomcol[1]
lstrfun e, subinstr("`tmp3'","cov(","",.)
lstrfun e, subinstr("`e'",")","",.)
lstrfun e, subinstr("`e'",":_cons","",.)
lstrfun e, subinstr("`e'",",","*",.)


local covfit= "`covfit' `e'"
use "`data'", clear


`qui' sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0)  method(`method') cov(`cov12b' `covariances' `covfit') iterate(100)
tempname b 
matrix `b'=r(table)

estat gof
local rmsea1=r(rmsea)

di "`covfit'"

local tmp4="`covfit'"
lstrfun r, subinstr("`tmp4'","e.itemA","0",.)
lstrfun r, subinstr("`r'","e.itemB","1",.)
lstrfun r, subinstr("`r'","*","",.)
lstrfun r, subinstr("`r'"," ","",.)
}
}


/*return list
ereturn list*/

estat gof
qui estat gof, stat(all)
tempname iter1 V 
local iter1=e(ic)
local tli1=r(tli)
local cfi1=r(cfi)
local srmr1=r(srmr)
local rmsea1=r(rmsea)
local ubrmsea1=r(ub90_rmsea)
local lbrmsea1=r(lb90_rmsea)
local pclose1= r(pclose) 
local chi21=r(chi2_ms)
local df1=r(df_ms)
local dfc1=6*`nbitems'+1
local p1=r(p_ms)
local bic1=r(bic)
local convergence1=e(converged)
local cov_fit1="`r'"
local arret_covfit1=`arret_covfit'


return matrix b1=`b'
return scalar iter1=`iter1'
return scalar tli1=`tli1'
return scalar cfi1=`cfi1'
return scalar srmr1=`srmr1'
return scalar rmsea1=`rmsea1'
return scalar ubrmsea1=`ubrmsea1'
return scalar lbrmsea1=`lbrmsea1'
return scalar pclose1=`pclose1'
return scalar chi21=`chi21'
return scalar df1=`df1'
return scalar dfc1=`dfc1'
return scalar p1=`p1'
return scalar bic1=`bic1'
return scalar convergence1=`convergence1'
return local cov_fit1 = "`cov_fit1'"
return scalar arret_covfit1 =`arret_covfit1'
/*}*/


*di
*di in green "          ***********************************Model 1********************************************"
*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1'  _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'

/**************************************************************************************************************
Model 2
***************************************************************************************************************/

local sem
local var
forvalues i=1/`nbitems' {
   local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
   local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
   local sem `sem' `sem`i''
   local var `var' `var`i''
}

if "`model2'"=="" {
   local qui qui
}
else {
   local qui
}

`qui' sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var' iterate(100)  method(`method') cov(`cov12b' `covariances' `covfit') 
di "`sem'" 
di"`var'"
tempname b V
matrix `b'=r(table)
matrix `V'=e(V)
local truechange2=`b'[1,`=`nbitems'*4+1']
local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']


estat gof
qui estat gof, stat(all)
local iter2=e(ic)
local tli2=r(tli)
local cfi2=r(cfi)
local srmr2=r(srmr)
local rmsea2=r(rmsea)
local ubrmsea2=r(ub90_rmsea)
local lbrmsea2=r(lb90_rmsea)
local pclose2=r(pclose)
local chi22=r(chi2_ms)
local df2=r(df_ms)
local dfc2=3*`nbitems'+3
local p2=r(p_ms)
local bic2=r(bic)
local convergence2=e(converged)

return matrix b2=`b'
return scalar iter2=`iter2'
return scalar tli2=`tli2'
return scalar cfi2=`cfi2'
return scalar srmr2=`srmr2'
return scalar rmsea2=`rmsea2'
return scalar ubrmsea2=`ubrmsea2'
return scalar lbrmsea2=`lbrmsea2'
return scalar pclose2=`pclose2'
return scalar chi22=`chi22'
return scalar df2=`df2'
return scalar dfc2=`dfc2'
return scalar p2=`p2'
return scalar bic2=`bic2'
return scalar convergence2=`convergence2'
return scalar truechange2=`truechange2'
return scalar setruechange2=`=sqrt(`Vtruechange2')'
return scalar ztruechange2=`=`truechange2'/sqrt(`Vtruechange2')' 
return scalar ptruechange2=`=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'


if "`html'" != "" {
	di "<table id=rsoortglobaltable class=restable >"
	di "<caption></caption>"
	*di "<thead><tr><th></th><th></th><th colspan=3>Test of global Response-Shift</th><th colspan=3>Comparison with model 1</th></tr>"
	di "<tr><th>Models</th><th>Chi-square</th><th>df</th><th>p-value</th><th>BIC</th></tr></thead>"
	di "<tbody>"
	di "<tr><td>Model 1</td><td>" %8.2f `chi21' "</td><td>" %4.0f `df1' "</td><td>" %6.4f `p1' "</td><td>" %7.2f `bic1' "</td></tr>"
	di "<tr><td>Model 2</td><td>" %8.2f `chi22' "</td><td>" %4.0f `df2' "</td><td>" %6.4f `p2' "</td><td>" %7.2f `bic2' "</td></tr>"
	di "</tbody></table>"
}
else {
    di "{hline 51}"
    di in gr                                /*_col(39) "Test of global Response-Shift "               _col(79) "Comparison with model 1"*/
    di in gr "Models" _col(18)  "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC"  /*_col(39) "Chi-square" _col(54) "df" _col(59) "p-value" *_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
    di "{hline 51}"
    di in gr "Model 1" _col(20) %8.2f in ye `chi21' _col(30) %4.0f `df1' _col(37) %6.4f `p1' _col(45) %7.2f `bic1'
    di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(30) %4.0f `df2' _col(37) %6.4f `p2' _col(45) %7.2f `bic2' /*_col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' *_col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'*/
    di "{hline 51}"
}


if "`cas'"=="cas3" | "`cas'"=="cas4" | "`cas'"=="cas5" | "`cas'"=="cas6"{
local chi221=abs(`chi21'-`chi22')
local df21=`df2'-`df1'
local p21=1-chi2(`df21',`chi221')

if (`p21'>0.05) {
local search="nosearch" 
}

return scalar pvaleurM1M2=`p21'

}


/**************************************************************************************************************
Model 3
***************************************************************************************************************/

/**************************************************************************************************************
HIERARCHIE
***************************************************************************************************************/
if "`cas'"=="cas1" | "`cas'"=="cas2" | "`cas'"=="cas3" | "`cas'"=="cas4" {
/**************************************************************************************************************
Model 3 / Non uniform recalibration
***************************************************************************************************************/

tempname RS  RSprec
qui matrix `RS'=J(`nbitems',3,0)
qui matrix `RSprec'=J(`nbitems',3,0)
local df3=`dfc2'

*set trace on

forvalues j=1/`nbitems' {
	local unav_nonunif`j'=.
}

if "`matrixrs'"=="" {
	forvalues i=1/`nbitems' {
	   local nbUR:word count `uniformrecalibration'
	   forvalues j=1/`nbUR' {
		  local itemj: word `j' of `uniformrecalibration'
		  if "``i''"=="`itemj'" {
			 matrix `RS'[`i',2]=1
		  }
	   }
	   local nbNUR:word count `nonuniformrecalibration'
	   forvalues j=1/`nbNUR' {
		  local itemj: word `j' of `nonuniformrecalibration'
		 if "``i''"=="`itemj'" {
			 matrix `RS'[`i',1]=1
		  }
	   }
	   local nbR:word count `reprioritization'
	   forvalues j=1/`nbR' {
		  local itemj: word `j' of `reprioritization'
		  if "``i''"=="`itemj'" {
			 matrix `RS'[`i',3]=1
		  }
	   }
	}
}
else {
   matrix `RS'=`matrixrs'
}
*matrix list `RS'

if "`search'"=="" {

    if "`html'"=="" {
        di
        di "{hline 88}"
        di in green _col(40)  "Model 3"
        di "{hline 88}"
        di
        di in white _col(10) "Non uniform Recalibration"
    }
    else {
        di "<h2><br>Model 3</h2>"
        di "<table id=rsoortM3nonuniftable class=restable >"
        di "<caption>Non uniform Recalibration</caption>"
    }
    local continue=1
    forvalues i=1/`nbitems' {
       local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
       local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
       local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
       local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
       local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
    }
    local prec_chi2=`chi22'
    local testNU_varchi2=0
    local testNU_p=1

    if "`html'"=="" {
        di "{hline 88}"
        di in gr                                                                                _col(59) "Comparison with previous model"/*              _col(79) "Comparison with model 1"*/
        di in gr "Items" _col(18)  "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
        di "{hline 88}"
    }
    else {
        di "<thead><tr><th></th><th></th><th></th><th></th><th></th><th colspan=3 align=left>Comparison with previous model</th></tr>"
        di "<tr><th>Items</th><th>Chi-square</th><th>df</th><th>p-value</th><th>BIC</th><th>Chi-square</th><th>df</th><th><I>p</I>-value</th></tr></thead>"
        di "<tbody>"
    }

    while (`continue') {
       local cpt=0
       local testNU_varchi2_temp=0
       local testNU_p_temp=0
       local testNU_item_temp=0
       local chi2encours_temp=-1
       local continue=0
       local sem
       local var
       forvalues j=1/`nbitems' {
          local sem
          local var
          local already=0
          forvalues i=1/`nbitems' {
             if `RS'[`i',1]==0&`i'!=`j' {
                local sem `sem' `sem`i''
                local var `var' `var`i''
             }
             if `RS'[`i',1]==1&`i'!=`j' {
                local sem `sem' `sem`i''
                local var `var' `varrecNU`i''
             }
             else if `i'==`j'&`RS'[`j',1]==0 {
                local sem `sem' `sem`i''
                local var `var' `varrecNU`i''
             }
             else if `i'==`j'&`RS'[`j',1]==1 {
                local sem `sem' `sem`i''
                local var `var' `varrecNU`i''
                local already=1
             }
          }
		  /*di "`covfit'"*/
		 /* di "`sem'" 
		  di"`var'"*/
          if (`already'!=1) {
             qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var'  iterate(100)  method(`method') cov(`cov12b' `covariances' `covfit') 
			 di "`sem'" 
			 di"`var'"
             qui estat gof
			
             local chi2encours=r(chi2_ms)
             local dfencours=r(df_ms)
             local pencours=r(p_ms)
             local bicencours=r(bic)
			 
			 if "`cas'"=="cas4" | "`cas'"=="cas2" {
			 local nbtest=1-(0.05/(`nbitems'-`cpt'))
			 }
			 if "`cas'"=="cas1" | "`cas'"=="cas3" {
			 local nbtest=0.95
			 }
			 
		 
             if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
                local continue=1
                local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
                local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
                local testNU_item_temp=`j'
                local chi2encours_tmp=`chi2encours'
                local tmp=`chi2encours'
             }
             if ( `chi2encours'<`prec_chi2') {
			 local unav_nonunif`j'=0
				 if "`html'" != "" {
					di "<tr><td>``j''</td><td>" %8.2f `chi2encours' "</td><td>" %4.0f `dfencours' "</td><td>" %6.4f `pencours' "</td><td>" %7.2f `bicencours' "</td><td>" %8.2f `=abs(`chi2encours'-`prec_chi2' )' "</td><td>1</td><td>" %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' "</td></tr>"
				 }
				 else {
					di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
				 }
             }
             else {
			 local unav_nonunif`j'=1
                 if "`html'" != "" {
                    di "<tr><td>``j''</td><td>Unavailable</td></tr>"
					
				 }
                 else {
                    di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
                 }
             }
             local ++cpt
			 return scalar unav_nonunif`j'= `unav_nonunif`j''
          }
       }
       if (`testNU_item_temp'!=0) {
          matrix `RS'[`testNU_item_temp',1]=1
          local ++df3
          local testNU_varchi2=`testNU_varchi2_temp'
          local testNU_p=`testNU_p_temp'
          local testNU_item_temp=0
          local prec_chi2=`tmp'
       }
       if (`cpt'!=0) {
	  if "`html'" != "" {
	      di "<tr><td colspan=8><hr></td></tr>"
	  }
	  else {
              di "{hline 88}"
          }
       }
    }
    if "`html'" != "" {
        di "</tbody></table>"
    }



    /**************************************************************************************************************
    Model 3 / Uniform recalibration
    ***************************************************************************************************************/
forvalues j=1/`nbitems' {
	local unav_unif`j'=.
}

    if "`html'"=="" {
       di
       di in white _col(10) "Uniform Recalibration"
    }
    else {
       di "<table id=rsoortM3nonuniftable class=restable >"
       di "<caption>Uniform Recalibration</caption>"
    }
    local continue=1
    local var
    forvalues i=1/`nbitems' {
       local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
       local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
       local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
       local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
       local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
       if `RS'[`i',1]==1 {
          local var "`var' `varrecNU`i''"
       }
       if `RS'[`i',1]==0 {
          local var "`var' `var`i''"
       }
    }
    local testU_varchi2=0
    local testU_p=1
    if "`html'"=="" {
        di "{hline 88}"
        di in gr                                                                                _col(59) "Comparison with previous model"/*              _col(79) "Comparison with model 1"*/
        di in gr "Items" _col(18)  "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
        di "{hline 88}"
    }
    else {
        di "<thead><tr><th></th><th></th><th></th><th></th><th></th><th colspan=3 align=left>Comparison with previous model</th></tr>"
        di "<tr><th>Items</th><th>Chi-square</th><th>df</th><th>p-value</th><th>BIC</th><th>Chi-square</th><th>df</th><th><I>p</I>-value</th></tr></thead>"
        di "<tbody>"
    }

    while (`continue') {
       local cpt=0
       local testU_varchi2_temp=0
       local testU_p_temp=0
       local testU_item_temp=0
       local chi2encours_temp=-1
       local continue=0
       local sem
       forvalues j=1/`nbitems' {
          local sem
          local already=0
          forvalues i=1/`nbitems' {
             if `RS'[`i',2]==0&`i'!=`j' {
                local sem `sem' `sem`i''
             }
             if `RS'[`i',2]==1&`i'!=`j' {
                local sem `sem' `semrecU`i''
             }
             else if `i'==`j'&`RS'[`j',2]==0 {
                local sem `sem' `semrecU`i''
             }
             else if `i'==`j'&`RS'[`j',2]==1 {
                local sem `sem' `semrecU`i''
                local already=1
             }
          }
		  
		 /* di "`sem'" 
		  di"`var'"*/
          if (`already'!=1) {
             qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var'  iterate(100)  method(`method') cov(`cov12b' `covariances' `covfit')
			 di "`sem'" 
			 di"`var'"
             qui estat gof
			
             local chi2encours=r(chi2_ms)
             local dfencours=r(df_ms)
             local pencours=r(p_ms)
             local bicencours=r(bic)
			 
			 if "`cas'"=="cas4" | "`cas'"=="cas2" {
			 local nbtest=1-(0.05/(`nbitems'-`cpt'))
			 }
			 if "`cas'"=="cas1" | "`cas'"=="cas3" {
			 local nbtest=0.95
			 }
			 
             if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
                local continue=1
                local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
                local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
                local testU_item_temp=`j'
                local chi2encours_tmp=`chi2encours'
                local tmp=`chi2encours'
             }

             if ( `chi2encours'<`prec_chi2') {
			 local unav_unif`j'=0
				 if "`html'" != "" {
					di "<tr><td>``j''</td><td>" %8.2f `chi2encours' "</td><td>" %4.0f `dfencours' "</td><td>" %6.4f `pencours' "</td><td>" %7.2f `bicencours' "</td><td>" %8.2f `=abs(`chi2encours'-`prec_chi2' )' "</td><td>1</td><td>" %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' "</td></tr>"
				 }
				 else {
					di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
				 }
             }
             else {
			 local unav_unif`j'=1
                 if "`html'" != "" {
                    di "<tr><td>``j''</td><td>Unavailable</td></tr>"
                 }
                 else {
                    di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
                 }
             }
             local ++cpt
			 return scalar unav_unif`j'= `unav_unif`j''
          }
       }
       if (`testU_item_temp'!=0) {
          matrix `RS'[`testU_item_temp',2]=1
          local ++df3
          local testU_varchi2=`testU_varchi2_temp'
          local testU_p=`testU_p_temp'
          local testU_item_temp=0
          local prec_chi2=`tmp'
       }
       if (`cpt'!=0) {
	  if "`html'" != "" {
	      di "<tr><td colspan=8><hr></td></tr>"
	  }
	  else {
              di "{hline 88}"
          }
       }
    }
    if "`html'" != "" {
        di "</tbody></table>"
    }




    /**************************************************************************************************************
    Model 3 / Reprioritization
    ***************************************************************************************************************/
forvalues j=1/`nbitems' {
	local unav_reprio`j'=.
}

    if "`html'"=="" {
       di
       di in white _col(10) "Reprioritization"
    }
    else {
       di "<table id=rsoortM3nonuniftable class=restable >"
       di "<caption>Reprioritization</caption>"
    }

    local continue=1
    local var
    local sem
    forvalues i=1/`nbitems' {
       local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
       local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
       local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
       local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
       local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
	   local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
       if `RS'[`i',1]==1 {
          local var "`var' `varrecNU`i''"
       }
       if `RS'[`i',1]==0 {
          local var "`var' `var`i''"
       }
    }
    local testU_varchi2=0
    local testU_p=1
    if "`html'"=="" {
        di "{hline 88}"
        di in gr                                                                                _col(59) "Comparison with previous model"/*              _col(79) "Comparison with model 1"*/
        di in gr "Items" _col(18)  "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
        di "{hline 88}"
    }
    else {
        di "<thead><tr><th></th><th></th><th></th><th></th><th></th><th colspan=3 align=left>Comparison with previous model</th></tr>"
        di "<tr><th>Items</th><th>Chi-square</th><th>df</th><th>p-value</th><th>BIC</th><th>Chi-square</th><th>df</th><th><I>p</I>-value</th></tr></thead>"
        di "<tbody>"
    }

    while (`continue') {
       local cpt=0
       local testR_varchi2_temp=0
       local testR_p_temp=0
       local testR_item_temp=0
       local chi2encours_temp=-1
       local continue=0
       local sem
       forvalues j=1/`nbitems' {
          local sem
          local already=0
          forvalues i=1/`nbitems' {
             if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
                local sem `sem' `sem`i''
             }
             else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
                local sem `sem' `semrecU`i''
             }
             else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
                local sem `sem' `semrep`i''
             }
             else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
                local sem `sem' `semrecUrep`i''
             }
             else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
                local sem `sem' `semrep`i''
             }
             else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
                local sem `sem' `semrecUrep`i''
             }
             else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
                local already=1
             }
             else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
                local sem `sem' `semrep`i''
                local already=1
             }
             else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
                local sem `sem' `semrecUrep`i''
                local already=1
             }
          }
		  di "`sem'" 
		  di"`var'"
          if (`already'!=1) {
             qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var'  iterate(100)  method(`method') cov(`cov12b' `covariances' `covfit')
			 di "`sem'" 
			 di"`var'"
             qui estat gof
			
             local chi2encours=r(chi2_ms)
             local dfencours=r(df_ms)
             local pencours=r(p_ms)
             local bicencours=r(bic)
			 
			 if "`cas'"=="cas4" | "`cas'"=="cas2"  {
			 local nbtest=1-(0.05/(`nbitems'-`cpt'))
			 }
			 if "`cas'"=="cas1" | "`cas'"=="cas3" {
			 local nbtest=0.95
			 }
			 
			 			 
             if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
                local continue=1
                local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
                local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
                local testR_item_temp=`j'
                local chi2encours_tmp=`chi2encours'
                local tmp=`chi2encours'
             }
             if ( `chi2encours'<`prec_chi2') {
			 local unav_reprio`j'= 0
                 if "`html'" != "" {
                    di "<tr><td>``j''</td><td>" %8.2f `chi2encours' "</td><td>" %4.0f `dfencours' "</td><td>" %6.4f `pencours' "</td><td>" %7.2f `bicencours' "</td><td>" %8.2f `=abs(`chi2encours'-`prec_chi2' )' "</td><td>1</td><td>" %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' "</td></tr>"
                 }
                 else {
                    di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
                 }
             }
             else {
			 local unav_reprio`j'= 1
                 if "`html'" != "" {
                    di "<tr><td>``j''</td><td>Unavailable</td></tr>"
                 }
                 else {
                    di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
                 }
             }
             local ++cpt
			 return scalar unav_reprio`j'= `unav_reprio`j''
          }
       }
       if (`testR_item_temp'!=0) {
          matrix `RS'[`testR_item_temp',3]=1
          local ++df3
          local testR_varchi2=`testR_varchi2_temp'
          local testR_p=`testR_p_temp'
          local testR_item_temp=0
          local prec_chi2=`tmp'
       }
       if (`cpt'!=0) {
	  if "`html'" != "" {
	      di "<tr><td colspan=8><hr></td></tr>"
	  }
	  else {
              di "{hline 88}"
          }
       }
    }
    if "`html'" != "" {
        di "</tbody></table>"
    }
}



}



/**************************************************************************************************************
PAS DE HIERARCHIE
***************************************************************************************************************/

if "`cas'"=="cas5" | "`cas'"=="cas6" | "`cas'"=="cas7" | "`cas'"=="cas8" {



/**************************************************************************************************************
Model 3 / Type of Response Shift 
***************************************************************************************************************/
forvalues nbpass=0/63 {
	forvalues j=1/`nbitems' {
		forvalues typeRS=1/3{ 
		local unav`=`nbpass'`j'`typeRS''=.
		}
	}
}

tempname RS  RSprec
qui matrix `RS'=J(`nbitems',3,0)
qui matrix `RSprec'=J(`nbitems',3,0)
local df3=`dfc2'

if "`matrixrs'"=="" {
	forvalues i=1/`nbitems' {
	   local nbUR:word count `uniformrecalibration'
	   forvalues j=1/`nbUR' {
		  local itemj: word `j' of `uniformrecalibration'
		  if "``i''"=="`itemj'" {
			 matrix `RS'[`i',2]=1
		  }
	   }
	   local nbNUR:word count `nonuniformrecalibration'
	   forvalues j=1/`nbNUR' {
		  local itemj: word `j' of `nonuniformrecalibration'
		 if "``i''"=="`itemj'" {
			 matrix `RS'[`i',1]=1
		  }
	   }
	   local nbR:word count `reprioritization'
	   forvalues j=1/`nbR' {
		  local itemj: word `j' of `reprioritization'
		  if "``i''"=="`itemj'" {
			 matrix `RS'[`i',3]=1
		  }
	   }
	}
}
else {
   matrix `RS'=`matrixrs'
}
*matrix list `RS'

if "`search'"=="" {


    if "`html'"=="" {
        di
        di "{hline 88}"
        di in green _col(40)  "Model 3"
        di "{hline 88}"
        di
        di in white _col(10) "Type of response shift"
    }
    else {
        di "<h2><br>Model 3</h2>"
        di "<table id=rsoortM3nonuniftable class=restable >"
        di "<caption>Non uniform Recalibration</caption>"
    }
    local continue=1
    forvalues i=1/`nbitems' {
       local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
       local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
       local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
       local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
	   local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
	   local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
    }
    local prec_chi2=`chi22'
    local test_varchi2=0
    local test_p=1

    if "`html'"=="" {
        di "{hline 88}"
        di in gr                                                                                _col(59) "Comparison with previous model"/*              _col(79) "Comparison with model 1"*/
        di in gr "Items" _col(18)  "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
        di "{hline 88}"
    }
    else {
        di "<thead><tr><th></th><th></th><th></th><th></th><th></th><th colspan=3 align=left>Comparison with previous model</th></tr>"
        di "<tr><th>Items</th><th>Chi-square</th><th>df</th><th>p-value</th><th>BIC</th><th>Chi-square</th><th>df</th><th><I>p</I>-value</th></tr></thead>"
        di "<tbody>"
    }

	
	local nbpass=0
	local ajust=0
    while (`continue') {
	   
	   local cpt=0
	   local test_varchi2_temp=0
       local test_p_temp=0
       local test_item_temp=0
       local chi2encours_temp=-1
       local continue=0
       local sem
       local var
	   forvalues typeRS=1/3{
	  
		
			forvalues v=1/`nbitems' {
				if `RS'[`v',2]==1&`RS'[`v',1]==1 {
					local ajust=1
				}				
			}
		
	
	   		forvalues j=1/`nbitems' {
			  local sem
			  local var
			  local already=0
			  
			  forvalues i=1/`nbitems' {
			  
				  if `typeRS'==1 {
				  if `RS'[`i',2]==0 & `RS'[`i',3]==0 {
						local sem "`sem' `sem`i''"
				   }
				   if `RS'[`i',2]==0 & `RS'[`i',3]==1 {
						local sem "`sem' `semrep`i''"
				   }
				   if `RS'[`i',2]==1 & `RS'[`i',3]==0{
					local sem "`sem' `semrecU`i''"
				   }
				   if `RS'[`i',2]==1 & `RS'[`i',3]==1{
					  local sem "`sem' `semrecUrep`i''"
				   }
				  
				  
					  
						 if `RS'[`i',1]==0&`i'!=`j' {
							local var `var' `var`i''
						 }
						 if `RS'[`i',1]==1&`i'!=`j' {
							local var `var' `varrecNU`i''
						 }
						 else if `i'==`j'&`RS'[`j',1]==0 {
							local var `var' `varrecNU`i''
						 }
						 else if `i'==`j'&`RS'[`j',1]==1 {
							local var `var' `varrecNU`i''
							local already=1
						 }
					  
				  }
				  
				  if `typeRS'==2 {
				  /*matrix list `RS'*/
				  if `RS'[`i',1]==1 {
					  local var "`var' `varrecNU`i''"
				   }
				   
				   if `RS'[`i',1]==0 {
					  local var "`var' `var`i''"
				   }
				   				  
					 if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
						local sem `sem' `sem`i''
					 }
					 else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
						local sem `sem' `semrecU`i''
					 }
					 else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
						local sem `sem' `semrep`i''
					 }
					 else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
						local sem `sem' `semrecUrep`i''
					 }
					 else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
						local sem `sem' `semrecU`i''
					 }
					 else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1 {
						local already=1
					 }
					 else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
						local sem `sem' `semrecUrep`i''
					 }
					 else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
						local sem `sem' `semrecUrep`i''
						local already=1
					 }
					  
				 }
				
				
				   if `typeRS'==3 {
				   if `RS'[`i',1]==1 {
					  local var "`var' `varrecNU`i''"
				   }
				   
				   if `RS'[`i',1]==0 {
					  local var "`var' `var`i''"
				   }
				   				  
					 if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
						local sem `sem' `sem`i''
					 }
					 else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
						local sem `sem' `semrecU`i''
					 }
					 else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
						local sem `sem' `semrep`i''
					 }
					 else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
						local sem `sem' `semrecUrep`i''
					 }
					 else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
						local sem `sem' `semrep`i''
					 }
					 else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
						local sem `sem' `semrecUrep`i''
					 }
					 else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
						local already=1
					 }
					 else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
						local sem `sem' `semrep`i''
						local already=1
					 }
					 else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
						local sem `sem' `semrecUrep`i''
						local already=1
					 }
					
				  
				 }
			  
			  }
			  
			 
			  /*set trace off*/
			  if (`already'!=1) {
				  qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var'  iterate(100)  method(`method') cov(`cov12b' `covariances' `covfit') 
				  di "`sem' "
				  di "`var' " 
				 qui estat gof
			
				 local chi2encours=r(chi2_ms)
				 local dfencours=r(df_ms)
				 local pencours=r(p_ms)
				 local bicencours=r(bic)
				 if "`cas'"=="cas6" | "`cas'"=="cas8"  {
					local nbtest=1-(0.05/(`nbitems'*3-(`=`cpt'+`nbpass'+`ajust'')))
				 }
				 if "`cas'"=="cas5" | "`cas'"=="cas7" {
			     local nbtest=0.95
			     } 
			   
				 if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`test_varchi2_temp'&`chi2encours'<`prec_chi2') {
					local continue=1
					local test_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
					local test_p_temp =1-chi2(1,`test_varchi2_temp')
					local test_item_temp=`j'
					local chi2encours_tmp=`chi2encours'
					local tmp=`chi2encours'
					local typeRS_encours=`typeRS'
				 }
				 
				 if ( `chi2encours'<`prec_chi2') {
				 local unav`=`nbpass'`j'`typeRS''=0
					 if "`html'" != "" {
						di "<tr><td>``j''</td><td>" %8.2f `chi2encours' "</td><td>" %4.0f `dfencours' "</td><td>" %6.4f `pencours' "</td><td>" %7.2f `bicencours' "</td><td>" %8.2f `=abs(`chi2encours'-`prec_chi2' )' "</td><td>1</td><td>" %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' "</td></tr>"
					 }
					 else {
						di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
					 }
				 }
				 else {
				 local unav`=`nbpass'`j'`typeRS''=1
					 if "`html'" != "" {
						di "<tr><td>``j''</td><td>Unavailable</td></tr>"
					 }
					 else {
						di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
					 }
				 }
				 return scalar unav`=`nbpass'`j'`typeRS''= `unav`=`nbpass'`j'`typeRS'''
				 
				local ++cpt
				 
				 
				 
			  }
		   }
		  
	   }
		 
       if (`test_item_temp'!=0) {
		if `typeRS_encours'==1 {
          matrix `RS'[`test_item_temp',1]=1
		}
		if `typeRS_encours'==2 {
			matrix `RS'[`test_item_temp',2]=1
		}
		if `typeRS_encours'==3 {
			matrix `RS'[`test_item_temp',3]=1
		}
		  
		  /*matrix list `RS'*/
          local ++df3
          local test_varchi2=`test_varchi2_temp'
          local test_p=`test_p_temp'
          local test_item_temp=0
          local prec_chi2=`tmp'
		  
		
       }
	   local ++nbpass
      if (`cpt'!=0) {
	  if "`html'" != "" {
	      di "<tr><td colspan=8><hr></td></tr>"
	  }
	  else {
              di "{hline 88}"
          }
       }
    }
    if "`html'" != "" {
        di "</tbody></table>"
    }
}



}


/**************************************************************************************************************
Model 3 Final
***************************************************************************************************************/

di
local continue=1
local var
local sem
forvalues i=1/`nbitems' {
   local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
   local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
   local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
   local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
   local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
   local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
   if `RS'[`i',1]==1 {
      local var "`var' `varrecNU`i''"
   }
   if `RS'[`i',1]==0 {
      local var "`var' `var`i''"
   }
   if `RS'[`i',2]==0&`RS'[`i',3]==0 {
      local sem "`sem' `sem`i''"
   }
   if `RS'[`i',2]==0&`RS'[`i',3]==1 {
      local sem "`sem' `semrep`i''"
   }
   if `RS'[`i',2]==1&`RS'[`i',3]==0 {
      local sem "`sem' `semrecU`i''"
   }
   if `RS'[`i',2]==1&`RS'[`i',3]==1 {
      local sem "`sem' `semrecUrep`i''"
   }
}

qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var'  iterate(100)   method(`method') cov(`cov12b' `covariances' `covfit')
di "`sem'" 
di"`var'" 
tempname b V
matrix `b'=r(table)
matrix `V'=e(V)
local truechange=`b'[1,`=`nbitems'*4+1']
local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
qui estat gof
local iter3=e(ic)
local tli3=r(tli)
local cfi3=r(cfi)
local srmr3=r(srmr)
local rmsea3=r(rmsea)
local ubrmsea3=r(ub90_rmsea)
local lbrmsea3=r(lb90_rmsea)
local pclose3=r(pclose)
local chi23=r(chi2_ms)
local dfc3=`df3'
local p3=r(p_ms)
local bic3=r(bic)
local convergence3= e(converged)


return matrix b3=`b'
return scalar iter3=`iter3'
return scalar tli3=`tli3'
return scalar cfi3=`cfi3'
return scalar srmr3=`srmr3'
return scalar rmsea3=`rmsea3'
return scalar ubrmsea3=`ubrmsea3'
return scalar lbrmsea3=`lbrmsea3'
return scalar pclose3=`pclose3'
return scalar chi23=`chi23'
return scalar df3=`df3'
return scalar dfc3=`dfc3'
return scalar p3=`p3'
return scalar bic3=`bic3'
return scalar convergence3=`convergence3'

/**************************************************************************************************************
Bilan
***************************************************************************************************************/

if "`html'"=="" {
    di
    di  "{hline 74}"
    di in gr           _col(22) "Non uniform"       _col(46) "Uniform"
    di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(58) "Reprioritization"
    di  "{hline 74}"
}
else {
    di "<table id=rsoortbilantable class=restable >"
    di "<caption></caption>"
    di "<thead><tr><th>Items</th><th>Non-uniform<br>Recalibration</th><th>Uniform<br>Recalibration</th><th><br>Repriorisation</th></tr></thead>"
    di "<tbody>"
}
forvalues i=1/`nbitems' {
   local recNU
   local recU
   local rep
   if (`RS'[`i',1]==1) {
      local recNU "*"
   }
   if (`RS'[`i',2]==1) {
      local recU "*"
   }
   if (`RS'[`i',3]==1) {
      local rep "*"
   }
   if "`html'"=="" {
       di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
   }
   else {
       di "<tr><td>``i''</td><td>`recNU'</td><td>`recU'</td><td>`rep'</td></tr>"
   }
}
if "`html'"=="" {
    di  "{hline 74}"
}
else {
    di "</tbody></table>"
}


/**************************************************************************************************************
Model 4
***************************************************************************************************************/

if "`model4'"=="" {
   local qui qui
}
else {
   local qui
}
local arret_covfit=999 


`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var'  iterate(100)  cov(`cov12b' `covariances' `covfit')  method(`method') 
di "`sem'" 
di"`var'"
tempname b
matrix `b'=r(table)

estat gof
local rmsea4=r(rmsea)

*set trace on

while `rmsea4' >0.08 {

di"`rmsea4'"
tempfile data
save `data', replace
/*on récupère les indices de modifs*/
estat mindice
matrix indice = r(mindices)
clear
/* on ajoute dans une colonne le nom des items concernés*/
svmat2 indice , r(nomcol) full
/*on controle l'ajout de covariances uniquement sur un même temps*/
gen tmp=substr(nomcol,1,3)
drop if tmp!="cov"

gen tmp1=substr(nomcol,11,1)
gen tmp2=substr(nomcol,20,1)
drop if tmp1 != tmp2

/*On vérifie qu'il reste des lignes de covariances à ajouter*/
local vide = indice1[1]
if "`vide'" == "." {
local covfit= "`covfit'"
local arret_covfit=1
local rmsea4=0
use "`data'", clear
}
else {
/*on trie par ordre croissant pour ajouter les covariances les plus influentes*/
local arret_covfit=0
gsort - indice1

local tmp3=nomcol[1]
lstrfun e, subinstr("`tmp3'","cov(","",.)
lstrfun e, subinstr("`e'",")","",.)
lstrfun e, subinstr("`e'",":_cons","",.)
lstrfun e, subinstr("`e'",",","*",.)

/*matrix list indice */

local covfit= "`covfit' `e'"
di "`covfit'"

use "`data'", clear
di "`data'"


`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var'  iterate(100)  cov(`cov12b' `covariances' `covfit')  method(`method')
di "`sem'" 
di"`var'"
tempname b
matrix `b'=r(table)

estat gof
local rmsea4=r(rmsea)


local tmp4="`covfit'"
lstrfun r, subinstr("`tmp4'","e.itemA","0",.)
lstrfun r, subinstr("`r'","e.itemB","1",.)
lstrfun r, subinstr("`r'","*","",.)
lstrfun r, subinstr("`r'"," ","",.)
}
}




di "`covfit'"
tempname V
matrix `V'=e(V)
local truechange=`b'[1,`=`nbitems'*4+1']
local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']

qui estat gof,stat(all)
local iter4=e(ic)
local tli4=r(tli)
local cfi4=r(cfi)
local srmr4=r(srmr)
local rmsea4=r(rmsea)
local ubrmsea4=r(ub90_rmsea)
local lbrmsea4=r(lb90_rmsea)
local pclose4=r(pclose)
local chi24=r(chi2_ms)
local df4=r(df_ms)
local dfc4=`df3'+1
local p4=r(p_ms)
local chi2encours=r(chi2_ms)
local bic4=r(bic)
local convergence4=e(converged)
local cov_fit4="`r'"
local arret_covfit4=`arret_covfit'
local z=`truechange'/sqrt(`Vtruechange')


return matrix b4=`b'
return scalar iter4=e(ic)
return scalar tli4=`tli4'
return scalar cfi4=`cfi4'
return scalar srmr4=`srmr4'
return scalar rmsea4=`rmsea4'
return scalar ubrmsea4=`ubrmsea4'
return scalar lbrmsea4=`lbrmsea4'
return scalar  pclose4=`pclose4'
return scalar chi24=`chi24'
return scalar df4=`df4'
return scalar dfc4=`dfc4'
return scalar p4=`p4'
return scalar bic4=`bic4'
return scalar convergence4=`convergence4'
return local cov_fit4 = "`cov_fit4'"
return scalar arret_covfit4 = `arret_covfit4'
return scalar truechange=`truechange'
return scalar setruechange=`=sqrt(`Vtruechange')'
return scalar ztruechange=`=`truechange'/sqrt(`Vtruechange')' 
return scalar ptruechange=`=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'





if "`html'" != "" {
	di "<table id=rsoortM4table class=restable >"
	di "<caption></caption>"
	di "<thead><tr><th>Models</th><th>chi2</th><th>df</th><th><I>p</I></th><th>BIC</th><th>RMSEA</th><th>IC<sub>90%</sub>(RMSEA)</th><th>SRMR</th><th>CFI</th><th>TLI</th></tr></thead>"
	di "<tbody>"
	di "<tr><td>Model 1</td><td>" %8.2f `chi21' "</td><td>" %4.0f `df1' "</td><td>" %7.2f `bic1' "</td><td>" %6.4f `p1' "</td><td>" %6.4f `rmsea1' "</td><td>" %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' "</td><td>" %6.4f `srmr1' "</td><td>" %6.2f `cfi1' "</td><td>" %6.2f `tli1' "</td></tr>"
	di "<tr><td>Model 2</td><td>" %8.2f `chi22' "</td><td>" %4.0f `df2' "</td><td>" %7.2f `bic2' "</td><td>" %6.4f `p2' "</td><td>" %6.4f `rmsea2' "</td><td>" %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' "</td><td>" %6.4f `srmr2' "</td><td>" %6.2f `cfi2' "</td><td>" %6.2f `tli2' "</td></tr>"
	di "<tr><td>Model 4</td><td>" %8.2f `chi24' "</td><td>" %4.0f `df4' "</td><td>" %7.2f `bic4' "</td><td>" %6.4f `p4' "</td><td>" %6.4f `rmsea4' "</td><td>" %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4'  "</td><td>" %6.4f `srmr4' "</td><td>" %6.2f `cfi4' "</td><td>" %6.2f `tli4' "</td></tr>"
	di "</tbody></table>"
}
else {
        di
        di  "{hline 95}"
        di in gr "Models" _col(14) "chi2" _col(22) "df" _col(31) "p" _col(40) "BIC" _col(47) "RMSEA" _col(55) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
        di  "{hline 95}"
        di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `df1' _col(26) %6.4f `p1' _col(36) %7.2f `bic1' _col(46) %6.4f `rmsea1' _col(54) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1'  _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
        di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `df2' _col(26) %6.4f `p2' _col(36) %7.2f `bic2' _col(46) %6.4f `rmsea2' _col(54) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2'  _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
        *di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3'  _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
        di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `df4' _col(26) %6.4f `p4' _col(36) %7.2f `bic4' _col(46) %6.4f `rmsea4' _col(54) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4'  _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
        di  "{hline 95}"
}


if "`html'" != "" {
	di "<table id=rsoorttruechangetable class=restable >"
	di "<caption></caption>"
	di "<thead><tr><th></th><th>Estimation</th><th>s.e.</th><th>z</th><th><I>p</I>-value</th></tr></thead>"
	di "<tbody>"
	di "<tr><td>True change (Model 2)</td><td>" %8.4f `truechange2' "</td><td>" %8.4f `=sqrt(`Vtruechange2')' "</td><td>" %6.2f `=`truechange2'/sqrt(`Vtruechange2')' "</td><td>" %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))' "</td></tr>"
	di "<tr><td>True change (Model 4)</td><td>" %8.4f `truechange' "</td><td>" %8.4f `=sqrt(`Vtruechange')' "</td><td>" %6.2f `=`truechange'/sqrt(`Vtruechange')' "</td><td>" %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))' "</td></tr>"
	di "</tbody></table>"
}
else {
        di
        di  "{hline 77}"
        di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
        di  "{hline 77}"
        di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
        di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
        di  "{hline 77}"
        di
}
qui use `saveMultirsoort_indicefit',clear



end
