Auto-fit zig zag

A zig zag which automatically finds the best fit to the price data. I think it would be very handy with a universe of stocks, but I have limited coding ability.

When fitted manually, one starts with a high % parameter and lowers the % to minimize the 'gap' between the zig and highs/lows, within an acceptable limit. Obviously larger % is better in most cases, so long as the zig fits snugly.

I imagine something like:

a = abs(zig-close)/close
aa = HHV(a,100)
aaa = aa<param

I'm hoping someone has done this already. Please let me know.

Since the best fit is where the zig % is closest to zero, 'optimal' fit is a better word. Optimal fit could be defined as the largest % zig possible without the maximum abs(zig-c) going over x. Anyone?