/*
 * tools/lib/lvm_check_number.c
 *
 * Copyright (C) 1997 - 2002  Heinz Mauelshagen, Sistina Software
 *
 * June 1998
 * March 1999
 * January 2000
 * February 2002
 *
 *
 * 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
 *    31/01/2000 - use debug_enter()/debug_leave()
 *               - rewritten
 *    14/02/2002 - lvm_check_number_ll() to return ( long long) numbers
 *
 */

#include <liblvm.h>

#define MAX_N	80

long lvm_check_number ( char *number_str, int unit) {
   long ret = ( long) lvm_check_number_ll ( number_str, unit);
   if ( ret > UINT_MAX) ret = -1L;
   debug_leave ( "lvm_check_number -- LEAVING with ret: %Ld\n", ret);
   return ret;
}

long long lvm_check_number_ll ( char *number_str, int unit) {
   long long ret = 0;
   long mul = 1;
   int i = 0;
   int c = 0;
   int dot = 0;
   char *ptr = NULL;
   char n_buff[MAX_N];
   char *dimensions = "kmgt";

   debug_enter ( "lvm_check_number -- CALLED with \"%s\"\n", number_str);

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

   memset ( n_buff, 0, sizeof ( n_buff));
   strncpy ( n_buff, number_str, sizeof ( n_buff) - 1);

   for ( ptr = n_buff; *ptr != 0; ptr++) {
      if ( *ptr == ',') *ptr = '.';
      if ( *ptr == '.') dot++;
      if ( ! isdigit ( *ptr) && *ptr != '.') break;
   }

   if ( *ptr != 0) {
      if ( ptr[1] == 0) {
         ret = -1LL;
         if ( unit == TRUE) {
            c = tolower ( *ptr);
            for ( i = 0; dimensions[i] != 0; i++)
               if ( c == dimensions[i]) break;
            if ( dimensions[i] != 0) { /* wrong dimension given? */
               for ( ; i > 0; i--) mul *= 1024;
               *ptr = 0;
               ret = 0LL;
            }
         } else ret = -1LL;
      } else ret = -1LL;
   } else if ( dot > 1) ret = -1LL;
   else if ( unit == TRUE) mul = 1024;

   if ( ret == 0LL) ret = atof ( n_buff) * mul;

lvm_check_number_end:

   debug_leave ( "lvm_check_number_ll -- LEAVING with ret: %Ld\n", ret);
   return ret;
} /* lvm_check_number_ll */
