/*
 *  longio.h       Copyright 1985  Landon M. Dyer
 *
 * Minor mods for Amiga, DBUG macros    19Apr86  edb
 */

#include <stdio.h>
#include "convert.h"

#ifdef DBUG
#include <local/dbug.h>
#else
#include "dbugstubs.h"
#endif

extern long filpos;
extern int printing;
extern char buf[];


/*
 * Get a longword or complain about premature EOF
 *
 */
getlong(fd, p_lw)
int fd;
long *p_lw;
{
	DBUG_ENTER("getlong");
    if (readlong(fd, p_lw) == EOF)
        panic("Premature EOF getting longword");
    DBUG_RETURN(OK);
}


/*
 * Read 68000 longword from file,
 * stuff it into '*p_lw' in the
 * host machine's longword format.
 *
 */
readlong(fd, p_lw)
int fd;
long *p_lw;
{
    char buf[4], *out;

	DBUG_ENTER("readlong");
	DBUG_3("io", "input filepos=%ld", lseek(fd, 0L, 1));
    out = (char *)p_lw;
    if (read(fd, buf, 4) != 4)          /* probably end of file */
        DBUG_RETURN(EOF);

    filpos += 4;
#if MACHINE == MSDOS || MACHINE == VAXVMS
    /*
     * 8086/8088 conversion
     * hh hl lh ll ==> ll lh hl hh
     */
    out[0] = buf[3];
    out[1] = buf[2];
    out[2] = buf[1];
    out[3] = buf[0];
#endif

#if MACHINE == Amiga
    out[0] = buf[0];
    out[1] = buf[1];
    out[2] = buf[2];
    out[3] = buf[3];
#endif
	DBUG_4("io","got 0x%lx, ret=0x%lx", *(long *)buf, *(long *)out);
	DBUG_RETURN(0);
}


/*
 * Write word to file,
 * in 68000 format.
 */
writeword(fd, w)
int fd;
unsigned int w;
{
    char buf[2], *out;

	DBUG_ENTER("writeword");

    out = (char *)&w;
#if MACHINE == MSDOS || MACHINE == VAXVMS
    buf[0] = out[1];
    buf[1] = out[0];
#endif

#if MACHINE == Amiga
    buf[0] = out[0];
    buf[1] = out[1];
#endif
	DBUG_3("io", "out filepos=0x%lx", lseek(fd, 0L, 1));
	DBUG_4("io", "got 0x%x, writing 0x%x", w, *(unsigned short *) out);
    if (write(fd, buf, 2) != 2)
        panic("Write error (word)");

	DBUG_RETURN(0);
}


/*
 * Write longword to file, in
 * 68000 format.
 */
writelong(fd, lw)
int fd;
long lw;
{
    char buf[4], *out;

	DBUG_ENTER("writelong");

    out = (char *)&lw;
#if MACHINE == MSDOS || MACHINE == VAXVMS
    buf[0] = out[3];
    buf[1] = out[2];
    buf[2] = out[1];
    buf[3] = out[0];
#endif

#if MACHINE == Amiga
    buf[0] = out[0];
    buf[1] = out[1];
    buf[2] = out[2];
    buf[3] = out[3];
#endif

	DBUG_3("io", "out filepos=0x%lx", lseek(fd, 0L, 1));
	DBUG_4("io", "got 0x%lx, writing 0x%lx", lw, *(long *) out);
    if (write(fd, buf, 4) != 4)
        panic("Write error (longword)");

	DBUG_RETURN(0);
}

