/*****

      $Source: d:\gunther\source\grc/RCS/portio.c,v $
      $Author: gunther $
      $Date: 1996/01/02 23:17:24 $
      $Revision: 1.1 $

 *****/

#include "portio.h"
#include <string.h>

int byte_order = BYTEORDER_UP;
int dest_order = BYTEORDER_UP;


typedef union
{
    long number;
    char string[sizeof(long)];
} ByteOrderType;


int
byteorder()
{
    ByteOrderType bot;

    bot.number = 0x12345678;
    return bot.string[0] == 0x78 ? BYTEORDER_UP : BYTEORDER_DOWN;
}


void 
init_portio(int argc, char **argv)
{
    int i;

    byte_order = byteorder();

    for(i = 1; i < argc; i++)
    {
        if(!strcmp(argv[i], "-target"))
        {
            i++;

            if(!strcmp(argv[i], "i386"))
                dest_order = BYTEORDER_UP;

            else if(!strcmp(argv[i], "alpha"))
                dest_order = BYTEORDER_UP;     /* I don't know, please fix it */

            else if(!strcmp(argv[i], "ppc"))
                dest_order = BYTEORDER_UP;     /* I don't know, please fix it */

            else if(!strcmp(argv[i], "r3000"))
                dest_order = BYTEORDER_UP;     /* I don't know, please fix it */

            else if(!strcmp(argv[i], "r4000"))
                dest_order = BYTEORDER_UP;     /* I don't know, please fix it */
        }
    }
}


void
reverse_byteorder(void *dest, void *src, int size)
{
    register int i;
    char *d = (char *) dest;
    char *s = (char *) src;

    for(i = 0; i < size; i++)
        d[i] = s[size - i - 1];
}


int
pio_write(FILE *f, void *buf, int bufsize)
{
    char bo_buf[8];

    if(bufsize > 8) 
        return 0;

    if(byte_order != dest_order)
        reverse_byteorder(bo_buf, buf, bufsize);

    else
        memcpy(bo_buf, buf, bufsize);

    return fwrite(bo_buf, 1, bufsize, f);
}


int
pio_read(FILE *f, void *buf, int bufsize)
{
    int retcode;
    char bo_buf[8];

    if(bufsize > 8)
        return 0;

    if((retcode = fread(bo_buf, 1, bufsize, f)) != bufsize)
    {
        fprintf(stderr, "Error reading %d byte[s] from external file.", bufsize);
        return retcode;
    }

    if(byte_order != dest_order)
        reverse_byteorder(buf, bo_buf, bufsize);

    else
        memcpy((char *) buf, bo_buf, bufsize);

    return retcode;
}

