function Result_struct = calculate_key_measurements(nMat, key_points)
% Calculates key measurements on the mesh for comparison with the measured values
% and the same key measurements calculated using the control points.
%
% :param nMat:  Matrix with nodal coordinates.
%
% :param key_points: Struct with the nodes corresponding to the key locations on
%                    the body.
%
% :return Result_struct: Struct with the key points and the key measurements.
%                        This can be used for reporting or further processing.
%
% Created by : ABR august@lightness.eu
% Date : 2024-06-11

C1 = nMat(  nMat(:,1) == key_points.C1(2), :);      % Top of head
C3 = nMat(  nMat(:,1) == key_points.C3(2), :);      % Groin
C4 = nMat(  nMat(:,1) == key_points.C4(2), :);      % Heel, left
C5 = nMat(  nMat(:,1) == key_points.C5(2), :);      % Right hand shoulder
C6 = nMat(  nMat(:,1) == key_points.C6(2), :);      % Left hand shoulder
C15 = nMat( nMat(:,1) == key_points.C15(2),:);      % Knee joint center
C16 = nMat( nMat(:,1) == key_points.C16(2),:);      % Hip joint center

C7 = nMat(  nMat(:,1) == key_points.C7(2), :);
C11 = nMat( nMat(:,1) == key_points.C11(2),:);
C12 = nMat( nMat(:,1) == key_points.C12(2),:);
C13 = nMat( nMat(:,1) == key_points.C13(2),:);
C14 = nMat( nMat(:,1) == key_points.C14(2),:);


% Shoulder-to-groin length
shoulder_to_groin = C5(4) - C3(4);

% Shoulder width
shoulder_width = C6(3) - C5(3);

% Total length
knee_to_foot_XZ = sqrt( (C15(2)-C4(2))^2 + (C15(4)-C4(4))^2 );
hip_to_knee_XZ = sqrt( (C16(2)-C15(2))^2 + (C16(4)-C15(4))^2 );

total_length = (C1(4) - C3(4)) - (C16(4) - C3(4)) + hip_to_knee_XZ + knee_to_foot_XZ;

% Head circumference
circumferenceMatrix = [C13 ; C12 ; C11 ; C14 ; C7];
head_circumference = 2.0 * sum ( sqrt( diff(circumferenceMatrix(:,2)).^2 + diff(circumferenceMatrix(:,3)).^2 ) );

% Calculate the angle between the z-axis and the foot-knee vector
dx_foot_to_knee = C15(2)-C4(2);
dz_foot_to_knee = C15(4)-C4(4);
angleZX_foot_to_knee = atand(dx_foot_to_knee / dz_foot_to_knee);

dx_hip_to_knee = C16(2)-C15(2);
dz_hip_to_knee = C16(4)-C15(4);
angleZX_hip_to_knee = atand(dx_hip_to_knee / dz_hip_to_knee);


Result_struct.C1 = C1;
Result_struct.C3 = C3;
Result_struct.C4 = C4;
Result_struct.C5 = C5;
Result_struct.C6 = C6;
Result_struct.C7 = C7;
Result_struct.C11 = C11;
Result_struct.C12 = C12;
Result_struct.C13 = C13;
Result_struct.C14 = C14;
Result_struct.C15 = C15;
Result_struct.C16 = C16;

Result_struct.total_length = total_length;
Result_struct.shoulder_to_groin = shoulder_to_groin;
Result_struct.shoulder_width = shoulder_width;
Result_struct.head_circumference = head_circumference;
Result_struct.angleZX_foot_to_knee = angleZX_foot_to_knee;
Result_struct.angleZX_hip_to_knee = angleZX_hip_to_knee;



