Check out this great post by Richard Seroter on using the BAM API to collect BAM data inside a loop, creating a hierarchy of activities. Not doing too much with the BAM API I found it a great way to understand it’s usage and flexibility.