/*
    gdr_swab.c 

    A simple program to swap bytes in a Geosat GDR, converting it from
    big-endian byte order to little-endian byte order (PC, VAX).
    Note that a simple pairwise byte-swapping (as in the Unix "swab"
    utility) will not accomplish the correct swap of four-byte integers.

    Usage: gdr_swab  original.gdr  swapped.gdr

    Walter H.F. Smith, 9 August 1995
*/

#include <stdio.h>

/*
    The GDR record struct assumes long int is a four byte int on your compiler;
    if you have 8 byte ints then delete the word "long" or use a switch
    on your compiler to force long to 4 bytes.
*/

struct GDR {
    long  int ilong[5];      /* secs, musecs, lat, lon, orbit are 4-byte */
    short int ishort[29];    /* remaining fields are 2-byte */
} gdr;

main(argc, argv)
int    argc;
char **argv;
{
    int i;
    FILE *in, *out;
    void swab4(), swab2();

    /* Three arguments required */

    if (argc != 3) {
      fprintf (stderr,"usage: gdr_swab  original.gdr  swapped.gdr\n");
      exit(-1);
    }

    if ((in=fopen(argv[1],"rb")) == NULL) {
       fprintf(stderr, "Can't open input file %s\n",argv[1]);
       exit (-1);
    }

    if ((out=fopen(argv[2],"wb")) == NULL) {
       fprintf(stderr, "Can't open output file %s\n",argv[2]);
       exit (-1);
    }

    while ( (fread((char *)&gdr, 78, 1, in)) == 1) {
        for (i = 0; i < 5; i++) {
            swab4((unsigned char *)&gdr.ilong[i]);
        }
        for (i = 0; i < 29; i++) {
            swab2((unsigned char *)&gdr.ishort[i]);
        }
        fwrite((char *)&gdr, 78, 1, out);
    }
    exit(0);
}

void swab4(b4)
unsigned char b4[];
{
    /* Swap four bytes from 0123 to 3210 */

    unsigned char temp;

    temp = b4[0];
    b4[0] = b4[3];
    b4[3] = temp;

    temp = b4[1];
    b4[1] = b4[2];
    b4[2] = temp;
    return;
}

void swab2(b2)
unsigned char b2[];
{
    /* Swap two bytes  */

    unsigned char temp;

    temp = b2[0];
    b2[0] = b2[1];
    b2[1] = temp;
    return;
}
