cleanedup code and added some comments