/* Copyright (C) Warwick Allison, 1995 */
/* NetHack may be freely redistributed.  See license for details. */

/*
 * Generic Audio component.
 */

#include <regex.h>

#define AUDIOMAP_FILE "audiomap"

typedef struct audio_mapping_rec {
	struct re_pattern_buffer regex;
	char* filename;
	int volume;
	struct audio_mapping_rec* next;
} audio_mapping;

void
play_audio_for_string(str)
	const char* str;
{
	static audio_mapping* map=0;
	static int init=0;
	audio_mapping* cursor;

	if (!init) {
		FILE* f=fopen(AUDIOMAP_FILE, "r");
		init=1;

		if (!f) {
			raw_print(AUDIOMAP_FILE " not found");
		} else {
			char action[32];
			char text[256];
			char filename[256];
			int volume;
			int line=0;

			while (1) {
				int count=fscanf(f, " %[A-Za-z_]", action);

				if (count==EOF) break;

				if (count!=1) {
					sprintf(text, "%s:%d: syntax error\n", AUDIOMAP_FILE, line);
					raw_print(text);
					break;
				}

				line++;

				if (strcmp(action,"MESG")==0) {
					if (fscanf(f, " \"%[^\"]\" PLAY%*[\t ]\"%[^\"]\" %d",
						text, filename, &volume)==3)
					{
						const char* err;
						audio_mapping* new_map;

						if (access(filename, R_OK)==0) {
							new_map=(audio_mapping*)alloc(sizeof(audio_mapping));
							new_map->regex.translate=0;
							new_map->regex.fastmap=0;
							new_map->regex.buffer=0;
							new_map->regex.allocated=0;
							new_map->regex.regs_allocated=REGS_FIXED;
							new_map->filename=strdup(filename);
							new_map->volume=volume;
							new_map->next=map;

							err=re_compile_pattern(text, strlen(text), &new_map->regex);

							if (err) {
								sprintf(text, "%s:%d: %s\n", AUDIOMAP_FILE, line, err);
								raw_print(text);
								free(new_map->filename);
								free(new_map);
							} else {
								map=new_map;
							}
						} else {
							sprintf(text, "%s:%d: %s not readable.\n", AUDIOMAP_FILE, line, filename);
							raw_print(text);
						}
					} else {
						sprintf(text, "%s:%d: syntax error in action\n", AUDIOMAP_FILE, line);
						raw_print(text);
						break;
					}
				} else {
					sprintf(text, "%s:%d: syntax error in event\n", AUDIOMAP_FILE, line);
					raw_print(text);
					break;
				}
			}

			fclose(f);
		}
	}

	cursor=map;

	while (cursor) {
		if (re_search(&cursor->regex, str, strlen(str), 0, 9999, 0)>=0) {
			QAudio::play(cursor->filename, cursor->volume);
		}

		cursor=cursor->next;
	}
}
