0 value bottom
8000 constant line-size
: insert 0 { cadr len p -- }
here bottom ?do
cadr len i 2@ compare
1 < if i to p leave then
2 cells +loop
p
if p p 2 cells + here p - move ( Shift to make room for new item.)
cadr len p 2!
2 cells allot
else cadr len 2, ( Put new item at end.)
then ;
: read-and-sort { handle }
here to bottom
begin
line-size 2 + allocate throw ( 2 + allows for CR/LF.)
dup line-size handle read-line throw
while ( adr len)
tuck resize throw
swap insert
repeat
2drop ;
: main 0 { handle }
BL parse
r/o open-file throw
dup read-and-sort
close-file throw
s" sorted.txt" w/o open-file throw
to handle
here bottom ?do
i 2@ 2dup handle write-line throw
drop free throw
2 cells +loop
handle close-file throw
bye ;