/*###########################################################################
#                                                                           #
#                                xnprintf()                                 #
#                                                                           #
#               Copyright (c) 2002-2005 David TAILLANDIER                   #
#                                                                           #
###########################################################################*/

/*

This software is distributed under the "general public licence (GPL)".

This software is also released under the modified BSD licence in another
file (same source-code, only license differ).


This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA




====================
Revision history:

february 26th 2005 David TAILLANDIER  6th bug found. This was just a typo
   which did not pass the regression test. Thanks to Luc PEUVRIER.

december 29th 2002 David TAILLANDIER  a little simplification into the
   handling of (v)as(n)printf into core(). puts() return-value is now checked.

december 15th 2002 David TAILLANDIER  asnprintf and vasnprintf added.
   return value of asprintf and vasprintf adapted to standards.
   Some other minor code modifications.
   First bugs found (and corrected):
      - memory was not freed when (v)asprintf returned an error.
      - problem when submiting an empty string.
      - (v)snprintf did not checked the case of a NULL string pointer.
      - incorrect handling of empty string inside (v)asprintf.
      - erroneous test-condition in type_s() witch made an infinite loop in
        some cases.

may 23rd 2002 David TAILLANDIER  some minor code enhacement and
   simplification.

february 28th 2002 David TAILLANDIER  Initial release.
   Added a test suite. Every major bugs seems corrected.

february 16th 2002 David TAILLANDIER  early-buggy initial release

====================


'printf' function family use the following format string:

   %[flag][width][.prec][modifier]type

   %% is the escape sequence to print a '%'
   %  followed by an unknown format will print the characters without
      trying to do any interpretation

   flag:   none   +     -     #     (blank)
   width:  n    0n    *
   prec:   none   .0    .n     .*
   modifier:    F N L h l    ('F' and 'N' are ms-dos/16-bit specific)
   type:  d i o u x X f e g E G c s p n


The function needs to allocate memory to store the full text before to
actually writting it.  i.e if you want to fnprintf() 1000 characters, the
functions will allocate 1000 bytes.
This behaviour can be modified: you have to customise the code to fluch the
internal buffer (writing to screen or file) when it reach a given size. Then
the buffer can have a shorter length. But what ?  If you really need to write
HUGE string, don't use printf !
During the process, some other memory is allocated (1024 bytes minimum)
to handle the output of partial sprintf() calls. If you have only 10000 bytes
free in memory, you *may* not be able to nprintf() a 8000 bytes-long text.

note: if a buffer overflow occurs, exit() is called. This situation should
never appear ... but if you want to be *really* sure, you have to modify the
code to handle those situations (only one place to modify).
A buffer overflow can only occur if your sprintf() do strange things or when
you use strange formats.



internals
=========

A temporary buffer is allocated at the beggining ; It is then enlarged when
needed (never srinked) by every sub-functions ; It is freed when the print is
done. The goal is to save a lot of alloc/free. Its initial size is given by
the macro 'ALLOC_CHUNK'. It had to be enlarged very few times because its size
is big enought to handle common sprintf() queries.
The macro 'ALLOC_SECURITY_MARGIN' gives the number of bytes used as security
margin because sprintf() *may* write more characters as expected (but no
enought to overflow beyond 'ALLOC_SECURITY_MARGIN').
In the unlikely case a buffer overflow occurs, a marquer should detect it at
the end of the buffer ; "exit(-1)" is then done.

*/

/*#########################################################################*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <limits.h>


#if defined _16BIT_ || defined __TINY__ || defined __SMALL__ || defined __MEDIUM__ || defined __COMPACT__ || defined __LARGE__ || defined __HUGE__
#    define __DOS_16BIT__
#endif


#ifdef __DOS_16BIT__
#    define ALLOC_CHUNK 512
#    define ALLOC_SECURITY_MARGIN 100  /* don't need big margin for ms-dos/16-bit ; saves memory */
#else
#    define ALLOC_CHUNK 2048
#    define ALLOC_SECURITY_MARGIN 1024   /* big value because some platforms have very big 'G' exponant */
#endif                                   /* (for example, the VAX has 308 digit exponant)              */
#if ALLOC_CHUNK < ALLOC_SECURITY_MARGIN
#    error  !!! ALLOC_CHUNK < ALLOC_SECURITY_MARGIN !!!
#endif
/* note: to have some interest, ALLOC_CHUNK should be _much_ greater than ALLOC_SECURITY_MARGIN */

