// LOESS-LABS.NET
// Dylan Barry, 2026, GNU GPLv3
//
// A LOT of this code was done by ChatGPT,
// especially the optimization.

#define MOZZI_AUDIO_CHANNELS MOZZI_STEREO
#define MOZZI_CONTROL_RATE 128  // Hz

#include <Mozzi.h>
#include <Oscil.h>
#include <tables/sin2048_int8.h>
#include <tables/saw4096_int8.h>
#include <tables/triangle_valve_2048_int8.h>


// Potentiometer and CV inputs
const byte TONE_POT    = A0;
const byte AMNT_POT    = A1;
const byte PITCH_POT   = A2;
const byte FINE_POT    = A3;
const byte SCALE_POT   = A4;
const byte FM_CV_PIN   = A5;
const byte AMNT_CV_PIN = A6;
const byte VOCT_PIN    = A7;

const int VOCT_ZERO_DEADBAND = 12;

// Quantizer hysteresis: 0.15 semitones = 15 cents
const float QUANT_HYSTERESIS_SEMITONES = 0.15f;


// Switches and button
const byte QUANT_TOGGLE = 2;
const byte WAVE_TOGGLE  = 3;
const byte MODE_TOGGLE  = 4;
const byte SLEW_BTN     = 5;


// Oscillators
Oscil<TRIANGLE_VALVE_2048_NUM_CELLS, MOZZI_AUDIO_RATE>
    aTri(TRIANGLE_VALVE_2048_DATA);

Oscil<SAW4096_NUM_CELLS, MOZZI_AUDIO_RATE>
    bSaw(SAW4096_DATA);

Oscil<SIN2048_NUM_CELLS, MOZZI_AUDIO_RATE>
    aModSin(SIN2048_DATA);

Oscil<SAW4096_NUM_CELLS, MOZZI_AUDIO_RATE>
    aModSaw(SAW4096_DATA);

int fm_intensity = 0;
bool is_fold_mode = false;

int audio_fold_drive = 1;
int audio_wet_weight = 0;
int audio_dry_weight = 1024;
bool audio_fold_active = false;

const float CARRIER_BASE_FREQ = 32.70f;  // C1

// Scales
// Bit N represents semitone interval N above the root.
const uint16_t SCALE_MASKS[] PROGMEM = {
  0b101010110101, // Major:             0, 2, 4, 5, 7, 9, 11
  0b010110101101, // Natural Minor:     0, 2, 3, 5, 7, 8, 10
  0b011010101101, // Dorian:            0, 2, 3, 5, 7, 9, 10
  0b010110101011, // Phrygian:          0, 1, 3, 5, 7, 8, 10
  0b101011010101, // Lydian:            0, 2, 4, 6, 7, 9, 11
  0b010010101001  // Minor Pentatonic:  0, 3, 5, 7, 10
};

// Scale selection, from CCW to CW
// Unquantized
// Major
// Natural Minor
// Dorian
// Phrygian
// Lydian
// Minor Pentatonic
byte getScaleIndex(int scalePotRaw) {
  if (scalePotRaw < 144) {
    return 6;  // Unquantized
  }

  byte index =
      (byte)(((long)(scalePotRaw - 144) * 6L) / 880L);

  return (index > 5) ? 5 : index;
}

// Quantizer Function
// Input pitch and root are measured in semitones relative to C1.
// Returns the closest valid scale note.
int quantizeSemitone(
    float pitchSemitones,
    int rootSemitone,
    byte scaleIndex) {

  uint16_t mask = pgm_read_word(&SCALE_MASKS[scaleIndex]);

  int lower = (int)pitchSemitones;
  int upper = lower + 1;

  int lowerNote = lower;
  int upperNote = upper;

  bool foundLower = false;
  bool foundUpper = false;

  for (byte offset = 0; offset < 12; ++offset) {
    int candidate = lower - offset;
    int relative = (candidate - rootSemitone) % 12;

    if (relative < 0) {
      relative += 12;
    }

    if (!foundLower && (mask & (1U << relative))) {
      lowerNote = candidate;
      foundLower = true;
    }

    candidate = upper + offset;
    relative = (candidate - rootSemitone) % 12;

    if (relative < 0) {
      relative += 12;
    }

    if (!foundUpper && (mask & (1U << relative))) {
      upperNote = candidate;
      foundUpper = true;
    }

    if (foundLower && foundUpper) {
      break;
    }
  }

  float lowerDistance = pitchSemitones - (float)lowerNote;
  float upperDistance = (float)upperNote - pitchSemitones;

  // Ties choose the lower note.
  return (upperDistance < lowerDistance) ? upperNote : lowerNote;
}

