I suggest to try to post coherent code instead of the fragments of
the dis-functional trash we see below.
Why are all lines commented out with '#' ?
Why do you use the '%' in ${1%} ?
Why didn't you close the loop with 'done' ?
What is the called syntax you used ?
For a start you may call your script with the -x option, as in
sh -x your_script your_args
to see what's going on.
And reduce your scripts to the essentials before re-posting.
Good luck!