def get_domain_by_sid(query_sid, scop):
    """
    Get a Bio.SCOP domain id for supplied sid. This could be done
    directly by scop.getDomainBySid(query_sid) except the various 
    exceptions and error conditions that can arise and we need to deal
    with (see comments in function).

    Parameters:
        query_sid - SCOP domain id (eg 'd1ubia_' of the domain to query.    
        scop - previously built Bio.SCOP Scop instance

    Return value:
        Bio.SCOP domain instance fo the query_sid
    """
    dom =scop.getDomainBySid(query_sid)
    if dom == None:
        # some domains seem to start with g rather than d
        # e.g. g1avo.4 or g1dk9.1 
        # they are in the astral-scopdom-seqres-all-1.73.fa file
        # with the g at the start, but for some reason get None when
        # looking up that sid, need to replace g with d instead.
        if query_sid[0] == 'g':
            query_sid = 'd' + query_sid[1:]
        # when using sids from older versions of ASTRAL SCOP
        # (e.g. 1.65 as used in Hulsen et al. (2006) sometimes
        # we get identifiers with _ as chainid e.g. d1ab4__ which
        # have been changed to have a as chainid instead as per recent PDB
        # remediation. So we'll try chainid a instead of _
        if query_sid[5] == '_':
            query_sid = query_sid[:5] + 'a' + query_sid[6]

        dom = scop.getDomainBySid(query_sid)

    return dom