program define predraschwlm,rclass
syntax varlist , genlt(string) id(string)

tempfile filesave
qui save `filesave',replace
tempname diff theta
matrix `diff'=r(beta)
matrix `theta'=r(theta)


qui count
local N=r(N)

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

tempname item offset id
qui gen `id'=_n

forvalues i=0/`nbitems' {
   local thetascore`i'=`theta'[1,`=`i'+1']
}

tempname nbmiss
qui egen `nbmiss'=rowmiss(`varlist')
tempfile s
qui save `s',replace
forvalues i=1/`N' {
   use `s',clear
   if `nbmiss'[`i']!=0 {
      local w`i'=0
      local l`i'=1
      forvalues j=1/`nbitems' {
         local item`j'=``j''[`N']
         local diff`j'=`diff'[1,`j']
         local rep`i'_`j'=``j''[`i']
         if `rep`i'_`j''!=. {
            local w`i' `w`i''+exp(x-`diff`j'')/(1+exp(x-`diff`j''))^2
            local l`i' `l`i''*exp(`rep`i'_`j''*(x-`diff`j''))/(1+exp(x-`diff`j''))
         }
      }
      local w`i' sqrt(`w`i'')
      *di "`i'"
      clear
      qui set obs 20001
      qui gen u=_n
      qui gen x=(u-10001)/1000
      qui gen f=`w`i''*`l`i''
      qui gsort -f
      local tl`i'=x[1]
   }
}
qui use `filesave',clear
qui capture drop `genlt'
qui gen `genlt'=.
tempname scores
qui genscore `varlist',score(`scores')
forvalues i=0/`nbitems' {
   qui replace `genlt'=`thetascore`i'' if `scores'==`i'
}
forvalues i=1/`N' {
   if `genlt'[`i']==. {
      qui replace `genlt'=`tl`i'' in `i' if `genlt'==.
   }
}
end