One of Scotland's most historic religious buildings feared its 800 years of worship would come to an end.