#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <time.h>
#include <SDL2/SDL.h>

int can_pass(char* filename) {
    FILE* ptr = fopen(filename, "r");
    char c = fgetc(ptr);
    fclose(ptr);
    return (c != '0');
}

int main(int argc, char** argv) {
    assert(argc == 2);
    if(SDL_Init(SDL_INIT_AUDIO)) {fprintf(stderr, "cannot initialize audio");exit(1);}
    SDL_AudioSpec wavSpec;
    Uint32 wavLength;
    Uint8 *wavBuffer;
    SDL_LoadWAV(argv[1], &wavSpec, &wavBuffer, &wavLength);
    SDL_AudioDeviceID deviceId = SDL_OpenAudioDevice(NULL, 0, &wavSpec, NULL, 0);
    int success = SDL_QueueAudio(deviceId, wavBuffer, wavLength);
    SDL_PauseAudioDevice(deviceId, 0);
    clock_t start = clock();
    clock_t finish = clock();
    while((double)finish - (double)start < (wavLength)/44100.0*100000.0 && can_pass("sound/sem.txt")) {
        usleep(10000);
        finish = clock();
    }
    //usleep((int)((wavLength)/44100.0*100000.0));
    SDL_CloseAudioDevice(deviceId);
    SDL_FreeWAV(wavBuffer);
    SDL_Quit();
    return 0;
}
// yummy