/*

File: address_set.c
Author: Neil Cafferkey
Copyright (C) 1999-2001 Neil Cafferkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.

*/

#include <stdio.h>

#include "set_protos.h"
#include "address_set_protos.h"
#include "address_protos.h"


/* Function: SearchAddressSet
 * ==========================
 * Searches for an address with the same bank and offset as the search key.
 * If a matching address is found, it is returned and the search key is
 * killed. If no match is found the search key is added to the set and
 * returned.
 */

Address SearchAddressSet(AddressSet address_set,Address test_address)
{
   Address temp_address;
   BOOL found;
   AddressSetNode node=address_set->first;

   /* Search the address set for an equivalent address */

   for(found=FALSE;(node!=NULL)&&!found;node=node->next)
      found=IsSameAddress(temp_address=node->element,test_address);


   /* Kill the input address and return the previously existing equivalent
      address */

   if(found)
   {
      KillAddress(test_address);
      return temp_address;
   }

   /* Include the input address in the address set and return the address */

   else
   {
      PutInSet(address_set,test_address);
      return test_address;
   }
}


#ifndef NDEBUG

/* Function: ShowAddressSet
 * ========================
 * Prints out the contents of the address set for testing.
 */

VOID ShowAddressSet(AddressSet set)
{
   AddressSet temp_set=DupSet(set);

   while(!IsEmptySet(temp_set))
      ShowAddress(TakeFromSet(temp_set));

   KillSet(temp_set);

   return;
}

#endif


#ifdef TEST

#include <assert.h>


LONG main(VOID)
{
   AddressSet set=CreateSet(),set2;

   PutInSet(set,7);
   PutInSet(set,4);
   PutInSet(set,18);

   assert(IsInSet(set,18));
   assert(IsInSet(set,18));
   assert(!IsInSet(set,0));
   assert(!IsEmptySet(set));

   set2=DupSet(set);

   printf("%d\n",TakeFromSet(set));
   printf("%d\n",TakeFromSet(set));
   printf("%d\n",TakeFromSet(set));

   ShowSet(set2);

   printf("%d\n",TakeFromSet(set2));
   printf("%d\n",TakeFromSet(set2));
   printf("%d\n",TakeFromSet(set2));

   assert(IsEmptySet(set2));
   assert(TakeFromSet(set)==NULL);
   assert(!IsInSet(set,18));

   KillSet(set);

   return EXIT_SUCCESS;
}

#endif


