Computer generation of Feynman diagrams for perturbation theory I. General algorithm