Fixed memory issues. Added comments and a bit of cleanup.