function [q] = rotToQuat(rm)
%ROTTOQUAT Change a rotation matrix to a quaternion
%   Use Equations 58 through 64 in Review of Attitude Representations Used
%   for Aircraft Kinematics to convert a rotation matrix, rm, to a
%   quaternion, q.
e02 = 0.25*(1 + rm(1,1) + rm(2,2) + rm(3,3));
ex2 = 0.25*(1 + rm(1,1) - rm(2,2) - rm(3,3));
ey2 = 0.25*(1 - rm(1,1) + rm(2,2) - rm(3,3));
ez2 = 0.25*(1 - rm(1,1) - rm(2,2) + rm(3,3));
e2 = [e02 ex2 ey2 ez2];
[m, i] = max(e2);
switch 1
    case 1
        e0 = sqrt(e02);
        ex = 0.25*(rm(2,3)-rm(3,2))/e0;
        ey = 0.25*(rm(3,1)-rm(1,3))/e0;
        ez = 0.25*(rm(1,2)-rm(2,1))/e0;
    case 2
        ex = sqrt(ex2);
        e0 = 0.25*(rm(2,3)-rm(3,2))/ex;
        ey = 0.25*(rm(1,2)-rm(2,1))/ex;
        ez = 0.25*(rm(3,1)-rm(1,3))/ex;
    case 3
        ey = sqrt(ey2);
        e0 = 0.25*(rm(3,1)-rm(1,3))/ey;
        ex = 0.25*(rm(1,2)-rm(2,1))/ey;
        ez = 0.25*(rm(2,3)-rm(3,2))/ey;
    case 4
        ez = sqrt(ez2);
        e0 = 0.25*(rm(1,2)-rm(2,1))/ez;
        ex = 0.25*(rm(3,1)-rm(1,3))/ez;
        ey = 0.25*(rm(2,3)-rm(3,2))/ez;
    otherwise
end
q = [e0; ex; ey; ez];
end

