Added a few comments and fixed a bit of logic