/*
 * tools/lib/lvm_check_number.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Germany
 *
 * June 1998
 * March 1999
 *
 *
 * 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/03/1999 - enhanced unit check and added default of Megabyte
 *
 */

#include <liblvm.h>

#define MAX_N	32

int lvm_check_number ( char *number_str, int unit) {
   int ret = 0;
   int mul = 1;
   char *ptr = NULL;
   char n_buff[MAX_N];

#ifdef DEBUG
   debug ( "lvm_check_number -- CALLED with \"%s\"\n", number_str);
#endif

   if ( number_str == NULL || strlen ( number_str) > MAX_N-1 ||
        ( unit != TRUE && unit != FALSE)) {
      ret = -LVM_EPARAM;
      goto lvm_check_number_end;
   }

   strcpy ( n_buff, number_str);
   ptr = n_buff;

   for ( ; *ptr != 0; ptr++) {
      if ( ! isdigit ( *ptr) && ptr[1] != 0) {
         ret = -1;
         break;
      }
      if ( unit == TRUE && ptr[1] == 0) {
         if ( tolower ( *ptr) == 'k' ||
              tolower ( *ptr) == 'm' ||
              tolower ( *ptr) == 'g' ||
              tolower ( *ptr) == 't') {
            if ( tolower ( *ptr) == 'k')      mul = 1;
            else if ( tolower ( *ptr) == 'm') mul = 1024;
            else if ( tolower ( *ptr) == 'g') mul = 1024*1024;
            else if ( tolower ( *ptr) == 't') mul = 1024*1024*1024;
            *ptr = 0;
            break;
         } else mul = 1024;
      }
   }
   if ( ret == 0) ret = atoi ( n_buff) * mul;

lvm_check_number_end:
#ifdef DEBUG
   debug ( "lvm_check_number -- LEAVING with ret: %d\n", ret);
#endif

   return ret;
}
