/*
 * tools/lib/lvm_show_size.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Germany
 *
 * June,October 1997
 * May,June 1998
 * February 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
 *
 *    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
 *
 */

#include <liblvm.h>

#define TERABYTE	( 1024 * 1024 * 1024)

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

   if ( sl != LONG && sl != SHORT) return NULL;

   if ( ( size_buf = malloc ( NAME_LEN)) == NULL) {
      fprintf ( stderr, "malloc error in %s [line %d]\n", __FILE__, __LINE__);
      return NULL;
   }

   memset ( size_buf, 0, NAME_LEN);
   if ( size > 0) {
      for ( s = 0; size_char[s] != 0; s++) {
         if ( size >= byte) {
            sz = sprintf ( size_buf, "%.2f", ( float) size / byte);
            while ( size_buf[sz-1] == '0') sz--;
            if ( size_buf[sz-1] == '.') sz--;
            if ( sl == LONG) sz += sprintf ( &size_buf[sz], " %sbyte%c",
                                             size_string[s], 0);
            else             sz += sprintf ( &size_buf[sz], " %cB%c",
                                             size_char[s], 0);
            break;
         }
         byte /= 1024;
      }
   } else size_buf[0] = '0';

   return size_buf;
}
