function leg_scaling_factor = calculate_scaling_factor_legs_z(tcp, tcp_kpis_T5, baby_measurements)
% Calculates the scaling factor to match total length once the head and the
% torso have been scaled.
%
% :param tcp:           Matrix with target control points
%
% :param tcp_kpis_T5:   Structure with the key measurements calculated on the tcps
%                       after the preceeding scaling operation.
%
% :param baby_measurements:   Measured size of the baby
%
% :output leg_scaling_factor:  Scalar factor that the legs must be scaled to match the measured
%
% The code consists of the following five distances:
%
% ALEN : Distance along Z between the top of the head and the groin.
% BLEN : Distance between the hip joint and the groin along Z.
% CLEN : Distance from the hip joint to the knee joint in the XZ-plane.
% DLEN : Distance from the knee joint to the heel in the XZ-plane.
%
% baby_measurements(1) : Measured total length to match
%

ALEN = tcp_kpis_T5.C1(3) - tcp_kpis_T5.C3(3);
BLEN = tcp_kpis_T5.C16(3) - tcp_kpis_T5.C3(3);

CLEN = sqrt( (tcp_kpis_T5.C16(1)-tcp_kpis_T5.C15(1))^2 + (tcp_kpis_T5.C16(3)-tcp_kpis_T5.C15(3))^2 );
DLEN = sqrt( (tcp_kpis_T5.C15(1)-tcp_kpis_T5.C4(1))^2 + (tcp_kpis_T5.C15(3)-tcp_kpis_T5.C4(3))^2 );

leg_scaling_factor = (baby_measurements(1) - ALEN + BLEN) / (CLEN + DLEN);
