@SuppressWarnings("rawtypes")
    public static byte[] generateCanonicalRRsetData(RRset rrset, long ttl,
            int labels) {
        DNSOutput image = new DNSOutput();

        if (ttl == 0) {
            ttl = rrset.getTTL();
        }

        Name n = rrset.getName();

        if (labels == 0) {
            labels = n.labels();
        } else {
            // correct for Name()'s conception of label count.
            labels++;
        }

        boolean wildcardName = false;

        if (n.labels() != labels) {
            n = n.wild(n.labels() - labels);
            wildcardName = true;
            log.trace("Detected wildcard expansion: " + rrset.getName()
                    + " changed to " + n);
        }

        // now convert the wire format records in the RRset into a
        // list of byte arrays.
        ArrayList<byte[]> canonical_rrs = new ArrayList<byte[]>();

        for (Iterator i = rrset.rrs(); i.hasNext();) {
            Record r = (Record) i.next();

            if ((r.getTTL() != ttl) || wildcardName) {
                // If necessary, we need to create a new record with a new ttl
                // or ownername.
                // In the TTL case, this avoids changing the ttl in the
                // response.
                r = Record.newRecord(n, r.getType(), r.getDClass(), ttl, r
                        .rdataToWireCanonical());
            }

            byte[] wire_fmt = r.toWireCanonical();
            canonical_rrs.add(wire_fmt);
        }

        // put the records into the correct ordering.
        // Calculate the offset where the RDATA begins (we have to skip
        // past the length byte)
        int offset = rrset.getName().toWireCanonical().length + 10;
        ByteArrayComparator bac = new ByteArrayComparator(offset, false);

        Collections.sort(canonical_rrs, bac);

        for (Iterator<byte[]> i = canonical_rrs.iterator(); i.hasNext();) {
            byte[] wire_fmt_rec = i.next();
            image.writeByteArray(wire_fmt_rec);
        }

        return image.toByteArray();
    }