;+
;PROCEDURE: TCROSSP
;Purpose:
;  Vectorized routine to calculate the cross product of two tplot
;  variables containing arrays of 3d vectors and storing the result
;  in a tplot variable
;
;Arguments: 
; v1: The name of the tplot variable storing the first vector in the cross product
; v2: The name of the tplot variable storing the second vector in the
; cross product
; 
; newname(optional): the name of the output tplot variable
;
; error(optional): named variable in which to return error state of
; the computation.  1 = success 0 = failure
;
;NOTES: 
;---> its not really clear how the dlimits should be set in the
;output from this function...at the moment the output variable just
;inherits from v1
;---> Time data from v1 will also be inherited for the output variable
;
;---> The dimensions of v1 and v2 must match or an error will be thrown
;
;
; $LastChangedBy: pcruce $
; $LastChangedDate: 2007-12-20 11:53:35 -0800 (Thu, 20 Dec 2007) $
; $LastChangedRevision: 2214 $
; $URL: svn+ssh://thmsvn@ambrosia.ssl.berkeley.edu/repos/ssl_general/trunk/cotrans/special/tcrossp.pro $
;-
;

pro tcrossp,v1,v2, newname = newname,error=error


if keyword_set(error) then error = 0

;input checks
if(not keyword_set(v1)) then begin 

  message, /continue, 'tcrossp: argument v1 must be set'

  return

endif

if(tnames(v1) eq '') then begin 

  message, /continue, 'tcrossp: argument v1 must be set'

  return

endif

if(not keyword_set(v2)) then begin 

  message, /continue, 'tcrossp: argument v2 must be set'

  return

endif

if(tnames(v2) eq '') then begin 

  message, /continue, 'tcrossp: argument v2 must be set'

  return

endif

if not keyword_set(newname) then newname = v1+'_cross_'+v2

get_data, v1, data = v1_d, dlimits = v1_dl

get_data, v2, data = v2_d, dlimits = v2_dl

v1_s = size(v1_d.y,/dimension)

v2_s = size(v2_d.y,/dimension)

;make sure the number of dimensions in input arrays is correct
if(n_elements(v1_s) ne 2 || n_elements(v2_s) ne 2) then begin

  message, /continue, 'tcrossp: V1 and V2 may contain only 2-d data arrays'
 
  return
endif

;make sure the dimensions match
if(not array_equal([v1_s[0],3],v2_s)) then begin 

  message, /continue, 'tcrossp: Dimensions of v2 incorrect'

  return

endif

if(not array_equal([v2_s[0],3],v1_s)) then begin

  message, /continue, 'tcrossp: Dimensions of v1 incorrect'

  return

endif


;the calculation(delightfully symmetric)
x = v1_d.y[*,1] * v2_d.y[*,2] - v1_d.y[*,2] * v2_d.y[*,1]
y = v1_d.y[*,2] * v2_d.y[*,0] - v1_d.y[*,0] * v2_d.y[*,2]
z = v1_d.y[*,0] * v2_d.y[*,1] - v1_d.y[*,1] * v2_d.y[*,0]


;stick em together as a single array
out_d = [[x],[y],[z]] 

str_element,v1_d,'v',success=s

if s then $
   out = {x:v1_d.x, y:out_d, v:v1_d.v} $
else $
   out = {x:v1_d.x, y:out_d}

store_data, newname, data = out, dlimits = v1_dl

error = 1

return

end
