In such case the proceeds of such sale shall be applied as well to the interest, portion, or installment of the principal due as towards the whole or residue of the sum secured by such mortgage, and not due and payable at the time of such sale; and if such residue does not bear interest, then the court may direct the same to be paid with a rebate of the legal interest, for the time during which such residue shall not be due and payable; or the court may direct the balance of the proceeds of such sale, after paying the sum due, with costs, to be put out at interest, for the benefit of the complainant, to be paid to him as the installments or portions of the principal or interest may become due, and the surplus for the benefit of the defendant, his representative, or assigns, to be paid to them on the order of the court.