/* Copyright (C) 2002 Damir Zucic */

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

			    half_nice_bond.c

Purpose:
	Draw half of a nice bond. Nice bond is a curved bond, constructed
	by using three spheres (two atoms and one probe).

Input:
	(1) Pointer to Aux2S structure, which contains required data.
	(2) Bond index.

Output:
	(1) Half of a nice bond drawn.
	(2) Return value.

Return value:
	(1) Positive on success.
	(2) Negative on failure.

Notes:
	(1) Read the file nice_bonds.c, related drawings and mathematical
	    formulas are there.

	(2) The special case  (alpha2 > PI/2) requires careful treatment.

	(3) The bond is drawn  circle by circle.  Only  one half  of each
	    circle is drawn,  because it is assumed  that another side of
	    the circle is invisible to the observer. The rear side of the
	    bond is not drawn!

	(4) Two different factors  (nominator_x and nominator_y) are used
	    to project the circle center,  but only one  (nominator_x) to
	    calculate the offset of the point at the surface. This has to
	    be done like that  because two factors  were used  to project
	    the atoms,  while only one factor (x) was used to prepare the
	    projection of  the atomic radius  when using  some  spacefill
	    style to draw atoms.

	(5) Indentation is exceptionally 4 spaces.

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

#include <stdio.h>
#include <stdlib.h>
#include <math.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:=================================================*/

double		AbsoluteValue_ (VectorS *);
double		ScalarProduct_ (VectorS *, VectorS *);
void		VectorProduct_ (VectorS *, VectorS *, VectorS *);
unsigned long	SpacefillColor_ (AtomS *, GUIS *, double);
unsigned long	Sp2Color_ (AtomS *, GUIS *, double);
unsigned long	WeightColors_ (unsigned long, unsigned long, double, GUIS *);

/*======draw half of a nice bond:============================================*/

