If the mortgaged premises cannot be sold in parcels, the court shall order the whole to be sold, and the proceeds of the sale shall be applied first to the payment of the principal due, interest and costs, and then to the residue secured by the mortgage and not due; and if the residue does not bear interest, a deduction shall be made therefrom by discounting the legal interest. In all cases where the proceeds of the sale are more than sufficient to pay the amount due and costs, the surplus shall be applied to all interests in, or liens or claims of liens against, the property eliminated by sale under this section in the order of priority that the interest, lien, or claim attached to the property. Any remaining surplus shall be paid to the mortgage debtor, his or her heirs and assigns.