pro tstvwimg, rawimg, binned_data, cl, out, nerr
;
; This procedure performs vector weighted binning on a raw image and compares
; it with the binned image processed by the IP. It also creates a 1024x1024 
; byte array (out) from  the medium-l list (cl).  Elements of the array 
; corresponding to the areas specified in the list are filled from the 
; binned array. 

out = intarr(1024,1024)
; out(0:*) = 0
; if (value eq 0) then out(0:*) = 255
l=n_elements(cl)
j = 0L
total_errs = 0
line_errs = 0
p = 0
nal = cl(2)
print,nal
table_start = '7000'XL
xvec_offset = (long(cl(16) and 'ffff'x) + $
              (long(cl(17) and 'ffff'x) * '10000'x)) - table_start
nx = cl(18)
yvec_offset = (long(cl(19) and 'ffff'x) + $
              (long(cl(20) and 'ffff'x) * '10000'x)) - table_start
ny = cl(21)
xvec = long(cl(xvec_offset:xvec_offset+nx-1))
yvec = long(cl(yvec_offset:yvec_offset+ny-1))
wt_table = lonarr(nx, ny)
for ix = 0, nx-1 do begin
    wt_table (0, ix) = ishft ((xvec(ix) * yvec), -15)
endfor
;print,wt_table
shift_count = cl(25) and '7fff'x            ; AND out the ms bit (Shift Flag)
nerr = 0
for i=0,nal-1  do begin
  nextal = (i)*10+22
  ix = (long(cl(nextal)) and 'ffff'x) + (long(cl(nextal+1) and 'ffff'x) * '10000'x)
  ixr = ix - table_start
  nent = cl(nextal + 2)
  ixre = ixr + nent*2 - 1
;  print,"New List"
  print, nextal,ix,ixr,table_start,nent,ixre,nerr,format='(i6,5z10, "  nerr=", i6)'
  for j = ixr,ixre,2 do begin
    add = long(cl(j) and 'ffff'x) + (long(cl(j+1) and 'ffff'x) * '10000'x)
    r = add / 1024
    c = add mod 1024
    sum_r = lonarr(3)
    temp = 0l
    ;for ir = r, r+ny-1 do begin
    ;    for ic = c, c+nx-1 do begin
    ;        ;print, rawimg(ic,ir), wt_table(ic-c,ir-r)
    ;        mult48, long(rawimg(ic,ir)), long(wt_table(ic-c,ir-r)), result
    ;        sum_r = sum_r + result
    ;    endfor
    ;endfor
    sbf = rawimg(c:c+nx-1, r:r+ny-1) * wt_table(0:nx-1,0:ny-1)
    sample = 0l
    for ir = 0,ny-1 do $
        for ic = 0, nx-1 do $
            sample = sample + sbf(ic,ir)

    ;sample = sum_r(1) or (ishft (sum_r(0), 16))    
    ;sample = total (rawimg(c:c+nx-1, r:r+ny-1) * wt_table(0:nx-1,0:ny-1))
    sample = ishft (long(sample), shift_count - 32)
    ;sample = ishft (long(sample), shift_count-16)
    if (sample ne binned_data(p)) then begin
        nerr = nerr + 1
        print, r, c, sample, binned_data(p), sum_r, format='(2i6, 2x, 2i8, 2x, 3z10)'
    ;    stop
    endif
    out(c:c+5,r:r+5) = binned_data(p)
    p = p + 1
  end
end
return
end
