;+
;NAME:
; tsub_average
;PURPOSE:
; Subtracts average or median values from the data in a tplot
; variable, returns a new variable, only one at a time for now
;CALLING SEQUENCE:
; tsub_average, varname, out_name, new_name=new_name,median=median
;INPUT:
; varname =  a tplot variable name
;OUTPUT:
; out_name = variable name of the output tplot variable
;KEYWORDS:
; new_name = can be used to input the new variable name, if not input
; the default is to add a '-d' to the input name (or '-m' for median
; subtraction) and the name is passed out in this variable
;HISTORY:
; 18-jul-2007, jmm, jimm@ssl.berkeley.edu
;$LastChangedBy: $
;$LastChangedDate: $
;$LastChangedRevision: $
;$URL: $
;-
Pro tsub_average, varname, nn, new_name = new_name, median = median, $
                     _extra = _extra

  If(keyword_set(new_name)) Then nn = new_name Else Begin
    If(keyword_set(median)) Then nn = varname+'-m'$
    Else nn = varname+'-d'
  Endelse
  get_data, varname, data = d, limits = lim, dlimits = dlim
  szsv = size(d.y)
  If(szsv[0] Le 2) Then Begin
    svalue = average(d.y, 1, /double, ret_median = median)
    d.y = d.y-(replicate(1, n_elements(d.x))#svalue)
    store_data, nn, data = temporary(d), limits = temporary(lim), $
      dlimits = temporary(dlim)
  Endif Else If(szsv[0] Eq 3) Then Begin
    svalue = average(d.y, 1, /double, ret_median = median)
    tdata = rebin(svalue, szsv[1], szsv[2], n_elements(d.x))
    tdata = transpose(tdata, [2, 0, 1])
    d.y = d.y-temporary(tdata)
    store_data, nn, data = temporary(d), limits = temporary(lim), $
      dlimits = temporary(dlim)
  Endif Else Begin
    message, /cont, 'Operation not supported for data arrays of more than 2d'
    nn = ''
  Endelse

  new_name = nn
  Return
End