Main alhorithm