pro scc_missing_blocks,img,hdr,nmissing,missn,misslist,nblocks,map=map
;+
; $Id: scc_missing_blocks.pro,v 1.2 2014/08/07 11:45:14 secchia Exp $
;
; Project     : STEREO SECCHI
;                   
; Name        : scc_missing_blocks
;               
; Purpose     : finds and maps missing blocks 
;               
; Explanation : 
;               
; Use         : IDL> scc_missing_blocks
;    
; Inputs      : img = fits image, hdr = header (string or structure) 
;               
; Outputs     : nmissing = number of missing blocks, missn = array of missing blocks, misslist 34 base string of missing blocks locations 
;
; Keywords :	MAP    displays a map of bad blocks represented by 1's 
;               
; Common      : 
;               
; Restrictions: 
;               
; Side effects: 
;               
; Category    : Pipeline 
;               
; Prev. Hist. : None.
;
; Written     : Lynn McNutt 05/02/2007 
;               
; Modified    :
;
; $Log: scc_missing_blocks.pro,v $
; Revision 1.2  2014/08/07 11:45:14  secchia
; using image size not header values for xysize
;
; Revision 1.1  2007/05/03 14:30:25  mcnutt
; Bug 100 and Bug 84 added misslist and nmissing for rice and HC
;

z=size(hdr)
if(z(2) ne 8)then scch=fitshead2struct(hdr,scch) else scch=hdr
blksz=64
ax1=scch.naxis1 & ax2=scch.naxis2
xz=size(img)
ax1=xz[1] & ax2=xz[2]
blocks=intarr(ax1/blksz,ax2/blksz)
for n=0,(ax1/blksz)-1 do $
    for n1=0,(ax2/blksz)-1 do $
    	if(total(img(n*blksz:n*blksz+(blksz-1),n1*blksz:n1*blksz+(blksz-1))) eq 0)then blocks(n,n1)=1

; remove missing blocks created by secchi_reduce when image is not square 2112-2048 COR2
if (ax1/blksz gt ax2/blksz and total(blocks(0,*))/n_elements(blocks(0,*)) eq 1) then blocks(0,*)=0 
if (ax1/blksz gt ax2/blksz and total(blocks((ax1/blksz)-1,*))/n_elements(blocks((ax1/blksz)-1,*)) eq 1) then blocks((ax1/blksz)-1,*)=0 
if (ax2/blksz gt ax1/blksz and total(blocks(*,0))/n_elements(blocks(*,0)) eq 1) then blocks(*,0)=0 
if (ax2/blksz gt ax1/blksz and total(blocks(*,(ax2/blksz)-1))/n_elements(blocks(*,(ax2/blksz)-1)) eq 1) then blocks(*,(ax1/blksz)-1)=0 

missn=where(blocks eq 1)
nmissing=0 & misslist=''
if(missn(0) gt -1)then begin
  nmissing=n_Elements(missn)
  miss34=inttobn(missn,34)
  for n=0,n_Elements(missn)-1 do MISSLIST=misslist+string(miss34(n),'(a2)')
endif

if keyword_set(map) then begin
    fmt='('+string(ax1/blksz)+'(i1,1x))'
    for n=(ax2/blksz)-1,0,-1 do print,format=fmt,blocks(*,n)
    print,nmissing
    print,MISSLIST
endif

nblocks=n_elements(blocks)

end
