FUNCTIONAL VERSION WITH THREADS IMPLEMENTED