     sumEnergy/=SIZE;
     energy[(SIZE/SLICE)-1] = newEnergy;
     long diff = millis()-t;
-    if (newEnergy > 1.3 * sumEnergy && diff > .9*beat_length) {
+    if (newEnergy > 1.2 * sumEnergy && diff > .8*beat_length) {
       if (offBeat) {
-        float newBPM = 60000/(float)diff;
-        bpm = bpm*.9 + newBPM*.1;
+        t = millis();  
         beat_length = beat_length*.9 + diff*.1;
-        t = millis();  
+        if (beat_length < 375) beat_length = 375; //160bpm
+        if (beat_length > 600) beat_length = 600; //100bpm
+        
+        bpm = 60000/(float)beat_length;
       }
       offBeat = false;
     } 
     else {
       offBeat = true;
     }
-  }
 
+//Serial.println(bpm);
+          }
+  
+  
 }
 

  digitalWrite(spectrumReset,LOW);
  delay(5);
  // Reading the analyzer now will read the lowest frequency.
}

//just loop and read - need to add normalization

byte spectrum[9];


#define SIZE 512
#define SLICE 16

byte huge[SIZE];
long energy[SIZE/SLICE];
int p = 0;
volatile long t;
long start;
long last_beat;
long beat_length;
