Major bug fixes

Fixed many issues and the program runs well.