/*
 * libsal/skiplists/delete.c
 * Delete a node from a skip list
 * 
 * For copyright details, see libsal/license.h
 */

#include <libsal/skiplists/internal.h>
#include <libsal/license.h>
#include <libsal/proto.h>
#include <libsal/defines.h>
#include <libsal/types.h>

int sal_skiplist_Delete(sal_skiplist_skiplist pstList, void * szKey)
{
  int k, m;
  sal_skiplist_node update[SAL_SKIPLIST_MAXNOOFLEVELS];
  sal_skiplist_node p,q,r;
  
  k = m = pstList->iLevel;
  q = sal_skiplist_FindForUpdate(pstList, szKey, update);
  r = sal_skiplist_GetEndNode();
  
  if ((*pstList->compare_func)(q->szData, szKey) == 0)
  {
    for (k = 0; k <= m && (p = update[k])->pstForward[k] == q; k++)
      p->pstForward[k] = q->pstForward[k];
    
    free(q);
    
    while (pstList->pstHeader->pstForward[m] == r && m > 0)
      m--;
    
    pstList->iLevel = m;
    return 1;
  }
  else
    return 0;
}
