added comments a changed code a bit for clarity