/* Simple ASCII demo for deadline
 * Thrown together in a couple of hours.
 * By the Introx team 2005 
 * */

#include "main.h"

FMUSIC_MODULE *tuneptr;

long lof(FILE *fptr){
  long old, new;
  fseek(fptr, 0, SEEK_CUR);
  old = ftell(fptr);
  fseek(fptr, 0, SEEK_END);
  new = ftell(fptr);
  fseek(fptr, 0, old);
  return new;
}

short initfmod(char *me)
{

    int audio_samplerate;
    int returncode;
    int sndinit_tries;
    
    FILE *fp;
    long modulesize;
    char *rawmodule;

    tuneptr = NULL;
    sndinit_tries = 1;
    returncode = 0;
    audio_samplerate = 44100;

    /* Initialize fmod */
    printw("Initialising fmod..");
    while (!FSOUND_Init(audio_samplerate, 24, 0)) {
        audio_samplerate = (44100 / ++sndinit_tries);
        printw("\nFailed! Trying a lower samplerate..");
        if (audio_samplerate <= 5512) {
            printf("\nERROR: ");
            switch (FSOUND_GetError()) {
            case FMOD_ERR_INIT:
                printw("init failed.\n");
                break;
            case FMOD_ERR_ALLOCATED:
                printw("device in use.\n");
                break;
            case FMOD_ERR_OUTPUT_FORMAT:
                printw
                    ("shitty card.\n");
                break;
            default:
                printw("Unknown error.\n");
                break;
            }
            return -1;
        }
    }
    printw("%dhz.\n", audio_samplerate);


    printw("Extracting tune..");
    fp = fopen(me, "r");
    if(!fp){
      printw("Nothing to extract from!\n");
      return -1;
    }
    modulesize = 30652;
    rawmodule = malloc(modulesize);
    fseek(fp, lof(fp)-modulesize, SEEK_SET);
    printw("%ldb ok.\n", fread(rawmodule, 1, modulesize, fp));
    
    printw("Initialising tune..");
    tuneptr = FMUSIC_LoadSongEx(rawmodule, 0, modulesize, FSOUND_LOADMEMORY, NULL, 0);
    if (tuneptr == NULL) {
        printw("failed! err %d.\n", FSOUND_GetError());
        return -1;
    }
    printw("Ok\n");
    free(rawmodule);

    FSOUND_DSP_SetActive(FSOUND_DSP_GetFFTUnit(), 1);

    return 0;
    
}

void kill_sound(void){
  FMUSIC_FreeSong(tuneptr);
  FSOUND_Close();
}


