One thing that is immediately obvious is that each occurrence of

$+(rules\,$mkfn(#),\,$2.txt)

Should be...

$+(rules\,$mkfn(#),\,$2,.txt)