Memory freeing fix
Cleaned up code with more detailed comments (docstrings)