pro colorbar, min, max, ticks, x0, y0, xsiz, ysiz, $
    charsize=charsize, horiz=horiz, reverse=reverse, cmin=cmin, cmax=cmax
;
; draws color bar from min to max with ticks tickmark intervals.
; The lower left hand corner is located at x0, y0 (normal coordinates, 0-1).
; The size is xsiz,ysiz (normal coordinates, 0-1). 
; Keywords:
; If charsize is set, it specifies label character size (default=1)
; If horiz is set, a horizontal bar is drawn (default is vertical)
; If reverse is set, the color scale is reversed.
; If cmin and cmax are present, the color scale runs between these table values,
;    otherwise, it runs from 0 to the maximum color index.

on_error,1
if not keyword_set(charsize) then charsize=1
if not keyword_set(cmin) then cmin=0
if not keyword_set(cmax) then cmax=!d.table_size-2

if (!d.flags and 1) then begin
  xpix=804
  ypix=622
endif else begin
  if !d.window eq -1 then message,'Must open a window first'
  xpix=!d.x_size
  ypix=!d.y_size
endelse

xdim=fix(xsiz*xpix)/2*2
ydim=fix(ysiz*ypix)/2*2
xs=float(xdim)/float(xpix)
ys=float(ydim)/float(ypix)
x1=x0+xs
y1=y0+ys

if keyword_set(horiz) then begin
  ca=bytscl(findgen(xdim),top=cmax-cmin)+cmin
  if keyword_set(reverse) then ca=cmax+cmin-ca
  cb=bytarr(xdim,ydim)
  for i=0,xdim-1 do cb(i,*)=ca(i)
  tv, cb, x0, y0, xsize=xs, ysize=ys, /normal
  xsbox=[x0,x0,x1,x1,x0]
  ysbox=[y0,y1,y1,y0,y0]
  plots,xsbox,ysbox,/normal
  for it=0,ticks do begin
    val=min+it*float(max-min)/float(ticks)
    lab=string(val,'(F7.1)')
    xt=x0+it*xs/float(ticks)
    plots,[xt,xt],[y0,y0+ys/4.],/normal
    xl=xt-.04*charsize
    yl=y0-.03*charsize
    xyouts,xl,yl,lab,/normal,size=charsize
  endfor
endif else begin
  ca=bytscl(findgen(ydim),top=cmax-cmin)+cmin
  if keyword_set(reverse) then ca=cmax+cmin-ca
  cb=bytarr(xdim,ydim)
  for i=0,ydim-1 do cb(*,i)=ca(i)
  tv, cb, x0, y0, xsize=xs, ysize=ys, /normal
  xsbox=[x0,x0,x1,x1,x0]
  ysbox=[y0,y1,y1,y0,y0]
  plots,xsbox,ysbox,/normal
  for it=0,ticks do begin
    val=min+it*float(max-min)/float(ticks)
    lab=string(val,'(F7.1)')
    yt=y0+it*ys/float(ticks)
    plots,[x1-xs/4.,x1],[yt,yt],/normal
    xl=x1
    yl=yt-.004*charsize
    xyouts,x1,yl,lab,/normal,size=charsize
  endfor
endelse
;
return
end