;+
; Procedure: minvar.pro
; This program computes the principal variance directions and variances of a
; vector quantity (can be 2D or 3D).  This routine is a simple version
; designed to be used by a tplot wrapper with the contrans_var library
;
; Input: Vxyz, an (ndim,npoints) array of data
; Output: eigenVijk, an (ndim,ndim) array containing the principal axes vectors
;         Maximum variance direction eigenvector, Vi=eigenVijk(*,0)
;         Intermediate variance direction, Vj=eigenVijk(*,1) (descending order)
;
;         Vrot: if set to a name, that name becomes an array of (ndim,npoints)
;         containing the rotated data in the new coordinate system, ijk.
;         Vi(maximum direction)=Vrot(0,*)
;         Vj(intermediate direction)=Vrot(1,*)
;         Vk(minimum variance direction)=Vrot(2,*)
;
;         lambdas2=if set to a name returns the eigenvalues of the
;         computation
;
;
;Written by: Vassilis Angelopoulos
;
;
; $LastChangedBy: pcruce $
; $LastChangedDate: 2007-10-04 15:40:27 -0700 (Thu, 04 Oct 2007) $
; $LastChangedRevision: 1667 $
; $URL: svn+ssh://thmsvn@ambrosia.ssl.berkeley.edu/repos/ssl_general/tags/tdas_3_01/cotrans/special/minvar/minvar.pro $
;
;-
pro minvar,Vxyz,eigenVijk,Vrot=Vrot,lambdas2=lambdas2

ndim=n_elements(Vxyz(*,0))
if (ndim gt 3) then begin
  print,'minvar computation may take a while: number of dimensions= ',ndim
  if(ndim gt 10) then begin
    print,'computation aborted: too many dimensions'
    return
  endif
endif
eigenVijk=make_array(ndim,ndim,/double)
lambdas2=make_array(ndim,/double)
sigmas=make_array(ndim,/double)
Vrot=pcomp(Vxyz,coefficients=eigenVijk,eigenvalues=lambdas2,variances=sigmas,/covariance,/double)
for jth=0,ndim-1 do begin
  eigenVijk(*,jth)=eigenVijk(*,jth)/sqrt(lambdas2(jth))
endfor
;
;Ensure correct orientation of minvar axis
;coordinate system will place minimum variance direction along the z-axis
;
if (eigenVijk(0,2) lt 0) then begin
  eigenVijk(*,2)=-eigenVijk(*,2) & Vrot(2,*)=-Vrot(2,*)
  eigenVijk(*,1)=-eigenVijk(*,1) & Vrot(1,*)=-Vrot(1,*)
endif
;
return
;
end