For one, you've got a syntax error (noted by the crazy color coding now that I've added the [noparse]
..
[/noparse] bbcode tags around your code).
Second, why on earth do you have so many echo statements (e.g. instead of just one or maybe two)?
Third, where are $search_wave and $wave ever defined? Have you tried echo'ing (or, even better, [man]var_dump/man'ing them) to verify that they hold the values that you think to do?
Finally, what is the point of code like this:
$wave=0
etc. ? Doesn't seem like it's going to result in valid HTML (and, as such, do anything meaningful).