void setup() {
  startMozzi();

  pinMode(11, OUTPUT);

  pinMode(QUANT_TOGGLE, INPUT_PULLUP);
  pinMode(WAVE_TOGGLE, INPUT_PULLUP);
  pinMode(MODE_TOGGLE, INPUT_PULLUP);
  pinMode(SLEW_BTN, INPUT_PULLUP);

  pinMode(VOCT_PIN, INPUT);
}


void updateControl() {
  static float smoothedCarrier = CARRIER_BASE_FREQ;
  static float smoothedMod = 200.0f;

  static int filteredPitchPot = -1;

  // Quantizer hysteresis state

  static bool quantizerStateValid = false;
  static int heldQuantizedNote = 0;
  static int lastQuantizerRoot = -1;
  static byte lastQuantizerScale = 255;

  static bool lastReading = HIGH;
  static bool debouncedState = HIGH;
  static unsigned long lastDebounceTime = 0;

  const unsigned long debounceDelay = 20;

  static unsigned long pressStart = 0;
  static unsigned long slewMs = 0;
  static bool holdHandled = false;

  bool rawBtn = digitalRead(SLEW_BTN);
  unsigned long now = millis();

  // Button debounce
  if (rawBtn != lastReading) {
    lastDebounceTime = now;
  }

  lastReading = rawBtn;

  if ((now - lastDebounceTime) > debounceDelay) {
    if (rawBtn != debouncedState) {
      debouncedState = rawBtn;

      if (debouncedState == LOW) {
        pressStart = now;
        holdHandled = false;
      } else if (!holdHandled) {
        unsigned long duration = now - pressStart;

        if (duration >= 20) {
          slewMs = duration;
        }
      }
    }
  }

  // Hold button for 1.5 seconds to disable slew
  if (debouncedState == LOW &&
      !holdHandled &&
      (now - pressStart >= 1500)) {

    slewMs = 0;
    holdHandled = true;
  }

  // Read controls
  int voctRaw  = mozziAnalogRead(VOCT_PIN);
  int rawPitch = mozziAnalogRead(PITCH_POT);
  int finePot  = mozziAnalogRead(FINE_POT);
  int scalePot = mozziAnalogRead(SCALE_POT);

  int potA = mozziAnalogRead(TONE_POT);
  int cvA  = mozziAnalogRead(FM_CV_PIN);
  int potB = mozziAnalogRead(AMNT_POT);
  int cvB  = mozziAnalogRead(AMNT_CV_PIN);

  // Reduce small pitch-pot ADC fluctuations

  if (filteredPitchPot < 0) {
    filteredPitchPot = rawPitch;
  } else if (abs(rawPitch - filteredPitchPot) >= 2) {
    filteredPitchPot = rawPitch;
  }

  is_fold_mode = (digitalRead(MODE_TOGGLE) == LOW);
  bool quantToggleState = (digitalRead(QUANT_TOGGLE) == HIGH);

  if (voctRaw <= VOCT_ZERO_DEADBAND) {
    voctRaw = 0;
  }

  // Pitch calculation
  //
  // Coarse pitch establishes the root.
  // CV transposes the pitch.
  // Scale selection determines whether the pitch is quantized.
  float potSemitones =
      (float)filteredPitchPot * (60.0f / 1023.0f);

  float voctSemitones =
      (float)voctRaw * (60.0f / 1023.0f);

  float pitchSemitones = potSemitones + voctSemitones;

  // Root follows the coarse knob in semitone increments.
  int rootSemitone = (int)(potSemitones + 0.5f);

  byte scaleIndex = getScaleIndex(scalePot);
  bool isCarrierQuantized = (scaleIndex < 6);

  float selectedSemitones = pitchSemitones;


  // Quantization with hysteresis
  if (isCarrierQuantized) {

    // Calculate the normal nearest scale note.
    int nearestNote = quantizeSemitone(
        pitchSemitones,
        rootSemitone,
        scaleIndex);

    // Initialize or reset if the root or scale changes.
    if (!quantizerStateValid ||
        rootSemitone != lastQuantizerRoot ||
        scaleIndex != lastQuantizerScale) {

      heldQuantizedNote = nearestNote;

      lastQuantizerRoot = rootSemitone;
      lastQuantizerScale = scaleIndex;

      quantizerStateValid = true;
    }

    // Only evaluate hysteresis when the candidate note changes.
    else if (nearestNote != heldQuantizedNote) {

      // Midpoint between the currently held note and candidate note.
      float switchingPoint =
          ((float)heldQuantizedNote + (float)nearestNote) * 0.5f;

      // Moving upward: require the CV to cross the upper threshold.
      if (nearestNote > heldQuantizedNote) {

        if (pitchSemitones >
            switchingPoint + QUANT_HYSTERESIS_SEMITONES) {

          heldQuantizedNote = nearestNote;
        }
      }

      // Moving downward: require the CV to cross the lower threshold.
      else {

        if (pitchSemitones <
            switchingPoint - QUANT_HYSTERESIS_SEMITONES) {

          heldQuantizedNote = nearestNote;
        }
      }
    }

    selectedSemitones = (float)heldQuantizedNote;
  }

  // Reset the quantizer state when unquantized.
  // This ensures quantization immediately selects the correct note
  // when it is enabled again.
  else {
    quantizerStateValid = false;
  }

  // Fine tuning: -200 to +200 cents
  float fineSemitones =
      (float)map(finePot, 0, 1023, -200, 200) / 100.0f;

  // One frequency conversion
  float targetCarrierFreq =
      CARRIER_BASE_FREQ *
      powf(2.0f, (selectedSemitones + fineSemitones) / 12.0f);

  targetCarrierFreq = constrain(targetCarrierFreq, 20.0f, 5000.0f);


  // FM mode

  if (!is_fold_mode) {
    int combinedTone = constrain(potA + cvA, 0, 1023);

    float modBaseFreq =
        (float)map(combinedTone, 0, 1023, 20, 2000);

    float targetModFreq = modBaseFreq;

    bool modulatorSlave =
        quantToggleState && isCarrierQuantized;

    if (modulatorSlave) {
      float carrierRatio = targetCarrierFreq / CARRIER_BASE_FREQ;
      targetModFreq = modBaseFreq * carrierRatio;
    }

    targetModFreq = constrain(targetModFreq, 20.0f, 5000.0f);

    smoothedMod += (targetModFreq - smoothedMod) * 0.5f;

    aModSin.setFreq(smoothedMod);
    aModSaw.setFreq(smoothedMod);

    int combinedAmnt = constrain(potB + cvB, 0, 1023);

    fm_intensity = map(combinedAmnt, 0, 1023, 0, 255);

  } else {

    // Wavefolder mode
    int fold_level = constrain(potA + cvA, 0, 1023);

    audio_fold_active = (fold_level >= 10);
    audio_fold_drive = map(fold_level, 10, 1023, 1, 12);

    audio_wet_weight = constrain(potB + cvB, 0, 1023);
    audio_dry_weight = 1023 - audio_wet_weight;
  }


  // Carrier slew
  if (slewMs == 0) {
    smoothedCarrier = targetCarrierFreq;
  } else {
    float tickMs = 1000.0f / (float)MOZZI_CONTROL_RATE;
    float coeff = tickMs / (float)slewMs;

    if (coeff > 1.0f) {
      coeff = 1.0f;
    }

    smoothedCarrier +=
        (targetCarrierFreq - smoothedCarrier) * coeff;
  }

  aTri.setFreq(smoothedCarrier);
  bSaw.setFreq(smoothedCarrier);
}


