/*
    Tucnak - VHF contest log
    Copyright (C) 2002-2006  Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif

#ifdef HAVE_SYS_KD_H
#include <sys/kd.h>
#endif 

#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif


#ifdef KIOCSOUND 

int main(int argc, char *argv[]){
    int ret, fd, freq, arg;
    int quiet = 0;

    if (argc > 1 && strcmp(argv[1], "-q") == 0) quiet = 1;

    fd=open("/dev/console", O_WRONLY|O_SYNC);
    if (fd<0) {
        if (!quiet) fprintf(stderr, "Can't open /dev/console, error %d %s\n", errno, strerror(errno));
        return 1;
    }

    if (argc > 1){
        freq = atoi(argv[1]);
        if (freq){ 
            arg=1193180/freq;
            if (!quiet) printf("%d\n", 1193180/arg); 
        }else 
            arg=0;
            
        ret=ioctl(fd, KIOCSOUND, arg);
        if (ret){
            close(fd);
            if (!quiet) fprintf(stderr, "Can't run IOCTL KIOCSOUND, error %d %s\n", errno, strerror(errno));
            return 1;
        }
        close(fd);
        return 0;
    }
    
    while(1){
        ret=read(0, &freq, sizeof(freq));
        if (ret!=sizeof(freq)){
            close(fd);
            if (ret>0 && !quiet) fprintf(stderr, "Can't read %d bytes from /dev/console (only %d), error %d %s\n", (int)sizeof(freq), ret, errno, strerror(errno));
            return 1;
        }
        if (freq==-1) break;
        if ((freq!=0 && freq<50) || freq>20000) continue;
        if (freq) 
            arg=1193180/freq;
        else 
            arg=0;
        
        ret=ioctl(fd, KIOCSOUND, arg);
        if (ret){
            close(fd);
            if (!quiet) fprintf(stderr, "Can't run IOCTL KIOCSOUND, error %d %s\n", errno, strerror(errno));
            return 1;
        }

    }
    close(fd);
    return 0;
}

#else

#ifdef WIN32
#include <windows.h>
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
    main(0, NULL);
}
#endif

int main(int argc, char *argv[]){
    fprintf(stderr, "ioctl(KIOCSOUND) not supported on this system\n");
    return 0;
}

#endif
