/* 
 * amiga_fprintf.c - Amiga style vfprint(), vprintf(), fprintf(), printf(),
 *                   vsprintf(), sprintf()

    This file is part of libRILc, a standard C library for GCC on Amiga OS.
    Copyright © 1997, 1998  Rask Ingemann Lambertsen

    This 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 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 library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, if you link this library with files compiled
    with a GNU compiler to produce an executable, this does not cause the
    resulting executable to be covered by the GNU General Public License.
    This exception does not however invalidate any other reasons why the
    executable file might be covered by the GNU General Public License.
*/

/*
 * WARNING: Uses exec.library/RawDoFmt() style format strings, not ANSI stdio
 * ones. Thus no floating point and short int arguments by default.
 */

#define __PRINTF_STYLE AMIGA

#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <utility/tagitem.h>
#include <stdio.h>
#include <stdarg.h>

#ifdef __PPC__
#include <ppcproto/dos.h>
#include <powerup/ppclib/tasks.h>
#include <powerup/gcclib/powerup_protos.h>
#else
#include <proto/exec.h>
#include <proto/dos.h>
#endif

#include <stdlib.h>
#include "internal/systemcalls.h"
#include "internal/signalcheck.h"

/* Data structure for PutChProc. */
struct PutChData
{
    FILE   *stream;
    ULONG   numwritten;
    TEXT    lastchar;
};

/* PutChProc funtion for RawDoFmt(). Because RawDoFmt() calls this with an
   extra '\0' at the end, this function uses one character write-behind.
 */

#ifdef __PPC__
STATIC VOID PutCh (TEXT ch __asm__("r3"),
                struct PutChData *pcd __asm__("r4"))
#else
STATIC VOID PutCh (TEXT ch __asm__("d0"),
                struct PutChData *pcd __asm__("a3"))
#endif
{
    if (pcd->numwritten > 0)
    {
        putc (pcd->lastchar, pcd->stream);
    }
    pcd->lastchar = ch;
    pcd->numwritten ++;
}

struct stuffCharData { char *buf; };

#ifdef __PPC__
STATIC VOID stuffChar (TEXT ch __asm__("r3"), struct stuffCharData *scd __asm__("r4"))
#else
STATIC VOID stuffChar (TEXT ch __asm__("d0"), struct stuffCharData *scd __asm__("a3"))
#endif
{
    *(scd->buf++) = ch;
}

/* This function returns the number of bytes of data a RawDoFmt() format
   string requires, and optionally converts a varargs list to a word/long
   array ready for formatting by RawDoFmt().
   If output is NULL, this function will just calculate the needed storage
   space for the output stream without converting the varargs. */

STATIC ULONG convertargs (const char *fmt, va_list vargs, APTR output)
{
    ULONG totallength = 0;

    for (; *fmt; fmt ++)
    {
        /* Search for argument specifiers. */
        if (*fmt == '%')
        {
            fmt ++;
            {
                /* Save fmt so we can back out if necessary. */
                const char *fmt0;
                BOOL longarg = FALSE, done = FALSE, error = FALSE;

                for (fmt0 = fmt; *fmt && !done; fmt ++)
                {
                    switch (*fmt)
                    {
                        case 'l':
                        longarg = TRUE;
                        break;

                        case 'd':
                        case 'x':
                        case 'c':
                        case 'u':
                        if (longarg)
                        {
                            if (output)
                                *((ULONG *) output)++ = va_arg (vargs, ULONG);
                            totallength += sizeof (ULONG);
                        }
                        else
                        {
                            if (output)
                                *((UWORD *) output)++ = va_arg (vargs, UWORD);
                            totallength += sizeof (UWORD);
                        }
                        done = TRUE;
                        break;

                        case 'b':
                        case 's':
                        if (output)
                            *((ULONG *) output)++ = va_arg (vargs, ULONG);
                        totallength += sizeof (ULONG);
                        done = TRUE;
                        break;

                        case '0':
                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                        case '6':
                        case '7':
                        case '8':
                        case '9':
                        case '-':
                        case '.':
                        break;

                        default:
                        done = TRUE;
                        error = TRUE;
                        break;
                    }
                }

                /* If something went wrong, back out. */
                if (error)
                    fmt = fmt0;
            }
        }
    }
    return (totallength);
}

