Here's a dummy code i have on my stack. It used the algoritm i explained ealier.