function [Tve,Le,Re,sym] = vveig(Mvv,Rv)

% VVEIG   Vessel eigenmode representation
%   [TVE,LE,RE,SYM] = VVEIG(MVV,RV) returns the vessel eigenmodes TVE, their
%   self inductance LE, their nominal resistance RE and a 0-1 vector flagging
%   the symetric eigenmodes in SYM. MVV is the vessel filament mutual and RV
%   their resistance.
%
%   The transformation from eigenmode currents to vessel current distribution is
%   IV = TVE*IE. The transformation of a mutual matrix to the current
%   distribution to the mutual to the eigenmodes is MXE = MXV*TVE. In particular
%   LEE = TVE'*MVV*TVE = diag(LE) and REE = TVE'*RV*TVE = diag(RE). Note that
%   inv(TVE) ~= TVE' except if all RV are equal.
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

nv = length(Rv);

% resistance normalisation
Re = 1 ./ sum(1 ./ Rv);

% diagonalisation
[Tve,Le] = eig(Mvv ./ (sqrt(Rv)*sqrt(Rv'))); % the mode time constants in Le
Le = diag(Le) * Re;
k = flipud(isort(Le));
Le = Le(k);
Tve = sqrt(Re) * Tve(:,k) ./ sqrt(Rv(:,ones(1,nv)));

% parity
sym = sum((Tve(1:floor((nv+1)/2),:) + Tve(nv:-1:ceil((nv+1)/2),:)).^2) > 1e-6;
fact = sign(Tve(1,:));
fact(~sym) = sign(Tve(2,~sym) - Tve(1,~sym));
Tve = Tve .* fact(ones(nv,1),:);
