Minor bugfixes

- Refactor theory code
- Bugfixes

Signed-off-by: Dustin Ngo (laptop) <dustin.ngo@gmail.com>