fix much bugs

Bad variable names
Bad iterations (overflowing)
Writing output like what how Java does