# Input: tot, min, names
# Output: Each row corresponds to a list.

!distribute item $wims_read_parm into tot,min
names=!item 3 to -1 of $wims_read_parm

!readproc defs
level=$confparm1
suffix=$confparm2
level=!listintersect $level and $Levels
!default level=freq
suffix=!listintersect $suffix and $suffix1
words=!items2words $confparm3
wordst=!words2items $words

!for l in $exclusive_levels
 !if $l isitemof $level
  level=$l
  !break
 !endif
!next l

!for n_ in $names
 out_$n_=
 res_$n_=
!next n_

!if $words!=$empty
 translator_unknown=
 !for n_ in $names
  !if $n_ notwordof nm nf
   data=!lookup $n_-raw in $listdic
   out_$n_=!listintersect $data and $wordst
  !else
   dictionary=$module_dir/data/$n_-raw.dic
   data=!exec translator $words
   out_$n_=!words2items $data
  !endif 
  test=!itemcnt $(out_$n_)
  !if $test<$min
   words=
   !break
  !endif
 !next n_
 !if $words!=$empty
  !goto out
 !else
  !for n_ in $names
   out_$n_=
  !next n_
 !endif
!endif

!if $suffix!=$empty
 !for n_ in $names
  !for s in $suffix
   data=!lookup $n_-suf-$s in $listdic
   res_$n_=!append item $data to $(res_$n_)
  !next s
  res_$n_=!listuniq $(res_$n_)
  test=!itemcnt $(res_$n_)
  !if $test<$min
   suffix=$empty
   !break
  !endif
 !next n_
!endif

!if $level notitemof $diclevels or nm notitemof $names
 :redo
 !for n_ in $names
  !for l in $level
   data=!lookup $n_-$l in $listdic
   out_$n_=!append item $data to $(out_$n_)
  !next l
  out_$n_=!listuniq $(out_$n_)
  test=!itemcnt $(out_$n_)
  !if $test<$min and $level notwordof freq rare raw
   level=freq
   !goto redo
  !endif
  !if $suffix!=$empty
   res_$n_=!listintersect $(out_$n_) and $(res_$n_)
   test=!itemcnt $(res_$n_)
   !if $test<$min
    suffix=$empty
    !break
   !endif
  !endif
 !next n_
 !if $suffix!=$empty
  !for n_ in $names
   out_$n_=$(res_$n_)
  !next n_
 !endif
!else #diclevels
 !if $suffix!=$empty
  !for n_ in $names
   !if $level iswordof raw
    out_$n_=$(res_$n_)
   !else
    data=!lookup $n_-freq in $listdic
    out_$n_=!listintersect $data and $(res_$n_)
    test=!itemcnt $(out_$n_)
    !if $test<$min
     out_$n_=$(res_$n_)
    !endif
   !endif
  !next n_
 !else
  !for n_ in $names
   t=0
   data=
   !while $t<$tot
    d1=!randrecord data/$n_-$level.rec
    data=!listunion $data and $d1
    t=!itemcnt $data
   !endwhile
   out_$n_=$data
  !next n_ 
 !endif 
!endif

:out
slib_out=
!for n_ in $names
 !if , isin $(out_$n_)
  out_$n_=!randperm $(out_$n_)
 !endif
 out_$n_=!item 1 to $tot of $(out_$n_)
 out_$n_=!nonempty item $(out_$n_)
 slib_out=$slib_out$(out_$n_);
!next n_

