#include "main.h"
#include <avr/pgmspace.h>
#include "valout.h"


// #define APPEND_ZERO				// append 0 to output string

#define DECIMAL	','
// #define DECIMAL '.'


#ifdef VAL_32					// 32 bit numbers
#define	table_type	prog_uint32_t
#define	table_read(x,y)	pgm_read_dword(x+y)

table_type TEST[] = {    10L,
			100L,
		       1000L,
		      10000L,
		     100000L,
		    1000000L,
		   10000000L,
		  100000000L,
		 1000000000L };

static u8 buff[sizeof("-214748364.8")];		// maximum number length


void valout( s32 val, s8 digits, s8 point, u8 *outp )

#else						// 16 bit numbers
#define	table_type	prog_uint16_t
#define	table_read(x,y)	pgm_read_word(x+y)

table_type TEST[] = {	 10L,
			100L,
		       1000L,
		      10000L };

static u8 buff[sizeof("-3276.8")];		// maximum number length


void valout( s16 val, s8 digits, s8 point, u8 *outp )
#endif
{
  u8 d, i, notzero;
  u8 *buffp = buff;

  if( val < 0 ){			// handle sign
    val = -val;
    *buffp++ = '-';
  }
  point -= sizeof(TEST) / sizeof(table_type) + 1;
  notzero = 0;
  for( i = sizeof(TEST) / sizeof(table_type); i; i-- ){
    for( d = '0';
      val >= table_read(TEST,i-1);
      val -= table_read(TEST,i-1) ){
      d++;
      notzero = 1;
    }
    if( notzero )
      *buffp++ = d ;
    if( ++point == 0 ){			// insert decimal point
      if( notzero == 0 )
	*buffp++ = d;			// zero prior decimal point
      notzero = 1;
      *buffp++ = DECIMAL;		// decimal point sign
    }
  }
  *buffp++ = val + '0';			// remainder = ones
  *buffp = 0;
  digits -= buffp - buff;		// length of string
  while( --digits >= 0 )
    *outp++ = ' ';			// insert spaces until min length
  buffp = buff;
#ifdef APPEND_ZERO
  do
    *outp++ = *buffp;
  while( *buffp++ );			// copy with '\0'
#else
  while( *buffp )
    *outp++ = *buffp++;			// copy without '\0'
#endif
}
