correct substitute function implementation; add tests