Some refactoring and commenting.
Note: to_real was changed to to_double.