Hi i must admit honestly that i dont understand your code completeley. But if i understand your problem right you want to:?
Create a list of directories (down the "directory-tree) starting from $sourcedir.
Store this list in an array e.g..
Loop (foreach array element e.g.):
{
Descent into every dir and copy *txt to $targetdir
}
(Special treatment required for "." and ".." directories (the current and the dir nearer to the "root-dir" these must be removed from the list)