Optimized and refactored the code. Things seem to work now.