// NMI Sample Player using the SID volume register
// Code by Scan of Desire (Richard-William Loerakker)
// Sample from ART OF NOISE: MOMENTS IN LOVE

import "c64"

const unsigned int SAMPLE_SIZE = 0x6100;
char[SAMPLE_SIZE] SAMPLE = kickasm(resource "moments_sample.bin") {{  .import binary "moments_sample.bin" }};

volatile char* sample = SAMPLE;

void main() {
    // Boosting 8580 Digis
    // See https://gist.github.com/munshkr/30f35e39905e63876ff7 (line 909)
    asm {
				lda #$ff
				sta $d406
				sta $d40d
				sta $d414

				lda #$49
				sta $d404				
				sta $d40b
				sta $d412	    
    }
    asm { sei }
    *CIA2_INTERRUPT = CIA_INTERRUPT_CLEAR;
    *KERNEL_NMI = &nmi;
    *CIA2_TIMER_A = 0x88; // speed
    *CIA2_INTERRUPT = 0x81;
    *CIA2_TIMER_A_CONTROL = 0x01;
    asm { cli }
}

interrupt(hardware_all) void nmi() {
    (*BORDERCOL)++;
    asm { lda CIA2_INTERRUPT }
    *SID_VOLUME = *sample & $0f;
    *KERNEL_NMI = &nmi2;
    (*BORDERCOL)--;
}

interrupt(hardware_all) void nmi2() {
    (*BORDERCOL)++;
    asm { lda CIA2_INTERRUPT }
    *SID_VOLUME = *sample >> 4;
    sample++;
    if (>sample == >(SAMPLE+$6100)) {
        sample = SAMPLE;
    }
    *KERNEL_NMI = &nmi;
    (*BORDERCOL)--;
}