Added comments, made minor changes for optimization