#include <ncbi.h>
#include "blastapp.h"
#include "gcode.h"

/*-------------------------  ovlap_x()---------------------------------

	ovlap_x(hp1, hp2)

	return TRUE if hp1 and hp2 overlap; otherwise return FALSE.
*/
Boolean
ovlap_x(hp1, hp2)
	register HSPPtr	hp1, hp2;
{
	register Coord_t	pos10, pos11, pos20, pos21;

	/* Return FALSE if hits are on different strands */
	if (SIGN(hp1->frame) != SIGN(hp2->frame))
		return FALSE;


	/* Look first for overlapping on subject/database sequence... */

	pos10 = hp1->s_pos;
	pos20 = hp2->s_pos;
	pos11 = pos10 + hp1->len - 1;
	pos21 = pos20 + hp2->len - 1;

	if (pos10 <= pos20 && pos11 >= pos21)
		return TRUE;
	if (pos20 <= pos10 && pos21 >= pos11)
		return TRUE;


	/* Look for overlapping on the query sequence... */

	if (hp1->frame > 0) {
		pos10 = hp1->q_pos * CODON_LEN + hp1->frame - 1;
		pos20 = hp2->q_pos * CODON_LEN + hp2->frame - 1;
	}
	else {
		pos10 = hp1->q_pos * CODON_LEN - hp1->frame + 1;
		pos20 = hp2->q_pos * CODON_LEN - hp2->frame + 1;
	}
	pos11 = pos10 + hp1->len * CODON_LEN - 1;
	pos21 = pos20 + hp2->len * CODON_LEN - 1;

	if (pos10 <= pos20 && pos11 >= pos21)
		return TRUE;
	if (pos10 >= pos20 && pos11 <= pos21)
		return TRUE;

	return FALSE;
}


/*-------------------------  ovlap_x2()---------------------------------

	ovlap_x2(hp1, hp2)

	return TRUE iff hp1 and hp2 overlap on both 1st and 2nd sequences;
	otherwise return FALSE.
*/
Boolean
ovlap_x2(hp1, hp2)
	register HSPPtr	hp1, hp2;
{
	register Coord_t	pos10, pos11, pos20, pos21;

	/* Return FALSE if hits are on different strands */
	if (SIGN(hp1->frame) != SIGN(hp2->frame))
		return FALSE;


	/* Look first for overlapping on subject/database sequence... */

	pos10 = hp1->s_pos;
	pos20 = hp2->s_pos;
	pos11 = pos10 + hp1->len;
	pos21 = pos20 + hp2->len;

	if (pos10 > pos20 && pos11 > pos21)
		return FALSE;
	if (pos10 < pos20 && pos11 < pos21)
		return FALSE;


	/* Look for overlapping on the query sequence... */

	if (hp1->frame > 0) {
		pos10 = hp1->q_pos * CODON_LEN + hp1->frame;
		pos20 = hp2->q_pos * CODON_LEN + hp2->frame;
	}
	else {
		pos10 = hp1->q_pos * CODON_LEN - hp1->frame;
		pos20 = hp2->q_pos * CODON_LEN - hp2->frame;
	}
	pos11 = pos10 + hp1->len * CODON_LEN;
	pos21 = pos20 + hp2->len * CODON_LEN;

	if (pos10 <= pos20 && pos11 >= pos21)
		return TRUE;
	if (pos10 >= pos20 && pos11 <= pos21)
		return TRUE;

	return FALSE;
}
