/*
 * tools/lib/lvm_check_number.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * June 1998
 * March 1999
 * January 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/03/1999 - enhanced unit check and added default of Megabyte
 *    31/01/2000 - use debug_enter()/debug_leave()
 *               - rewritten
 *
 */

#include <liblvm.h>

#define MAX_N	80

long lvm_check_number ( char *number_str, int unit) {
   int ret = 0;
   long mul = 1;
   int i = 0;
   int c = 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) > MAX_N-1 ||
        ( unit != TRUE && unit != FALSE)) {
      ret = -LVM_EPARAM;
      goto lvm_check_number_end;
   }

   memset ( n_buff, 0, MAX_N);
   strncpy ( n_buff, number_str, MAX_N - 1);
   ptr = n_buff;

   for ( ; *ptr != 0; ptr++) {
      if ( *ptr == ',') *ptr = '.';
      if ( ! isdigit ( *ptr) && *ptr != '.') break;
   }
   if ( *ptr != 0) {
      if ( ptr[1] == 0) {
         ret = -1;
         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 = 0;
            }
         } else ret = -1;
      } else ret = -1;
   } else if ( unit == TRUE) mul = 1024;

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

lvm_check_number_end:

   debug_leave ( "lvm_check_number -- LEAVING with ret: %d\n", ret);
   return ret;
}
