;+                                                            
; NAME:
;	BCS_CLEAN
; PURPOSE:
;	to clean BDA INDEX (or ROADMAP) of records with 
;       mode/block id changes and SAA/NIGHT transitions
; CALLING SEQUENCE:
;	clean=bcs_clean(bda_index)
; INPUTS:
;       bda_index    - BDA index (or roadmap) structure
; OUTPUTS:
;       clean        - index vector of clean records
; KEYWORDS:
;       modeid       - modeid to filter out  (def = none)
;       blockid      - blockid to filter out (def = none)
;       err          - 1 if no clean records found, 0 otherwise
; PROCEDURE:
;                      Uses simple WHERE on MODEID, BLOCKID, and BCS_STATUS
;                      fields in structure
; HISTORY:
;                      Written, Nov. 1992 by D. Zarro (Applied Research Corp).
;                      Modified, Jan 1995 by Zarro to accept all BLOCKIDS
;-

function bcs_clean,bda_index,err=err,modeid=modeid,blockid=blockid

on_error,1
err=1

;
;-- Check structure input
;

sz=size(bda_index)
if sz(n_elements(sz)-2) ne 8 then begin
 message,'usage --> CLEAN=BCS_CLEAN(BDA_INDEX,[MODEID=MODEID],[BLOCKID=BLOCKID])
endif

;-- Check if INDEX or ROADMAP was entered
;

tags=strupcase(tag_names(bda_index))
yes_index=(tags(0) eq 'GEN') and (tags(1) eq 'BCS')
if yes_index then temp=bda_index.bcs else temp=bda_index 

;
;-- Check block id
;

if n_elements(blockid) ne 0 then begin
 valid=where(temp.blockid eq blockid,count)
 if count eq 0 then begin
  message,'no records with BLOCKID '+string(blockid,'(i1)'),/cont
  return,0
 endif
endif
  
;
;-- Check mode id 
;

if n_elements(modeid) ne 0 then begin
 valid=where(temp.modeid eq modeid,count)
 if count eq 0 then begin
  message,'no records with MODEID '+string(modeid,'(i1)'),/cont
  return,0
 endif
endif 

;
;-- Check for clean parts of orbit (no SAA nor Night)
; 

ndsets=n_elements(bda_index)
bcs_status=temp.bcs_status
bits=2^indgen(8)
valid_data=intarr(ndsets)
for i=0,ndsets-1 do begin
 on_bits=bcs_status(i) and bits
 valid_data(i)=(on_bits(4) eq 0) and (on_bits(5) eq 0)
endfor

clean_data=(temp.dgi gt 0) and valid_data
if n_elements(blockid) ne 0 then $
 clean_data=(temp.blockid eq blockid) and clean_data

if n_elements(modeid) ne 0 then $
 clean_data=clean_data and (temp.modeid eq modeid)

find=where(clean_data,ngood)
if ngood eq 0 then begin
 message,'no valid data in file; cannot proceed',/cont
 return,0
endif

;-- made it this far, so must be ok.

err=0

return,clean_data 

end

