Major refactorization and cleaning. Still not working, but valgrind does not complain too much and the program returns 0 (not segfault or inproper free()).