def match_variant_sequence_to_reference_context(
        variant_sequence,
        reference_context,
        min_transcript_prefix_length,
        max_transcript_mismatches,
        include_mismatches_after_variant=False,
        max_trimming_attempts=2):
    variant_sequence_in_reading_frame = None
    for i in range(max_trimming_attempts + 1):
        variant_sequence_too_short = (
            (reference_context.strand == "+" and
                len(variant_sequence.prefix) < min_transcript_prefix_length) or
            (reference_context.strand == "-" and
                len(variant_sequence.suffix) < min_transcript_prefix_length)
        )
        if variant_sequence_too_short:
            logger.info(
                "Variant sequence %s shorter than min allowed %d (iter=%d)",
                variant_sequence,
                min_transcript_prefix_length,
                i + 1)
            return None
        variant_sequence_in_reading_frame = \
            VariantSequenceInReadingFrame.from_variant_sequence_and_reference_context(
                variant_sequence=variant_sequence,
                reference_context=reference_context)
        if variant_sequence_in_reading_frame is None:
            return None
        n_mismatch_before_variant = (
            variant_sequence_in_reading_frame.number_mismatches_before_variant)
        n_mismatch_after_variant = (
            variant_sequence_in_reading_frame.number_mismatches_after_variant)
        logger.info("Iter
            i + 1,
            max_trimming_attempts + 1,
            variant_sequence_in_reading_frame))
        total_mismatches = n_mismatch_before_variant
        if include_mismatches_after_variant:
            total_mismatches += n_mismatch_after_variant
        if total_mismatches <= max_transcript_mismatches:
            return variant_sequence_in_reading_frame
        logger.info(
            ("Too many mismatches (%d) between variant sequence %s and "
             "reference context %s (attempt=%d/%d)"),
            n_mismatch_before_variant,
            variant_sequence,
            reference_context,
            i + 1,
            max_trimming_attempts + 1)
        current_min_coverage = variant_sequence.min_coverage()
        logger.info(
            "Trimming to subsequence covered by at least %d reads",
            current_min_coverage + 1)
        variant_sequence = variant_sequence.trim_by_coverage(
            current_min_coverage + 1)
    return None