the place is uncertain, as he reports that he served the Khwarazmshah (ruler) of the region, the Ma'munid Abu al-Hasan Ali. The latter ruled from 997 to 1009, which indicates that Avicenna moved sometime during that period. He may have moved in 999, the year which the Samanid state fell after the Turkic Qarakhanids captured Bukhara and imprisoned the Samanid ruler Abd al-Malik II. Due to his high position and strong connection with the Samanids, Avicenna may have found himself in an unfavorable position after the fall of his suzerain. It was through the minister of Gurganj, Abu'l-Husayn as-Sahi, a patron of Greek sciences, that Avicenna entered into the service of Abu al-Hasan Ali. Under the Ma'munids, Gurganj became a centre of learning, attracting many prominent figures, such as Avicenna and his former teacher Abu Sahl al-Masihi, the mathematician Abu Nasr Mansur, the physician Ibn al-Khammar, and the philologist al-Tha'alibi. In Gurgan Avicenna later moved due to "necessity" once more (in 1012), this time to the west. There he travelled through the Khurasani cities of Nasa, Abivard, Tus, Samangan and Jajarm. He was planning to visit the ruler of the city of Gurgan, the Ziyarid Qabus (), a cultivated patron of writing, whose court attracted many distinguished poets and scholars. However, when Avicenna eventually arrived, he discovered that the ruler had been dead since the winter of 1013. Avicenna then left Gurgan for Dihistan, but returned after becoming ill. There he met Abu 'Ubayd al-Juzjani (died 1070) who became his pupil and companion. Avicenna stayed briefly in Gurgan, reportedly serving Qabus' son and successor Manuchihr () and resided in the house of a patron. In Ray and Hamadan In , Avicenna went to the city of Ray, where he entered into the service of the Buyid amir (ruler) Majd al-Dawla () and his mother Sayyida Shirin, the de facto ruler of the realm. There he served as the physician at the court, treating Majd al-Dawla, who was suffering from melancholia. Avicenna reportedly later served as the "business manager" of Sayyida Shirin in Qazvin and Hamadan, though details regarding this tenure are unclear. During this period, Avicenna finished his Canon of Medicine, and started writing his Book of Healing. In 1015, during Avicenna's stay in Hamadan, he participated in a public debate, as was custom for newly arrived scholars in western Iran at that time. The purpose of the debate was