/***********************************************************************\

    Filename: corrsubr.c

\***********************************************************************/

#include <stdio.h>
#include <language.h>
#include "clxtypo.h"
#include "lex.h"
#include "corelex.h"
#include "correct.h"
#include "environ.h"
#include "spath.h"

CORRECT Corinfo;                /* The correction globals. */

/* Add an alternative to the ranked list, using Coorder to order it by 
   theta-similarity.  */ 

void rankalt(word, thetaval, flags)
char   *word;
unsigned thetaval;
int     flags;
{
ALTINFO *alt;
unsigned int try;
unsigned int pos;
unsigned int altindex;
unsigned int dupalt;
unsigned int count;

/*    printf("in rank: %s, %04x\n", word, thetaval);*/

   /* find position to insert at. */

   count = Corcount;
   for (try = 0; try < count; ++try)
   {
       alt = &Coranklist[Coorder[try]];
       if (thetaval > alt->al_simil)
           break;

                /* if a duplicate alternative is found with a higher 
                   similarity, don't bother inserting */ 

       if (flags == alt->al_flags && strcmp(word, alt->al_word) == 0)
           return;
   }
   pos = try;

        /* check whether the alternative is duplicated at or below the
           position to insert at */ 

   dupalt = FALSE;
   for (; try < count; ++try)
   {
       alt = &Coranklist[Coorder[try]];
       if (flags == alt->al_flags && strcmp(word, alt->al_word) == 0)
       {
           dupalt = TRUE;
           break;
       }
   }

        /* if a duplicate alternative was found with a lower similarity, 
           substitute in the new similarity and move it up in the list */ 

        /* otherwise, fill in a new ALTINFO structure -- the bottom one if 
           the list is full, or just the next available one */ 

   if (dupalt)
   {
       altindex = Coorder[try];
       alt->al_simil = thetaval;
   }
   else
   {
       if (count == _SPListAlts)
           altindex = Coorder[_SPListAlts - 1];
       else
           altindex = count;
       alt = &Coranklist[altindex];
       strecpy(alt->al_word, word);
       alt->al_flags = flags;
       alt->al_simil = thetaval;

                /* increment the count if the list isn't already full */ 

       if (count < _SPListAlts)
           ++Corcount;
   }
        /* make space for the new alternative (or for the old alternative, 
           with its new similarity) */ 

   for (; try > pos; --try)
       Coorder[try] = Coorder[try - 1];

   /* insert the new alternative */

   Coorder[pos] = altindex;

        /* If the inserted alternate is at the end of the list then update 
           the minrank value.  */ 

   if (pos == _SPListAlts - 1)
       Cominrank = thetaval;
}
