/* poke - write a value directly into memory
 *
 * Copyright (C) 1994 by Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de)
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted, provided
 * that the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation.  This software is provided "as is" without express or
 * implied warranty.
 *
 * V1.0: 27/Nov/94 first version
 */
#define THIS_PROGRAM    "poke"
#define THIS_VERSION    "1.0"

#include <exec/types.h>
#include <exec/libraries.h>
#include <dos/dos.h>
#include <dos/rdargs.h>
#include <stdlib.h>
#include <string.h>

#define SysBase_DECLARED
#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/utility.h>

extern struct Library *SysBase;

static const char amiga_version[] = "\0$VER: " THIS_PROGRAM " " THIS_VERSION " (" __COMMODORE_DATE__ ")";

const char Template[] = "ADDR/A,VALUE/A,B=BYTE/S,S=SHORT=W=WORD/S,L=LONG/S";
__aligned struct {
    STRPTR  addr;
    STRPTR  value;
    LONG    isbyte, isword, islong;
} Args;

void
_main()
{
    struct RDArgs *rdargs;
    APTR addr;
    ULONG val;
    LONG rc = RETURN_OK;

    if( SysBase->lib_Version < 37 ) {
        #define MESSAGE "requires AmigaOS 2.04 or higher\n"
        Write(Output(), MESSAGE, sizeof(MESSAGE)-1);
        _exit(RETURN_FAIL);
        #undef MESSAGE
    }

    if( rdargs = ReadArgs(Template, (LONG *)&Args, NULL) ) {
        int used = 0;
        if( Args.isbyte )   used++;
        if( Args.isword )   used++;
        if( Args.islong )   used++;
        if( used > 1 ) {
            PutStr("only one type specifier allowed\n");
            rc = RETURN_ERROR;
        }
        else {
            char *endp1, *endp2;
            addr = (APTR)strtoul(Args.addr, &endp1, 0);
            val  = strtoul(Args.value, &endp2, 0);
            if( *endp1 != '\0' || *endp2 != '\0' ) {
                PutStr("invalid address or value\n");
                rc = RETURN_ERROR;
            }
            else
            if( Args.islong )
                *(ULONG *)addr = val;
            else
            if( Args.isword )
                *(USHORT *)addr = (SHORT)val;
            else
                *(UBYTE *)addr = (BYTE)val;
        }
        FreeArgs(rdargs);
    }
    else {
        PutStr("required argument missing\n");
        rc = RETURN_ERROR;
    }
    _exit((int)rc);
}

