def check_snp_reference(snp, ref, flip):
    """Utility function to check if a snp has the correct reference allele.

    :param snp: The :py:class:`gepyto.structures.variants.SNP` object.
    :type snp: :py:class:`gepyto.structures.variants.SNP`

    :param ref: The :py:class:`Reference` reference object.
    :type ref: :py:class:`Reference`

    :param flip: A flag. If True, the return value is a variant with alleles
                 flipped if necessary. If False, a bool is returned: True
                 if the alleles are correct.
    :type flip: bool

    :returns: Either a :py:class:`gepyto.structures.variant.SNP` with
              flipped alleles or a bool.

    This is used internally by :py:class:`Reference`, but it is also
    available to users, but you need to provide a pyfaidx Fasta object.

    """
    ref_allele = ref.get_nucleotide(snp.chrom, snp.pos)
    if ref_allele is None:
        s = "Can't find locus 'chr{}:{}' in the reference genome.".format(snp
            .chrom, snp.pos)
        raise ValueError(s)
    if ref_allele == snp.ref:
        return snp if flip else True
    if ref_allele == snp.alt:
        if flip:
            snp.ref, snp.alt = snp.alt, snp.ref
            return snp
        else:
            return False
    raise ValueError('Invalid alleles for variant {}. Reference is {}'.
        format(snp, ref_allele))
