contract BasicCoinManager is Owned {
  // a structure wrapping a deployed BasicCoin
  struct Coin {
    address coin;
    address owner;
    address tokenreg;
  }

  // a new BasicCoin has been deployed
  event Created(address indexed owner, address indexed tokenreg, address indexed coin);

  // a list of all the deployed BasicCoins
  Coin[] coins;

  // all BasicCoins for a specific owner
  mapping (address => uint[]) ownedCoins;

  // the base, tokens denoted in micros (matches up with BasicCoin interface above)
  uint constant public base = 1000000;

  // return the number of deployed
  function count() constant returns (uint) {
    return coins.length;
  }

  // get a specific deployment
  function get(uint _index) constant returns (address coin, address owner, address tokenreg) {
    Coin c = coins[_index];

    coin = c.coin;
    owner = c.owner;
    tokenreg = c.tokenreg;
  }

  // returns the number of coins for a specific owner
  function countByOwner(address _owner) constant returns (uint) {
    return ownedCoins[_owner].length;
  }

  // returns a specific index by owner
  function getByOwner(address _owner, uint _index) constant returns (address coin, address owner, address tokenreg) {
    return get(ownedCoins[_owner][_index]);
  }

  // deploy a new BasicCoin on the blockchain
  function deploy(uint _totalSupply, string _tla, string _name, address _tokenreg) payable returns (bool) {
    TokenReg tokenreg = TokenReg(_tokenreg);
    BasicCoin coin = new BasicCoin(_totalSupply, msg.sender);

    uint ownerCount = countByOwner(msg.sender);
    uint fee = tokenreg.fee();

    ownedCoins[msg.sender].length = ownerCount + 1;
    ownedCoins[msg.sender][ownerCount] = coins.length;
    coins.push(Coin(coin, msg.sender, tokenreg));
    tokenreg.registerAs.value(fee)(coin, _tla, base, _name, msg.sender);

    Created(msg.sender, tokenreg, coin);

    return true;
  }

  // owner can withdraw all collected funds
  function drain() only_owner {
    if (!msg.sender.send(this.balance)) {
      throw;
    }
  }
}
// Manages BasicCoin instances, including the deployment & registration
function countByOwner(address _owner) constant returns (uint) {
  return ownedCoins[_owner].length;
}

// returns the number of coins for a specific owner