FUNCTION SCALEIMG,img2,left=left,right=right,equal=equal
;scales an image, to be displayed with tv later
;example: given a stokes v/i image with v/i e [-15%,50%] and want to
;display it with a range of [-50%,50%] to have v/i=0 in a neutral grey
;call the function newimg=scaleimg(oldimg,-0.5,0.5)
;if the keyword equal is set then the range is scaled to +-max(abs(img))
;either (left and right) or 'equal' have to be set, equal overrides l and r 
;20.11.07 LK
;14.1.14: [0,0,i] instead of [*,*,i] for speed
on_error,2

img=img2 ;pass by reference?

if not ((keyword_set(left) and keyword_set(right)) or keyword_set(equal)) then message,'SCALEIMG,img,left=left,right=right,equal=equal'

if keyword_set(left) and keyword_set(right) then begin
range = right-left
endif

;image or array?
dims = (size(img))[0]
if dims eq 3 then nmax = (size(img))[3] else nmax=1

for i=0,nmax-1 do begin

if keyword_set(equal) then begin
left  = -max(abs(img[*,*,i]))
right = max(abs(img[*,*,i]))
range = right-left
endif


;lk changed 1 to 1. -> otherwise dark image
temp = round((!d.table_size - 1.)/range * (img[*,*,i]-left))

;correct for values below or above range

img[0,0,i] = temp >0 <(!d.table_size - 1.)

endfor

return, img

END
