No contemporary source states where Queen Margaret died, but in the 14thc. John of Fordun wrote that Queen Margaret died in castro puellarum in Edinburgh. It is recorded that King Edgar died at Edinburgh Castle in January 1107. But the first reference to a church in the castle comes about 1130 with Bishop Robert of St Andrew's charter confirming the church in the castle to the monks of Holyrood Abbey. It is not certain to which church this refers, as there was a second church in the castle, dedicated to St Mary. In 1174, the castle was handed over to King Henry II of England as security for the ransom of King William the Lion of Scotland, who was in prison at the time in Falaise (Normandy). The castle was only restored to the Scottish King in 1186 on King William’s marriage to Ermengarde de Beaumont.