// Fast wavefolder
int applyWavefoldFast(int inputSample) {
  if (!audio_fold_active) {
    return inputSample;
  }

  long scaled = (long)inputSample * 4 * audio_fold_drive;

  int threshold = 512;
  int folded = (int)scaled;

  if (folded > threshold) {
    folded = threshold - (folded - threshold);
  } else if (folded < -threshold) {
    folded = -threshold - (folded + threshold);
  }

  if (folded > threshold) {
    folded = threshold - (folded - threshold);
  } else if (folded < -threshold) {
    folded = -threshold - (folded + threshold);
  }

  if (folded > threshold) {
    folded = threshold - (folded - threshold);
  } else if (folded < -threshold) {
    folded = -threshold - (folded + threshold);
  }

  long wet = folded >> 1;

  int absInput = inputSample < 0 ? -inputSample : inputSample;

  if (wet > absInput) {
    wet = absInput;
  } else if (wet < -absInput) {
    wet = -absInput;
  }

  long mixed =
      ((long)inputSample * audio_dry_weight +
       wet * audio_wet_weight) >> 10;

  return (int)mixed;
}


// Audio-rate update
AudioOutput updateAudio() {
  int sig = 0;

  if (!is_fold_mode) {
    int8_t modSample =
        (digitalRead(WAVE_TOGGLE) == LOW)
        ? aModSaw.next()
        : aModSin.next();

    int modulation = fm_intensity * modSample;

    // Advances carrier phase once
    sig = aTri.phMod(modulation);

  } else {
    int triSampleRaw = aTri.next();

    // Advances carrier phase once
    sig = applyWavefoldFast(triSampleRaw);
  }

  // Square-wave output on pin 11
  if (sig >= 0) {
    PORTB |= (1 << 3);
  } else {
    PORTB &= ~(1 << 3);
  }

  int sawSample = bSaw.next() * 28;
  int triSample = sig * 36;

  return StereoOutput::fromNBit(12, sawSample, triSample);
}


void loop() {
  audioHook();
}