public int generate(int period)
    {
        //we generate paths with length 'period' and check whether the first and
        //last node is the same. this gives us cycles of length period-1
        period++;
        if (graph == null)
            graph = new StateGraph(balls, max_height);
        int patterns = 0;

        if(DEBUG)
            System.err.println("Generating cycles with period "+(period-1));

        for (long root : graph.getNodes())
        {
            if(DEBUG)
            {
                System.err.print("Starting from root: ");
                graph.print(root);
            }
            LinkedList<Long> path = new LinkedList<Long>();
            long node = root;
            while(path.size() < period)
            {
                path.add(node);
                node = graph.getNextChild(node, 0); //always get the first child
            }

            while(path != null)
            {
                if (path.get(0) == path.get(period-1))
                {
                    //cycle. restore the siteswap and handle it.
                    int[] siteswap = new int[period-1];
                    for (int i = 0; i<period-1; i++)
                    {
                        int height = graph.getLabel(path.get(i), path.get(i+1));
                        siteswap[i] = height;
                    }
                    patterns++;

                    Siteswap s = new Siteswap(siteswap);
                    //dont handle siteswaps which turn out to have smaller period
                    //e.g. don't handle '3' as a siteswap with period >1
                    if(s.getSequence().length == period-1) 
                        handler.handle(s);
                }

                path = getNextPath(path, period);
            }
        }
        return patterns;
    }