Soon they were both imprisoned on the order of Nasir-ad-Din Faraj. Together in prison, the two leaders renewed their friendship, making an agreement that Sultan Ahmed Jalayir should keep Baghdad while Qara Yusuf would have Azerbaijan. Ahmad also adopted his son Pirbudag. When Timur died in 1405 Nasir-ad-Din Faraj released them both. However, according to Faruk Sümer, they were released on the orders of rebellious wali of Damascus - Sheykh Mahmud. Qara Yusuf, having returned from exile in Egypt and went back to Anatolia. He forced Timur's governor in Van Izzaddin Shir to submit, while capturing Altamış, another viceroy set up by Timur and sending him to Barquq. He later moved on to Azerbaijan. He defeated the Timurid Abu Bakr at the Battle of Nakhchivan on 14 October 1406 and reoccupied Tabriz. Abu Bakr and his father Miran Shah tried to recapture Azerbaijan, but on 20 April 1408, Qara Yusuf inflicted a decisive defeat on them at the Battle of Sardrud in which Miran Shah was killed. This battle, one of the most important in the history of the Orient, nullified the results of Timur's conquests in the West. In 1409 fall, he entered Tabriz and sent a raiding party to Shirvan, especially Shaki, which was fruitless. Another invasion force was sent to capture Sultaniyya and Qazvin under command of Bistam Beg. Same year, he marched to Anatolia and deposed Salih Şihabeddin Ahmed, thus ending Mardin branch of Artuqids. Instead he was married to a daughter of Yusuf and sent to govern Mosul. Having firmly established as a ruler of Azerbaijan with Tabriz as his capital, Qara Yusuf fell foul of his former ally Sultan Ahmed Jalayir. Sultan Ahmed Jalayir tried to seize Azerbaijan, but was defeated near Tabriz on 30 August 1410. He was captured and forced to abdicate in favor of Pirbudag (7 year old biological son of Qara Yusuf) and to appoint Shah Muhammad (another son of Qara Yusuf) to be governor of Baghdad. He was executed the next day passing Iraq into the hands of Qara Yusuf after Bistam Beg urged him. Qara Yusuf declared his son as "sultan" and crowned him in 1411, however he was still in charge as regent.