after the Treaty of Stensby in 1238 and remained its property (together with the rest of Northern Estonia – see Danish Estonia) for the next 138 years. In 1240 building of the cathedral was completed in the place it stands today. In the second half of the 13th century Toompea (the Great Castle) was surrounded with a wall by the hill's perimeter, built mainly by vassals who owned the plots there. Beginning from the same period Toompea started to develop into the centre of provincial authority, clergy and nobility in Northern Estonia. Most of the vassals chose Toompea for their residence – living in their estates in the conquered countryside was deemed too dangerous; by the end of the 13th century the Great Castle was densely populated. The distinction between Toompea and the Lower Town (Tallinn) also developed at the time as Tallinn gained its own administration – at least in 1248, when the King of Denmark Eric IV granted the town Lübeck city rights, but possibly even earlier. In 1265 the Lower Town was exempted from the rule of the castellan and in 1288 the commanders of the castle also lost judicial power over the citizens of the Lower Town. Construction and expansion works on both castles continued in the subsequent centuries. In the first half of the 14th century the southern wall of the Great Castle was renovated and its moat was joined with the eastern moat of the Small Castle. In this way the outer ward of the castles was built, after its southern and southeastern sides were surrounded with a wall. The castle as a whole had two exits at the time: the more important one was outer ward's southern gate, through which the road led to Tõnismägi, the second was the gate at its eastern, which connected Toompea with Lower Town via the Long and Short Legs. In the aftermath of the St. George's Night Uprising, in 1346 Denmark sold its possessions in Northern Estonia and followed 215 years under the rule of the Livonian Order. Tallinn (the Lower Town), which was still subjected to Lübeck city rights and only nominally depended on the feudal system, developed into a flourishing Hanseatic city, while Toompea remained politically and socially antithetical to the Lower Town. The boundaries of the territory of Toompea and Tallinn were fixed with an agreement in 1348, when from the city's patrimony was