Adding documentation, error checking input arguments and cleaning code.