Finally fixed the code. Pro tip: Never use uninitialized variables.