changed a lot of stuff to long and/or unsigned ints to avoid overflow