Restructured code for modularity and fixed Valgrind memory errors