I am concerned about you going through Madrid three times, which is not very efficient. Can you fly into Barcelona? Can you stay in Madrid at the end of the trip instead of in the middle? I would feel more comfortable to sleep in the city from which I fly home, rather than planning to take a 2.5-hour train that morning, before connecting to the airport.
The best train ticket prices are for sale now, 2 months in advance. Barcelona-Madrid is the most expensive ticket, and therefore offers the most advance savings. But don't buy tickets until you are sure of your plans.
Most of your trains will be direct, not needing connections, so counting them isn't necessarily hard. Another oddity of the Renfe Spain pass (a set of online e-tickets sold on the Renfe site), in addition to counting train segments instead of calendar days, is that you must reserve each leg in chronological order, nothing out of order!
If you choose the Eurail Spain pass (a physical pass sold here and mailed to you at home), then you are counting calendar days, such as 4 travel days for $258 per person, and pay about $20 for each seat reservation on top of that, and the number of seats for pass holders is limited.