pro rd_telem, lun_filnam, irec, rec1, err, badmf, force=force, reverse=reverse
;
;+
;Name:
;	rd_telem
;Purpose:
;	To read raw telemetry file
;Input:
;	lun_filnam	- logical unit or file name of file to read
;	irec		- record number (starting at 0)
;OPTIONAL INPUT:
;	force		- if present and non-zero, read that major frame
;			  no mater what the error check says
;			  CURRENTLY: any bad minor frames and the procedure
;			  automatically skips it
;	reverse		- Go BACKWARDS until finding a good record.  This
;			  allows us to check last valid data in a file.
;Output:
;	rec1		- one major frame (144x64)
;	err		- error flag
;				= 0	is ok
;				= 36 (0010 0100)	is end of file (or file not found)
;			  When using the "forced" mode, if the error ne 36, then check the following bits
;			  (note: cannot use b5 in order to maintain EOF = 36)
;				b/0  (0000 0001)	is bad sync word
;				b/1  (0000 0010)	is bad frame indicator
;	badmf		- 64 element vector showing where bad minor frame is
;			  1 indicates a bad minor frame 
;History:
;	Written Fall '91 by M.Morrison
;	14-Nov-91 (MDM) - Added "reverse" option
;	
;-
;
;
siz = size(lun_filnam)
vtyp = siz(siz(0)+1)
;
if (vtyp eq 7) then begin               ;passed file name
    get_lun, lun
    openr, lun, lun_filnam, /block
end else begin
    lun = lun_filnam
end
;
step = 1		;default is to increment forward
if (keyword_set(reverse)) then step = -1
irec = irec - step		;to increment in case of ERR=1
repeat begin
    irec = irec + step		;to increment in case of ERR=1
    ;
    ibyt = long(144*64)*irec	;each record is 9216
    rec1 = bytarr(144,64)
    ;
    on_ioerror, error
    point_lun, lun, ibyt
    readu, lun, rec1
    err = 0
    goto, no_error
    ;
    error:
	err=36
    no_error:
    ;
    if (err ne 36) then begin
	sync0 = rec1(16,*)
	sync1 = rec1(17,*)
	diff = abs(sync0 - 250) + abs(sync1 - 243)
	if (total(diff) ne 0) then begin
	    err = err + 1	;set b/0
	    badmf = bytarr(64)
	    ss = where(diff ne 0)
	    badmf(ss) = 1
	end

	fi = rec1(19,0)
	if ((fi mod 64) ne 0) then err = err + 2	;Added 23-Sep-91
							;Check that minor frame
							;is synced
    end
    qexit = 0
    if ((err eq 0) or (err eq 36) or keyword_set(force)) then qexit = 1
end until (qexit)
;
if (err eq 36) then rec1 = bytarr(144,64)	;make sure it is converted to zeros
;
if (vtyp eq 7) then free_lun, lun
end
