/*
 * tools/lib/lvm_show_size.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * June,October 1997
 * May,June 1998
 * February 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
 *
 *    11/10/1997 - use larger values (eg. MB instead of GB)
 *               - fix returning NULL string with size 0
 *    22/05/1998 - malloc a buffer for each call
 *    08/06/1998 - changed size parameter to type long long
 *    02/02/1999 - fixed buf with presentation of zero
 *    31/01/2000 - use debug_enter()/debug_leave()
 *
 */

#include <liblvm.h>

#define TERABYTE	( 1024 * 1024 *1024)

char *lvm_show_size ( unsigned long long size, size_len_t sl) {
   int s;
   int sz;
   unsigned long long byte = TERABYTE;
   char *size_buf = NULL;
   char *ret = NULL;
   static char size_char[] = "TGMK";
   static char *size_string[] = {
      "Tera",
      "Giga",
      "Mega",
      "Kilo",
   };

   if ( ( size_buf = malloc ( NAME_LEN)) == NULL) {
      fprintf ( stderr, "malloc error in %s [line %d]\n", __FILE__, __LINE__);
      ret = NULL;
   } else {
      memset ( size_buf, 0, NAME_LEN);
      ret = size_buf;
      if (size == 0LL) {
	  sz += sprintf ( size_buf, "0");
      } else for ( s = 0; size_char[s]; s++) {
         if ( size >= byte) {
            sz = snprintf ( size_buf, NAME_LEN - 1, "%.2f",
                                      (double) size / byte);
            if ( strcmp ( &size_buf[sz-3], ".00") == 0) sz -= 3;
            if (size_buf[sz-1] == '.') sz--;
            if (sl == LONG)
               sz += snprintf ( &size_buf[sz], NAME_LEN - sz - 1,
                                               " %sbyte", size_string[s]);
            else
               sz += snprintf ( &size_buf[sz], NAME_LEN - sz - 1,
                                               " %cB", size_char[s]);
            break;
         }
         byte /= 1024;
      }
   }

   return ret;
}