#if 0 /* AARRGGHH!! PPCRawDoFmt() never calls the callback function. */
#error Old, obsolete, broken code enabled!
int vfprintf (FILE *stream, const char *fmt, va_list args)
{
    ULONG totallength;
    APTR  argstream = 0;
    struct PutChData pcd;

    outfh = stream->fh;
    numprinted = 0;

    /* Try to convert the varargs list into an argument array for RawDoFmt(). */

    /* Find the length (in an even number of bytes) of the argument stream. */
    totallength = convertargs (fmt, args, NULL);

    VFPrintf (outfh, "converting %ld byts of varargs...\n", &totallength);

    /* Allocate memory for argument stream. */
    if (totallength)
    {
      if (! ((argstream = AllocMem (totallength, MEMF_ANY))))
          return (-1);

      /* Convert varargs to array. */
      totallength = convertargs (fmt, args, argstream);

      VFPrintf (outfh, "Converted %ld byts of varargs.\n", &totallength);
    }

    /* Format it. */
    pcd.stream = stream;
    pcd.numwritten = 0;
    RawDoFmt (fmt, argstream, (VOID (*)()) PutCh, &pcd);
    if (pcd.numwritten != 0)
        pcd.numwritten --;

    VFPrintf (outfh, "Wrote %ld bytes to stream.\n", &numprinted);

    /* Clean up and return. */
    if (totallength)
        FreeMem (argstream, totallength);
    return (pcd.numwritten);
}

#else /* 0 */

int vfprintf (FILE *stream, const char *fmt, va_list args)
{
    ULONG totallength;
    APTR  argstream = 0;
    LONG numwritten;
    __syscall_handle sh;

    __check_signals ();

    /* Try to convert the varargs list into an argument array for RawDoFmt(). */

    /* Find the length (in an even number of bytes) of the argument stream. */
    totallength = convertargs (fmt, args, NULL);
    /* VPrintf ("Estimated conversion of %lu bytes.\n", &totallength); */

    /* Allocate memory for argument stream. */
    if (totallength)
    {
      if (! ((argstream = malloc (totallength))))
          return (-1);

      /* Convert varargs to array. */
      totallength = convertargs (fmt, args, argstream);
      /* VPrintf ("Converted %lu bytes.\n", &totallength); */
    }

    /* Format it. */
    sh = __syscall_start ();
    numwritten = VFPrintf (stream->fh, fmt, argstream);
    __syscall_end (sh);

    /* Clean up and return. */
    if (totallength)
        free (argstream);

    return (numwritten);
}

#endif /* !0 */

int printf (const char *fmt, ...)
{
    int written;
    va_list vargs;

    va_start (vargs, fmt);

    written = vfprintf (stdout, fmt, vargs);

    va_end (vargs);

    return (written);
}

int fprintf (FILE *output, const char *fmt, ...)
{
    int written;
    va_list vargs;

    va_start (vargs, fmt);

    written = vfprintf (output, fmt, vargs);

    va_end (vargs);

    return (written);
}

int vprintf (const char *fmt, va_list vargs)
{
        return (vfprintf (stdout, fmt, vargs));
}

int vsprintf (char *buf, const char *fmt, va_list args)
{
    ULONG totallength;
    APTR  argstream = 0;
    __syscall_handle sh;

    __check_signals ();

    /* Try to convert the varargs list into an argument array for RawDoFmt(). */

    /* Find the length (in an even number of bytes) of the argument stream. */
    totallength = convertargs (fmt, args, NULL);

    /* Allocate memory for argument stream. */
    if (totallength)
    {
      if (! ((argstream = malloc (totallength))))
          return (-1);

      /* Convert varargs to array. */
      convertargs (fmt, args, argstream);
    }

    /* Format it. */
    sh = __syscall_start ();
#ifdef __PPC__
    PPCRawDoFmt (fmt, argstream, NULL, buf);
#else
    {
      struct stuffCharData scd;
      scd.buf = buf;
      RawDoFmt (fmt, argstream, (VOID (*)()) stuffChar, &scd);
    }
#endif
    __syscall_end (sh);

    /* Clean up an return. */
    if (totallength)
      free (argstream);
    return (strlen (buf));
}

int sprintf (char *buf, const char *fmt, ...)
{
    int written;
    va_list vargs;

    va_start (vargs, fmt);

    written = vsprintf (buf, fmt, vargs);

    va_end (vargs);

    return (written);
}
