This is a more robust version of this script.
I wrote it as a function, so you can simply copy and paste it into any script to add an adaptive period setting capability.
In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.