  #compact 
  % Title "ConsoleG Demo: MIDI Sound & Timing"

  % WindowStyle WS_OVERLAPPEDWINDOW
  % Animated
 '% ScaleUp
 '% PlaceCentral
 '% AnchorCentral
 '% shaders
  % MidiSound

  uses ConsoleG
 
  BeginScript

  sys beat

  sub TimedEvents()
  =================
  indexbase 1
  % midi  midiOutShortMsg hmo,
  % cycle %1++ : if %1>%2 then %1=1
  '
  type msm
    byte c,n,v,w
    =
    sys m 'MIDI SHORT MESSAGE
  end type
  '
  static msm     s,s1
  static byte    s2[64]
  static int     ch=0, n=48, tempo=30
  static float   pt=64,pti=.125
  static int     c0,c1,c2,c3,c4,c5,c6,c7 'COUNTERS
  static int     e0,e1,e2,e3,e4,e5,e6,e7 'EVENTS
  static int     t0,t1,t2,t3,t4,t5,t6,t7 'TIMERS
  static int     init
  '
  'FOR LONG MESSAGES
  static sys     lh,c
  static midihdr hdr
  static byte    msg[0x2000]
  sys i

  t0++

  'PITCH BEND STEP
  pt=t1*10 '32=semitone
  'vibrato effect
  'pt+=pti
  'if pt>=65 then pti=-pti
  'if pt<=63 then pti=-pti
  's1={0xE0+ch,0,pt}
  'midi s1.m

  if t0=tempo then
    finit
    t0=0
    if init<1 then
      '
      'SELECT INSTRUMENTS
      midi 0x00c0  '0 piano
      midi 0x10c1  '1 hammond organ
      midi 0x5ec2  '2 synth
      midi 0x0ec3  '3 tubular bells
      midi 0x49c4  '4 flute
      midi 0x74c5  '5 taiko drums
                   '9 percussion preset
      'TUNING ADJUSTMENT
      'msg={0xB0, 0x64, 0x00, 0x65, 0x03, 0x60, 0x7f, 48,120,120,  0x99,40,120} 'increment piano note 48
      'msg={0xB0, 0x64, 0x00, 0x65, 0x03, 0x61, 0x7f, 48,120,120,  0x99,40,120} 'decrement piano note 48
      'msg={0xB0, 0x64, 0x00, 0x65, 0x03, 0x06, 0x01, 48,120,120,  0x99,40,120} 'data piano note 48
      c=0
      lh=sizeof midihdr
      hdr={@msg,c,0,0,0}
      midiOutPrepareHeader hmo, @hdr,lh
      if c then midiOutLongMsg hmo,@hdr,lh
      init+=1
      sleep 10
    end if
    cycle t1 4
    s ={0x90+ch,n,64} 'c n v
    if t1=1 then s.v=100 :  beat++
    if t1=4 then s.v=50
    if beat=2 then
      e1=1
    end if
    if beat>1 then '8
      if beat=3 then
        CloseScene
      end if
      exit sub
    end if
    msg={0x99,35,70, 0x90,55,60 } : c=6
    hdr.dwBufferLength=c
    midiOutLongMsg hmo,@hdr,lh
    midi s.m
    's.n+=8 'harmonic
    'midi s.m
  end if
  '
  if e1 then
    cycle t2 4
    if t2=4 then
    end if
    if c1++>20 then e1=0
  end if  
  end sub

  timercall=@TimedEvents

  sub main()
  ==========

  'WaitForEvent '0 off 1 on (default on)
  static int  z, y, x

  if opening then 'FIRST CALL ONLY
  end if

  if closing then 'FINAL CALL BEFORE SHUTDOWN
  end if

  if not pick then
    pushstate
    move 0,0
    static sys tally
    scale 1.5
    '
    macro pr(a,b) 'PRINTING LIST
      pushstate : color .5,1,1 : print a : popstate
      pushstate : color 1,1,.5 : move 8 : print b : popstate
      printl ""
    end macro
    '
    pr "10ms Count:    ", str(tickCount)
    pr "Frame Count:   ", str(tally++)
    pr "Beat Count:    ", str(beat)

    popstate
  end if

  end sub 'main

  EndScript