improved version and added proper comments