/* For free support for VSIDE, please visit www.vsdsp-forum.com */

// Starting point template for creating VSOS applications.
// This will create a <projectname>.APP file, which you can copy to 
// your VS1005 Developer Board and run it from there.

// If you rename your application to INIT.APP, then the kernel will
// load it automatically after booting.

#include <vo_stdio.h>
#include <volink.h>     // Linker directives like DLLENTRY
#include <apploader.h>  // RunLibraryFunction etc
#include <codecvorbis.h>
#include <libdecvorb.h>
#include <kernel.h>
#include <sysmemory.h>

struct Codec *cod = NULL;
void (*Delete)(struct Codec *cod) = NULL;

void fini(void);

DLLENTRY(Create)
struct Codec *Create(void) {
  g_others_p = AllocMemXY(4096, 2048);
  if (g_others_p) {
    g_dctlo_p = g_others_p + 2048;
    FreeMemY((void __mem_y *)g_others_p, 2048);
  }

  if (cod = CodVorbisCreate()) {
    u_int16 *p = &cod[1];
    p += 8;
    cod->Decode = CodVorbisDecode;
    // Remember original Delete() function address
    Delete = cod->Delete;
    // Grab Delete() so that we can do our own clean-up
    cod->Delete = (void *)fini;
  }
  return cod; 
}

void fini(void) {
  if (cod) {
    if (Delete) {
      Delete(cod);
      Delete = NULL;
    }
    cod = NULL;
  }

  if (g_others_p) {
    FreeMemY((void __mem_y *)g_dctlo_p, 2048);
    FreeMemX(g_others_p, 4096);
    g_others_p = g_dctlo_p = NULL;
  }
}
