Complete functional version for big input and commented code