Fixed a few bugs and refactored code

Based on @nisargjhaveri's suggestions