(a) When the building or improvement is erected under or by virtue of any contract with a lessee in possession, and the erection thereof is not in violation of the terms or conditions of the lease, the lien shall attach to such building or improvement, and to the unexpired term of the lease, and the holder of the lien shall have the right to avoid a forfeiture of the lease by paying rent to the lessor, as it becomes due and payable, or by the performance of any other act or duty to which the lessee may be bound; and if the lien is enforced by a sale of the building or improvement, the purchaser may, at his election, become entitled to the possession of the demised premises, and to remain therein for the unexpired term, by paying rent to the lessor, or performing any other act or duty to which the lessee was bound, as if he were the assignee of the lease; or he may, within 60 days after the sale, remove such building or improvement from the premises; and if he elects to take possession and to remain therein until the expiration of the term of the lease, he may, within a reasonable time after the expiration of the term, remove such building or improvement from the premises. If, before a sale, the holder of the lien has made any payments of rent, or other pecuniary compensation to the lessor, which ought to have been paid by the lessee, he shall be reimbursed for such payments from the proceeds of the sale.
(b) When a lien attaches under subsection (a), the lessor, at any time before a sale of the property, shall have a right to discharge the same, by paying to the holder the amount secured thereby, including costs and all moneys he may have paid to the lessor to prevent a forfeiture of the lease, and, after a sale, he shall have the right to prevent the removal of the building or improvement from the premises by paying to the purchaser the value of such building or improvement; and upon such payment, either to the holder of the lien or to the purchaser, such building or improvement shall become the property of the lessor.