BAI: Documentation for the code, and some refactoring