# Cantus Firmus playing

from math import floor
from numpy import linspace, append, zeros
from scipy.io.wavfile import write

freqSamp,rptsList,freqList,zeroList=44100,[],[],[]

cantusFirmus=[48, 50, 50, 45, 45, 47, 43, 45, 47, 47, 50, 48, 
              48, 45, 47, 52, 48, 45, 48, 50, 47, 48, 47, 48]

rangeET={36: 65.41, 38: 73.42, 40: 82.41, 41: 87.31, 
         43: 98, 45: 110, 47: 123.47, 48: 138.81,
         50: 146.83, 52: 164.81, 53: 174.61, 
         55: 196, 57: 220, 59: 246.94, 60: 261.63}
         
notes=[]

for idx in cantusFirmus:
    note=rangeET[idx]
    notes.append(note)

for note in notes:
    flNote=floor(freqSamp/note)
    flNote=flNote if flNote%2==0 else flNote-1
    rptsList.append(flNote)
    freqList.append(floor(note))
    zeroList.append(freqSamp-floor(note)*flNote)
    
print(rptsList,freqList,zeroList)

CF=[]

# triangle oscillator and padding

for count in range(24):

    halfRpts=rptsList[count]//2

    firstHalf=linspace(-1.0,1.0,halfRpts,False).astype(float)
    lastHalf=linspace(1.0,-1.0,halfRpts,False).astype(float)
    triData=append(firstHalf,lastHalf)

    rpts=freqList[count]-1
    triNote=triData
    while rpts>0:
        triNote=append(triNote,triData)
        rpts=rpts-1
    
    CF=append(CF,triNote)
    
    padding=zeros(zeroList[count]).astype(float)
    
    CF=append(CF,padding)
    
write('CF.wav',freqSamp,CF)