# 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 adj
   data=!lookup $N-all in $listdic
   out_$N=!listintersect $data and $wordst
  !else
   dictionary=$module_dir/data/$N-all.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
 res=
 !for s in $suffix
  suf_$s=!lookup suf-$s in $listdic
  res=!append item $(suf_$s) to $res
 !next s
 res=!listuniq $res
 !for N in $names
  !if $N=adj
   res_adj=$res
  !else
   res_$N=!lookup $N-all in $listdic
   res_$N=!listintersect $res and $(res_$N)
  !endif
  test=!itemcnt $(res_$N)
  !if $test<$min
   suffix=$empty
   !break
  !endif
 !next N
!endif

!if $level notitemof $diclevels or adj 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 all
   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 all
    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
   t=0
   data=
   !while $t<$tot
    d1=!randrecord data/$level.dic
    data=!listunion $data and $d1
    t=!itemcnt $data
   !endwhile
   out_$N=$data
 !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

