/*
 * envgen.c - Envelope generator code 
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "envgen.h"

int envgen_init(envelope * env, unsigned long atime, long avalue,
                                unsigned long dtime, long dvalue,
                                unsigned long stime, long svalue,
                                unsigned long rtime, long rvalue) {

  env->stage = ENV_OFF;
  env->evpos = 0;
  env->curvalue = 0;

  env->atime = atime;
  env->avalue = avalue;
  env->dtime = dtime;
  env->dvalue = dvalue;
  env->stime = stime;
  env->svalue = svalue;
  env->rtime = rtime;
  env->rvalue = rvalue;

  return 0;
}


int envgen_start(envelope * env) {
  env->stage = ENV_ATTACK;
  env->evpos = 0;
  env->curvalue = 0;

  return 0;
}

int envgen_release(envelope * env) {
  env->stage = ENV_RELEASE;
  env->evpos = 0;

  return 0;
}

int envgen_generate(long * value) {
  if (env->stage != ENV_OFF) {
    *value = env->curvalue; 
   
    env->evpos++;
    if (env->evpos > env->stages[env->stage].time) {
      env->stage++;
      if (env->stage == ENV_FINISH)
        env->stage = ENV_OFF;

    }  
  }
  
  return env->stage;
}


