/* Copyright (C) 2000-2002 Damir Zucic */

/*=============================================================================

				draw_comparison.c

Purpose:
	Draw sequence comparison.

Input:
	(1) Pointer to RuntimeS structure, with some runtime data.
	(2) Pointer to GUIS structure, with GUI data.
	(3) Pointer to NearestAtomS structure, with information about the
	    atom occupying the given pixel.
	(4) The number of pixels in the main window free area.
	(5) The refreshI,  used to check the NearestAtomS associated with
	    a given pixel.

Output:
	(1) Sequence comparison should be drawn to the main window.
	(2) Return value.

Return value:
	(1) The number of dots drawn.

Notes:
	(1) The initial drawing destination is the hidden pixmap, and the
	    content of this pixmap is copied later to the main window.

	(2) The x axis is used for the reference sequence  and the y axis
	    is used for the sequence from the general purpose buffer.

========includes:============================================================*/

#include <stdio.h>

#include <string.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include "defines.h"
#include "typedefs.h"

/*======function prototypes:=================================================*/

int		RefreshPixmap_ (Display *, Pixmap, GC,
				unsigned int, unsigned int, unsigned long);

/*======draw sequence comparison:============================================*/

size_t DrawComparison_ (RuntimeS *runtimeSP, GUIS *guiSP,
			NearestAtomS *nearest_atomSP, size_t pixelsN,
			unsigned int refreshI)
{
size_t		dots_drawnN = 0;
int		max_length;
unsigned int	square_width, square_height;
int		max_screen_x0, max_screen_y0;
int		ref_residueI, ref_startI, ref_endI, ref_residuesN;
int		residueI, startI, endI, residuesN;
char		*ref_residue_nameP;
char		*residue_nameP;
int		*reference_codeIP, *codeIP;
int		nameI, namesN = 23;
static char	nameAA[23][4] =
		{"ALA","ASX","CYS","ASP","GLU","PHE","GLY","HIS","ILE","LYS",
		 "LEU","MET","ASN","PRO","GLN","ARG","SER","THR","VAL","TRP",
		 "TYR","GLX","UNK"};
static int	replacement_matrixAA[23][23] =
		{{1,0,0,0,0, 0,1,0,0,0, 0,0,0,1,0, 0,1,1,0,0, 0,0,0},
		 {0,1,0,1,1, 0,0,1,0,1, 0,0,1,0,1, 0,0,0,0,0, 0,1,0},
		 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		 {0,1,0,1,1, 0,0,1,0,0, 0,0,1,0,1, 0,0,0,0,0, 0,1,0},
		 {0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0}};
size_t		pixelI;
NearestAtomS	*curr_pixelSP;
int		segmentI, segment_width, minimal_score;
int		shifted_ref_residueI, shifted_residueI;
int		score;
int		rowI, columnI;
int		screen_x0, screen_y0, screen_x1, screen_y1;
int		colorI;

/*------prepare some parameters:---------------------------------------------*/

max_length = RESNAMESIZE - 1;
square_width = (unsigned int) runtimeSP->zoom_factor;
if (square_width < 1) square_width = 1;
square_height = square_width;
max_screen_x0 = guiSP->main_win_free_area_width - 1;
max_screen_y0 = guiSP->main_win_free_area_height - 1;
ref_residuesN = (int) runtimeSP->reference_residuesN;
residuesN = (int) runtimeSP->residuesN;
segment_width = runtimeSP->segment_width;
minimal_score = runtimeSP->minimal_score;

/*------initialize code arrays:----------------------------------------------*/

/* Reference sequence: */
for (ref_residueI = 0; ref_residueI < ref_residuesN; ref_residueI++)
	{
	/* Pointer to reference residue name: */
	ref_residue_nameP = runtimeSP->reference_sequenceP +
			    ref_residueI * max_length;

	/* Pointer to reference residue code: */
	reference_codeIP = runtimeSP->reference_residue_codeIP + ref_residueI;

	/* Initialize code with default value (22, unknown residue): */
	*reference_codeIP = 22;

	/* Scan the set of standard residue names: */
	for (nameI = 0; nameI < namesN; nameI++)
		{
		/* Compare the current reference residue */
		/* name with  the current standard name: */
		if (strncmp (ref_residue_nameP, nameAA[nameI], 3) == 0)
			{
			*reference_codeIP = nameI;
			break;
			}
		}
	}

/* The current working sequence (stored to the main sequence buffer): */
for (residueI = 0; residueI < residuesN; residueI++)
	{
	/* Pointer to residue name: */
	residue_nameP = runtimeSP->sequenceP + residueI * max_length;

	/* Pointer to residue code: */
	codeIP = runtimeSP->residue_codeIP + residueI;

	/* Initialize code with default value (22, unknown residue): */
	*codeIP = 22;

	/* Scan the set of standard residue names: */
	for (nameI = 0; nameI < namesN; nameI++)
		{
		/* Compare the current reference residue */
		/* name with  the current standard name: */
		if (strncmp (residue_nameP, nameAA[nameI], 3) == 0)
			{
			*codeIP = nameI;
			break;
			}
		}
	}

/*------refresh the hidden pixmap:-------------------------------------------*/

/* Refresh the hidden pixmap, where drawing */
/* will be done (background must be black): */
RefreshPixmap_ (guiSP->displaySP,
		guiSP->main_hidden_pixmapID,
		guiSP->theGCA[0],
		guiSP->control_winS.x0, guiSP->input_winS.y0,
		guiSP->black_colorID);

/*------initialize mol_complexI and styleI in each NearestAtomS:-------------*/

/* The mol_complexI is used to store score: */
for (pixelI = 0; pixelI < pixelsN; pixelI++)
	{
	curr_pixelSP = nearest_atomSP + pixelI;
	curr_pixelSP->mol_complexI = 0;
	curr_pixelSP->styleI = 0;
	}

/*------prepare ranges for serial indices:-----------------------------------*/

/* Index range for the reference sequence: */
ref_startI = runtimeSP->reference_offset;
ref_endI = (int) guiSP->main_win_free_area_width / square_width + ref_startI;
if (ref_endI >= ref_residuesN) ref_endI = ref_residuesN - 1;

/* Index range for the current working sequence: */
startI = runtimeSP->sequence_offset;
endI = (int) guiSP->main_win_free_area_height / square_height + startI;
if (endI >= residuesN) endI = residuesN - 1;

/*------scan sequences and prepare scores:-----------------------------------*/

/* Scan the reference sequence (horizontal scan): */
for (ref_residueI = ref_startI; ref_residueI <= ref_endI; ref_residueI++)
	{
	/* Scan the current working sequence (vertical scan): */
	for (residueI = startI; residueI <= endI; residueI++)
		{
		/* Reset score (the number of matching */
		/* residues in  the current  segment): */
		score = 0;

		/* Scan the current segment: */
		for (segmentI = 0; segmentI < segment_width; segmentI++)
			{
			/* Prepare and check shifted indices: */
			shifted_ref_residueI = ref_residueI + segmentI;
			if (shifted_ref_residueI > ref_endI) continue;
			shifted_residueI = residueI + segmentI;
			if (shifted_residueI > endI) continue;

			/* Prepare row and column index: */
			rowI = *(runtimeSP->residue_codeIP +
			       shifted_residueI);
			columnI = *(runtimeSP->reference_residue_codeIP +
				 shifted_ref_residueI);

			/* Compare codes: */
			if (!replacement_matrixAA[rowI][columnI]) continue;

			/* If this point is reached, increment score: */
			score++;
			}

		/* If the current score is lower than */
		/* the minimal score,  do not use it: */
		if (score < minimal_score) continue;

		/* If this point is reached, the current score is larger or */
		/* equal to the minimal score.  Compare new scores with old */
		/* scores associated with residues in  the current segment. */
		/* The NearestAtomS array is used as the buffer for scores. */
		for (segmentI = 0; segmentI < segment_width; segmentI++)
			{
			/* Prepare and check  the screen */
			/* position of the current pair: */
			screen_x0 = (int) square_width *
				    (ref_residueI + segmentI - ref_startI);
			if (screen_x0 > max_screen_x0) continue;
			screen_y0 = (int) square_height *
				    (residueI + segmentI - startI);
			if (screen_y0 > max_screen_y0) continue;

			/* Prepare and check the pixel index: */
			pixelI = guiSP->main_win_free_area_width * screen_y0 +
				 screen_x0;
			if (pixelI >= pixelsN) continue;

			/* Pointer to NearestAtomS structure */
			/* associated with the current pair: */
			curr_pixelSP = nearest_atomSP + pixelI;

			/* Compare scores: */
			if (curr_pixelSP->mol_complexI >= score) continue;

			/* If the new score  is better than */
			/* the old one it should be stored: */
			curr_pixelSP->mol_complexI = score;
			}
		}
	}

/*------compare residues again and set styleI:-------------------------------*/

/* styleI values:              */
/* 0 = mismatch (bad substit.) */
/* 1 = exact match             */
/* 2 = acceptable substitution */

/* Scan the reference sequence (horizontal scan): */
for (ref_residueI = ref_startI; ref_residueI <= ref_endI; ref_residueI++)
	{
	/* Prepare and check the column index: */
	columnI = *(runtimeSP->reference_residue_codeIP + ref_residueI);

	/* Prepare and check screen_x0: */
	screen_x0 = (int) square_width * (ref_residueI - ref_startI);
	if (screen_x0 > max_screen_x0) continue;

	/* Scan the current working sequence (vertical scan): */
	for (residueI = startI; residueI <= endI; residueI++)
		{
		/* Prepare the row index: */
		rowI = *(runtimeSP->residue_codeIP + residueI);

		/* Prepare and check screen_y0: */
		screen_y0 = (int) square_height * (residueI - startI);
		if (screen_y0 > max_screen_y0) continue;

		/* Prepare and check the pixel index: */
		pixelI = guiSP->main_win_free_area_width * screen_y0 +
			 screen_x0;
		if (pixelI >= pixelsN) continue;

		/* Pointer to NearestAtomS structure */
		/* associated with the current pair: */
		curr_pixelSP = nearest_atomSP + pixelI;

		/* If these indices are equal, the residues are equal: */
		if (rowI == columnI)
			{
			curr_pixelSP->styleI = 2;
			continue;
			}

		/* If indices are different, compare residue codes: */
		if (replacement_matrixAA[rowI][columnI])
			{
			curr_pixelSP->styleI = 1;
			}
		}
	}

/*------prepare yellow and magenta color:------------------------------------*/

/* Yellow is used for exact matches: */
XSetForeground (guiSP->displaySP, guiSP->theGCA[2], guiSP->yellow_colorID);

/* Magenta is used for acceptable substitutions: */
XSetForeground (guiSP->displaySP, guiSP->theGCA[1], guiSP->magenta_colorID);

/*------draw comparison to hidden pixmap:------------------------------------*/

/* Scan the reference sequence (horizontal scan): */
for (ref_residueI = ref_startI; ref_residueI <= ref_endI; ref_residueI++)
	{
	/* Horizontal position: */
	screen_x0 = (int) square_width * (ref_residueI - ref_startI);
	if (screen_x0 > max_screen_x0) continue;

	/* Column index: */
	columnI = *(runtimeSP->reference_residue_codeIP + ref_residueI);

	/* Scan the current working sequence (vertical scan): */
	for (residueI = startI; residueI <= endI; residueI++)
		{
		/* Vertical position: */
		screen_y0 = (int) square_height * (residueI  - startI);
		if (screen_y0 > max_screen_y0) continue;

		/* Row index: */
		rowI = *(runtimeSP->residue_codeIP + residueI);

		/* Compare codes: */
		if (!replacement_matrixAA[rowI][columnI]) continue;

		/* Prepare and check the pixel index: */
		pixelI = guiSP->main_win_free_area_width * screen_y0 +
			 screen_x0;
		if (pixelI >= pixelsN) continue;

		/* Pointer to NearestAtomS structure */
		/* associated with the current pair: */
		curr_pixelSP = nearest_atomSP + pixelI;

		/* Compare the current score with the minimal score: */
		if (curr_pixelSP->mol_complexI < minimal_score) continue;

		/* The styleI  will be used as  the color index */
		/* (0 = mismatch, 1 = subst., 2 = exact match): */
		colorI = curr_pixelSP->styleI;
		if (colorI == 0) continue;
		if ((colorI != 1) && (colorI != 2)) continue;

		/* If this point is reached,  the current */
		/* score is good enough; draw the square: */
		XFillRectangle (guiSP->displaySP,
				guiSP->main_hidden_pixmapID,
				guiSP->theGCA[colorI],
				screen_x0, screen_y0,
				square_width, square_height);

		/* Update the "dots counter": */
		dots_drawnN++;
		}
	}

/*------draw lines at the right and bottom edge:-----------------------------*/

/* Prepare edge coordinates: */
screen_x0 = (int) square_width * (ref_endI - ref_startI + 1);
if (screen_x0 <= max_screen_x0) screen_x1 = screen_x0;
else screen_x1 = max_screen_x0;
screen_y0 = (int) square_height * (endI - startI + 1);
if (screen_y0 <= max_screen_y0) screen_y1 = screen_y0;
else screen_y1 = max_screen_y0;

/* Use cyan color for bounding rectangle: */
XSetForeground (guiSP->displaySP, guiSP->theGCA[0], guiSP->cyan_colorID);

/* Draw the right edge: */
if (screen_x0 <= max_screen_x0)
	{
	XDrawLine (guiSP->displaySP,
		   guiSP->main_hidden_pixmapID,
		   guiSP->theGCA[0],
		   screen_x0, 0, screen_x0, screen_y1);
	}

/* Draw the bottom edge: */
if (screen_y0 <= max_screen_y0)
	{
	XDrawLine (guiSP->displaySP,
		   guiSP->main_hidden_pixmapID,
		   guiSP->theGCA[0],
		   0, screen_y0, screen_x1, screen_y0);
	}

/*------copy the prepared image to the main window:--------------------------*/

/* Copy hidden pixmap to the main window: */
XCopyArea (guiSP->displaySP,
	   guiSP->main_hidden_pixmapID, guiSP->main_winS.ID,
	   guiSP->theGCA[0],
	   0, 0,
	   guiSP->main_win_free_area_width, guiSP->main_win_free_area_height,
	   0, 0);

return (size_t) dots_drawnN;
}

/*===========================================================================*/


