fixed the ugly code (with pointers) and added comments