heavily revised to simplify code and include multiplicity() function -KL