/*
 * Copyrighted as an unpublished work.
 * (c) Copyright 1991 Brian Smith
 * All rights reserved.
 *
 * Read the LICENSE file for details on distribution and use.
 *
 */

#include <stdio.h>
#include <sys/fcntl.h>
#include <sys/unistd.h>

main(argc, argv)
int argc;
char **argv;
{
    int fd, new_fd, rc, max_wave;
    unsigned char tmp_byte;
    int tmp_int;
    int i;
    double augmentation;

    if (argc != 3)
    {
        printf("usage: %s <oldfile> <newfile>\n", argv[0]);
        exit(-1);
    }

    fd = open(argv[1], O_RDONLY);
    if (fd == -1)
    {
        perror("opening oldfile");
        exit(-1);
    }

    new_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if (new_fd == -1)
    {
        perror("opening newfile");
        exit(-1);
    }

    printf("normalizing from input file..");
    fflush(stdout);
    i = 0;
    max_wave = 0;
    while(1)
    {
        i++ ; i &= 0x7FFF;
        if (!i)
            write(1, ".", 1);

        rc = read(fd, &tmp_byte, 1);
        if (rc == 0)
            break;
        tmp_int = tmp_byte - 128;
        if (abs(tmp_int) > max_wave)
            max_wave = abs(tmp_int);
    }
    write(1, "\n", 1);

    augmentation = (double)0x80 / (double)max_wave;
    printf("max_wave\t%d\n", max_wave);
    printf("augmentation\t%f\n", augmentation);


    /* write out new file */
    lseek(fd, 0, SEEK_SET);
    while (1)
    {
        rc = read(fd, &tmp_byte, 1);
        if (rc == 0)
            break;

        tmp_int = tmp_byte - 128;
        tmp_int *= augmentation;
        tmp_int += 128;

        tmp_byte = tmp_int;

        rc = write(new_fd, &tmp_byte, 1);
        if (rc != 1)
        {
            perror("writing to new_fd");
            exit(-1);
        }
    }
        

    return(0);
}
