<P> However, the Tang did manage to restore at least indirect control over former Tang territories as far west as the Hexi Corridor and Dunhuang in Gansu . In 848 the ethnic Han Chinese general Zhang Yichao (799 - 872) managed to wrestle control of the region from the Tibetan Empire during its civil war . Shortly afterwards Emperor Xuānzong of Tang (r . 846 - 859) acknowledged Zhang as the protector (防禦 使, Fangyushi) of Sha Prefecture and jiedushi military governor of the new Guiyi Circuit . </P> <P> In addition to natural calamities and jiedushi amassing autonomous control, the Huang Chao Rebellion (874--884) resulted in the sacking of both Chang'an and Luoyang, and took an entire decade to suppress . Although the rebellion was defeated by the Tang, it never recovered from that crucial blow, weakening it for the future military powers to take over . There were also large groups of bandits, in the size of small armies, that ravaged the countryside in the last years of the Tang, who smuggled illicit salt, ambushed merchants and convoys, and even besieged several walled cities . </P> <P> Zhu Wen, originally a salt smuggler who had served under the rebel Huang, surrendered to Tang forces . By helping to defeat Huang, he was granted a series of rapid military promotions . In 907 the Tang dynasty was ended when Zhu Wen, now a military governor, deposed the last emperor of Tang, Emperor Ai of Tang, and took the throne for himself (known posthumously as Emperor Taizu of Later Liang). He established the Later Liang, which inaugurated the Five Dynasties and Ten Kingdoms period . A year later Zhu Wen had the deposed Emperor Ai poisoned to death . </P> <P> Taizong set out to solve internal problems within the government which had constantly plagued past dynasties . Building upon the Sui legal code, he issued a new legal code that subsequent Chinese dynasties would model theirs upon, as well as neighboring polities in Vietnam, Korea, and Japan . The earliest law code to survive was the one established in the year 653, which was divided into 500 articles specifying different crimes and penalties ranging from ten blows with a light stick, one hundred blows with a heavy rod, exile, penal servitude, or execution . </P>

Who was the last ruler of the tang dynasty