#include <FastLED.h>
 
#define TIMING 0

#define LED_PIN     3
#define NUM_LEDS    1630
#define LED_TYPE    WS2812
#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];
const uint8_t led_count[] = {160, 145, 142, 135, 125, 118, 110, 102, 95, 86, 78, 70, 62, 53, 45, 37, 29, 21, 12, 4, 1};

#define NUM_RINGS (sizeof(led_count) / sizeof(led_count[0]))
#define FIRE_WIDTH 64
#define FIRE_HEIGHT NUM_RINGS
static uint8_t heat[FIRE_WIDTH][FIRE_HEIGHT];
CRGBPalette256 currentPalette;

void setup() {
  Serial.begin(115200);
  FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  uint8_t i = 0;
  do {
    currentPalette[i] = HeatColor(i);
  } while (++i);
}


void loop() {
	unsigned long t1 = micros();
  Fire2012(random8() / 2 + 128);
	unsigned long t2 = micros();

  CRGB *led = leds;
  uint8_t ring = 0;
  // map the modified Fire2012() onto the rings
  do {
    uint8_t count = led_count[ring];
    uint16_t td = FIRE_WIDTH * 255 / count;
    uint16_t t = 0;
    for (uint8_t i = 0; i < count ; i++) {
      uint8_t h = heat[t >> 8][FIRE_HEIGHT - 1 - ring];
      *led++ = currentPalette[h];
      t += td;
    }
  } while (++ring < NUM_RINGS);
	unsigned long t3 = micros();

  FastLED.show();

  if (TIMING) {
    static unsigned long t2_sum, t3_sum;
    t2_sum += t2 - t1;
    t3_sum += t3 - t2;
    static byte frame;
    if (!(++frame % 64)) {
      Serial.print(F("fire "));
      Serial.print(t2_sum / 64);
      Serial.print(F("us\tmap "));
      Serial.print(t3_sum / 64);
      Serial.print(F(" us\t"));
      Serial.println(FastLED.getFPS());
      t2_sum = t3_sum = 0;
    }
  }
}

void Fire2012(uint8_t activity) {
  for (uint8_t h = 0; h < FIRE_WIDTH; h++) {
    // Step 1.  Cool down every cell a little
    for( uint8_t i = 1; i < FIRE_HEIGHT - 1; i++) {
      heat[h][i] = qsub8( heat[h][i],  random8(32));
    }

    // Step 2.  Heat from each cell drifts 'up' and diffuses a little
    for( uint8_t k = FIRE_HEIGHT - 1; k >= 1; k--) {
      uint8_t hleft = (h + FIRE_WIDTH - 1) % FIRE_WIDTH;
      uint8_t hright = (h+1) % FIRE_WIDTH;
      heat[h][k] = (heat[h][k]
                  + heat[hleft][k - 1]
                  + heat[h][k - 1]
                  + heat[hright][k - 1] ) / 4;
    }

    if( random8() < activity ) {
      heat[h][0] = qadd8( heat[h][0], random8(64));
    } else {
      heat[h][0] = qsub8( heat[h][0], random8(64));
    }

  }
}