;+
;PROCEDURE: TNORMALIZE
;Purpose:
;  Vectorized routine to normalize all the vectors stored in a tplot
;  variable
;
;
;Arguments: 
; v: The name of the tplot variable storing the vectors to be
; normalized
; newname(optional): The name of the output tplot variable. Defaults
; to v+'_normalized'
; error(optional): Named variable in which to return the error state
; of the computation, 1 = success, 0 = failure
; 
;
;NOTES:
;
; $LastChangedBy: bckerr $
; $LastChangedDate: 2008-07-31 16:52:00 -0700 (Thu, 31 Jul 2008) $
; $LastChangedRevision: 3322 $
; $URL: svn+ssh://thmsvn@ambrosia.ssl.berkeley.edu/repos/ssl_general/trunk/cotrans/special/tnormalize.pro $
;-

;helper function
;calculates the norm of a bunch of vectors simultaneously
function ctv_norm_vec_helper,v

COMPILE_OPT HIDDEN

if not keyword_set(v) then return, -1L

if size(v,/n_dim) ne 2 then return,-1L

return, sqrt(total(v^2,2))

end

;helper function
;normalizes a bunch of vectors simultaneously
function ctv_normalize_vec_helper,v

COMPILE_OPT HIDDEN

if not keyword_set(v) then return, -1L

if size(v,/n_dim) ne 2 then return,-1L

n_a = ctv_norm_vec_helper(v)

if(size(n_a,/n_dim) eq 0 && n_a eq -1L) then return,-1L

v_s = size(v,/dimension)

;calculation is pretty straight forward
;we turn n_a into an N x D so computation can be done element by element
n_b = rebin(n_a,v_s[0],v_s[1])

return,v/n_b

end

pro tnormalize,v,newname=newname,error=error

if arg_present(error) then error = 0

if not keyword_set(v) then begin

    message,/continue,'TNORMALIZE: input vector v must be set'

    return

endif 

if tnames(v) eq '' then begin

    message,/continue,'TNORMALIZE: input vector v must be set'

    return

endif 

if not keyword_set(newname) then newname = v + '_normalized'

get_data,v,data=d,limits=l,dlimits=dl

y = ctv_normalize_vec_helper(d.y)

if(size(y,/n_dim) eq 0 && y[0] eq -1L) then begin
    
    message,/continue,'TNORMALIZE: failed to normalize input vector'

    return

endif


str_element,d,'v',SUCCESS=s

if(s) then $
  d = {x:d.x,y:y,v:d.v} $
else $
  d = {x:d.x,y:y} 

store_data,newname,data=d,limits=l,dlimits=dl

error = 1

return

end
