Listing 3

/*begin************************************************
*   Program   : closest
*   Descript. : Returns the number of the closest color
*               from the palette, given the desired red
*               green, and blue. Find the closest point
*               by using the red index arrey. Look at
*               points on both sides of the closest
*               point. While searching, if a point is
*               closer then it is the shortest distance
*               Once you are examining points that are
*               farther away in just the one dimension
*               (red) then you are done.
*end**************************************************/

int closest( int red, int green, int blue )
{
long least;
long dif;
long sum;
int index;
int left;
int right;

index = redindex[ red ];
least = dist( red, green, blue, index );
left = index;
right = index;

while( ( left >= 0 ) || (right < PAL_LEN ) )
   {
   if ( -left >= 0 )
      {
      /* if red dist. alone is greater, then quit */
      dif = red - pals[ left ].red;
      if ( ( dif * dif ) > least )
         left = -1;
      else
         {
         sum = dist( red, green, blue, left );
         if ( sum < least )
            {
            least = sum;
            index = left;
            }
         }
      }
   if ( ++right < PAL_LEN )
      {
      /* if red dist. alone is greater, then quit */
      dif = red - pals[ right ].red;
      if ( ( dif * dif ) > least )
         right = PAL_LEN;
      else
         {
         sum = dist( red, green, blue, right );
         if ( sum < least )
            {
            least = sum;
            index = right;
            }
         }
      }
   }
return( pals[ index ].num );
}


/*begin*************************************************
*  Program   : dist
*  Descript. : Color distance (squared)
*end**************************************************/

long dist( int red, int green, int blue, int num )
{
long dif;
long sum;
pal *palt;

palt = &pals[ num ];
dif = red - palt->red;
sum = dif * dif;
dif = green - palt->grn;
sum += dif * dif;
dif = blue - palt->blu;
sum += dif * dif;
return( sum );
}
/* End of File */