/*****************************************************************************
 *
 *   File Name: swapbin.c
 *
 *   Purpose:   
 *
 *     Swaps the order of bytes in a binary file of short integers 
 *     (16 bit words)
 *
 *   Revision History:
 *
 *  V #  Date           Description
 *  ===  =============  ====================================
 *    0  6-17-93        original
 *    1  11-23-93       change fopen for VAX
 *
 ****************************************************************************/

/*___________________________________________________________________________
 |                                                                           |
 |                              Include Files                                |
 |___________________________________________________________________________|
*/

#include <stdio.h>
#include <stdlib.h>


/*___________________________________________________________________________
 |                                                                           |
 |                              Local Defines                                |
 |___________________________________________________________________________|
*/

#define BLKSIZE 1024

/*****************************************************************************
 *
 *   FUNCTION NAME: main (swapbin)
 *
 *   PURPOSE:
 *
 *     Swaps the order of bytes in a binary file of short integers 
 *     (16 bit words)
 *
 *   INPUTS:
 *
 *     fileNameIn - file name of the 16 bit binary file to be swapped.
 *        This file is not modified.  No wild card are allowd
 *
 *   OUTPUTS:
 *
 *     fileNameOut - file name of the byte swapped 16 bit binary file.
 *
 *   SYNTAX:   
 *
 *     swapbin fileNameIn fileNameOut
 *
 *
 *   KEYWORDS: binary, byteswap, dd, conversion, portablility
 *
 ****************************************************************************/

int main(int argc, char *argv[])
{
    int         i;
    char        *pcBuf, cTmp;
    FILE        *pfileIn, *pfileOut;
    size_t      numRead;

    switch (argc) {

      case 3:
        break;

      default:
        printf("Usage: swapbin inFile outFile\n");
        exit(1);
        break;
    }
    
#ifdef VAX
    pfileIn = fopen(argv[1], "rb", "mrs=2", "rfm=fix", "ctx=stm");
    pfileOut = fopen(argv[2], "wb", "mrs=2", "rfm=fix", "ctx=stm");

#else
    pfileIn = fopen(argv[1], "rb");
    pfileOut = fopen(argv[2], "wb");
#endif
    
    if (pfileIn == NULL  ||  pfileOut == NULL)
    {
        fprintf(stderr, "error: file specification\n");
        exit(1);
    }

    pcBuf = (char *)malloc(BLKSIZE * sizeof(char));

    while ((numRead = fread(pcBuf, sizeof(char), BLKSIZE, pfileIn))  >  0) {

        for (i = 0; i < numRead; i += 2) {

            cTmp = pcBuf[i];
            pcBuf[i] = pcBuf[i+1];
            pcBuf[i+1] = cTmp;
        }

        fwrite(pcBuf, sizeof(char), numRead, pfileOut);
    }

    free(pcBuf);
    fclose(pfileIn);
    fclose(pfileOut);
    return 0;
}