import "c64.kc"
import "sinus.kc"
import "memory.kc"

byte* SCREEN = $400;
byte* LOGO = $2000;
kickasm(resource "logo.png", pc LOGO, bytes 6*40*8) {{
    .var logoPic = LoadPicture("logo.png", List().add($444444, $808080, $000000, $ffffff))
    .for (var y=0; y<6	; y++)
        .for (var x=0;x<40; x++)
            .for(var cp=0; cp<8; cp++)
                .byte logoPic.getMulticolorByte(x,cp+y*8)
}}

const word XSIN_SIZE = 512;

signed word[XSIN_SIZE] align($100) xsin;

void main() {
    asm { sei }
    *BORDERCOL = WHITE;
    *BGCOL = *BGCOL2 = DARK_GREY;
    *BGCOL3 = BLACK;
    *D018 = toD018(SCREEN, LOGO);
    *D016 = VIC_MCM;
    fill(SCREEN, 1000, BLACK);
    fill(COLS, 1000, WHITE|8);
    for(byte ch: 0..239) {
        SCREEN[ch] = ch;
    }
    sin16s_gen2(xsin, XSIN_SIZE, -320, 320);
    loop();
}

word xsin_idx = 0;

void loop() {
    while(true) {
        // Wait for the raster to reach the bottom of the screen
        while(*RASTER!=$ff) {}
        (*BORDERCOL)++;
        signed word xpos = *(xsin+xsin_idx);
        render_logo(xpos);
        xsin_idx += 2;
        if(xsin_idx==XSIN_SIZE*2) {
            xsin_idx = 0;
        }
        (*BORDERCOL)--;
    }
}

void render_logo(signed word xpos) {
    byte logo_idx;
    byte screen_idx;
    *D016 = VIC_MCM|((byte)xpos&7);
    signed byte x_char = (signed byte)(xpos>>3);
    byte line = 0;
    if(xpos<0) {
        // Render right side of the logo and some spaces
        logo_idx = (byte)(-x_char);
        screen_idx = 0;
        while(logo_idx!=40) {
            inline for(line: 0..5) {
                (SCREEN+40*line)[screen_idx] = logo_idx+40*line;
            }
            screen_idx++;
            logo_idx++;
        }
        while(screen_idx!=40) {
            inline for(line: 0..5) {
                (SCREEN+40*line)[screen_idx] = $00;
            }
            screen_idx++;
        }
    } else {
        // Render some spaces and the left of the logo
        byte logo_start = (byte)x_char;
        screen_idx = 0;
        while(screen_idx!=logo_start) {
            inline for(line: 0..5) {
                (SCREEN+40*line)[screen_idx] = $00;
            }
            screen_idx++;
        }
        logo_idx = 0;
        while(screen_idx!=40) {
            inline for(line: 0..5) {
                (SCREEN+40*line)[screen_idx] = logo_idx+40*line;
            }
            screen_idx++;
            logo_idx++;
        }
    }
}
