#include <sys/stat.h>
#include <fcntl.h>
#include <linux/kd.h>
#include <unistd.h>

#include <stropts.h>
#include <sys/time.h>

#include <map>
#include <string>

std::map<char, int> freqs = {{'.', 1},
							 {'C', 261},
							 {'D', 277},
							 {'E', 329},
							 {'F', 349},
							 {'G', 392},
							 {'A', 440},
							 {'B', 493}};

int fd;
void beep(unsigned int, int);

int main(int argc, char* argv[]) {
	fd = open("/dev/console", O_WRONLY);

	std::string notes = argv[1];

	int sleep_time = atoi(argv[2]);

	for (char x : notes) {
		beep(freqs[x], sleep_time);
	}

	close(fd);
	return 0;
}

void msleep(int ms) {
	struct timespec ts;
	ts.tv_sec = 0;
	ts.tv_nsec = ms * 1000000;

	nanosleep(&ts, NULL);
}

void beep(unsigned int hz, int sleep_ms) {
	unsigned int CLOCK_TICK_RATE = 1190000;

	ioctl(fd, KIOCSOUND, CLOCK_TICK_RATE / hz);
	msleep(sleep_ms);
	ioctl(fd, KIOCSOUND, 0);
}

