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

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


/*
 * Get a longword or complain about premature EOF
 *
 */
getlong(fd, p_lw)
int fd;
long *p_lw;
{
    if (readlong(fd, p_lw) == EOF)
	panic("Premature EOF getting longword");
    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;
    int i;

    out = (char *)p_lw;
    if (read(fd, buf, 4) != 4)		/* probably end of file */
	return EOF;

    filpos += 4;
    /*
     * 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];
}


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

    out = (char *)&w;
    buf[0] = out[1];
    buf[1] = out[0];
    if (write(fd, buf, 2) != 2)
	panic("Write error (word)");
}


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

    out = (char *)&lw;
    buf[0] = out[3];
    buf[1] = out[2];
    buf[2] = out[1];
    buf[3] = out[0];

    if (write(fd, buf, 4) != 4)
	panic("Write error (longword)");
}


/*
 * Read-and-write (copy from one
 * file to another).
 */
randw(ifd, count, ofd)
int ifd;
long count;
int ofd;
{
if(debug)printf("~ randw(%d, %ld, %d)\n", ifd, count, ofd);
    for (; count > BUFFERSIZE; count -= BUFFERSIZE)
	randw(ifd, BUFFERSIZE, ofd);
    if (read(ifd, buf, (int)count) != (int)count)
	panic("Read error.");
    if (write(ofd, buf, (int)count) != (int)count)
	panic("Write error.");
}


/*
 * Write single byte to file
 */
emit(c, fd)
int c;
int fd;
{
    char cc;

    cc = (char)c;
    if (write(fd, &cc, 1) != 1)
	panic("Emit write error.");
}
