Fix loops, add documentation, clean up nonsense