/*
 *  To save a lot of push/pop, every variable are stored into this
 *  structure, which is passed among nearly every sub-functions.
 */
typedef struct {
     const char * src_string;        /* current position into intput string */
     char *       buffer_base;       /* output buffer */
     char *       dest_string;       /* current position into output string */
     size_t       buffer_len;        /* length of output buffer */
     size_t       real_len;          /* real current length of output text */
     size_t       pseudo_len;        /* total length of output text if it where not limited in size */
     size_t       maxlen;
     va_list      vargs;             /* pointer to current position into vargs */
     char *       sprintf_string;
     FILE *       fprintf_file;
     char         flavour;           /* kind of function:  asprintf() nprintf() snprintf() or fnprintf() */
} xprintf_struct;

/*########################### realloc_buff ################################*/
/*
 *  Realloc buffer if needed
 *  Return value:  0 = ok
 *               EOF = not enought memory
 */
static
int
realloc_buff( xprintf_struct * s,
              size_t len
            )
{
     char * ptr;

     if ( len + ALLOC_SECURITY_MARGIN + s->real_len   >   s->buffer_len )
       {
          len += s->real_len + ALLOC_CHUNK;
          ptr = (char *)realloc( (void *)(s->buffer_base), len );
          if ( ptr == NULL )
            {
               s->buffer_base = NULL;
               return EOF;
            }

          s->dest_string = ptr + (size_t)( s->dest_string - s->buffer_base );
          s->buffer_base = ptr;
          s->buffer_len = len;

          (s->buffer_base)[(s->buffer_len)-1] = 1;        /* overflow marquer */
       }

     return 0;
}

/*############################ usual_char #################################*/
/*
 *  Prints 'usual' characters    up to next '%'
 *                            or up to end of text
 */
static
int
usual_char( xprintf_struct * s )
{
     size_t len;

     len = strcspn( s->src_string, "%" );     /* reachs the next '%' or end of input string */
     /* note: 'len' is never 0 because the presence of '%' */
     /* or end-of-line is checked in the calling function  */

     if ( realloc_buff(s,len) == EOF )
          return EOF;

     memcpy( s->dest_string, s->src_string, len );
     s->src_string  += len;
     s->dest_string += len;
     s->real_len    += len;
     s->pseudo_len  += len;

     return 0;
}

/*############################ print_it ###################################*/
/*
 *  Return value: 0 = ok
 *                EOF = error
 */
static
int
print_it( xprintf_struct * s,
          size_t           approx_len,
          const char *     format_string,
          ...
        )
{
     va_list varg;
     int     vsprintf_len;
     size_t  len;

     if ( realloc_buff(s,approx_len) == EOF )
          return EOF;

     va_start( varg, format_string );
     vsprintf_len = vsprintf( s->dest_string, format_string, varg );
     va_end( varg );

     if ( (s->buffer_base)[(s->buffer_len)-1] != 1 )     /* check for overflow */
       {
          fprintf( stderr, "ERROR in xnprintf library: overflow" );
          exit( -1 );            /* ... sorry ... what else to do ?    */
       }

     if ( vsprintf_len == EOF )    /* must be done *after* overflow-check */
          return EOF;

     s->pseudo_len  += vsprintf_len;
     len = strlen( s->dest_string );
     s->real_len    += len;
     s->dest_string += len;

     return 0;
}

/*############################## type_s ###################################*/
/*
 *  Prints a string (%s)
 *  We need special handling because:
 *     a: the length of the string is unknown
 *     b: when .prec is used, we must not access any extra byte of the
 *        string (of course, if the original sprintf() does... what the
 *        hell, not my problem)
 *
 *  Return value: 0 = ok
 *                EOF = error
 */
