/*
 * tools/lib/pv_check_number.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * October 1997
 * December 1998
 * February 2000
 *
 *
 * This LVM library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This LVM library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this LVM library; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA
 *
 */

/*
 * Changelog
 *
 *    16/12/1998 - fixed array index bug
 *    31/01/2000 - use debug_enter()/debug_leave()
 *
 */

#include <liblvm.h>

int pv_check_number ( pv_t **pv, int max_number) {
   int pv_number = 0;
   int ret = 0;
   int p = 0;
   int *pv_number_count = NULL;

#ifdef DEBUG
   debug_enter ( "pv_check_number -- CALLED\n");
#endif

   if ( pv == NULL || max_number < 1) ret = -LVM_EPARAM;
   else {
      for ( p = 0; pv[p] != NULL; p++)
         if ( pv_number < pv[p]->pv_number) pv_number = pv[p]->pv_number;
   
      if ( pv_number > max_number) ret = -LVM_EPV_CHECK_NUMBER_MAX_NUMBER;
      else if ( ( pv_number_count = malloc ( pv_number * sizeof ( int)))
                == NULL) {
         fprintf ( stderr, "malloc error in %s [line %d]\n",
                           __FILE__, __LINE__);
         ret = -LVM_EPV_CHECK_NUMBER_MALLOC;
      } else {
         memset ( pv_number_count, 0, pv_number * sizeof ( int));
         for ( p = 0; p < pv_number; p++) pv_number_count[pv[p]->pv_number-1]++;
         for ( p = 0; p < pv_number; p++) {
            if ( pv_number_count[p] != 1) {
               ret = -LVM_EPV_CHECK_NUMBER_PV_NUMBER;
               break;
            }
            ret = p;
         }
      }
   
      if ( pv_number_count != NULL) free ( pv_number_count);
   }

#ifdef DEBUG
   debug_leave ( "pv_check_number -- LEAVING with ret: %d\n", ret);
#endif
   return ret;
}
