The magic words are "Smith Normal Form". The magic reference is "Integral Matrices" by M. Newman, which discusses many questions of this sort in a lucid way.