This function is overall a bit confusing, and could use some cleanup. Some stuff looks like it could be inside the DEBUG if statement, if it's only used then.