of the household of the caliph's wife and children, director of the mint at Madinat al-Zahra, commander of the Cordoba police, and qadi of the frontier. During his time as qadi in north Africa, Ibn Abi Amir developed close ties with the North African Berbers. Considerable resentment arose in Cordoba against the increasing numbers of Berbers brought from north Africa by al-Mansur and his children Abd al-Malik and Sanchuelo. It was said that Sanchuelo ordered anyone attending his court to wear Berber turbans, which Roger Collins suggests may not have been true, but shows that hostile anti-Berber propaganda was being used to discredit the sons of al-Mansur. In 1009, Sanchuelo had himself proclaimed Hisham II's successor, and then went on military campaign. However, while he was away a revolt took place. Sanchuelo's palace was sacked and his support fell away. As he marched back to Cordoba his own Berber mercenaries abandoned him. Knowing the strength of ill feeling against them in Cordoba, they thought Sanchuelo would be unable to protect them, and so they went elsewhere in order to survive and secure their own interests. Sanchuelo was left with only a few followers, and was captured and killed in 1009. Hisham II abdicated and was succeeded by Muhammad II al-Mahdi. Having abandoned Sanchuelo, the Berbers who had formed his army turned to support another ambitious Umayyad, Sulayman. They obtained logistical support from Count Sancho Garcia of Castile. Marching on Cordoba, they defeated Saqaliba general Wadih and forced Muhammad II al-Mahdi to flee to Toledo. They then installed Sulayman as caliph, and based themselves in the Madinat al-Zahra to avoid friction with the local population. Wadih and al-Mahdi formed an alliance with the Counts of Barcelona and Urgell and marched back on Cordoba. They defeated Sulayman and the Berber forces in a battle near Cordoba in 1010. To avoid being destroyed, the Berbers fled towards Algeciras. Al-Mahdi swore to exterminate the Berbers and pursued them. However, he was defeated in battle near Marbella. With Wadih, he fled back to Cordoba while his Catalan allies went home. The Berbers turned around and besieged Cordoba. Deciding that he was about to lose, Wadih overthrew al-Mahdi and sent his head to the Berbers, replacing him with Hisham II. However, the Berbers did not end the siege. They methodically destroyed Cordoba's suburbs, pinning the inhabitants inside the old Roman walls and destroying the Madinat al-Zahra.