{
try
{
final ByteArrayOutputStream arrayStream =
new ByteArrayOutputStream();
final OutputStream stream = new DynaByteOutputStream(arrayStream);
// Write the template settings bit mask.
int settings = this.sector == null ? 0 : 1;
settings |= this.game.getNid() << 1;
stream.write(settings);
// Write the sector coordinates
if (this.sector != null)
{
stream.write(this.sector.getX());
stream.write(this.sector.getY());
}
// Or else write the sun power
else
{
stream.write(this.suns.getPercent());
}
// Write the factories
for (final ComplexFactory complexFactory: getAllFactories())
{
if (complexFactory.isDisabled()) continue;
final Factory factory = complexFactory.getFactory();
stream.write(factory.getNid());
if (factory.isMine())
{
for (final int yield: complexFactory.getYields())
stream.write(yield + 1);
stream.write(0);
}
else
stream.write(complexFactory.getQuantity());
}
// Write end marker
stream.write(0);
stream.close();
// Get byte array from stream
final byte[] data = arrayStream.toByteArray();
// Return base 64 encoded bytes