int HalfNiceBond_ (Aux2S *aux2SP, int bondI)
{
static int		imageI;
static int		image_center_screen_x, image_center_screen_y;
static int		left_edge, right_edge, bottom_edge;
static double		screen_atomic_z;
static double		nominator_x, nominator_y;
static RawAtomS		*raw_atom1SP, *raw_atom2SP;
static double		user_screen_atomic_distance;
static double		atomic_to_screen_scale;
static double		user_atomic_position;
static VectorS		*light_vectorSP;
static double		delta_x, delta_y, delta_z, rho;
static double		angle, cos_angle, sin_angle;
static int		atom1_styleI, atom2_styleI;
static double		r1, r2, r3;
static AtomS		*far_atomSP;
static double		far_radius, far_z;
static double		denominator, reciprocal_denominator;
static double		pixel_atomic_size;
static double		r13, r23, d0;
static double		cos_alpha1, alpha1, sin_alpha1;
static double		cos_alpha2;
static double		u0min, u0max, v0max;
static double		a0, rho0;
static double		scale_factor;
static VectorS		start0_vectorS, end0_vectorS;
static double		linear_increment, double_linear_increment;
static double		angular_increment;
static double		reciprocal_delta_u0;
static double		delta_a0_u0, root_argument;
static VectorS		unit_vector0S, unit_vector1S, unit_vector2S;
static VectorS		aux_vector0S, aux_vector1S;
static double		abs_value, reciprocal_abs_value;
static double		u0, v0;
static double		circle_x0, circle_y0, circle_z0;
static double		projection_factor_x, projection_factor_y;
static double		rationalized_x, rationalized_y;
static int		circle_screen_x0, circle_screen_y0;
static double		r13_1, r13_2;
static double		probe_offset_x, probe_offset_y, probe_offset_z;
static double		probe_x, probe_y, probe_z;
static double		surface_offset_1, surface_offset_2;
static double		surface_offset_x, surface_offset_y, surface_offset_z;
static double		surface_x, surface_y, surface_z;
static int		surface_screen_x, surface_screen_y;
static size_t		pixelI;
static NearestAtomS	*curr_pixelSP;
static int		drawF;
static double		shifted_z;
static VectorS		normal_vectorS;
static double		normal_abs_value;
static double		scalar_product;
static double		cos_light_angle;
static unsigned long	colorID, aux_color1ID, aux_color2ID, aux_color3ID;
static int		localI;
static int		pixel_screen_x, pixel_screen_y;
static int		pixel_shift_xA[4] = { 0,  1,  0,  1};
static int		pixel_shift_yA[4] = { 0,  0,  1,  1};
static int		octantI;
static double		pi_over_eight;
static int		pixel_shift_x, pixel_shift_y;
static int		local_pixelsN;
static unsigned long	colorIDA[5];

/*---------------------------------------------------------------------------*/

/* Copy some data and prepare some parameters. */

/* Image index: */
imageI = aux2SP->imageI;

/* Image center, in screen units: */
image_center_screen_x = aux2SP->configSP->center_screen_x[imageI];
image_center_screen_y = aux2SP->configSP->center_screen_y;

/* Bounding rectangle: */
left_edge   = aux2SP->configSP->image_screen_x0[imageI];
right_edge  = aux2SP->configSP->image_screen_x1[imageI];
bottom_edge = (int) aux2SP->guiSP->main_win_free_area_height;

/* Screen position, in atomic units: */
screen_atomic_z = aux2SP->configSP->screen_atomic_z;

/* Prepare two factors which are required for scaling: */
nominator_x = aux2SP->configSP->user_screen_atomic_distance *
	      aux2SP->configSP->atomic_to_screen_scale_x;
nominator_y = aux2SP->configSP->user_screen_atomic_distance *
	      aux2SP->configSP->atomic_to_screen_scale_y;

/* Pointers to raw atomic data: */
raw_atom1SP = &aux2SP->atom1SP->raw_atomS;
raw_atom2SP = &aux2SP->atom2SP->raw_atomS;

/* Both atoms should be on the opposite side of */
/* the screen,  with  respect to  the observer: */
if (raw_atom1SP->z[imageI] < screen_atomic_z) return -1;
if (raw_atom2SP->z[imageI] < screen_atomic_z) return -2;

/* Distance between user and screen, in atomic units: */
user_screen_atomic_distance = aux2SP->configSP->user_screen_atomic_distance;

/* The scale factor  required for conversion from atomic to */
/* screen units. There are originally two such factors. Use */
/* the  larger one  here  because  it goes  to denominator. */
if (aux2SP->configSP->atomic_to_screen_scale_x >
    aux2SP->configSP->atomic_to_screen_scale_y)
    {
    atomic_to_screen_scale = aux2SP->configSP->atomic_to_screen_scale_x;
    }
else atomic_to_screen_scale = aux2SP->configSP->atomic_to_screen_scale_y;

/* User position in atomic units: */
user_atomic_position = aux2SP->configSP->user_atomic_position;

/* Pointer to the light source vector: */
light_vectorSP = &aux2SP->configSP->light_vectorS;

/*---------------------------------------------------------------------------*/

/* Copy and check the atomic radii. Two atoms forming the bond */
/* should be drawn using some sort of spacefill drawing style. */

/* Radius of the first atom (the current bond belongs to this atom): */
atom1_styleI = raw_atom1SP->atom_styleI;
if ((atom1_styleI == SPACEFILL) || (atom1_styleI == SPACEFILL2))
    {
    r1 = raw_atom1SP->radius;
    }
else if ((atom1_styleI == COVALENT) || (atom1_styleI == COVALENT2))
    {
    r1 = raw_atom1SP->covalent_radius;
    }
else if ((atom1_styleI == SMALL_ATOM) || (atom1_styleI == SMALL_ATOM2))
    {
    r1 = raw_atom1SP->small_radius;
    }
else if ((atom1_styleI == BIG_SPHERE) || (atom1_styleI == BIG_SPHERE2))
    {
    r1 = raw_atom1SP->van_der_Waals_radius;
    }
else return -3;

/* Radius of the second atom (the bond partner of the first atom): */
atom2_styleI = raw_atom2SP->atom_styleI;
if ((atom2_styleI == SPACEFILL) || (atom2_styleI == SPACEFILL2))
    {
    r2 = raw_atom2SP->radius;
    }
else if ((atom2_styleI == COVALENT) || (atom2_styleI == COVALENT2))
    {
    r2 = raw_atom2SP->covalent_radius;
    }
else if ((atom2_styleI == SMALL_ATOM) || (atom2_styleI == SMALL_ATOM2))
    {
    r2 = raw_atom2SP->small_radius;
    }
else if ((atom2_styleI == BIG_SPHERE) || (atom2_styleI == BIG_SPHERE2))
    {
    r2 = raw_atom2SP->van_der_Waals_radius;
    }
else return -4;

/* The probe radius should be larger than zero: */
r3 = aux2SP->bond_probe_radius;
if (r3 <= 0.001) return -5;

/*---------------------------------------------------------------------------*/

/* Now estimate the size  (in atomic units) of the pixel which */
/* represents the  most distant point.  This point  belongs to */
/* the atom  (i.e. sphere) which is farther from the observer. */
/* The atom with higher z value is treated as the farther one. */

/* Find which atom has higher z value (in most cases, but */
/* not always,  this atom is farther  from the observer): */
if (raw_atom2SP->z[imageI] > raw_atom1SP->z[imageI])
    {
    far_atomSP = aux2SP->atom2SP;
    far_radius = r2;
    }
else
    {
    far_atomSP = aux2SP->atom1SP;
    far_radius = r1;
    }

/* Find the z coordinate of the most distant point: */
far_z = far_atomSP->raw_atomS.z[imageI] + far_radius;

/* Check is this point on  the opposite side of */
/* the screen,  with  respect to  the observer. */
/* If it is, the entire bond will be invisible. */
if (far_z < screen_atomic_z) return -6;

/* Prepare denominator  required to calculate */
/* the atomic size of the most distant pixel: */
denominator = user_screen_atomic_distance * atomic_to_screen_scale;
if (denominator <= 0.001) return -7;

/* The size of the most distant pixel in atomic units: */
pixel_atomic_size = 1.0 * (far_z - user_atomic_position) / denominator;

/*---------------------------------------------------------------------------*/

/* Calculate and check some geometric parameters */
/* (check definitions in the file nice_bonds.c). */

/* Relative distances: */
r13 = r1 + r3;
if (r13 <= 0.001) return -8;
r23 = r2 + r3;
d0 = aux2SP->curr_bondSP->bond_length;
if (d0 <= 0.001) return -9;

/* Prepare and carefuly check the angle alpha1: */
cos_alpha1 = (r13 * r13 + d0 * d0 - r23 * r23) / (2 * d0 * r13);
if (cos_alpha1 <= 0.001) return -10;
else if (cos_alpha1 < -0.999) return -11;
else if (cos_alpha1 > 0.999) return -12;
if (cos_alpha1 <= -0.999) alpha1 = 3.1415927;
else if (cos_alpha1 == 0.999) alpha1 = 0.0;
else alpha1 = acos (cos_alpha1);
sin_alpha1 = sin (alpha1);

/* Cosine of the angle alpha2,  required to */
/* handle the special case (alpha2 > PI/2): */
cos_alpha2 = (r23 * r23 + d0 * d0 - r13 * r13) / (2 * d0 * r23);

/* The remaining ranges and distances: */
u0min = r1  * cos_alpha1;
if (cos_alpha2 > 0.0) u0max = r13 * cos_alpha1;
else u0max = d0 - r2 * cos_alpha2;
v0max = r1  * sin_alpha1;
a0    = r13 * cos_alpha1;
rho0  = r13 * sin_alpha1;

/*---------------------------------------------------------------------------*/

/* Find the start point and the end point, which define the bond axis. */

/* Distance between two atoms which form the bond (three components): */
delta_x = raw_atom2SP->x[imageI] - raw_atom1SP->x[imageI];
delta_y = raw_atom2SP->y         - raw_atom1SP->y;
delta_z = raw_atom2SP->z[imageI] - raw_atom1SP->z[imageI];

/* Prepare the start point: */
scale_factor = u0min / d0;
start0_vectorS.x = raw_atom1SP->x[imageI] + scale_factor * delta_x;
start0_vectorS.y = raw_atom1SP->y         + scale_factor * delta_y;
start0_vectorS.z = raw_atom1SP->z[imageI] + scale_factor * delta_z;

/* Prepare the end point: */
scale_factor = u0max / d0;
end0_vectorS.x = raw_atom1SP->x[imageI] + scale_factor * delta_x;
end0_vectorS.y = raw_atom1SP->y         + scale_factor * delta_y;
end0_vectorS.z = raw_atom1SP->z[imageI] + scale_factor * delta_z;

/* Both points  should be on  the opposite side */
/* of the screen, with respect to the observer: */
if (start0_vectorS.z < screen_atomic_z) return -13;
if (  end0_vectorS.z < screen_atomic_z) return -14;

/*---------------------------------------------------------------------------*/

/* Prepare  three unit vectors,  required for angular scan.  These */
/* three vectors define the plane, required to define the  circle. */

/* Prepare the unit vector pointing from the start point to the end point: */
unit_vector0S.x = end0_vectorS.x - start0_vectorS.x;
unit_vector0S.y = end0_vectorS.y - start0_vectorS.y;
unit_vector0S.z = end0_vectorS.z - start0_vectorS.z;
abs_value = AbsoluteValue_ (&unit_vector0S);
if (abs_value <= 0.001) return -15;
reciprocal_abs_value = 1.0 / abs_value;
unit_vector0S.x *= reciprocal_abs_value;
unit_vector0S.y *= reciprocal_abs_value;
unit_vector0S.z *= reciprocal_abs_value;

/* Prepare the unit vector parallel to z axis: */
aux_vector0S.x = 0.0;
aux_vector0S.y = 0.0;
aux_vector0S.z = 1.0;

/* Check the absolute value of  the vector product between  unit_vector0S */
/* and aux_vector0S; if the absolute value is too small, use aux_vector0S */
/* perpendicular to z axis  (the vector parallel to x axis will be good): */
VectorProduct_ (&aux_vector1S, &unit_vector0S, &aux_vector0S);
abs_value = AbsoluteValue_ (&aux_vector1S);
if (abs_value < 0.001)
    {
    aux_vector0S.x = 1.0;
    aux_vector0S.y = 0.0;
    aux_vector0S.z = 0.0;
    }

/* Prepare the unit vector perpendicular to unit_vector0S */
/* and to z axis.  This is  the first vector  required to */
/* define the plane,  which is used to define the circle. */
VectorProduct_ (&unit_vector1S, &unit_vector0S, &aux_vector0S);
abs_value = AbsoluteValue_ (&unit_vector1S);
reciprocal_abs_value = 1.0 / abs_value;
unit_vector1S.x *= reciprocal_abs_value;
unit_vector1S.y *= reciprocal_abs_value;
unit_vector1S.z *= reciprocal_abs_value;

/* Prepare the second unit vector required to define the plane: */
VectorProduct_ (&unit_vector2S, &unit_vector0S, &unit_vector1S);

/*---------------------------------------------------------------------------*/

/* Prepare  the linear increment.  This variable  should be used as */
/* the maximal translational step, to prevent holes in the surface. */

/* The linear increment should be smaller than pixel size: */
linear_increment = 0.70 * pixel_atomic_size;
double_linear_increment = 2.0 * linear_increment;

/* Check the distance between the start point and end point. */
/* The curved surface will be drawn only if this distance is */
/* at least  three times larger  than  the linear increment. */
if (u0max - u0min < 3.0 * linear_increment) return -16;

/*---------------------------------------------------------------------------*/

/* Prepare the angular increment. This variable should be used as */
/* the maximal  angular step,  to prevent holes  in  the surface. */

/* Calculate the angular increment, in radians: */
if (v0max <= 0.001) return -17;
angular_increment = 0.70 * linear_increment / v0max;

/* Be sure that the angular increment is not larger than PI/4: */
if (angular_increment > 0.78539816) angular_increment = 0.78539816;

/*---------------------------------------------------------------------------*/

/* Draw half of the bond. */

/* Prepare some factors which are used to */
/* reduce the number  of multiplications: */
delta_x = end0_vectorS.x - start0_vectorS.x;
delta_y = end0_vectorS.y - start0_vectorS.y;
delta_z = end0_vectorS.z - start0_vectorS.z;
reciprocal_delta_u0 = 1.0 / (u0max - u0min);

/* Loop which scans the variable u0 (see nice_bonds.c for definition): */
for (u0 = u0min - double_linear_increment; u0 <= u0max; u0 += linear_increment)
    {
    /* Calculate and check v0: */
    if (u0 < 0.0) v0 = v0max;
    else
	{
	delta_a0_u0 = a0 - u0;
	root_argument = r3 * r3 - delta_a0_u0 * delta_a0_u0;
	if (root_argument <= 0.000001) continue;
	v0 = rho0 - sqrt (root_argument);
	if (v0 <= 0.001) continue;
	}

    /* Reduce v0 slightly, to ensure better connection with the atom: */
    if (v0 > v0max) v0 = v0max;
    v0 -= pixel_atomic_size;
    if (v0 < 0.001) v0 = 0.0;

    /* Calculate the position of the point on the axis, */
    /* defined by u0.  This point is the circle center. */
    scale_factor = (u0 - u0min) * reciprocal_delta_u0;
    circle_x0 = start0_vectorS.x + delta_x * scale_factor;
    circle_y0 = start0_vectorS.y + delta_y * scale_factor;
    circle_z0 = start0_vectorS.z + delta_z * scale_factor;

    /* Prepare  the reciprocal denominator,  used to */
    /* reduce the number of mathematical operations: */
    denominator = circle_z0 - user_atomic_position;
    if (denominator <= 0.001) continue;
    reciprocal_denominator = 1.0 / denominator;

    /* Prepare two factors required for projection: */
    projection_factor_x = nominator_x * reciprocal_denominator;
    projection_factor_y = nominator_y * reciprocal_denominator;

    /* Project the position of the circle center. Note that */
    /* two different  projection  factors  are  used  here! */
    rationalized_x = circle_x0 * projection_factor_x;
    rationalized_y = circle_y0 * projection_factor_y;
    circle_screen_x0 = (int) rationalized_x + image_center_screen_x;
    circle_screen_y0 = (int) rationalized_y + image_center_screen_y;

    /* The angular loop, required to create the rotational surface: */
    for (angle = 0.0; angle <= 6.2831853; angle += angular_increment)
	{
	/* Cosine and sine of the angle: */
	cos_angle = cos (angle);
	sin_angle = sin (angle);

	/* Calculate the relative position of the probe */
	/* center  with  respect  to the center  of the */
	/* first atom.  Note that  a0  is the  parallel */
	/* component of r13 with respect to the u0 axis */
	/* and  rho0  is  the perpendicular  component. */
	r13_1 = rho0 * cos_angle;
	r13_2 = rho0 * sin_angle;
	probe_offset_x = a0    * unit_vector0S.x +
			 r13_1 * unit_vector1S.x +
			 r13_2 * unit_vector2S.x;
	probe_offset_y = a0    * unit_vector0S.y +
			 r13_1 * unit_vector1S.y +
			 r13_2 * unit_vector2S.y;
	probe_offset_z = a0    * unit_vector0S.z +
			 r13_1 * unit_vector1S.z +
			 r13_2 * unit_vector2S.z;

	/* Calculate the absolute position of the probe sphere: */
	probe_x = raw_atom1SP->x[imageI] + probe_offset_x;
	probe_y = raw_atom1SP->y         + probe_offset_y;
	probe_z = raw_atom1SP->z[imageI] + probe_offset_z;

	/* Relative  position  of  the  point  at the */
	/* surface with respect to the circle center: */
	surface_offset_1 = v0 * cos_angle;
	surface_offset_2 = v0 * sin_angle;
	surface_offset_x = surface_offset_1 * unit_vector1S.x +
			   surface_offset_2 * unit_vector2S.x;
	surface_offset_y = surface_offset_1 * unit_vector1S.y +
			   surface_offset_2 * unit_vector2S.y;
	surface_offset_z = surface_offset_1 * unit_vector1S.z +
			   surface_offset_2 * unit_vector2S.z;

	/* Calculate the coordinates of the point at bond surface: */
	surface_x = circle_x0 + surface_offset_x;
	surface_y = circle_y0 + surface_offset_y;
	surface_z = circle_z0 + surface_offset_z;

	/* The vector from the point at the surface */
	/* to  the center of  the spherical  probe: */
	normal_vectorS.x = probe_x - surface_x;
	normal_vectorS.y = probe_y - surface_y;
	normal_vectorS.z = probe_z - surface_z;

	/* If this vector has a positive  z component, */
	/* do not draw this point because it is not on */
	/* the side which is visible for the observer: */
	if (normal_vectorS.z >= 0.0) continue;

	/* Calculate the absolute value of this vector: */
	normal_abs_value = AbsoluteValue_ (&normal_vectorS);

	/* Project the relative position of surface point. Note */
	/* that  projection_factor_x is used in both equations! */
	rationalized_x = surface_offset_x * projection_factor_x;
	rationalized_y = surface_offset_y * projection_factor_x;

	/* Combine the projection of  the circle */
	/* center and projection of the relative */
	/* position of the point at the surface: */
	surface_screen_x = (int) rationalized_x + circle_screen_x0;
	surface_screen_y = (int) rationalized_y + circle_screen_y0;

	/* Prepare the color. */

	/* The scalar product between the normal */
	/* vector and  the light source  vector: */
	scalar_product = ScalarProduct_ (&normal_vectorS, light_vectorSP);

	/* Cosine of  the angle between  the normal */
	/* vector and the light source unit vector: */
	if (normal_abs_value <= 0.001) cos_light_angle = 0.0;
	else cos_light_angle = scalar_product / normal_abs_value;

	/* Prepare color: */
	switch (atom1_styleI)
	    {
	    case SPACEFILL:
	    case COVALENT:
	    case SMALL_ATOM:
	    case BIG_SPHERE:
		colorID = SpacefillColor_ (aux2SP->atom1SP, aux2SP->guiSP,
					   cos_light_angle);
		break;

	    case SPACEFILL2:
	    case COVALENT2:
	    case SMALL_ATOM2:
	    case BIG_SPHERE2:
		colorID = Sp2Color_ (aux2SP->atom1SP, aux2SP->guiSP,
				     cos_light_angle);
		break;

	    default:
		colorID = aux2SP->guiSP->white_colorID;
	    }

	/* Set color to GC: */
	XSetForeground (aux2SP->guiSP->displaySP,
			aux2SP->guiSP->theGCA[0],
			colorID);

	/* Draw four pixels: */
	for (localI = 0; localI < 4; localI++)
	    {
	    /* Prepare and check the pixel position: */
	    pixel_screen_x = surface_screen_x + pixel_shift_xA[localI];
	    pixel_screen_y = surface_screen_y + pixel_shift_yA[localI];
	    if (pixel_screen_x < 0)            continue;
	    if (pixel_screen_x < left_edge)    continue;
	    if (pixel_screen_x >= right_edge)  continue;
	    if (pixel_screen_y < 0)            continue;
	    if (pixel_screen_y >= bottom_edge) continue;

	    /* Prepare and check the index for the */
	    /* array of  NearestAtomS  structures: */
	    pixelI = aux2SP->guiSP->main_win_free_area_width *
		     pixel_screen_y + pixel_screen_x;
	    if (pixelI >= aux2SP->pixelsN) continue;

	    /* Pointer to NearestAtomS struct. */
	    /* assigned to  the current pixel: */
	    curr_pixelSP = aux2SP->nearest_atomSP + pixelI;

	    /*------------------------------------------------------------*/
	    /* There are three cases when this pixel should be drawn:     */
	    /* (1) Nothing was drawn to this pixel in this drawing step.  */
	    /* (2) Drawing was done  but the point at the bond surface is */
	    /*     closer to  the observer  than  the point drawn before. */
	    /* (3) Drawing was done  and the point at the bond surface is */
	    /*     more distant than the point drawn before. However, the */
	    /*     pixel belongs  to the atom  to which this bond belongs */
	    /*     and the  z coordinate of the point at the bond surface */
	    /*     is just slightly larger than the stored z value.       */
	    /*------------------------------------------------------------*/

	    /* Assume initially that drawing is not necessary: */
	    drawF = 0;

	    /* Check for the cases when drawing is necessary: */
	    do
		{
		/* Case (1) - no drawing was done before: */
		if (aux2SP->refreshI != curr_pixelSP->last_refreshI)
		    {
		    drawF = 1;
		    break;
		    }

		/* If this point is reached, drawing was done before. */

		/* Case (2): drawing was done before, but the point at the */
		/* bond surface  is closer  than  the point  drawn before. */
		if (surface_z < curr_pixelSP->z)
		    {
		    drawF = 1;
		    break;
		    }

		/* Now check the conditions for the case (3): */

		/* The pixel should belong to the surface of the atom: */
		if (curr_pixelSP->bondI != -1) break;

		/* The pixel  should belong  to the */
		/* same atom and macromol. complex: */
		if (curr_pixelSP->mol_complexI != aux2SP->mol_complexI) break;
		if (curr_pixelSP->atomI != aux2SP->atomI) break;

		/* If z is too large, no drawing will be done: */
		shifted_z = curr_pixelSP->z + 2.0 * pixel_atomic_size;
		if (surface_z > shifted_z) break;

		/* Case (3): all conditions were satisfied. */
		drawF = 1;

		/* End of inner single pass loop: */
		} while (0);

	    /* Check is drawing necessary at all: */
	    if (drawF == 0) continue;

	    /* Draw the current pixel: */
	    XDrawPoint (aux2SP->guiSP->displaySP,
			aux2SP->guiSP->main_hidden_pixmapID,
			aux2SP->guiSP->theGCA[0],
			pixel_screen_x, pixel_screen_y);

	    /* Refresh the NearestAtomS structure */
	    /* associated with the current pixel: */
	    curr_pixelSP->styleI = atom1_styleI;
	    curr_pixelSP->last_refreshI = aux2SP->refreshI;
	    curr_pixelSP->mol_complexI = aux2SP->mol_complexI;
	    curr_pixelSP->atomI = aux2SP->atomI;
	    curr_pixelSP->bondI = bondI;
	    curr_pixelSP->z = surface_z;
	    curr_pixelSP->colorID = colorID;
	    }
	}
    }

/*---------------------------------------------------------------------------*/

/* Change the linear and the angular increment, before color smoothing. */

/* Reduce the linear increment: */
linear_increment *= 0.70;
double_linear_increment = 2.0 * linear_increment;

/* Reduce the angular increment: */
angular_increment *= 0.70;

/*---------------------------------------------------------------------------*/

/* For most of the pixels, the original color will be replaced by the color */
/* calculated  by averaging  the colors of  up to five  neighboring pixels. */

/* Prepare some factors which are used to */
/* reduce the number  of multiplications: */
delta_x = end0_vectorS.x - start0_vectorS.x;
delta_y = end0_vectorS.y - start0_vectorS.y;
delta_z = end0_vectorS.z - start0_vectorS.z;
rho = sqrt (delta_x * delta_x + delta_y * delta_y);

/* Identify the octant which contains this half of the bond: */
if (rho >= 0.001)
    {
    cos_angle = delta_x / rho;
    if      (cos_angle <= -0.999) angle = 3.1415927;
    else if (cos_angle >=  0.999) angle = 0.0;
    else angle = acos (cos_angle);
    sin_angle = delta_y / rho;
    if (sin_angle < 0.0) angle = 6.2831853 - angle;
    pi_over_eight = 3.1415927 / 8.0;
    if      (angle <  1.0 * pi_over_eight) octantI = 0;
    else if (angle <  3.0 * pi_over_eight) octantI = 1;
    else if (angle <  5.0 * pi_over_eight) octantI = 2;
    else if (angle <  7.0 * pi_over_eight) octantI = 3;
    else if (angle <  9.0 * pi_over_eight) octantI = 4;
    else if (angle < 11.0 * pi_over_eight) octantI = 5;
    else if (angle < 13.0 * pi_over_eight) octantI = 6;
    else if (angle < 15.0 * pi_over_eight) octantI = 7;
    else octantI = 0;
    }
else octantI = 0;

/* Prepare the shifts which define neighboring pixels: */
switch (octantI)
    {
    case 0:
	pixel_shift_x = -1;
	pixel_shift_y =  0;
	break;

    case 1:
	pixel_shift_x = -1;
	pixel_shift_y = -1;
	break;

    case 2:
	pixel_shift_x =  0;
	pixel_shift_y = -1;
	break;

    case 3:
	pixel_shift_x =  1;
	pixel_shift_y = -1;
	break;

    case 4:
	pixel_shift_x =  1;
	pixel_shift_y =  0;
	break;

    case 5:
	pixel_shift_x =  1;
	pixel_shift_y =  1;
	break;

    case 6:
	pixel_shift_x =  0;
	pixel_shift_y =  1;
	break;

    case 7:
	pixel_shift_x = -1;
	pixel_shift_y =  1;
	break;

    default:
	pixel_shift_x =  0;
	pixel_shift_y =  0;
    }

for (u0 = u0min - double_linear_increment; u0 <= u0max; u0 += linear_increment)
    {
    /* Calculate and check v0: */
    if (u0 < 0.0) v0 = v0max;
    else
	{
	delta_a0_u0 = a0 - u0;
	root_argument = r3 * r3 - delta_a0_u0 * delta_a0_u0;
	if (root_argument <= 0.000001) continue;
	v0 = rho0 - sqrt (root_argument);
	if (v0 <= 0.001) continue;
	}

    /* Reduce v0 slightly, to ensure better connection with the atom: */
    if (v0 > v0max) v0 = v0max;
    v0 -= pixel_atomic_size;
    if (v0 <= 0.001) v0 = 0.0;

    /* Calculate the position of the point on the axis, */
    /* defined by u0.  This point is the circle center. */
    scale_factor = (u0 - u0min) * reciprocal_delta_u0;
    circle_x0 = start0_vectorS.x + delta_x * scale_factor;
    circle_y0 = start0_vectorS.y + delta_y * scale_factor;
    circle_z0 = start0_vectorS.z + delta_z * scale_factor;

    /* Prepare  the reciprocal denominator,  used to */
    /* reduce the number of mathematical operations: */
    denominator = circle_z0 - user_atomic_position;
    if (denominator <= 0.001) continue;
    reciprocal_denominator = 1.0 / denominator;

    /* Prepare two factors required for projection: */
    projection_factor_x = nominator_x * reciprocal_denominator;
    projection_factor_y = nominator_y * reciprocal_denominator;

    /* Project the position of the circle center. Note that */
    /* two different  projection  factors  are  used  here! */
    rationalized_x = circle_x0 * projection_factor_x;
    rationalized_y = circle_y0 * projection_factor_y;
    circle_screen_x0 = (int) rationalized_x + image_center_screen_x;
    circle_screen_y0 = (int) rationalized_y + image_center_screen_y;

    /* The angular loop, required to create the rotational surface: */
    for (angle = 0.0; angle <= 6.2831853; angle += angular_increment)
	{
	/* Cosine and sine of the angle: */
	cos_angle = cos (angle);
	sin_angle = sin (angle);

	/* Calculate the relative position of the probe */
	/* center  with  respect  to the center  of the */
	/* first atom.  Note that  a0  is the  parallel */
	/* component of r13 with respect to the u0 axis */
	/* and  rho0  is  the perpendicular  component. */
	r13_1 = rho0 * cos_angle;
	r13_2 = rho0 * sin_angle;
	probe_offset_x = a0    * unit_vector0S.x +
			 r13_1 * unit_vector1S.x +
			 r13_2 * unit_vector2S.x;
	probe_offset_y = a0    * unit_vector0S.y +
			 r13_1 * unit_vector1S.y +
			 r13_2 * unit_vector2S.y;
	probe_offset_z = a0    * unit_vector0S.z +
			 r13_1 * unit_vector1S.z +
			 r13_2 * unit_vector2S.z;

	/* Calculate the absolute position of the probe sphere: */
	probe_x = raw_atom1SP->x[imageI] + probe_offset_x;
	probe_y = raw_atom1SP->y         + probe_offset_y;
	probe_z = raw_atom1SP->z[imageI] + probe_offset_z;

	/* Relative  position  of  the  point  at the */
	/* surface with respect to the circle center: */
	surface_offset_1 = v0 * cos_angle;
	surface_offset_2 = v0 * sin_angle;
	surface_offset_x = surface_offset_1 * unit_vector1S.x +
			   surface_offset_2 * unit_vector2S.x;
	surface_offset_y = surface_offset_1 * unit_vector1S.y +
			   surface_offset_2 * unit_vector2S.y;
	surface_offset_z = surface_offset_1 * unit_vector1S.z +
			   surface_offset_2 * unit_vector2S.z;

	/* Calculate the coordinates of the point at bond surface: */
	surface_x = circle_x0 + surface_offset_x;
	surface_y = circle_y0 + surface_offset_y;
	surface_z = circle_z0 + surface_offset_z;

	/* The vector from the point at the surface */
	/* to  the center of  the spherical  probe: */
	normal_vectorS.x = probe_x - surface_x;
	normal_vectorS.y = probe_y - surface_y;
	normal_vectorS.z = probe_z - surface_z;

	/* If this vector has a positive z component, do */
	/* not redraw  this point  because  it is not on */
	/* the side  which is visible  for the observer: */
	if (normal_vectorS.z > 0.0) continue;

	/* Project the relative position of surface point. Note */
	/* that  projection_factor_x is used in both equations! */
	rationalized_x = surface_offset_x * projection_factor_x;
	rationalized_y = surface_offset_y * projection_factor_x;

	/* Combine the projection of  the circle */
	/* center and projection of the relative */
	/* position of the point at the surface: */
	surface_screen_x = (int) rationalized_x + circle_screen_x0;
	surface_screen_y = (int) rationalized_y + circle_screen_y0;

	/* Prepare the screen coordinates of the current pixel: */
	pixel_screen_x = surface_screen_x;
	pixel_screen_y = surface_screen_y;

	/* Prepare and check the index for the */
	/* array of  NearestAtomS  structures: */
	pixelI = aux2SP->guiSP->main_win_free_area_width *
		 pixel_screen_y + pixel_screen_x;
	if (pixelI >= aux2SP->pixelsN) continue;

	/* Pointer to NearestAtomS struct. */
	/* assigned to  the current pixel: */
	curr_pixelSP = aux2SP->nearest_atomSP + pixelI;

        /* Check is this pixel visible at all: */
        if (surface_z > curr_pixelSP->z + 0.1 * pixel_atomic_size) continue;

	/* Reset the counter which says how many */
	/* pixels should be taken  into account: */
	local_pixelsN = 0;

	/* Retrieve up to five colors of neighboring pixels: */
	for (localI = -2; localI <= 2; localI++)
	    {
	    /* Very close to the atom  the colors of atomic pixels */
	    /* should contribute more to ensure better connection: */
	    if (localI < 0)
		{
		if (u0 <= u0min + double_linear_increment) continue;
		}

	    /* Pixel coordinates in screen units: */
	    pixel_screen_x = surface_screen_x + localI * pixel_shift_x;
	    pixel_screen_y = surface_screen_y + localI * pixel_shift_y;
	    if (pixel_screen_x < 0)            continue;
	    if (pixel_screen_x < left_edge)    continue;
	    if (pixel_screen_x >= right_edge)   continue;
	    if (pixel_screen_y < 0)            continue;
	    if (pixel_screen_y >= bottom_edge) continue;

	    /* Prepare and check the index for the */
	    /* array of  NearestAtomS  structures: */
	    pixelI = aux2SP->guiSP->main_win_free_area_width *
		     pixel_screen_y + pixel_screen_x;
	    if (pixelI >= aux2SP->pixelsN) continue;

	    /* Pointer to NearestAtomS struct. */
	    /* assigned to  the current pixel: */
	    curr_pixelSP = aux2SP->nearest_atomSP + pixelI;

	    /* If nothing was drawn to this pixel in this step, skip it: */
	    if (aux2SP->refreshI != curr_pixelSP->last_refreshI) continue;

	    /* The pixel  should belong  to the */
	    /* same atom and macromol. complex: */
	    if (curr_pixelSP->mol_complexI != aux2SP->mol_complexI) continue;
	    if (curr_pixelSP->atomI != aux2SP->atomI) continue;

	    /* If this point is reached, copy the color of this pixel. */
	    colorIDA[local_pixelsN] = curr_pixelSP->colorID;

	    /* Update the counter which says how many */
	    /* pixels  should be taken  into account: */
	    local_pixelsN++;
	    }

	/* Replace the original color  of the current pixel with the color */
	/* calculated by averaging the colors of three neighboring pixels: */
	if (local_pixelsN == 0)
	    {
	    continue;
	    }
	else if (local_pixelsN == 1)
	    {
	    colorID = colorIDA[0];
	    }
	else if (local_pixelsN == 2) 
	    {
	    colorID = WeightColors_ (colorIDA[0], colorIDA[1],
				     0.5, aux2SP->guiSP);
	    }
	else if (local_pixelsN == 3)
	    {
	    aux_color1ID = WeightColors_ (colorIDA[0], colorIDA[1],
					  0.5, aux2SP->guiSP);
	    colorID = WeightColors_ (aux_color1ID, colorIDA[2],
				     0.33333, aux2SP->guiSP);
	    }
	else if (local_pixelsN == 4)
	    {
	    aux_color1ID = WeightColors_ (colorIDA[0], colorIDA[1],
					  0.5, aux2SP->guiSP);
	    aux_color2ID = WeightColors_ (colorIDA[2], colorIDA[3],
					  0.5, aux2SP->guiSP);
	    colorID = WeightColors_ (aux_color1ID, aux_color2ID,
				     0.5, aux2SP->guiSP);
	    }
	else if (local_pixelsN == 5)
	    {
	    aux_color1ID = WeightColors_ (colorIDA[0], colorIDA[1],
					  0.5, aux2SP->guiSP);
	    aux_color2ID = WeightColors_ (colorIDA[2], colorIDA[3],
					  0.5, aux2SP->guiSP);
	    aux_color3ID = WeightColors_ (aux_color1ID, aux_color2ID,
					  0.5, aux2SP->guiSP);
	    colorID = WeightColors_ (aux_color3ID, colorIDA[4],
				     0.2, aux2SP->guiSP);
	    }
	else continue;

	/* Set color to GC: */
	XSetForeground (aux2SP->guiSP->displaySP,
			aux2SP->guiSP->theGCA[0],
			colorID);

	/* Prepare and check the position of the first pixel: */
	pixel_screen_x = surface_screen_x;
	pixel_screen_y = surface_screen_y;
	if (pixel_screen_x < 0)            continue;
	if (pixel_screen_x < left_edge)    continue;
	if (pixel_screen_x >= right_edge)  continue;
	if (pixel_screen_y < 0)            continue;
	if (pixel_screen_y >= bottom_edge) continue;

	/* Prepare and check the index for the */
	/* array of  NearestAtomS  structures: */
	pixelI = aux2SP->guiSP->main_win_free_area_width *
		 pixel_screen_y + pixel_screen_x;
	if (pixelI >= aux2SP->pixelsN) continue;

	/* Pointer to NearestAtomS struct. */
	/* assigned to  the current pixel: */
	curr_pixelSP = aux2SP->nearest_atomSP + pixelI;

	/* Redraw the current pixel: */
	XDrawPoint (aux2SP->guiSP->displaySP,
		    aux2SP->guiSP->main_hidden_pixmapID,
		    aux2SP->guiSP->theGCA[0],
		    pixel_screen_x, pixel_screen_y);

	/* Refresh the colorID member of the NearestAtomS */
	/* structure  associated with  the current pixel: */
	curr_pixelSP->colorID = colorID;
	}
    }

/*---------------------------------------------------------------------------*/

/* If this point is reached, the entire bond was drawn: */
return 1;
}

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


