Fixed bugs and modified the logic to cater for cases that were not handled earlier