pro page_fmt, infil, outfil, lines, text=text, nonumber=nonumber
;+
; NAME:
;   page_fmt
; PURPOSE:
;   Add form-feeds and number pages every "lines" lines in an ascii file
; CALLING SEQUENCE:
;   page_fmt, infil, outfil
;   page_fmt, infil, outfil, 54
;   page_fmt, infil, outfil, 54, text='Page'	; Right justified
;   page_fmt, infil, outfil, 54, text='Page ??', /nonumber	; No page numbers
;
;   Existing <FF> (form-feed) characters are left in place and numbered
;   according.  This allows the user to force new pages at desired locations.
;
;   \newpage commands are treated just as if it were a <FF> character.
;
;   Two blank lines are inserted after each form-feed.
;   If the next 2 lines following a pre-exising <FF> are blank, then no
;   new blank lines are inserted.
;
; INPUTS:
;   infil	= Input file name
;   outfil	= Output file name
;   lines	= Number of lines between form-feeds (default = 54)
; OPTIONAL INPUT KEYWORDS:
;   text	= Text to write (def = 'Page') -- right justified
;   nonumber	= By default, will number the pages. If /nonumber, this will 
;			be inhibited.
; MODIFICATION HISTORY:
;    8-feb-94, J. R. Lemen, Written.
;    8-sep-94, JRL, Enabled \newpage allow new pages to be inserted (so that you
;		    don't have to know how to insert a ctl-L with the editor)
;-

buff = rd_tfile(infil)
if total(strlen(buff)) eq 0 then return

if n_elements(outfil) eq 0 then begin
   message,'OUTFIL not defined',/cont
   return
endif

FF = string(12b)	; Define the form-feed character
F1 = '\newpage'		; Must be lower case

if n_elements(lines) eq 0 then lines = 54
if n_elements(text) eq 0 then text = 'Page'

nlines = lines + 1 & outbuff = '' & npage = 1 & blank_count = 2
i = 0
while i le n_elements(buff)-1 do begin
  tt = buff(i)
  page_break = 0
  if strpos(tt,FF) ne -1 then page_break = 1	; loof for CTL-L
  if strpos(tt,F1) ne -1 then page_break = 1	; look for \newpage
  if nlines gt lines     then page_break = 1

  FFF = FF	; Uncomment next line to not have <FF> on Page 1
  ;if npage gt 1 then FFF = FF else FFF = ' '
     
  if page_break then begin
     if keyword_set(nonumber) then 					$
		header = string(FFF,text,format='(a,a78)') else 	$
		header = string(FFF,text,npage,format='(a,a75,i3)')
     outbuff = [outbuff, header,' ',' ']
     npage = npage + 1
     nlines = 3
     blank_count = 0
     if (strpos(tt,FF) ne -1) then i = i + 1
     if (strpos(tt,F1) ne -1) then i = i + 1
  endif else begin
     if (strlen(strcompress(tt,/remove)) ne 0) or 	$
	blank_count ge 2 then begin
	outbuff = [outbuff, tt]
        nlines = nlines + 1
     endif
     blank_count = blank_count + 1
     i = i + 1
  endelse
endwhile
outbuff = outbuff(1:*)		; Eliminate first blank

print,'Number of pages        = ',Npage-1,format='(a,i3)'
print,'Number of lines input  = ',n_elements(buff),format='(a,i3)'
print,'Number of lines output = ',n_elements(outbuff),format='(a,i3)'

prstr,outbuff,file=outfil
end