static
int
type_s( xprintf_struct * s,
        int              width,
        int              prec,
        const char *     format_string,
#ifdef __DOS_16BIT__
        const char far * arg_string,
        char             modifier
#else
        const char *     arg_string
#endif
      )
{
     size_t       string_len;

     if ( arg_string == NULL )
          return print_it( s, 6, "(null)", 0 );

     /* hand-made strlen() whitch stops when 'prec' is reached. */
     /* if 'prec' is -1 then it is never reached.               */
     string_len = 0;
     while ( arg_string[string_len]!=0 && (unsigned int)prec!=string_len )
          string_len++;

     if ( width != -1 )
          if ( string_len < (unsigned int)width )
               string_len = (unsigned int)width;

#ifdef __DOS_16BIT__
     switch( modifier )
       {
          case 'N':   return print_it( s, string_len, format_string, (const char near*)arg_string );
          case 'F':   return print_it( s, string_len, format_string, (const char far*)arg_string );
       }
     /* modifier == -1 */
     return print_it( s, string_len, format_string, (const char*)arg_string );
#else
     return print_it( s, string_len, format_string, arg_string );
#endif
}

/*############################### getint ##################################*/
/*
 *  Read a serie of digits. Stop when non-digit is found.
 *  Return value: the value read (between 0 and 32767).
 *  Note: no checks are made against overflow. If the string contain a big
 *  number, then the return value won't be what we want (but, in this case,
 *  the programmer don't know whatr he wants, then no problem).
 */
static
int
getint( const char * * string )
{
     int i;

     i = 0;

     while ( isdigit(**string) != 0 )
       {
          i = (i*10) + (**string-'0');
          (*string)++;
       }

     if ( i<0 || i>32767 )
          i = 32767;      /* if we have i==-10 this is not because the number is */
                          /* negative ; This is because the number is biiiig     */
     return i;
}

/*############################## dispatch #################################*/
/*
 *  Read a part of the format string. A part is 'usual characters' (ie "blabla")
 *  or '%%' escape sequence (to print a single '%') or any combination of
 *  format specifier (ie "%i" or "%10.2d").
 *  After the current part is managed, the function returns to caller with
 *  everything ready to manage the following part.
 *  The caller must ensure than the string is not empty, i.e. the first byte
 *  is not zero.
 *
 *  Return value:  0 = ok
 *                 EOF = error
 */
