Implemented the flatten function