Implement proper timeout to prevent programs from hanging. Also fixes memory leaks.
