MADRID (AP) — Defending champion Novak Djokovic recovered from a 3-0 deficit in the third set to defeat Nicolas Almagro 6-1, 4-6, 7-5 and reach the third round at the Madrid Open on Wednesday.

Djokovic rallied in the final set by breaking Almagro to go up 6-5 and served out to earn his 15th win of the season in over two hours. The victory left Djokovic on track to play a semifinal against four-time Madrid champion and home-crowd favorite Rafael Nadal, who struggled in a 7-6 (3), 3-6, 6-4 win over a Fabio Fognini of Italy in just under three hours.

“I haven’t played bad, I played really bad,” Nadal said. “It was uncomfortable.”

Nadal will play Nick Kyrgios of Australia, who defeated Ryan Harrison of the United States 6-3, 6-3. The second-seeded Djokovic will play veteran Spaniard Feliciano Lopez, who got past Gilles Simon of France 6-3, 3-6, 7-6 (3).

Djokovic cruised in the first set by breaking the 76th-ranked Almagro three times. The Spanish wild card entrant rallied in front of the home crowd in the second set, saving all four break points he conceded and breaking at 4-5 to eventually extend the match.

Almagro was two points away from going up 4-2 in the final set but was not able to capitalize on his chances.

It was an important opening-round win for the second-ranked Djokovic as he tries to turn his season around and regain his form going into the French Open later this month.

“When you’re not winning too many matches, you have to build the confidence level,” Djokovic said. “So to win the matches like this definitely helps confidence.”

Djokovic won in Doha to start the season but never made it past the quarterfinals in the following four tournaments he played. In his first clay-court tournament, in Monte Carlo, Djokovic was eliminated by David Goffin in quarterfinals.

“I’m still finding my way to that consistency level and quality of tennis that I’m looking for,” Djokovic said. “I’m aware that I’m not playing at my best, but I’m definitely believing in myself and the process. Eventually the game will come together. I can take a lot of positives from today.”

Djokovic had his playing time diminished this year because of an elbow injury. Wednesday’s match was his first since splitting with longtime coach Marian Vajda.

Nadal had a tough start against Fognini, needing to save 10 of 12 break points conceded to the Italian in the first set alone. Fognini served for the set at 5-4 but was not able to capitalize on his chance. He threw his racket on the ground three times in a row after losing a decisive point in the tiebreaker.

It was the 11th straight win for Nadal, and his tour-leading 30th victory for the year. The fifth-ranked Spaniard has won 22 of his last 24 sets.

“Even though I played…