Finalized code with cross validation logic