Code cleanup. Added comments and logging.