static
int
dispatch( xprintf_struct * s )
{
     const char * initial_ptr;
     char   format_string[24];        /* max length may be something like  "% +-#032768.32768Ld" */
     char * format_ptr;
     int    flag_plus, flag_minus, flag_space, flag_sharp, flag_zero;
     int    width;
     int    prec;
     char   modifier;
     char   type;
     int    approx_width;
     /* most of those variables are here to rewrite the format string */

#define SRCTXT  (s->src_string)
#define DESTTXT (s->dest_string)

/* incoherent format string. Characters after the '%' will be printed with the next call */
#define INCOHERENT()         do {SRCTXT=initial_ptr; return 0;} while (0)     /* do/while to avoid */
#define INCOHERENT_TEST()    do {if(*SRCTXT==0)   INCOHERENT();} while (0)    /* a null statement  */

/* 'normal' text */
     if ( *SRCTXT != '%' )
          return usual_char( s );

/* we then have a '%' */
     SRCTXT++;
     /* don't check for end-of-string ; this is done later */

/* '%%' escape sequence */
     if ( *SRCTXT == '%' )
       {
          if ( realloc_buff(s,1) == EOF )   /* because we can have "%%%%%%%%..." */
               return EOF;
          *DESTTXT = '%';
          DESTTXT++;
          SRCTXT++;
          (s->real_len)++;
          (s->pseudo_len)++;
          return 0;
       }

/* '%' managing */
     initial_ptr = SRCTXT;   /* save current pointer in case of incorrect        */
                             /* 'decoding'. Points just after the '%' so the '%' */
                             /* won't be printed in any case, as required.       */
     /* flag */
     flag_plus  = 0;     flag_minus = 0;     flag_space = 0;
     flag_sharp = 0;     flag_zero  = 0;

     for ( /*none*/; /*none*/; SRCTXT++ )
       {
          if ( *SRCTXT == ' ' ) { flag_space = 1;  continue; }
          if ( *SRCTXT == '+' ) { flag_plus  = 1;  continue; }
          if ( *SRCTXT == '-' ) { flag_minus = 1;  continue; }
          if ( *SRCTXT == '#' ) { flag_sharp = 1;  continue; }
          if ( *SRCTXT == '0' ) { flag_zero  = 1;  continue; }
          break;
       }

     INCOHERENT_TEST();     /* here is the first test for end of string */

     /* width */
     if ( *SRCTXT == '*' )      /* width given by next argument */
       {
          SRCTXT++;
          width = va_arg( s->vargs, int );
          if ( (unsigned int)width > 0x3fffU )    /* 'unsigned' to check against negative values too */
               width = 0x3fff;
       }
     else if ( isdigit(*SRCTXT) != 0 )      /* width given as ASCII number */
       {
          width = getint( &SRCTXT );
       }
     else
          width = -1;       /* no width specified */

     INCOHERENT_TEST();

     /* .prec */
     if ( *SRCTXT == '.' )
       {
          SRCTXT++;
          if ( *SRCTXT == '*' )     /* .prec given by next argument */
            {
               prec = va_arg( s->vargs, int );
               if ( (unsigned int)prec >= 0x3fffU )    /* 'unsigned' to check against negative values too */
                    prec = 0x3fff;
            }
          else
            {       /* .prec given as ASCII number */
               if ( isdigit(*SRCTXT) == 0 )
                    INCOHERENT();
               prec = getint( &SRCTXT );
            }
          INCOHERENT_TEST();
       }
     else
          prec = -1;        /* no .prec specified */

     /* modifier */
     if ( *SRCTXT == 'L' || *SRCTXT == 'h' || *SRCTXT == 'l'
#ifdef __DOS_16BIT__
          || *SRCTXT == 'F' || *SRCTXT == 'N'
#endif
        )
       {
          modifier = *SRCTXT;
          SRCTXT++;
          if ( modifier=='l' && *SRCTXT=='l' )
            {
               SRCTXT++;
               modifier = 'L';      /* 'll' == 'L'      long long == long double */
            }                       /* only for compatibility ; not portable     */
          INCOHERENT_TEST();
       }
     else
       {
          modifier = -1;    /* no modifier specified */
       }

     /* type */
     type = *SRCTXT;
     if ( strchr("diouxXfegEGcspn",type) == NULL )
          INCOHERENT();    /* unknown type */
     SRCTXT++;

     /* rewrite format-string */
     format_string[0] = '%';
     format_ptr = &(format_string[1]);

     if ( flag_plus  != 0 )    {   *format_ptr = '+';    format_ptr++;   }
     if ( flag_minus != 0 )    {   *format_ptr = '-';    format_ptr++;   }
     if ( flag_space != 0 )    {   *format_ptr = ' ';    format_ptr++;   }
     if ( flag_sharp != 0 )    {   *format_ptr = '#';    format_ptr++;   }
     if ( flag_zero  != 0 )    {   *format_ptr = '0';    format_ptr++;   }    /* '0' *must* be the last one */

     if ( width != -1 )
       {
          sprintf( format_ptr, "%i", width );   /* itoa() may be better but not ANSI nor POSIX */
          format_ptr += strlen( format_ptr );
       }

     if ( prec != -1 )
       {
          *format_ptr = '.';
          format_ptr++;
          sprintf( format_ptr, "%i", prec );
          format_ptr += strlen( format_ptr );
       }

     if ( modifier != -1 )
       {
          *format_ptr = modifier;
          format_ptr++;
       }

     *format_ptr = type;
     format_ptr++;
     *format_ptr = 0;

     /* vague approximation of minimal length if width or prec are specified */
     approx_width = width + prec;
     if ( approx_width < 0 )    /* because  width == -1   and/or   prec == -1 */
          approx_width = 0;

     switch ( type )
       {
          /* int */
          case 'd':
          case 'i':
          case 'o':
          case 'u':
          case 'x':
          case 'X':   switch ( modifier )
                        {
                           case -1 :   return print_it( s, approx_width, format_string, va_arg(s->vargs,int) );
                           case 'l':   return print_it( s, approx_width, format_string, va_arg(s->vargs,long int) );
                           case 'h':   return print_it( s, approx_width, format_string, va_arg(s->vargs, /*short*/ int) );
                           default :   INCOHERENT();                             /* 'int' instead of 'short int' because  */
                        }                                                        /* of default promotion is 'int'         */

          /* char */
          case 'c':   if ( modifier != -1 )
                           INCOHERENT();
                      return print_it(s,approx_width,format_string,va_arg(s->vargs,int));
                      /* note: because of default promotion 'int' is used instead of 'char' */

          /* math */
          case 'e':
          case 'f':
          case 'g':
          case 'E':
          case 'G':   switch ( modifier )
                        {
                           case -1 :   /* because of default promotion, no modifier means 'l' */
                           case 'l':   return print_it( s, approx_width, format_string, va_arg(s->vargs,double) );
                           case 'L':   return print_it( s, approx_width, format_string, va_arg(s->vargs,long double) );
                           default :   INCOHERENT();
                        }

#ifdef __DOS_16BIT__
          /* string */
          case 's':   switch ( modifier )
                        {
                           case -1 :   return type_s( s, width, prec, format_string, (const char far*)va_arg(s->vargs,const char*), modifier );
                           case 'N':   return type_s( s, width, prec, format_string, (const char far*)va_arg(s->vargs,const char near*), modifier );
                           case 'F':   return type_s( s, width, prec, format_string, (const char far*)va_arg(s->vargs,const char far*), modifier );
                           default :   INCOHERENT();
                        }

          /* pointer */
          case 'p':   switch ( modifier )
                        {
                           case -1 :   return print_it( s, approx_width, format_string, va_arg(s->vargs,void*) );
                           case 'N':   return print_it( s, approx_width, format_string, va_arg(s->vargs,void near*) );
                           case 'F':   return print_it( s, approx_width, format_string, va_arg(s->vargs,void far*) );
                           default :   INCOHERENT();
                        }

          /* store */
          case 'n':   {   
                         int far * p;

                         switch ( modifier )
                           {
                              case -1 :   p = (int far*)va_arg( s->vargs, int* );
                                          break;
                              case 'N':   p = (int far*)va_arg( s->vargs, int near* );
                                          break;
                              case 'F':   p = (int far*)va_arg( s->vargs, int far* );
                                          break;
                              default :   INCOHERENT();
                           }

                         if ( p != NULL )
                           {
                              *p = s->pseudo_len;
                              return 0;
                           }
                         return EOF;
                      }

#else   /* end of ms-dos/16-bit section */
          /* string */
          case 's':   return type_s( s, width, prec, format_string, va_arg(s->vargs,const char*) );

          /* pointer */
          case 'p':   if ( modifier == -1 )
                           return print_it( s, approx_width, format_string, va_arg(s->vargs,void *) );
                      INCOHERENT();

          /* store */
          case 'n':   if ( modifier == -1 )
                        {
                           int * p;
                           p = va_arg( s->vargs, int * );
                           if ( p != NULL )
                             {
                                *p = s->pseudo_len;
                                return 0;
                             }
                           return EOF;
                        }
                      INCOHERENT();

#endif
       }  /* switch */

     INCOHERENT();  /* unknown type */

#undef INCOHERENT
#undef INCOHERENT_TEST
#undef SRCTXT
#undef DESTTXT
}

