inlets = 1;
outlets = 2;
autowatch = 1;

twopi = 8. * Math.atan(1);
len = jsarguments[1];
if(len < 0 ){
  len = 8192;
} 

function blackman_harris()
{
  cf0 = .35878;
  cf1 = .48829;
  cf2 = .14128;
  cf3 = 0.01168;
  arg = twopi / len;
  j = 0;
  for(i = 0; i < twopi; i += arg){
    val = cf0 - cf1*Math.cos(i) + cf2*Math.cos(2*i) - cf3*Math.cos(3*i);
    outlet(1,val);
    outlet(0,j);
    j++;
  }
}


function blackman()
{
  cf0 = .42;
  cf1 = .5;
  cf2 = .08;
  cf3 = 0.0;
  arg = twopi / len;
  j = 0;
  for(i = 0; i < twopi; i += arg){
    val = cf0 - cf1*Math.cos(i) + cf2*Math.cos(2*i) - cf3*Math.cos(3*i);
    outlet(1,val);
    outlet(0,j);
    j++;
  }
}

function gaussian()
{
  arg = 12 / len;
  xarg = 1.0;
  j = 0;
  for(i = -6.0; i < 0; i += arg ){
    val = xarg * Math.pow(2.71828, -(i*i)/2.0);
    outlet(1,val);
    outlet(0,j);
    ++j;
  }
  for(i = arg; i < 6; i += arg ){
    val = xarg * Math.pow(2.71828, -(i*i)/2.0);
    outlet(1,val);
    outlet(0,j);
    ++j;
  }

}

function rcos()
{

  for(i = 0; i < len; i++){
    val = 0.5 + -0.5 * Math.cos( twopi * i / len );
    outlet(1,val);
    outlet(0,i);
  }
  
}

function triangle()
{
  len2 = len / 2;
  for(i = 0; i < len2; i++ ){
    val = i / len2;
    outlet(1,val);
    outlet(0,i);
  }
  for(i = len2; i < len; i++){
      val = (len - i) / len2;
      outlet(1,val);
      outlet(0,i);
    }
}

function pluckenv()
{
  atk = 20;
  for(i = 0; i < atk; i++)
    {
      val = i / atk;
      outlet(1,val);
      outlet(0,i);
    }
  for(i = 0; i < len - atk; i++){
    val = 1.0 - (i / (len - atk) );
    outlet(1,val);
    outlet(0,i+atk);
  }
}

function pluckenv2(atk)
{
  for(i = 0; i < atk; i++)
    {
      val = i / atk;
      outlet(1,val);
      outlet(0,i);
    }
  for(i = 0; i < len - atk; i++){
    val = 1.0 - (i / (len - atk) );
    outlet(1,val);
    outlet(0,i+atk);
  }
}

function adsr(atk,dk,sustval,rls)
{
  //  atk = 100;
  //  dk = 200;
  //  rls = 4000;
  //  sustval = 0.7;
  if(atk+dk+rls >= len){
    error("adsr: sum of arguments is greater then length of envelope");
    return;
  }
  sust = len - (atk+dk+rls);
  for(i = 0; i < atk; i++){
    val = i / atk;
    outlet(1,val);
    outlet(0,i);
  }
  loser = 1.0 - sustval;
  for(i = 0; i < dk; i++){
    val = 1.0 - (loser * i/dk);
    outlet(1,val);
    outlet(0,i+atk);
  }
  offset = atk+dk;
  for(i = 0; i < sust; i++){
    outlet(1,sustval);
    outlet(0,i+offset);
  }
  offset = atk+dk+sust;
  for(i = 0; i < rls; i++){
    val = sustval - (sustval * i/rls);
    outlet(1,val);
    outlet(0,i+offset);
  }
}
