Loop causing inexlicably "Index out of range for wave CU_AA"-error

Dear all,

I have encountered a strange problem that I can not figure out:

The following code should be used to compare a List of amino acids with a user-defined input sequence. The found values shall be written to a wave CU_AA, which should be enlarged by 1 whenever a new matching amino acid is found.
                     
                                for(c=0;c<(numpnts(AA_OLC));c+=1)
					 TransientActiveAA = AA_OLC [c]
 					// Compare Transient active AA and active AA:
					 if(cmpstr(TransientActiveAA,ActiveAA)==0)
						 // If equal
					 	Wave /T CU_AA
						 if(waveexists(CU_AA)==0)
						 	Make /O /T /N=1 CU_AA
							 CU_AA [0] = Codons [c]
					 	else
							 Redimension /N=(numpnts(CU_AA)+1) CU_AA
							Variable test = numpnts(CU_AA)
							CU_AA [test] = TheValue
						endif
					endif	
				endfor


On the second run of the loop, the program stops - error code: "Index out of range for wave CU_AA"

This I cannot understand, since the index normally changes from 1 (
Make command
) to 2 (
Redimension command
).

Where is the bug?

Thanks in advance for any help!

Regards,
Peter
This is wrong:

Variable test = numpnts(CU_AA)
CU_AA[test] = TheValue


It should be:

Redimension /N=(numpnts(CU_AA)+1) CU_AA
Variable test = numpnts(CU_AA)
CU_AA[test-1] = TheValue


A neater way to do it is:

Variable numPoints = numpnts(CU_AA)
CU_AA[numPoints] = {TheValue}       // Extend wave with new value

If you experience any performance issues with
Redimension
in the code, I would add some quadratic growth strategy to the code.

E.g:

variable oldSize, idx
for(...)
	Wave/Z/T wv
	if(!WaveExists(wv))
		Make/T/N=128 wv
		idx = 0
	endif
	oldSize = DimSize(wv, 0)
	if(idx >= oldSize)
		Redimension/N=(oldSize * 2) wv
		idx = oldSize
	endif
	wv[idx] = theValueYouWantToStore 
	idx += 1
endfor
// After you are done, remove excess rows
Redimension/N=(idx) wv