/*################################ core ###################################*/
/*
 *  flavour: 'p' = (v)printf
 *           's' = (v)sprintf
 *           'f' = (v)fprintf
 *           'a' = (v)as(n)printf
 *
 *  Return value: number of *virtualy* written characters
 *                EOF = error
 */
static
int
core( xprintf_struct * s )
{
     size_t len, save_len;
     char * dummy_base;

     /* basic checks */
     if ( (int)(s->maxlen) <= 0 )       /* 'int' to check against some convertion */
          return EOF;                   /* error for example if value is (int)-10 */
     s->maxlen--;      /* because initial maxlen counts final 0 */
     /* note: now 'maxlen' _can_ be zero */

     if ( s->src_string == NULL )
          s->src_string = "(null)";

     /* struct init and memory allocation */
     s->buffer_base = NULL;
     s->buffer_len = 0;
     s->real_len = 0;
     s->pseudo_len = 0;
     if ( realloc_buff(s,0) == EOF )
          return EOF;
     s->dest_string = s->buffer_base;

     /* process source string */
     for (;;)
       {
          /* up to end of source string */
          if ( *(s->src_string) == 0 )
            {
               *(s->dest_string) = 0;              /* final 0 */
               len = s->real_len + 1;
               break;
            }

          if ( dispatch(s) == EOF )
               goto free_EOF;

          /* up to end of dest string */
          if ( s->real_len >= s->maxlen )
            {
               (s->buffer_base)[s->maxlen] = 0;    /* final 0 */
               len = s->maxlen + 1;
               break;
            }
       }

     /* for (v)asnprintf */
     dummy_base = s->buffer_base;
     save_len = 0;                     /* just to avoid a compiler warning */

     /*---*/
     switch ( s->flavour )
       {
          /* (v)snprintf() */
          case 's':   memcpy( s->sprintf_string, s->buffer_base, len );
                      break;

          /* (v)nprintf() */
          case 'p':   if ( puts(s->buffer_base) == EOF )
                           goto free_EOF;
                      break;

          /* (v)fnprintf() */
          case 'f' :  if ( fwrite(s->buffer_base,1,len-1,s->fprintf_file) != len-1 )      /* -1 because we don't write the final zero */
                           goto free_EOF;
                      break;

          /* (v)as(n)printf() */
          default  :  dummy_base = (s->buffer_base) + (s->real_len);
                      save_len = s->real_len;
       }

     /*
      * process the remaining of source string to compute 'pseudo_len'. We
      * overwrite again and again, starting at 'dummy_base' because we don't
      * need the text, only char count.
      */
     while( *(s->src_string) != 0 )     /* up to end of source string */
       {
          s->real_len = 0;
          s->dest_string = dummy_base;
          if ( dispatch(s) == EOF )
               goto free_EOF;
       }

     if ( s->flavour == 'a' )      /* (v)as(n)printf    reduce buffer size */
       {
          s->buffer_base = (char *)realloc( (void *)(s->buffer_base), save_len+1 );
          if ( s->buffer_base == NULL )
               return EOF;     /* should rarely happen because we shrink the buffer */
          return s->pseudo_len;
       }

     free( s->buffer_base );
     return s->pseudo_len;

free_EOF:
     if ( s->buffer_base != NULL )
          free( s->buffer_base );
     return EOF;
}

