/**********************************************************
util.c

Written by: XXXXXXXXXXXXXXXXXXXXXX
 
Written in: ANSI C.

This file contains the utility routines required
to help solve the kasiski method.

It was designed to be used with the program kasiski.c. 


***********************************************************/

#include"util.h"



/* calculate the gcd for two constants. */
int gcd(int a, int b)
  {
    int i, n;
    int ans;

    if(a == b)
     return(a);

    if(a< b)
     n= a;
    else
     n= b;

    for(i= 1; i< n; i++)
     if(((a%i) == 0) && ((b%i) == 0))
       ans= i;

    return(ans);

  } /* gcd */



/* calculate the gcd for a list of constants. */
int ngcd(int *a, int n)
  {
    int  i, j, k;
    int  ans;
    char found;


    if(n< 2)
     return(0);

    k= a[0];
    for(i= 1; i< n; i++)
     if(a[i]< k)
       k= a[i];

    for(i= 1; i< k; i++)
      {
        found= TRUE;
        for(j= 0; (j< n) && found; j++)
          {
            if((a[j]%i) != 0)
              found= FALSE;
          }
        if(found)
          ans= i;
      }

    return(ans);


  } /* ngcd */



/* Check to see if there are non-alpha (a..z) characters
   in string (str).  Output boolean response.*/
Bool containSpecialCharactersP(char *str, int len)
  {
    int  i;
    Bool exist= FALSE;

    for(i= 0; ((i< len) && !exist); i++)
      if(!(((str[i] >= 'A') && (str[i] <= 'Z'))
          || ((str[i] >= 'a') && (str[i] <= 'z'))))
       exist= TRUE;

    return(exist);

  } /* containSpecialCharactersP */



/* Check to see if some substring contains a pattern that
   is a subset of a larger string (or equal to). 
   Output boolean response. */
Bool subsetP(char *str1, int len1, char *str2, int len2)
  {
    int  i, 
         n1,                  /* Larger string */
         n2;                  /* Smaller string */
    char *a, *b;
    Bool asubset= FALSE;



    /* Determine which string is larger. */
    if(len1> len2)
     {
       n1= len1;
       n2= len2;
       a= str1;
       b= str2;
     }
    else
     {
       n1= len2;
       n2= len1;
       a= str2;
       b= str1;
     }



    /* Check for subset. */
    for(i= 0; ((i<= (n1-n2)) && !asubset); i++)
     {
       if(strncmp(b, (a+i), n2)== 0)
         asubset= TRUE;
     }

    return(asubset);
    
  } /* subsetP */



/* Convert an upper character, to a lower case character. */
char up2LowerCase(char c)
  {
    char newc;

    if((c>= 'A') && (c<= 'Z'))
      newc= c+ ('a' - 'A');
    else
      newc= c;

    return(newc);
  } /* up2LowerCase */

