#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>


#define BLOCK_SIZE 256

short inbuf[BLOCK_SIZE];
unsigned char outbuf[BLOCK_SIZE];

void usage(char *cmd) 
{
       fprintf(stderr, "%s <file name>\n", cmd);
}

/* 16 bit swapping */
short swap_linear (short pcm_val)
{ 
  struct lohibyte { unsigned char lb, hb;}; 
  union 
  { 
      struct lohibyte b;
      short i;
  } exchange;
  unsigned char c;
  
  exchange.i      = pcm_val;
  c               = exchange.b.hb;
  exchange.b.hb   = exchange.b.lb; 
  exchange.b.lb   = c;
  return (exchange.i);
}

/*
 **************************************************************************
 **************************************************************************
*/

int main(int argc, char **argv)
{
    short count;
    FILE *infid, *outfid;
    int fd;
    int cnt1, cnt2;
    char *devfn = "/dev/dsptask/g711_ulaw";

    if (argc != 3) {
        return 1; /* Exit, error code 1 */
    }
 
    fd = open(devfn, O_RDWR);
    if (fd < 0) {
        fprintf(stderr, "cannot open %s, error %d\n", devfn, fd);
        return 1;
    }
    printf("Opened device\n");

     
    if ((infid = fopen(argv[1],"rb")) == NULL){  
        fprintf(stderr,"Cannot open input file %s\n",argv[2]);
        return 1; /* Exit, error code 1 */
    }
    printf("Opened input file\n");
        
    if ((outfid = fopen(argv[2],"wb")) == NULL) {
        fprintf(stderr,"Cannot open output file %s\n",argv[3]);
        return 1; /* Exit, error code 1 */
    }
    printf("Opened output file\n");
        
    /* Read input file and process */

    do
    {
        short i;
        count = fread(&inbuf, sizeof(short), BLOCK_SIZE, infid);
        printf("Read %d shorts from input file\n", count);

            /* Write these data to the DSP */
        cnt1 = write(fd, inbuf, BLOCK_SIZE*sizeof(short));
        if (cnt1 < 0) {
            perror("write failed");
            return 1;
        }
        printf("Written %d shorts to device\n", cnt1);

        /* Read processed data from the DSP */
        cnt2 = read(fd, outbuf, BLOCK_SIZE*sizeof(unsigned char));
        if (cnt2 < 0) {
            perror("read failed");
            return 1;
        }
        printf("Read %d chars from device\n", cnt2);

        if (fwrite(&outbuf, sizeof(unsigned char), cnt2, outfid) != cnt2) {
        //if (fwrite(&outbuf, sizeof(unsigned short int), count, outfid) != count) {  
            fprintf(stderr,"Write Access Error, File=%s\n",argv[3]); 
            return 1;
        }
        printf("Written %d chars to output file\n", count);
    } while (feof(infid)==0);

    close(fd);
    fclose(infid); 
    fclose(outfid);
    printf("Closed files and device and exiting\n");

    return 0; /* Exit, no errors */
}

