(a) In an action for possession or in an action for rent when the tenant is in possession, the tenant may counterclaim for any amount the tenant may recover under the rental agreement or this chapter. It is in the court's discretion whether the tenant is to remain in possession. The tenant shall pay into court rent accrued and thereafter accruing as it comes due. The court shall determine the amount due to each party. The party to whom a net amount is owed shall be paid first from the money paid into court, and the balance by the other party. If no rent remains due after application of this section, judgment shall be entered for the tenant in the action for possession. If the defense or counterclaim by the tenant is without merit and is not raised in good faith, the landlord may recover reasonable attorney's fees.
(b) In an action for rent when the tenant is not in possession, the tenant may counterclaim as provided in subsection (a) but is not required to pay any rent into court.