/*############################## _nprintf #################################*/
int
_nprintf( int          maxlen,
          const char * format_string,
          ...
        )
{
     xprintf_struct s;
     va_list        vargs;
     int            retval;

     va_start( vargs, format_string );

     s.src_string = format_string;
     s.maxlen = (size_t)maxlen;
     s.vargs = vargs;
     s.flavour = 'p';

     retval = core( &s );
     va_end( vargs );
     return retval;
}

/*############################# _vnprintf #################################*/
int
_vnprintf( int          maxlen,
           const char * format_string,
           va_list      vargs
         )
{
     xprintf_struct s;

     s.src_string = format_string;
     s.maxlen = (size_t)maxlen;
     s.vargs = vargs;
     s.flavour = 'p';

     return core( &s );
}

/*############################## _snprintf ################################*/
/*
int
_snprintf( char *       dest_string,
           int          maxlen,
           const char * format_string,
           ...
         )
{
     xprintf_struct s;
     va_list        vargs;
     int            retval;

     if ( dest_string == NULL )
          return EOF;

     va_start( vargs, format_string );

     s.src_string = format_string;
     s.maxlen = (size_t)maxlen;
     s.vargs = vargs;
     s.sprintf_string = dest_string;
     s.flavour = 's';

     retval = core( &s );
     va_end( vargs );
     if ( retval == EOF )
          if ( maxlen > 0 )
               dest_string[0] = 0;

     return retval;
}
*/
/*############################# _vsnprintf ################################*/
/*
int
_vsnprintf( char *       dest_string,
            int          maxlen,
            const char * format_string,
            va_list      vargs
          )
{
     xprintf_struct s;
     int            retval;

     if ( dest_string == NULL )
          return EOF;

     s.src_string = format_string;
     s.maxlen = (size_t)maxlen;
     s.vargs = vargs;
     s.sprintf_string = dest_string;
     s.flavour = 's';

     retval = core( &s );
     if ( retval == EOF )
          if ( maxlen > 0 )
               dest_string[0] = 0;

     return retval;
}
*/
/*############################## _fnprintf ################################*/
int
_fnprintf( FILE *       file,
           int          maxlen,
           const char * format_string,
           ...
         )
{
     xprintf_struct s;
     va_list        vargs;
     int            retval;

     va_start( vargs, format_string );

     s.src_string = format_string;
     s.maxlen = (size_t)maxlen;
     s.vargs = vargs;
     s.fprintf_file = file;
     s.flavour = 'f';

     retval = core( &s );
     va_end( vargs );
     return retval;
}

