Refactor into four files, and improve documentation