             { --- Subroutines to find index for cursor position --- }

procedure find_index_above_cx(var index:integer;cx,n:integer);
{ find index for pos. n lines above cx }
var i,j,x:integer;
begin
j:=n; i:=index;
while (j>=1) and (i>=TEXTSTART) do
    begin i:=index-ch_to_bol(index)-1; if i>0 then index:=i; j:=j-1; end;
if i>=TEXTSTART then
    begin
    x:=x_to_bol(index)+1;
    while x>cx do
        begin index:=index-1; x:=x-dx(index); end;
    end;
end; { find_index_above_cx }

procedure find_index_below_cx(var index:integer;cx,n:integer);
{ find index for pos. n lines below cx }
var i,j,x: integer;
begin
j:=n; i:=index;
while (j>=1) and (i<text_end) do
    begin
    i:=index+ch_to_eol(index);
    if (i<text_end) and (eol(i)) then index:=i+1;
    j:=j-1;
    end;
if index<text_end then
    begin
    x:=SCREENLEFT;
    while (x<cx) and (not eol(index)) do
        begin
        x:=x+dx(index); index:=index+1; end;
    end;
end; { find_index_below_cx }

procedure find_page_bottom_index;
{ finds the bottom index of the current page }
var i,j:integer;
begin
i:=page_top_index;
for j:=page_top_line to page_bottom_line do
    begin
    page_bottom_index:=i;
    i:=i+ch_to_eol(i)+1;
    end;
end; { find_page_bottom_index }

procedure find_page_bottom_line;
{ finds the bottom line of the current page }
begin
page_bottom_line:=min(page_top_line+PAGELEN-1,n_lines);
end; { find_page_bottom_line }

procedure restore_page(index:integer; var cx,cy:integer);
var i,l:integer;
begin
l:=line(index);
page_top_line:=max(1,l-(PAGELEN div 2)); find_page_bottom_line;
page_top_index:=index-ch_to_bol(index); cx:=SCREENLEFT;
find_index_above_cx(page_top_index,cx,l-page_top_line);
find_page_bottom_index;
display_rest_page(page_top_index,SCREENLEFT,SCREENTOP);
cx:=x_to_bol(index)+1; cy:=SCREENTOP+l-page_top_line;
end; { restore_page }

procedure find_page(index:integer; var cx,cy:integer);
var i,l:integer;
begin
l:=line(index);
if (l<page_top_line) or (page_bottom_line<l) then restore_page(index,cx,cy)
else begin cx:=x_to_bol(index)+1; cy:=SCREENTOP+l-page_top_line; end;
end; { find_page }

