I would like someone to explain me how can I optimize this code since it lags if first file (tokens.ini) gets large.

alias sortfile {
  set %h 2
  set %j $ini(tokens.ini,0)

  write -c tokens.txt
  write tokens.txt $readini(tokens.ini,$ini(tokens.ini,1),tokens) $ini(tokens.ini,1)

  while (%h <= %j) {
    set %t 1
    set %u $lines(tokens.txt)
    while (%t <= %u) {
      if ($readini(tokens.ini,$ini(tokens.ini,%h),tokens) > $gettok($read(tokens.txt,%t),1,32)) {
        write -il $+ %t tokens.txt $readini(tokens.ini,$ini(tokens.ini,%h),tokens) $ini(tokens.ini,%h)
        if ($lines(tokens.txt) >= 11) {
          .write -dl11 tokens.txt
        goto nextline
      else {
        if (%t = %u) && ($lines(tokens.txt) < 10) {
          write tokens.txt $readini(tokens.ini,$ini(tokens.ini,%h),tokens) $ini(tokens.ini,%h)
        inc %t
    inc %h

First file has several sections (like 800+) with 1 item each. I want the second file to get only the first 10 higher values. The way I made this code freezes mIRC for some seconds since there's a lot of lines to read. Any way to optimize it and make it faster without lagging?