/*############################# _vfnprintf ################################*/
int
_vfnprintf( FILE *       file,
            int          maxlen,
            const char * format_string,
            va_list      vargs
          )
{
     xprintf_struct s;

     s.src_string = format_string;
     s.maxlen = (size_t)maxlen;
     s.vargs = vargs;
     s.fprintf_file = file;
     s.flavour = 'f';

     return core( &s );
}

/*############################## _asprintf ################################*/
/*
int
_asprintf( char **      ptr,
           const char * format_string
         )
{
     xprintf_struct s;
     va_list        vargs;
     int            retval;

     va_start( vargs, format_string );

     s.src_string = format_string;
     s.vargs = vargs;
     s.flavour = 'a';
     s.maxlen = (size_t)INT_MAX;

     retval = core( &s );
     va_end( vargs );
     if ( retval != EOF )
       {
          *ptr = NULL;
          return EOF;
       }

     *ptr = s.buffer_base;
     return retval;
}
*/
/*############################# _vasprintf ################################*/
int
_vasprintf( char **      ptr,
            const char * format_string,
            va_list      vargs
          )
{
     xprintf_struct s;
     int            retval;

     s.src_string = format_string;
     s.vargs = vargs;
     s.flavour = 'a';
     s.maxlen = (size_t)INT_MAX;

     retval = core( &s );
     if ( retval == EOF )
       {
          *ptr = NULL;
          return EOF;
       }

     *ptr = s.buffer_base;
     return retval;
}

/*############################# _asnprintf ################################*/
int
_asnprintf( char **      ptr,
            int          maxlen,
            const char * format_string,
            ...
          )
{
     xprintf_struct s;
     va_list        vargs;
     int            retval;

     va_start( vargs, format_string );

     s.src_string = format_string;
     s.vargs = vargs;
     s.flavour = 'a';
     s.maxlen = (size_t)maxlen;

     retval = core( &s );
     va_end( vargs );
     if ( retval != EOF )
       {
          *ptr = NULL;
          return EOF;
       }

     *ptr = s.buffer_base;
     return retval;
}

/*############################# _vasnprintf ###############################*/
int
_vasnprintf( char **      ptr,
             int          maxlen,
             const char * format_string,
             va_list      vargs
           )
{
     xprintf_struct s;
     int            retval;

     s.src_string = format_string;
     s.vargs = vargs;
     s.flavour = 'a';
     s.maxlen = (size_t)maxlen;

     retval = core( &s );
     if ( retval == EOF )
       {
          *ptr = NULL;
          return EOF;
       }

     *ptr = s.buffer_base;
     return retval;
}

/*############################# END OF FILE ###############################*/

