A general algorithm for calculating jet cross sections in NLO QCD