fixed bug due to incorrect function calls
Cleaned up code to remove goto.