text:
using namespace std::literals;

namespace amuse {
static logvisor::Module Log("amuse::AudioGroupPool");

struct MakeCmdOp {
  template <class Tp, class R>
  static std::unique_ptr<SoundMacro::ICmd> Do(R& r) {
    std::unique_ptr<SoundMacro::ICmd> ret = std::make_unique<Tp>();
    static_cast<Tp&>(*ret).read(r);
    return ret;
  }
};

struct MakeCopyCmdOp {
  template <class Tp, class R>
  static std::unique_ptr<SoundMacro::ICmd> Do(R& r) {
    return std::make_unique<Tp>(static_cast<const Tp&>(r));
  }
};

struct MakeDefaultCmdOp {
  template <class Tp, class R>
  static std::unique_ptr<SoundMacro::ICmd> Do(R& r) {
    std::unique_ptr<SoundMacro::ICmd> ret = std::make_unique<Tp>();
    if (const SoundMacro::CmdIntrospection* introspection = SoundMacro::GetCmdIntrospection(r)) {
      for (const auto& field : introspection->m_fields) {
        if (field.m_name.empty()) {
          continue;
        }

        switch (field.m_tp) {
        case amuse::SoundMacro::CmdIntrospection::Field::Type::Bool:
          AccessField<bool>(ret.get(), field) = bool(field.m_default);
          break;
        case amuse::SoundMacro::CmdIntrospection::Field::Type::Int8:
        case amuse::SoundMacro::CmdIntrospection::Field::Type::Choice:
          AccessField<int8_t>(ret.get(), field) = int8_t(field.m_default);
          break;
        case amuse::SoundMacro::CmdIntrospection::Field::Type::UInt8:
          AccessField<uint8_t>(ret.get(), field) = uint8_t(field.m_default);
          break;
        case amuse::SoundMacro::CmdIntrospection::Field::Type::Int16:
          AccessField<int16_t>(ret.get(), field) = int16_t(field.m_default);
          break;
        case amuse::SoundMacro::CmdIntrospection::Field::Type::UInt16:
          AccessField<uint16_t>(ret.get(), field) = uint16_t(field.m_default);
          break;
        case amuse::SoundMacro::CmdIntrospection::Field::Type::Int32:
          AccessField<int32_t>(ret.get(), field) = int32_t(field.m_default);
          break;
        case amuse::SoundMacro::CmdIntrospection::Field::Type::UInt32:
          AccessField<uint32_t>(ret.get(), field) = uint32_t(field.m_default);
          break;
        case amuse::SoundMacro::CmdIntrospection::Field::Type::SoundMacroId:
        case amuse::SoundMacro::CmdIntrospection::Field::Type::SoundMacroStep:
        case amuse::SoundMacro::CmdIntrospection::Field::Type::TableId:
        case amuse::SoundMacro::CmdIntrospection::Field::Type::SampleId:
          AccessField<SoundMacroIdDNA<athena::Endian::Little>>(ret.get(), field).id = uint16_t(field.m_default);
          break;
        default:
          break;
        }
      }
    }
    return ret;
  }
};

struct IntrospectCmdOp {
  template <class Tp>
  static const SoundMacro::CmdIntrospection* Do(SoundMacro::CmdOp) {
    return &Tp::Introspective;
  }
};

static bool AtEnd(athena::io::IStreamReader& r) {
  uint32_t v = r.readUint32Big();
  r.seek(-4, athena::SeekOrigin::Current);
  return v == 0xffffffff;
}

template <athena::Endian DNAE>
AudioGroupPool AudioGroupPool::_AudioGroupPool(athena::io::IStreamReader& r) {
  AudioGroupPool ret;

  PoolHeader<DNAE> head;
  head.read(r);

  if (head.soundMacrosOffset) {
    r.seek(head.soundMacrosOffset, athena::SeekOrigin::Begin);
    while (!AtEnd(r)) {
      ObjectHeader<DNAE> objHead;
      atInt64 startPos = r.position();
      objHead.read(r);
      if (SoundMacroId::CurNameDB)
        SoundMacroId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::SoundMacro),
                                              objHead.objectId);
      auto& macro = ret.m_soundMacros[objHead.objectId.id];
      macro = MakeObj<SoundMacro>();
      macro->template readCmds<DNAE>(r, objHead.size - 8);
      r.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
  }

  if (head.tablesOffset) {
    r.seek(head.tablesOffset, athena::SeekOrigin::Begin);
    while (!AtEnd(r)) {
      ObjectHeader<DNAE> objHead;
      atInt64 startPos = r.position();
      objHead.read(r);
      if (TableId::CurNameDB)
        TableId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::Table), objHead.objectId);
      auto& ptr = ret.m_tables[objHead.objectId.id];
      switch (objHead.size) {
      case 0x10:
        ptr = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSR>());
        static_cast<ADSR&>(**ptr).read(r);
        break;
      case 0x1c:
        ptr = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSRDLS>());
        static_cast<ADSRDLS&>(**ptr).read(r);
        break;
      default:
        ptr = MakeObj<std::unique_ptr<ITable>>(std::make_unique<Curve>());
        static_cast<Curve&>(**ptr).data.resize(objHead.size - 8);
        r.readUBytesToBuf(&static_cast<Curve&>(**ptr).data[0], objHead.size - 8);
        break;
      }
      r.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
  }

  if (head.keymapsOffset) {
    r.seek(head.keymapsOffset, athena::SeekOrigin::Begin);
    while (!AtEnd(r)) {
      ObjectHeader<DNAE> objHead;
      atInt64 startPos = r.position();
      objHead.read(r);
      if (KeymapId::CurNameDB)
        KeymapId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::Keymap),
                                          objHead.objectId);
      auto& km = ret.m_keymaps[objHead.objectId.id];
      km = MakeObj<std::array<Keymap, 128>>();
      for (int i = 0; i < 128; ++i) {
        KeymapDNA<DNAE> kmData;
        kmData.read(r);
        (*km)[i] = kmData;
      }
      r.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
  }

  if (head.layersOffset) {
    r.seek(head.layersOffset, athena::SeekOrigin::Begin);
    while (!AtEnd(r)) {
      ObjectHeader<DNAE> objHead;
      atInt64 startPos = r.position();
      objHead.read(r);
      if (LayersId::CurNameDB)
        LayersId::CurNameDB->registerPair(NameDB::generateName(objHead.objectId, NameDB::Type::Layer),
                                          objHead.objectId);
      auto& lm = ret.m_layers[objHead.objectId.id];
      lm = MakeObj<std::vector<LayerMapping>>();
      uint32_t count;
      athena::io::Read<athena::io::PropType::None>::Do<decltype(count), DNAE>({}, count, r);
      lm->reserve(count);
      for (uint32_t i = 0; i < count; ++i) {
        LayerMappingDNA<DNAE> lmData;
        lmData.read(r);
        lm->push_back(lmData);
      }
      r.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
  }

  return ret;
}
template AudioGroupPool AudioGroupPool::_AudioGroupPool<athena::Endian::Big>(athena::io::IStreamReader& r);
template AudioGroupPool AudioGroupPool::_AudioGroupPool<athena::Endian::Little>(athena::io::IStreamReader& r);

AudioGroupPool AudioGroupPool::CreateAudioGroupPool(const AudioGroupData& data) {
  if (data.getPoolSize() < 16)
    return {};
  athena::io::MemoryReader r(data.getPool(), data.getPoolSize());
  switch (data.getDataFormat()) {
  case DataFormat::PC:
    return _AudioGroupPool<athena::Endian::Little>(r);
  default:
    return _AudioGroupPool<athena::Endian::Big>(r);
  }
}

AudioGroupPool AudioGroupPool::CreateAudioGroupPool(std::string_view groupPath) {
  AudioGroupPool ret;
  std::string poolPath(groupPath);
  poolPath += "/!pool.yaml";
  athena::io::FileReader fi(poolPath, 32 * 1024, false);

  if (!fi.hasError()) {
    athena::io::YAMLDocReader r;
    if (r.parse(&fi) && r.readString("DNAType") == "amuse::Pool") {
      if (auto __r = r.enterSubRecord("soundMacros")) {
        for (const auto& sm : r.getCurNode()->m_mapChildren) {
          ObjectId macroId = SoundMacroId::CurNameDB->generateId(NameDB::Type::SoundMacro);
          SoundMacroId::CurNameDB->registerPair(sm.first, macroId);
        }
      }

      if (auto __r = r.enterSubRecord("tables")) {
        for (const auto& t : r.getCurNode()->m_mapChildren) {
          if (auto __v = r.enterSubRecord(t.first.c_str())) {
            ObjectId tableId = TableId::CurNameDB->generateId(NameDB::Type::Table);
            TableId::CurNameDB->registerPair(t.first, tableId);
          }
        }
      }

      if (auto __r = r.enterSubRecord("keymaps")) {
        for (const auto& k : r.getCurNode()->m_mapChildren)
          if (auto __v = r.enterSubRecord(k.first.c_str())) {
            ObjectId keymapId = KeymapId::CurNameDB->generateId(NameDB::Type::Keymap);
            KeymapId::CurNameDB->registerPair(k.first, keymapId);
          }
      }

      if (auto __r = r.enterSubRecord("layers")) {
        for (const auto& l : r.getCurNode()->m_mapChildren) {
          size_t mappingCount;
          if (auto __v = r.enterSubVector(l.first.c_str(), mappingCount)) {
            ObjectId layersId = LayersId::CurNameDB->generateId(NameDB::Type::Layer);
            LayersId::CurNameDB->registerPair(l.first, layersId);
          }
        }
      }

      if (auto __r = r.enterSubRecord("soundMacros")) {
        ret.m_soundMacros.reserve(r.getCurNode()->m_mapChildren.size());
        for (const auto& sm : r.getCurNode()->m_mapChildren) {
          auto& smOut = ret.m_soundMacros[SoundMacroId::CurNameDB->resolveIdFromName(sm.first)];
          smOut = MakeObj<SoundMacro>();
          size_t cmdCount;
          if (auto __v = r.enterSubVector(sm.first.c_str(), cmdCount))
            smOut->fromYAML(r, cmdCount);
        }
      }

      if (auto __r = r.enterSubRecord("tables")) {
        ret.m_tables.reserve(r.getCurNode()->m_mapChildren.size());
        for (const auto& t : r.getCurNode()->m_mapChildren) {
          if (auto __v = r.enterSubRecord(t.first.c_str())) {
            auto& tableOut = ret.m_tables[TableId::CurNameDB->resolveIdFromName(t.first)];
            if (auto __att = r.enterSubRecord("attack")) {
              __att.leave();
              if (auto __vta = r.enterSubRecord("velToAttack")) {
                __vta.leave();
                tableOut = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSRDLS>());
                static_cast<ADSRDLS&>(**tableOut).read(r);
              } else {
                tableOut = MakeObj<std::unique_ptr<ITable>>(std::make_unique<ADSR>());
                static_cast<ADSR&>(**tableOut).read(r);
              }
            } else if (auto __dat = r.enterSubRecord("data")) {
              __dat.leave();
              tableOut = MakeObj<std::unique_ptr<ITable>>(std::make_unique<Curve>());
              static_cast<Curve&>(**tableOut).read(r);
            }
          }
        }
      }

      if (auto __r = r.enterSubRecord("keymaps")) {
        ret.m_keymaps.reserve(r.getCurNode()->m_mapChildren.size());
        for (const auto& k : r.getCurNode()->m_mapChildren) {
          size_t mappingCount;
          if (auto __v = r.enterSubVector(k.first.c_str(), mappingCount)) {
            auto& kmOut = ret.m_keymaps[KeymapId::CurNameDB->resolveIdFromName(k.first)];
            kmOut = MakeObj<std::array<Keymap, 128>>();
            for (size_t i = 0; i < mappingCount && i < 128; ++i)
              if (auto __r2 = r.enterSubRecord())
                (*kmOut)[i].read(r);
          }
        }
      }

      if (auto __r = r.enterSubRecord("layers")) {
        ret.m_layers.reserve(r.getCurNode()->m_mapChildren.size());
        for (const auto& l : r.getCurNode()->m_mapChildren) {
          size_t mappingCount;
          if (auto __v = r.enterSubVector(l.first.c_str(), mappingCount)) {
            auto& layOut = ret.m_layers[LayersId::CurNameDB->resolveIdFromName(l.first)];
            layOut = MakeObj<std::vector<LayerMapping>>();
            layOut->reserve(mappingCount);
            for (size_t lm = 0; lm < mappingCount; ++lm) {
              if (auto __r2 = r.enterSubRecord()) {
                layOut->emplace_back();
                layOut->back().read(r);
              }
            }
          }
        }
      }
    }
  }

  return ret;
}

int SoundMacro::assertPC(int pc) const {
  if (pc < 0)
    return -1;
  if (size_t(pc) >= m_cmds.size()) {
    fmt::print(stderr, FMT_STRING("SoundMacro PC bounds exceeded [{}/{}]\n"), pc, int(m_cmds.size()));
    abort();
  }
  return pc;
}

template <athena::Endian DNAE>
void SoundMacro::readCmds(athena::io::IStreamReader& r, uint32_t size) {
  uint32_t numCmds = size / 8;
  m_cmds.reserve(numCmds);
  for (uint32_t i = 0; i < numCmds; ++i) {
    uint32_t data[2];
    athena::io::Read<athena::io::PropType::None>::Do<decltype(data), DNAE>({}, data, r);
    athena::io::MemoryReader mr(data, sizeof(data));
    m_cmds.push_back(CmdDo<MakeCmdOp, std::unique_ptr<ICmd>>(mr));
  }
}
template void SoundMacro::readCmds<athena::Endian::Big>(athena::io::IStreamReader& r, uint32_t size);
template void SoundMacro::readCmds<athena::Endian::Little>(athena::io::IStreamReader& r, uint32_t size);

template <athena::Endian DNAE>
void SoundMacro::writeCmds(athena::io::IStreamWriter& w) const {
  for (const auto& cmd : m_cmds) {
    uint32_t data[2];
    athena::io::MemoryWriter mw(reinterpret_cast<uint8_t*>(data), sizeof(data));
    mw.writeUByte(uint8_t(cmd->Isa()));
    cmd->write(mw);
    athena::io::Write<athena::io::PropType::None>::Do<decltype(data), DNAE>({}, data, w);
  }
}
template void SoundMacro::writeCmds<athena::Endian::Big>(athena::io::IStreamWriter& w) const;
template void SoundMacro::writeCmds<athena::Endian::Little>(athena::io::IStreamWriter& w) const;

void SoundMacro::buildFromPrototype(const SoundMacro& other) {
  m_cmds.reserve(other.m_cmds.size());
  for (auto& cmd : other.m_cmds)
    m_cmds.push_back(CmdDo<MakeCopyCmdOp, std::unique_ptr<SoundMacro::ICmd>>(*cmd));
}

void SoundMacro::toYAML(athena::io::YAMLDocWriter& w) const {
  for (const auto& c : m_cmds) {
    if (auto __r2 = w.enterSubRecord()) {
      w.setStyle(athena::io::YAMLNodeStyle::Flow);
      w.writeString("cmdOp", SoundMacro::CmdOpToStr(c->Isa()));
      c->write(w);
    }
  }
}

void SoundMacro::fromYAML(athena::io::YAMLDocReader& r, size_t cmdCount) {
  m_cmds.reserve(cmdCount);
  for (size_t c = 0; c < cmdCount; ++c)
    if (auto __r2 = r.enterSubRecord())
      m_cmds.push_back(SoundMacro::CmdDo<MakeCmdOp, std::unique_ptr<SoundMacro::ICmd>>(r));
}

const SoundMacro* AudioGroupPool::soundMacro(ObjectId id) const {
  auto search = m_soundMacros.find(id);
  if (search == m_soundMacros.cend())
    return nullptr;
  return search->second.get();
}

const Keymap* AudioGroupPool::keymap(ObjectId id) const {
  auto search = m_keymaps.find(id);
  if (search == m_keymaps.cend())
    return nullptr;
  return search->second.get()->data();
}

const std::vector<LayerMapping>* AudioGroupPool::layer(ObjectId id) const {
  auto search = m_layers.find(id);
  if (search == m_layers.cend())
    return nullptr;
  return search->second.get();
}

const ADSR* AudioGroupPool::tableAsAdsr(ObjectId id) const {
  auto search = m_tables.find(id);
  if (search == m_tables.cend() || (*search->second)->Isa() != ITable::Type::ADSR)
    return nullptr;
  return static_cast<const ADSR*>((*search->second).get());
}

const ADSRDLS* AudioGroupPool::tableAsAdsrDLS(ObjectId id) const {
  auto search = m_tables.find(id);
  if (search == m_tables.cend() || (*search->second)->Isa() != ITable::Type::ADSRDLS)
    return nullptr;
  return static_cast<const ADSRDLS*>((*search->second).get());
}

const Curve* AudioGroupPool::tableAsCurves(ObjectId id) const {
  auto search = m_tables.find(id);
  if (search == m_tables.cend() || (*search->second)->Isa() != ITable::Type::Curve)
    return nullptr;
  return static_cast<const Curve*>((*search->second).get());
}

static SoundMacro::CmdOp _ReadCmdOp(athena::io::MemoryReader& r) { return SoundMacro::CmdOp(r.readUByte()); }

static SoundMacro::CmdOp _ReadCmdOp(athena::io::YAMLDocReader& r) {
  return SoundMacro::CmdStrToOp(r.readString("cmdOp"));
}

static SoundMacro::CmdOp _ReadCmdOp(SoundMacro::CmdOp& op) { return op; }

static SoundMacro::CmdOp _ReadCmdOp(const SoundMacro::ICmd& op) { return op.Isa(); }

template <class Op, class O, class... _Args>
O SoundMacro::CmdDo(_Args&&... args) {
  SoundMacro::CmdOp op = _ReadCmdOp(std::forward<_Args>(args)...);
  switch (op) {
  case CmdOp::End:
    return Op::template Do<CmdEnd>(std::forward<_Args>(args)...);
  case CmdOp::Stop:
    return Op::template Do<CmdStop>(std::forward<_Args>(args)...);
  case CmdOp::SplitKey:
    return Op::template Do<CmdSplitKey>(std::forward<_Args>(args)...);
  case CmdOp::SplitVel:
    return Op::template Do<CmdSplitVel>(std::forward<_Args>(args)...);
  case CmdOp::WaitTicks:
    return Op::template Do<CmdWaitTicks>(std::forward<_Args>(args)...);
  case CmdOp::Loop:
    return Op::template Do<CmdLoop>(std::forward<_Args>(args)...);
  case CmdOp::Goto:
    return Op::template Do<CmdGoto>(std::forward<_Args>(args)...);
  case CmdOp::WaitMs:
    return Op::template Do<CmdWaitMs>(std::forward<_Args>(args)...);
  case CmdOp::PlayMacro:
    return Op::template Do<CmdPlayMacro>(std::forward<_Args>(args)...);
  case CmdOp::SendKeyOff:
    return Op::template Do<CmdSendKeyOff>(std::forward<_Args>(args)...);
  case CmdOp::SplitMod:
    return Op::template Do<CmdSplitMod>(std::forward<_Args>(args)...);
  case CmdOp::PianoPan:
    return Op::template Do<CmdPianoPan>(std::forward<_Args>(args)...);
  case CmdOp::SetAdsr:
    return Op::template Do<CmdSetAdsr>(std::forward<_Args>(args)...);
  case CmdOp::ScaleVolume:
    return Op::template Do<CmdScaleVolume>(std::forward<_Args>(args)...);
  case CmdOp::Panning:
    return Op::template Do<CmdPanning>(std::forward<_Args>(args)...);
  case CmdOp::Envelope:
    return Op::template Do<CmdEnvelope>(std::forward<_Args>(args)...);
  case CmdOp::StartSample:
    return Op::template Do<CmdStartSample>(std::forward<_Args>(args)...);
  case CmdOp::StopSample:
    return Op::template Do<CmdStopSample>(std::forward<_Args>(args)...);
  case CmdOp::KeyOff:
    return Op::template Do<CmdKeyOff>(std::forward<_Args>(args)...);
  case CmdOp::SplitRnd:
    return Op::template Do<CmdSplitRnd>(std::forward<_Args>(args)...);
  case CmdOp::FadeIn:
    return Op::template Do<CmdFadeIn>(std::forward<_Args>(args)...);
  case CmdOp::Spanning:
    return Op::template Do<CmdSpanning>(std::forward<_Args>(args)...);
  case CmdOp::SetAdsrCtrl:
    return Op::template Do<CmdSetAdsrCtrl>(std::forward<_Args>(args)...);
  case CmdOp::RndNote:
    return Op::template Do<CmdRndNote>(std::forward<_Args>(args)...);
  case CmdOp::AddNote:
    return Op::template Do<CmdAddNote>(std::forward<_Args>(args)...);
  case CmdOp::SetNote:
    return Op::template Do<CmdSetNote>(std::forward<_Args>(args)...);
  case CmdOp::LastNote:
    return Op::template Do<CmdLastNote>(std::forward<_Args>(args)...);
  case CmdOp::Portamento:
    return Op::template Do<CmdPortamento>(std::forward<_Args>(args)...);
  case CmdOp::Vibrato:
    return Op::template Do<CmdVibrato>(std::forward<_Args>(args)...);
  case CmdOp::PitchSweep1:
    return Op::template Do<CmdPitchSweep1>(std::forward<_Args>(args)...);
  case CmdOp::PitchSweep2:
    return Op::template Do<CmdPitchSweep2>(std::forward<_Args>(args)...);
  case CmdOp::SetPitch:
    return Op::template Do<CmdSetPitch>(std::forward<_Args>(args)...);
  case CmdOp::SetPitchAdsr:
    return Op::template Do<CmdSetPitchAdsr>(std::forward<_Args>(args)...);
  case CmdOp::ScaleVolumeDLS:
    return Op::template Do<CmdScaleVolumeDLS>(std::forward<_Args>(args)...);
  case CmdOp::Mod2Vibrange:
    return Op::template Do<CmdMod2Vibrange>(std::forward<_Args>(args)...);
  case CmdOp::SetupTremolo:
    return Op::template Do<CmdSetupTremolo>(std::forward<_Args>(args)...);
  case CmdOp::Return:
    return Op::template Do<CmdReturn>(std::forward<_Args>(args)...);
  case CmdOp::GoSub:
    return Op::template Do<CmdGoSub>(std::forward<_Args>(args)...);
  case CmdOp::TrapEvent:
    return Op::template Do<CmdTrapEvent>(std::forward<_Args>(args)...);
  case CmdOp::UntrapEvent:
    return Op::template Do<CmdUntrapEvent>(std::forward<_Args>(args)...);
  case CmdOp::SendMessage:
    return Op::template Do<CmdSendMessage>(std::forward<_Args>(args)...);
  case CmdOp::GetMessage:
    return Op::template Do<CmdGetMessage>(std::forward<_Args>(args)...);
  case CmdOp::GetVid:
    return Op::template Do<CmdGetVid>(std::forward<_Args>(args)...);
  case CmdOp::AddAgeCount:
    return Op::template Do<CmdAddAgeCount>(std::forward<_Args>(args)...);
  case CmdOp::SetAgeCount:
    return Op::template Do<CmdSetAgeCount>(std::forward<_Args>(args)...);
  case CmdOp::SendFlag:
    return Op::template Do<CmdSendFlag>(std::forward<_Args>(args)...);
  case CmdOp::PitchWheelR:
    return Op::template Do<CmdPitchWheelR>(std::forward<_Args>(args)...);
  case CmdOp::SetPriority:
    return Op::template Do<CmdSetPriority>(std::forward<_Args>(args)...);
  case CmdOp::AddPriority:
    return Op::template Do<CmdAddPriority>(std::forward<_Args>(args)...);
  case CmdOp::AgeCntSpeed:
    return Op::template Do<CmdAgeCntSpeed>(std::forward<_Args>(args)...);
  case CmdOp::AgeCntVel:
    return Op::template Do<CmdAgeCntVel>(std::forward<_Args>(args)...);
  case CmdOp::VolSelect:
    return Op::template Do<CmdVolSelect>(std::forward<_Args>(args)...);
  case CmdOp::PanSelect:
    return Op::template Do<CmdPanSelect>(std::forward<_Args>(args)...);
  case CmdOp::PitchWheelSelect:
    return Op::template Do<CmdPitchWheelSelect>(std::forward<_Args>(args)...);
  case CmdOp::ModWheelSelect:
    return Op::template Do<CmdModWheelSelect>(std::forward<_Args>(args)...);
  case CmdOp::PedalSelect:
    return Op::template Do<CmdPedalSelect>(std::forward<_Args>(args)...);
  case CmdOp::PortamentoSelect:
    return Op::template Do<CmdPortamentoSelect>(std::forward<_Args>(args)...);
  case CmdOp::ReverbSelect:
    return Op::template Do<CmdReverbSelect>(std::forward<_Args>(args)...);
  case CmdOp::SpanSelect:
    return Op::template Do<CmdSpanSelect>(std::forward<_Args>(args)...);
  case CmdOp::DopplerSelect:
    return Op::template Do<CmdDopplerSelect>(std::forward<_Args>(args)...);
  case CmdOp::TremoloSelect:
    return Op::template Do<CmdTremoloSelect>(std::forward<_Args>(args)...);
  case CmdOp::PreASelect:
    return Op::template Do<CmdPreASelect>(std::forward<_Args>(args)...);
  case CmdOp::PreBSelect:
    return Op::template Do<CmdPreBSelect>(std::forward<_Args>(args)...);
  case CmdOp::PostBSelect:
    return Op::template Do<CmdPostBSelect>(std::forward<_Args>(args)...);
  case CmdOp::AuxAFXSelect:
    return Op::template Do<CmdAuxAFXSelect>(std::forward<_Args>(args)...);
  case CmdOp::AuxBFXSelect:
    return Op::template Do<CmdAuxBFXSelect>(std::forward<_Args>(args)...);
  case CmdOp::SetupLFO:
    return Op::template Do<CmdSetupLFO>(std::forward<_Args>(args)...);
  case CmdOp::ModeSelect:
    return Op::template Do<CmdModeSelect>(std::forward<_Args>(args)...);
  case CmdOp::SetKeygroup:
    return Op::template Do<CmdSetKeygroup>(std::forward<_Args>(args)...);
  case CmdOp::SRCmodeSelect:
    return Op::template Do<CmdSRCmodeSelect>(std::forward<_Args>(args)...);
  case CmdOp::WiiUnknown:
    return Op::template Do<CmdWiiUnknown>(std::forward<_Args>(args)...);
  case CmdOp::WiiUnknown2:
    return Op::template Do<CmdWiiUnknown2>(std::forward<_Args>(args)...);
  case CmdOp::AddVars:
    return Op::template Do<CmdAddVars>(std::forward<_Args>(args)...);
  case CmdOp::SubVars:
    return Op::template Do<CmdSubVars>(std::forward<_Args>(args)...);
  case CmdOp::MulVars:
    return Op::template Do<CmdMulVars>(std::forward<_Args>(args)...);
  case CmdOp::DivVars:
    return Op::template Do<CmdDivVars>(std::forward<_Args>(args)...);
  case CmdOp::AddIVars:
    return Op::template Do<CmdAddIVars>(std::forward<_Args>(args)...);
  case CmdOp::SetVar:
    return Op::template Do<CmdSetVar>(std::forward<_Args>(args)...);
  case CmdOp::IfEqual:
    return Op::template Do<CmdIfEqual>(std::forward<_Args>(args)...);
  case CmdOp::IfLess:
    return Op::template Do<CmdIfLess>(std::forward<_Args>(args)...);
  default:
    return {};
  }
}
template std::unique_ptr<SoundMacro::ICmd> SoundMacro::CmdDo<MakeCmdOp>(athena::io::MemoryReader& r);
template std::unique_ptr<SoundMacro::ICmd> SoundMacro::CmdDo<MakeCmdOp>(athena::io::YAMLDocReader& r);
template std::unique_ptr<SoundMacro::ICmd> SoundMacro::CmdDo<MakeDefaultCmdOp>(SoundMacro::CmdOp& r);
template const SoundMacro::CmdIntrospection* SoundMacro::CmdDo<IntrospectCmdOp>(SoundMacro::CmdOp& op);

std::unique_ptr<SoundMacro::ICmd> SoundMacro::MakeCmd(CmdOp op) {
  return CmdDo<MakeDefaultCmdOp, std::unique_ptr<SoundMacro::ICmd>>(op);
}

const SoundMacro::CmdIntrospection* SoundMacro::GetCmdIntrospection(CmdOp op) {
  return CmdDo<IntrospectCmdOp, const SoundMacro::CmdIntrospection*>(op);
}

std::string_view SoundMacro::CmdOpToStr(CmdOp op) {
  switch (op) {
  case CmdOp::End:
    return "End"sv;
  case CmdOp::Stop:
    return "Stop"sv;
  case CmdOp::SplitKey:
    return "SplitKey"sv;
  case CmdOp::SplitVel:
    return "SplitVel"sv;
  case CmdOp::WaitTicks:
    return "WaitTicks"sv;
  case CmdOp::Loop:
    return "Loop"sv;
  case CmdOp::Goto:
    return "Goto"sv;
  case CmdOp::WaitMs:
    return "WaitMs"sv;
  case CmdOp::PlayMacro:
    return "PlayMacro"sv;
  case CmdOp::SendKeyOff:
    return "SendKeyOff"sv;
  case CmdOp::SplitMod:
    return "SplitMod"sv;
  case CmdOp::PianoPan:
    return "PianoPan"sv;
  case CmdOp::SetAdsr:
    return "SetAdsr"sv;
  case CmdOp::ScaleVolume:
    return "ScaleVolume"sv;
  case CmdOp::Panning:
    return "Panning"sv;
  case CmdOp::Envelope:
    return "Envelope"sv;
  case CmdOp::StartSample:
    return "StartSample"sv;
  case CmdOp::StopSample:
    return "StopSample"sv;
  case CmdOp::KeyOff:
    return "KeyOff"sv;
  case CmdOp::SplitRnd:
    return "SplitRnd"sv;
  case CmdOp::FadeIn:
    return "FadeIn"sv;
  case CmdOp::Spanning:
    return "Spanning"sv;
  case CmdOp::SetAdsrCtrl:
    return "SetAdsrCtrl"sv;
  case CmdOp::RndNote:
    return "RndNote"sv;
  case CmdOp::AddNote:
    return "AddNote"sv;
  case CmdOp::SetNote:
    return "SetNote"sv;
  case CmdOp::LastNote:
    return "LastNote"sv;
  case CmdOp::Portamento:
    return "Portamento"sv;
  case CmdOp::Vibrato:
    return "Vibrato"sv;
  case CmdOp::PitchSweep1:
    return "PitchSweep1"sv;
  case CmdOp::PitchSweep2:
    return "PitchSweep2"sv;
  case CmdOp::SetPitch:
    return "SetPitch"sv;
  case CmdOp::SetPitchAdsr:
    return "SetPitchAdsr"sv;
  case CmdOp::ScaleVolumeDLS:
    return "ScaleVolumeDLS"sv;
  case CmdOp::Mod2Vibrange:
    return "Mod2Vibrange"sv;
  case CmdOp::SetupTremolo:
    return "SetupTremolo"sv;
  case CmdOp::Return:
    return "Return"sv;
  case CmdOp::GoSub:
    return "GoSub"sv;
  case CmdOp::TrapEvent:
    return "TrapEvent"sv;
  case CmdOp::UntrapEvent:
    return "UntrapEvent"sv;
  case CmdOp::SendMessage:
    return "SendMessage"sv;
  case CmdOp::GetMessage:
    return "GetMessage"sv;
  case CmdOp::GetVid:
    return "GetVid"sv;
  case CmdOp::AddAgeCount:
    return "AddAgeCount"sv;
  case CmdOp::SetAgeCount:
    return "SetAgeCount"sv;
  case CmdOp::SendFlag:
    return "SendFlag"sv;
  case CmdOp::PitchWheelR:
    return "PitchWheelR"sv;
  case CmdOp::SetPriority:
    return "SetPriority"sv;
  case CmdOp::AddPriority:
    return "AddPriority"sv;
  case CmdOp::AgeCntSpeed:
    return "AgeCntSpeed"sv;
  case CmdOp::AgeCntVel:
    return "AgeCntVel"sv;
  case CmdOp::VolSelect:
    return "VolSelect"sv;
  case CmdOp::PanSelect:
    return "PanSelect"sv;
  case CmdOp::PitchWheelSelect:
    return "PitchWheelSelect"sv;
  case CmdOp::ModWheelSelect:
    return "ModWheelSelect"sv;
  case CmdOp::PedalSelect:
    return "PedalSelect"sv;
  case CmdOp::PortamentoSelect:
    return "PortamentoSelect"sv;
  case CmdOp::ReverbSelect:
    return "ReverbSelect"sv;
  case CmdOp::SpanSelect:
    return "SpanSelect"sv;
  case CmdOp::DopplerSelect:
    return "DopplerSelect"sv;
  case CmdOp::TremoloSelect:
    return "TremoloSelect"sv;
  case CmdOp::PreASelect:
    return "PreASelect"sv;
  case CmdOp::PreBSelect:
    return "PreBSelect"sv;
  case CmdOp::PostBSelect:
    return "PostBSelect"sv;
  case CmdOp::AuxAFXSelect:
    return "AuxAFXSelect"sv;
  case CmdOp::AuxBFXSelect:
    return "AuxBFXSelect"sv;
  case CmdOp::SetupLFO:
    return "SetupLFO"sv;
  case CmdOp::ModeSelect:
    return "ModeSelect"sv;
  case CmdOp::SetKeygroup:
    return "SetKeygroup"sv;
  case CmdOp::SRCmodeSelect:
    return "SRCmodeSelect"sv;
  case CmdOp::WiiUnknown:
    return "WiiUnknown"sv;
  case CmdOp::WiiUnknown2:
    return "WiiUnknown2"sv;
  case CmdOp::AddVars:
    return "AddVars"sv;
  case CmdOp::SubVars:
    return "SubVars"sv;
  case CmdOp::MulVars:
    return "MulVars"sv;
  case CmdOp::DivVars:
    return "DivVars"sv;
  case CmdOp::AddIVars:
    return "AddIVars"sv;
  case CmdOp::SetVar:
    return "SetVar"sv;
  case CmdOp::IfEqual:
    return "IfEqual"sv;
  case CmdOp::IfLess:
    return "IfLess"sv;
  default:
    return ""sv;
  }
}

SoundMacro::CmdOp SoundMacro::CmdStrToOp(std::string_view op) {
  if (!CompareCaseInsensitive(op.data(), "End"))
    return CmdOp::End;
  else if (!CompareCaseInsensitive(op.data(), "Stop"))
    return CmdOp::Stop;
  else if (!CompareCaseInsensitive(op.data(), "SplitKey"))
    return CmdOp::SplitKey;
  else if (!CompareCaseInsensitive(op.data(), "SplitVel"))
    return CmdOp::SplitVel;
  else if (!CompareCaseInsensitive(op.data(), "WaitTicks"))
    return CmdOp::WaitTicks;
  else if (!CompareCaseInsensitive(op.data(), "Loop"))
    return CmdOp::Loop;
  else if (!CompareCaseInsensitive(op.data(), "Goto"))
    return CmdOp::Goto;
  else if (!CompareCaseInsensitive(op.data(), "WaitMs"))
    return CmdOp::WaitMs;
  else if (!CompareCaseInsensitive(op.data(), "PlayMacro"))
    return CmdOp::PlayMacro;
  else if (!CompareCaseInsensitive(op.data(), "SendKeyOff"))
    return CmdOp::SendKeyOff;
  else if (!CompareCaseInsensitive(op.data(), "SplitMod"))
    return CmdOp::SplitMod;
  else if (!CompareCaseInsensitive(op.data(), "PianoPan"))
    return CmdOp::PianoPan;
  else if (!CompareCaseInsensitive(op.data(), "SetAdsr"))
    return CmdOp::SetAdsr;
  else if (!CompareCaseInsensitive(op.data(), "ScaleVolume"))
    return CmdOp::ScaleVolume;
  else if (!CompareCaseInsensitive(op.data(), "Panning"))
    return CmdOp::Panning;
  else if (!CompareCaseInsensitive(op.data(), "Envelope"))
    return CmdOp::Envelope;
  else if (!CompareCaseInsensitive(op.data(), "StartSample"))
    return CmdOp::StartSample;
  else if (!CompareCaseInsensitive(op.data(), "StopSample"))
    return CmdOp::StopSample;
  else if (!CompareCaseInsensitive(op.data(), "KeyOff"))
    return CmdOp::KeyOff;
  else if (!CompareCaseInsensitive(op.data(), "SplitRnd"))
    return CmdOp::SplitRnd;
  else if (!CompareCaseInsensitive(op.data(), "FadeIn"))
    return CmdOp::FadeIn;
  else if (!CompareCaseInsensitive(op.data(), "Spanning"))
    return CmdOp::Spanning;
  else if (!CompareCaseInsensitive(op.data(), "SetAdsrCtrl"))
    return CmdOp::SetAdsrCtrl;
  else if (!CompareCaseInsensitive(op.data(), "RndNote"))
    return CmdOp::RndNote;
  else if (!CompareCaseInsensitive(op.data(), "AddNote"))
    return CmdOp::AddNote;
  else if (!CompareCaseInsensitive(op.data(), "SetNote"))
    return CmdOp::SetNote;
  else if (!CompareCaseInsensitive(op.data(), "LastNote"))
    return CmdOp::LastNote;
  else if (!CompareCaseInsensitive(op.data(), "Portamento"))
    return CmdOp::Portamento;
  else if (!CompareCaseInsensitive(op.data(), "Vibrato"))
    return CmdOp::Vibrato;
  else if (!CompareCaseInsensitive(op.data(), "PitchSweep1"))
    return CmdOp::PitchSweep1;
  else if (!CompareCaseInsensitive(op.data(), "PitchSweep2"))
    return CmdOp::PitchSweep2;
  else if (!CompareCaseInsensitive(op.data(), "SetPitch"))
    return CmdOp::SetPitch;
  else if (!CompareCaseInsensitive(op.data(), "SetPitchAdsr"))
    return CmdOp::SetPitchAdsr;
  else if (!CompareCaseInsensitive(op.data(), "ScaleVolumeDLS"))
    return CmdOp::ScaleVolumeDLS;
  else if (!CompareCaseInsensitive(op.data(), "Mod2Vibrange"))
    return CmdOp::Mod2Vibrange;
  else if (!CompareCaseInsensitive(op.data(), "SetupTremolo"))
    return CmdOp::SetupTremolo;
  else if (!CompareCaseInsensitive(op.data(), "Return"))
    return CmdOp::Return;
  else if (!CompareCaseInsensitive(op.data(), "GoSub"))
    return CmdOp::GoSub;
  else if (!CompareCaseInsensitive(op.data(), "TrapEvent"))
    return CmdOp::TrapEvent;
  else if (!CompareCaseInsensitive(op.data(), "UntrapEvent"))
    return CmdOp::UntrapEvent;
  else if (!CompareCaseInsensitive(op.data(), "SendMessage"))
    return CmdOp::SendMessage;
  else if (!CompareCaseInsensitive(op.data(), "GetMessage"))
    return CmdOp::GetMessage;
  else if (!CompareCaseInsensitive(op.data(), "GetVid"))
    return CmdOp::GetVid;
  else if (!CompareCaseInsensitive(op.data(), "AddAgeCount"))
    return CmdOp::AddAgeCount;
  else if (!CompareCaseInsensitive(op.data(), "SetAgeCount"))
    return CmdOp::SetAgeCount;
  else if (!CompareCaseInsensitive(op.data(), "SendFlag"))
    return CmdOp::SendFlag;
  else if (!CompareCaseInsensitive(op.data(), "PitchWheelR"))
    return CmdOp::PitchWheelR;
  else if (!CompareCaseInsensitive(op.data(), "SetPriority"))
    return CmdOp::SetPriority;
  else if (!CompareCaseInsensitive(op.data(), "AddPriority"))
    return CmdOp::AddPriority;
  else if (!CompareCaseInsensitive(op.data(), "AgeCntSpeed"))
    return CmdOp::AgeCntSpeed;
  else if (!CompareCaseInsensitive(op.data(), "AgeCntVel"))
    return CmdOp::AgeCntVel;
  else if (!CompareCaseInsensitive(op.data(), "VolSelect"))
    return CmdOp::VolSelect;
  else if (!CompareCaseInsensitive(op.data(), "PanSelect"))
    return CmdOp::PanSelect;
  else if (!CompareCaseInsensitive(op.data(), "PitchWheelSelect"))
    return CmdOp::PitchWheelSelect;
  else if (!CompareCaseInsensitive(op.data(), "ModWheelSelect"))
    return CmdOp::ModWheelSelect;
  else if (!CompareCaseInsensitive(op.data(), "PedalSelect"))
    return CmdOp::PedalSelect;
  else if (!CompareCaseInsensitive(op.data(), "PortamentoSelect"))
    return CmdOp::PortamentoSelect;
  else if (!CompareCaseInsensitive(op.data(), "ReverbSelect"))
    return CmdOp::ReverbSelect;
  else if (!CompareCaseInsensitive(op.data(), "SpanSelect"))
    return CmdOp::SpanSelect;
  else if (!CompareCaseInsensitive(op.data(), "DopplerSelect"))
    return CmdOp::DopplerSelect;
  else if (!CompareCaseInsensitive(op.data(), "TremoloSelect"))
    return CmdOp::TremoloSelect;
  else if (!CompareCaseInsensitive(op.data(), "PreASelect"))
    return CmdOp::PreASelect;
  else if (!CompareCaseInsensitive(op.data(), "PreBSelect"))
    return CmdOp::PreBSelect;
  else if (!CompareCaseInsensitive(op.data(), "PostBSelect"))
    return CmdOp::PostBSelect;
  else if (!CompareCaseInsensitive(op.data(), "AuxAFXSelect"))
    return CmdOp::AuxAFXSelect;
  else if (!CompareCaseInsensitive(op.data(), "AuxBFXSelect"))
    return CmdOp::AuxBFXSelect;
  else if (!CompareCaseInsensitive(op.data(), "SetupLFO"))
    return CmdOp::SetupLFO;
  else if (!CompareCaseInsensitive(op.data(), "ModeSelect"))
    return CmdOp::ModeSelect;
  else if (!CompareCaseInsensitive(op.data(), "SetKeygroup"))
    return CmdOp::SetKeygroup;
  else if (!CompareCaseInsensitive(op.data(), "SRCmodeSelect"))
    return CmdOp::SRCmodeSelect;
  else if (!CompareCaseInsensitive(op.data(), "WiiUnknown"))
    return CmdOp::WiiUnknown;
  else if (!CompareCaseInsensitive(op.data(), "WiiUnknown2"))
    return CmdOp::WiiUnknown2;
  else if (!CompareCaseInsensitive(op.data(), "AddVars"))
    return CmdOp::AddVars;
  else if (!CompareCaseInsensitive(op.data(), "SubVars"))
    return CmdOp::SubVars;
  else if (!CompareCaseInsensitive(op.data(), "MulVars"))
    return CmdOp::MulVars;
  else if (!CompareCaseInsensitive(op.data(), "DivVars"))
    return CmdOp::DivVars;
  else if (!CompareCaseInsensitive(op.data(), "AddIVars"))
    return CmdOp::AddIVars;
  else if (!CompareCaseInsensitive(op.data(), "SetVar"))
    return CmdOp::SetVar;
  else if (!CompareCaseInsensitive(op.data(), "IfEqual"))
    return CmdOp::IfEqual;
  else if (!CompareCaseInsensitive(op.data(), "IfLess"))
    return CmdOp::IfLess;
  return CmdOp::Invalid;
}

std::vector<uint8_t> AudioGroupPool::toYAML() const {
  athena::io::YAMLDocWriter w("amuse::Pool");

  if (!m_soundMacros.empty()) {
    if (auto __r = w.enterSubRecord("soundMacros")) {
      for (const auto& p : SortUnorderedMap(m_soundMacros)) {
        if (auto __v = w.enterSubVector(SoundMacroId::CurNameDB->resolveNameFromId(p.first))) {
          p.second.get()->toYAML(w);
        }
      }
    }
  }

  if (!m_tables.empty()) {
    if (auto __r = w.enterSubRecord("tables")) {
      for (const auto& p : SortUnorderedMap(m_tables)) {
        if (auto __v = w.enterSubRecord(TableId::CurNameDB->resolveNameFromId(p.first))) {
          w.setStyle(athena::io::YAMLNodeStyle::Flow);
          (*p.second.get())->write(w);
        }
      }
    }
  }

  if (!m_keymaps.empty()) {
    if (auto __r = w.enterSubRecord("keymaps")) {
      for (const auto& p : SortUnorderedMap(m_keymaps)) {
        if (auto __v = w.enterSubVector(KeymapId::CurNameDB->resolveNameFromId(p.first))) {
          for (const auto& km : *p.second.get()) {
            if (auto __r2 = w.enterSubRecord()) {
              w.setStyle(athena::io::YAMLNodeStyle::Flow);
              km.write(w);
            }
          }
        }
      }
    }
  }

  if (!m_layers.empty()) {
    if (auto __r = w.enterSubRecord("layers")) {
      for (const auto& p : SortUnorderedMap(m_layers)) {
        if (auto __v = w.enterSubVector(LayersId::CurNameDB->resolveNameFromId(p.first))) {
          for (const auto& lm : *p.second.get()) {
            if (auto __r2 = w.enterSubRecord()) {
              w.setStyle(athena::io::YAMLNodeStyle::Flow);
              lm.write(w);
            }
          }
        }
      }
    }
  }

  athena::io::VectorWriter fo;
  w.finish(&fo);
  return fo.data();
}

template <athena::Endian DNAE>
std::vector<uint8_t> AudioGroupPool::toData() const {
  athena::io::VectorWriter fo;

  PoolHeader<DNAE> head = {};
  head.write(fo);

  const uint32_t term = 0xffffffff;

  if (!m_soundMacros.empty()) {
    head.soundMacrosOffset = fo.position();
    for (const auto& p : m_soundMacros) {
      auto startPos = fo.position();
      ObjectHeader<DNAE> objHead = {};
      objHead.write(fo);
      p.second->template writeCmds<DNAE>(fo);
      objHead.size = fo.position() - startPos;
      objHead.objectId = p.first;
      fo.seek(startPos, athena::SeekOrigin::Begin);
      objHead.write(fo);
      fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
    athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo);
  }

  if (!m_tables.empty()) {
    head.tablesOffset = fo.position();
    for (const auto& p : m_tables) {
      auto startPos = fo.position();
      ObjectHeader<DNAE> objHead = {};
      objHead.write(fo);
      switch ((*p.second)->Isa()) {
      case ITable::Type::ADSR:
        static_cast<ADSR*>(p.second->get())->write(fo);
        break;
      case ITable::Type::ADSRDLS:
        static_cast<ADSRDLS*>(p.second->get())->write(fo);
        break;
      case ITable::Type::Curve: {
        const auto& data = static_cast<Curve*>(p.second->get())->data;
        fo.writeUBytes(data.data(), data.size());
        break;
      }
      default:
        break;
      }
      objHead.size = fo.position() - startPos;
      objHead.objectId = p.first;
      fo.seek(startPos, athena::SeekOrigin::Begin);
      objHead.write(fo);
      fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
    athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo);
  }

  if (!m_keymaps.empty()) {
    head.keymapsOffset = fo.position();
    for (const auto& p : m_keymaps) {
      auto startPos = fo.position();
      ObjectHeader<DNAE> objHead = {};
      objHead.write(fo);
      for (const auto& km : *p.second) {
        KeymapDNA<DNAE> kmData = km.toDNA<DNAE>();
        kmData.write(fo);
      }
      objHead.size = fo.position() - startPos;
      objHead.objectId = p.first;
      fo.seek(startPos, athena::SeekOrigin::Begin);
      objHead.write(fo);
      fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
    athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo);
  }

  if (!m_layers.empty()) {
    head.layersOffset = fo.position();
    for (const auto& p : m_layers) {
      auto startPos = fo.position();
      ObjectHeader<DNAE> objHead = {};
      objHead.write(fo);
      uint32_t count = p.second->size();
      athena::io::Write<athena::io::PropType::None>::Do<decltype(count), DNAE>({}, count, fo);
      for (const auto& lm : *p.second) {
        LayerMappingDNA<DNAE> lmData = lm.toDNA<DNAE>();
        lmData.write(fo);
      }
      objHead.size = fo.position() - startPos;
      objHead.objectId = p.first;
      fo.seek(startPos, athena::SeekOrigin::Begin);
      objHead.write(fo);
      fo.seek(startPos + objHead.size, athena::SeekOrigin::Begin);
    }
    athena::io::Write<athena::io::PropType::None>::Do<decltype(term), DNAE>({}, term, fo);
  }

  fo.seek(0, athena::SeekOrigin::Begin);
  head.write(fo);

  return fo.data();
}
template std::vector<uint8_t> AudioGroupPool::toData<athena::Endian::Big>() const;
template std::vector<uint8_t> AudioGroupPool::toData<athena::Endian::Little>() const;

template <>
void amuse::Curve::Enumerate<LittleDNA::Read>(athena::io::IStreamReader& r) {
  Log.report(logvisor::Fatal, FMT_STRING("Curve binary DNA read not supported"));
}

template <>
void amuse::Curve::Enumerate<LittleDNA::Write>(athena::io::IStreamWriter& w) {
  Log.report(logvisor::Fatal, FMT_STRING("Curve binary DNA write not supported"));
}

template <>
void amuse::Curve::Enumerate<LittleDNA::BinarySize>(size_t& sz) {
  Log.report(logvisor::Fatal, FMT_STRING("Curve binary DNA size not supported"));
}

template <>
void amuse::Curve::Enumerate<LittleDNA::ReadYaml>(athena::io::YAMLDocReader& r) {
  r.enumerate("data", data);
}

template <>
void amuse::Curve::Enumerate<LittleDNA::WriteYaml>(athena::io::YAMLDocWriter& w) {
  w.enumerate("data", data);
}

std::string_view amuse::Curve::DNAType() { return "amuse::Curve"sv; }

} // namespace amuse


text:
namespace ceres {
namespace internal {

// This is an abstract base class for linear operators. It supports
// access to size information and left and right multiply operators.
class LinearOperator {
 public:
  virtual ~LinearOperator();

  // y = y + Ax;
  virtual void RightMultiply(const double* x, double* y) const = 0;
  // y = y + A'x;
  virtual void LeftMultiply(const double* x, double* y) const = 0;

  virtual int num_rows() const = 0;
  virtual int num_cols() const = 0;
};

}  // namespace internal
}  // namespace ceres

#endif  // CERES_INTERNAL_LINEAR_OPERATOR_H_

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices.ComTypes;

namespace Roslyn.Utilities
{
    internal sealed class ComStreamWrapper : IStream
    {
        private readonly Stream _stream;

        public ComStreamWrapper(Stream stream)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream.CanSeek);

            _stream = stream;
        }

        public void Commit(int grfCommitFlags)
        {
            _stream.Flush();
        }

        /// <summary>
        /// The actual number of bytes read can be fewer than the number of bytes requested
        /// if an error occurs or if the end of the stream is reached during the read operation.
        /// </summary>
        public unsafe void Read(byte[] pv, int cb, IntPtr pcbRead)
        {
            int bytesRead = _stream.TryReadAll(pv, 0, cb);

            if (pcbRead != IntPtr.Zero)
            {
                *(int*)pcbRead = bytesRead;
            }
        }

        public unsafe void Seek(long dlibMove, int origin, IntPtr plibNewPosition)
        {
            long newPosition = _stream.Seek(dlibMove, (SeekOrigin)origin);
            if (plibNewPosition != IntPtr.Zero)
            {
                *(long*)plibNewPosition = newPosition;
            }
        }

        public void SetSize(long libNewSize)
        {
            _stream.SetLength(libNewSize);
        }

        public void Stat(out STATSTG pstatstg, int grfStatFlag)
        {
            pstatstg = new STATSTG()
            {
                cbSize = _stream.Length
            };
        }

        public unsafe void Write(byte[] pv, int cb, IntPtr pcbWritten)
        {
            _stream.Write(pv, 0, cb);
            if (pcbWritten != IntPtr.Zero)
            {
                *(int*)pcbWritten = cb;
            }
        }

        public void Clone(out IStream ppstm)
        {
            throw new NotSupportedException();
        }

        public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
        {
            throw new NotSupportedException();
        }

        public void LockRegion(long libOffset, long cb, int lockType)
        {
            throw new NotSupportedException();
        }

        public void Revert()
        {
            throw new NotSupportedException();
        }

        public void UnlockRegion(long libOffset, long cb, int lockType)
        {
            throw new NotSupportedException();
        }
    }
}


text:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<META NAME="Generator" CONTENT="Microsoft Word 97">
<TITLE>FeaturesSysMan</TITLE>
<META NAME="Template" CONTENT="C:\Program Files\MSOffice\Office\html.dot">

System management issues

The are a number of important issues related to the run time management of the control system.

What follows are some important points:

The whole control system must be started/stopped from a centralized procedure[RD01 - 5.1.2 Procedures]. This must be able to:
<DIR>
<DIR>

Start/stop processes in a predefined order and handling dependencies between processes

Verify the health of the system after startup/shutdown
</DIR>
</DIR>

During run-time a management application must monitor the system:
<DIR>
<DIR>

Detect terminating processes (and eventually restart them automatically) and notify other interested processes of the fact

Identify locked processes

Identify lack of resources
</DIR>
</DIR>

The mechanism used by the ESO Common Software is very well tested and satisfies all requirements (see next paragraph).

Alternatively an implementation of another environment for network and distributed system management can be investigated (some alternatives for the implementation of these concepts are: SNMP, Unicenter TNG [RD20] or Tivoli [RD21]).

Management of the control system should be possible without requiring root access.


text:
typedef struct NGraph {
	char* NMatrix;
	char* symbols;
} NGraph;

NGraph* newNGraph(int i, char k);
void freeNGraph(NGraph* ng);
void printNGraph(NGraph* ng, int i);
NGraph* BFS(graph_t* inputGraph, vsize_t vroot, vsize_t R, char valence);
void BFSInfo(graph_t* inputGraph, vsize_t vroot, vsize_t R, char valence, ProgInfo* prgInfo, int* tab);

#endif


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Geraniums 2. 1805

#### Original name
null

### Remarks
null


text:
Bad request

The server cannot process the request due to an apparent client error. Check the request syntax.

<?php
echo $this->exception->getMessage();
?>


text:
/*
    This file is part of cpp-ethereum.

    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Solidity parser.
 */

#pragma once

#include "libsolidity/ast/AST.h"

namespace dev
{
namespace solidity
{

class Scanner;

class Parser
{
public:
	Parser(ErrorList& errors): m_errors(errors){};

	ASTPointer<SourceUnit> parse(std::shared_ptr<Scanner> const& _scanner);
	std::shared_ptr<std::string const> const& sourceName() const;

private:
	class ASTNodeFactory;

	/// Start position of the current token
	int position() const;
	/// End position of the current token
	int endPosition() const;

	struct VarDeclParserOptions
	{
		VarDeclParserOptions() {}
		bool allowVar = false;
		bool isStateVariable = false;
		bool allowIndexed = false;
		bool allowEmptyName = false;
		bool allowInitialValue = false;
		bool allowLocationSpecifier = false;
	};

	///@{
	///@name Parsing functions for the AST nodes
	ASTPointer<ImportDirective> parseImportDirective();
	ASTPointer<ContractDefinition> parseContractDefinition(bool _isLibrary);
	ASTPointer<InheritanceSpecifier> parseInheritanceSpecifier();
	Declaration::Visibility parseVisibilitySpecifier(Token::Value _token);
	ASTPointer<FunctionDefinition> parseFunctionDefinition(ASTString const* _contractName);
	ASTPointer<StructDefinition> parseStructDefinition();
	ASTPointer<EnumDefinition> parseEnumDefinition();
	ASTPointer<EnumValue> parseEnumValue();
	ASTPointer<VariableDeclaration> parseVariableDeclaration(
		VarDeclParserOptions const& _options = VarDeclParserOptions(),
		ASTPointer<TypeName> const& _lookAheadArrayType = ASTPointer<TypeName>()
	);
	ASTPointer<ModifierDefinition> parseModifierDefinition();
	ASTPointer<EventDefinition> parseEventDefinition();
	ASTPointer<UsingForDirective> parseUsingDirective();
	ASTPointer<ModifierInvocation> parseModifierInvocation();
	ASTPointer<Identifier> parseIdentifier();
	ASTPointer<TypeName> parseTypeName(bool _allowVar);
	ASTPointer<Mapping> parseMapping();
	ASTPointer<ParameterList> parseParameterList(
		VarDeclParserOptions const& _options,
		bool _allowEmpty = true
	);
	ASTPointer<Block> parseBlock(ASTPointer<ASTString> const& _docString = {});
	ASTPointer<Statement> parseStatement();
	ASTPointer<IfStatement> parseIfStatement(ASTPointer<ASTString> const& _docString);
	ASTPointer<WhileStatement> parseWhileStatement(ASTPointer<ASTString> const& _docString);
	ASTPointer<ForStatement> parseForStatement(ASTPointer<ASTString> const& _docString);
	/// A "simple statement" can be a variable declaration statement or an expression statement.
	ASTPointer<Statement> parseSimpleStatement(ASTPointer<ASTString> const& _docString);
	ASTPointer<VariableDeclarationStatement> parseVariableDeclarationStatement(
		ASTPointer<ASTString> const& _docString,
		ASTPointer<TypeName> const& _lookAheadArrayType = ASTPointer<TypeName>()
	);
	ASTPointer<ExpressionStatement> parseExpressionStatement(
		ASTPointer<ASTString> const& _docString,
		ASTPointer<Expression> const& _lookAheadIndexAccessStructure = ASTPointer<Expression>()
	);
	ASTPointer<Expression> parseExpression(
		ASTPointer<Expression> const& _lookAheadIndexAccessStructure = ASTPointer<Expression>()
	);
	ASTPointer<Expression> parseBinaryExpression(int _minPrecedence = 4,
		ASTPointer<Expression> const& _lookAheadIndexAccessStructure = ASTPointer<Expression>()
	);
	ASTPointer<Expression> parseUnaryExpression(
		ASTPointer<Expression> const& _lookAheadIndexAccessStructure = ASTPointer<Expression>()
	);
	ASTPointer<Expression> parseLeftHandSideExpression(
		ASTPointer<Expression> const& _lookAheadIndexAccessStructure = ASTPointer<Expression>()
	);
	ASTPointer<Expression> parsePrimaryExpression();
	std::vector<ASTPointer<Expression>> parseFunctionCallListArguments();
	std::pair<std::vector<ASTPointer<Expression>>, std::vector<ASTPointer<ASTString>>> parseFunctionCallArguments();
	///@}

	///@{
	///@name Helper functions

	/// Used as return value of @see peekStatementType.
	enum class LookAheadInfo
	{
		IndexAccessStructure, VariableDeclarationStatement, ExpressionStatement
	};

	/// Performs limited look-ahead to distinguish between variable declaration and expression statement.
	/// For source code of the form "a[][8]" ("IndexAccessStructure"), this is not possible to
	/// decide with constant look-ahead.
	LookAheadInfo peekStatementType() const;
	/// Returns a typename parsed in look-ahead fashion from something like "a.b[8][2**70]".
	ASTPointer<TypeName> typeNameIndexAccessStructure(
		std::vector<ASTPointer<PrimaryExpression>> const& _path,
		std::vector<std::pair<ASTPointer<Expression>, SourceLocation>> const& _indices
	);
	/// Returns an expression parsed in look-ahead fashion from something like "a.b[8][2**70]".
	ASTPointer<Expression> expressionFromIndexAccessStructure(
		std::vector<ASTPointer<PrimaryExpression>> const& _path,
		std::vector<std::pair<ASTPointer<Expression>, SourceLocation>> const& _indices
	);
	/// If current token value is not _value, throw exception otherwise advance token.
	void expectToken(Token::Value _value);
	Token::Value expectAssignmentOperator();
	ASTPointer<ASTString> expectIdentifierToken();
	ASTPointer<ASTString> getLiteralAndAdvance();
	///@}

	/// Creates an empty ParameterList at the current location (used if parameters can be omitted).
	ASTPointer<ParameterList> createEmptyParameterList();

	/// Creates a @ref ParserError and annotates it with the current position and the
	/// given @a _description.
	void parserError(std::string const& _description);

	/// Creates a @ref ParserError and annotates it with the current position and the
	/// given @a _description. Throws the FatalError.
	void fatalParserError(std::string const& _description);

	std::shared_ptr<Scanner> m_scanner;
	/// Flag that signifies whether '_' is parsed as a PlaceholderStatement or a regular identifier.
	bool m_insideModifier = false;
	/// The reference to the list of errors and warning to add errors/warnings during parsing
	ErrorList& m_errors;
};

}
}


text:
:mod:`library`
==============

.. automodule:: library


text:
package engine.dialogue;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import engine.gridobject.GridObject;
import engine.gridobject.person.NPC;
import engine.gridobject.person.Person;
import engine.gridobject.person.Player;
import engine.images.ScaledImage;
import engine.state.WalkAroundState;

/**
 * A class that handles the flow of a conversation, dealing with who is responding and what to do in the
 * backend in order to provide the correct information to print to the screen.
 *
 */
public class ConversationManager extends AbstractManager implements InteractionBox {

	private NPCResponseNode currentResponseNode;
	private UserQueryNode currentUserQueryNode;
	private String textToBeDisplayed;
	private int widthOfText;
	private Player myPlayer;
	private GridObject myNPC;
	private static boolean responding = true;
	private int selectedOptionX;
	private int selectedOptionY;
	private static final int X_OFFSET = 5/10;
	private static final int Y_OFFSET = 3/10;
	private static final int SYMBOL_RADIUS = 10;
	private ConversationState myCurrentState;

	/**
	 * Creates new manager
	 * @param p Player
	 * @param n a grid object
	 * @param nrNode the first NPCResponse node to be used
	 */
	public ConversationManager(Player p, GridObject n, NPCResponseNode nrNode) {
		super();
		currentResponseNode = nrNode;
		textToBeDisplayed = currentResponseNode.getDialogue();
		myPlayer = p;
		myPlayer.addItem(currentResponseNode.getItem());
		myNPC = n;
		responding = false;
		myCurrentState = new ListeningState();
	}

	@Override
	public void getNextText() {
		myCurrentState.doState(this);

	}

	public Player getPlayer() {
		return myPlayer;
	}

	@Override
	public void setCurrentNode() {
		currentUserQueryNode = (UserQueryNode) getMatrix().getCurrentNode();
	}

	public void setCurrentNPCResponseNode(NPCResponseNode n) {
		currentResponseNode = n;
	}

	public NPCResponseNode getCurrentNPCResponseNode() {
		return currentResponseNode;
	}

	public UserQueryNode getCurrentUserQueryNode() {
		return currentUserQueryNode;
	}

	@Override
	public boolean isResponding() {
		return responding;
	}

	public void setResponding(boolean b) {
		responding = b;
	}

	@Override
	public String getTextToBeDisplayed() {
		return textToBeDisplayed;
	}

	public void setTextToBeDisplayed(String text) {
		textToBeDisplayed = text;
	}

	public void setCurrentState(ConversationState state) {
		myCurrentState = state;
	}

	public void setCurrentUserQueryNode(UserQueryNode currentNode) {
		currentUserQueryNode =  currentNode;
	}

}


text:
from django.apps import AppConfig

class MangacacheConfig(AppConfig):
    name = 'mangacache'


text:
</title>

</title>


text:
import pytest
from backports.ssl_match_hostname import CertificateError

@pytest.mark.parametrize("subdomain,should_redirect_to_https", [
    (1, True),
    (2, True),
    (3, False),
])
def test_http_redirects_to_https(docker_compose, nginxproxy, subdomain, should_redirect_to_https):
    r = nginxproxy.get("http://%s.web.nginx-proxy.tld/port" % subdomain)
    if should_redirect_to_https:
        assert r.history[0].is_redirect
        assert r.history[0].headers.get("Location") == "https://%s.web.nginx-proxy.tld/port" % subdomain
    assert "answer from port 8%s\n" % subdomain == r.text

@pytest.mark.parametrize("subdomain", [1, 2])
def test_https_get_served(docker_compose, nginxproxy, subdomain):
    r = nginxproxy.get("https://%s.web.nginx-proxy.tld/port" % subdomain, allow_redirects=False)
    assert r.status_code == 200
    assert "answer from port 8%s\n" % subdomain == r.text

def test_web3_https_is_500_and_SSL_validation_fails(docker_compose, nginxproxy):
    with pytest.raises(CertificateError) as excinfo:
        nginxproxy.get("https://3.web.nginx-proxy.tld/port")
    assert """hostname '3.web.nginx-proxy.tld' doesn't match 'nginx-proxy.tld'""" in str(excinfo.value)

    r = nginxproxy.get("https://3.web.nginx-proxy.tld/port", verify=False)
    assert r.status_code == 500


text:
package io.cattle.platform.allocator.service;

import io.cattle.platform.allocator.constraint.Constraint;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.lock.definition.LockDefinition;

import java.util.List;
import java.util.Map;

public interface AllocationHelper {

    /**
     * This address various usability issues allowing users to provide shorthand versions of the service
     * name
     */
    void normalizeLabels(long stackId, Map<String, String> systemLabels, Map<String, String> serviceUserLabels);

    List<Long> getHostsSatisfyingHostAffinity(Long accountId, Map<String, String> labelConstraints);

    @SuppressWarnings("rawtypes")
    List<Constraint> extractConstraintsFromEnv(Map env);

    @SuppressWarnings("rawtypes")
    List<Constraint> extractConstraintsFromLabels(Map labels, Instance instance);

    List<Long> getAllHostsSatisfyingHostAffinity(Long accountId, Map<String, String> labelConstraints);

    List<LockDefinition> extractAllocationLockDefinitions(Instance instance, List<Instance> instances);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MCTuristic_Centro_Historico.GUI
{
    public partial class GestionServicios : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions;

import com.intellij.lang.ASTNode;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiElementImpl;

/**
 * @author ven
 */
public abstract class GrCallImpl extends GroovyPsiElementImpl implements GrCall {
  public GrCallImpl(@NotNull ASTNode node) {
    super(node);
  }

  public GrArgumentList getArgumentList() {
    return findChildByClass(GrArgumentList.class);
  }

  public GrNamedArgument[] getNamedArguments() {
    GrArgumentList argList = getArgumentList();
    return argList != null ? argList.getNamedArguments() : GrNamedArgument.EMPTY_ARRAY;
  }

  public GrExpression[] getExpressionArguments() {
    GrArgumentList argList = getArgumentList();
    return argList != null ? argList.getExpressionArguments() : GrExpression.EMPTY_ARRAY;
  }

  public GrExpression removeArgument(int number) {
    final GrArgumentList list = getArgumentList();
    if (list == null) return null;
    final int exprLength = list.getExpressionArguments().length;
    if (exprLength > number) {
      return list.removeArgument(number);
    }

    return null;
  }

  public GrNamedArgument addNamedArgument(final GrNamedArgument namedArgument) throws IncorrectOperationException {
    GrArgumentList list = getArgumentList();
    assert list != null;
    if (list.getText().trim().length() == 0) {
      final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject());
      final GrArgumentList newList = factory.createExpressionArgumentList();
      list = (GrArgumentList)list.replace(newList);
    }
    return list.addNamedArgument(namedArgument);
  }

  @NotNull
  @Override
  public GrClosableBlock[] getClosureArguments() {
    return GrClosableBlock.EMPTY_ARRAY;
  }
}


text:
<!doctype html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


text:
require('babel-register')({
    presets: ['env']
});

require('jsdom-global/register');

const   _ = require('../../utils.js').default;

module.exports = {
    makeElementFocusable(test) {
        document.body.innerHTML = '

';

        const element = document.querySelector('div');

        // ---------------

        _.makeElementFocusable(element);

        // ---------------

        test.equal(element.tabIndex, 0, 'It should set the tabIndex attribute to zero.');

        test.doesNotThrow(() => {
            _.makeElementFocusable(null);
            _.makeElementFocusable(undefined);
        });

        test.done();
    },

    makeElementsFocusable(test) {
        document.body.innerHTML =
                `

`;

        const elements = document.querySelectorAll('div');

        // ---------------

        _.makeElementsFocusable(elements);

        // ---------------

        [].forEach.call(elements, (element) => {
            test.equal(element.tabIndex, 0, 'It should set the tabIndex attribute of all selected elements to zero.');
        });

        test.doesNotThrow(() => {
            _.makeElementsFocusable(null);
            _.makeElementsFocusable(undefined);
        });

        test.done();
    },

    makeElementNotFocusable(test) {
        document.body.innerHTML = '

';

        const element = document.querySelector('div');

        // ---------------

        _.makeElementNotFocusable(element);

        // ---------------

        test.equal(element.tabIndex, -1, 'It should set the tabIndex attribute to -1.');

        test.doesNotThrow(() => {
            _.makeElementNotFocusable(null);
            _.makeElementNotFocusable(undefined);
        });

        test.done();
    },

    makeElementsNotFocusable(test) {
        document.body.innerHTML =
                `

`;

        const elements = document.querySelectorAll('div');

        // ---------------

        _.makeElementsNotFocusable(elements);

        // ---------------

        [].forEach.call(elements, (element) => {
            test.equal(element.tabIndex, -1, 'It should set the tabIndex attribute of all selected elements to -1.');
        });

        test.doesNotThrow(() => {
            _.makeElementsNotFocusable(null);
            _.makeElementsNotFocusable(undefined);
        });

        test.done();
    },

    getFocusableChilds(test) {
        document.body.innerHTML =
                `

`;

        const parent = document.querySelector('#parent');

        // ---------------

        const childs = _.getFocusableChilds(parent);

        // ---------------

        test.equal(childs.length, 2);

        [].forEach.call(childs, (element) => {
            test.ok(element.tabIndex >= 0, 'It should return the array of focusable elements.');
        });

        test.doesNotThrow(() => {
            _.getFocusableChilds(null);
            _.getFocusableChilds(undefined);
        });

        test.done();
    },

    getAllFocusableElements(test) {
        document.body.innerHTML =
                `

`;

        // ---------------

        const elements = _.getAllFocusableElements();

        // ---------------

        test.equal(elements.length, 2);

        [].forEach.call(elements, (element) => {
            test.ok(element.tabIndex >= 0, 'It should return the array of focusable elements.');
        });

        test.done();
    },

    getNextFocusableElement(test) {
        document.body.innerHTML =
                `

`;

        const element = document.querySelector('#prev');

        // ---------------

        const next1 = _.getNextFocusableElement(element);
        const next2 = _.getNextFocusableElement(next1);

        // ---------------

        test.equal(next1.id, 'next', 'It should return the next focusable element.');
        test.equal(next2,    null,   'It should return "null" if the selected element is the last focusable element.');

        test.doesNotThrow(() => {
            _.getNextFocusableElement(null);
            _.getNextFocusableElement(undefined);
        });

        test.done();
    },

    getPreviousFocusableElement(test) {
        document.body.innerHTML =
                `

`;

        const element = document.querySelector('#next');

        // ---------------

        const prev1 = _.getPreviousFocusableElement(element);
        const prev2 = _.getPreviousFocusableElement(prev1);

        // ---------------

        test.equal(prev1.id, 'prev', 'It should return the previous focusable element.');
        test.equal(prev2,    null,   'It should return "null" if the selected element is the first focusable element.');

        test.doesNotThrow(() => {
            _.getPreviousFocusableElement(null);
            _.getPreviousFocusableElement(undefined);
        });

        test.done();
    },

    goToNextFocusableElement(test) {
        document.body.innerHTML =
                `

`;

        const element = document.querySelector('#prev');

        element.focus();

        // ---------------

        _.goToNextFocusableElement(element);

        // ---------------

        test.equal(document.activeElement.id, 'next', 'It should move the focus to the next focusable element.');

        test.doesNotThrow(() => {
            _.goToNextFocusableElement(element);
            _.goToNextFocusableElement(null);
            _.goToNextFocusableElement(undefined);
        });

        test.done();
    },

    goToPreviousFocusableElement(test) {
        document.body.innerHTML =
                `

`;

        const element = document.querySelector('#next');

        element.focus();

        // ---------------

        _.goToPreviousFocusableElement(element);

        // ---------------

        test.equal(document.activeElement.id, 'prev', 'It should move the focus to the previous focusable element.');

        test.doesNotThrow(() => {
            _.goToPreviousFocusableElement(element);
            _.goToPreviousFocusableElement(null);
            _.goToPreviousFocusableElement(undefined);
        });

        test.done();
    },

    makeElementClickable(test) {
        document.body.innerHTML =
                `

`;

        const elements = document.querySelectorAll('div');
        let   isClicked = false;
        const expectedResultsForMouse    = [true, true, false];
        const expectedResultsForKeyboard = [true, false, true];

        test.expect(11);

        // ---------------

        function callback() {
            test.ok(true, 'It should execute the callback function on the "click" event for the element.');
            isClicked = true;
        }

        // ---------------

        _.makeElementClickable(elements[0], callback);
        _.makeElementClickable(elements[1], callback, { mouse: true,  keyboard: false });
        _.makeElementClickable(elements[2], callback, { mouse: false, keyboard: true  });

        // ---------------

        [0, 1, 2].forEach((i) => {
            isClicked = false;

            elements[i].click();

            test.equal(isClicked, expectedResultsForMouse[i],
                'It should execute the callback function on the "mouse click" event.');
        });

        [0, 1, 2].forEach((i) => {
            isClicked = false;

            elements[i].dispatchEvent(
                new KeyboardEvent('keydown', {
                    keyCode: 13,
                    which:   13
                })
            );

            test.equal(isClicked, expectedResultsForKeyboard[i],
                'It should execute the callback function on the "enter pressed" event.');
        });

        test.doesNotThrow(() => {
            _.makeElementClickable(null);
            _.makeElementClickable(undefined);
            _.makeElementClickable(elements[0], null);
            _.makeElementClickable(elements[0], undefined);
        });

        test.done();
    },

    makeChildElementsClickable(test) {
        document.body.innerHTML =
                `

`;

        const parents = document.querySelectorAll('.parent');
        const elements = [
            parents[0].querySelectorAll('div'),
            parents[1].querySelectorAll('div'),
            parents[2].querySelectorAll('div')
        ];
        let   isClicked = false;
        const expectedResultsForMouse    = [true, true, false];
        const expectedResultsForKeyboard = [true, false, true];

        test.expect(29);

        // ---------------

        function callback() {
            let counter = 0;

            return (index) => {
                test.ok(true, 'It should set the event listener for the click event for the element.');
                test.equal(index, (counter++) % 2, 'It should pass the index of the child element to the callback function.');
                isClicked = true;
            };
        }

        // ---------------

        _.makeChildElementsClickable(parents[0], elements[0], callback());
        _.makeChildElementsClickable(parents[1], elements[1], callback(),
            { mouse: true,  keyboard: false });
        _.makeChildElementsClickable(parents[2], elements[2], callback(),
            { mouse: false, keyboard: true  });

        // ---------------

        [0, 1, 2].forEach((testNumber) => {
            const expectedResult = expectedResultsForMouse[testNumber];

            [0, 1].forEach((i) => {
                isClicked = false;

                elements[testNumber][i].click();

                test.equal(isClicked, expectedResult,
                    'It should execute the callback function on the "mouse click" event.');
            });
        });

        [0, 1, 2].forEach((testNumber) => {
            const expectedResult = expectedResultsForKeyboard[testNumber];

            [0, 1].forEach((i) => {
                isClicked = false;

                elements[testNumber][i].dispatchEvent(
                    new KeyboardEvent('keydown', {
                        keyCode: 13,
                        which:   13
                    })
                );

                test.equal(isClicked, expectedResult,
                    'It should execute the callback function on the "enter pressed" event.');
            });
        });

        test.doesNotThrow(() => {
            _.makeChildElementsClickable(null);
            _.makeChildElementsClickable(undefined);
            _.makeChildElementsClickable(parents, null);
            _.makeChildElementsClickable(parents, undefined);
            _.makeChildElementsClickable(parents, elements, null);
            _.makeChildElementsClickable(parents, elements, undefined);
        });

        test.done();
    },

    onFocus(test) {
        document.body.innerHTML = '

';

        const element = document.querySelector('div');

        test.expect(2);

        // ---------------

        function callback() {
            test.ok(true, 'It should execute the callback function on the "focus" event.');
        }

        // ---------------

        _.onFocus(element, callback);

        // ---------------

        element.focus();

        test.doesNotThrow(() => {
            _.onFocus(null);
            _.onFocus(undefined);
            _.onFocus(element, null);
            _.onFocus(element, undefined);
        });

        test.done();
    },

    onBlur(test) {
        document.body.innerHTML = '

';

        const element = document.querySelector('div');

        test.expect(2);

        // ---------------

        function callback() {
            test.ok(true, 'It should execute the callback function on the "blur" event.');
        }

        // ---------------

        _.onBlur(element, callback);

        // ---------------

        element.focus();
        element.blur();

        test.doesNotThrow(() => {
            _.onBlur(null);
            _.onBlur(undefined);
            _.onBlur(element, null);
            _.onBlur(element, undefined);
        });

        test.done();
    },

    clearFocus(test) {
        document.body.innerHTML = '

';

        const element = document.querySelector('div');

        test.expect(1);

        // ---------------

        element.focus();
        _.clearFocus();

        // ---------------

        test.notEqual(element, document.activeElement);

        test.done();
    }
};


text:
<?php

namespace s9e\TextFormatter\Tests\Plugins\Censor;

use s9e\TextFormatter\Configurator;
use s9e\TextFormatter\Plugins\Censor\Parser;
use s9e\TextFormatter\Tests\Plugins\ParsingTestsRunner;
use s9e\TextFormatter\Tests\Plugins\ParsingTestsJavascriptRunner;
use s9e\TextFormatter\Tests\Plugins\RenderingTestsRunner;
use s9e\TextFormatter\Tests\Test;

/**
* @covers s9e\TextFormatter\Plugins\Censor\Parser
*/
class ParserTest extends Test
{
	use ParsingTestsRunner;
	use ParsingTestsJavascriptRunner;
	use RenderingTestsRunner;

	public function getParsingTests()
	{
		return array(
			array(
				'apple',
				'<rt><CENSOR>apple</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('apple');
				}
			),
			array(
				'apple',
				'<rt><FOO>apple</FOO></rt>',
				array('tagName' => 'FOO'),
				function ($constructor)
				{
					$constructor->Censor->add('apple');
				}
			),
			array(
				'apple',
				'<rt><CENSOR replacement="orange">apple</CENSOR></rt>',
				array('attrName' => 'replacement'),
				function ($constructor)
				{
					$constructor->Censor->add('apple', 'orange');
				}
			),
			array(
				'You dirty 苹果',
				'<rt>You dirty <CENSOR with="orange">苹果</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('苹果', 'orange');
				}
			),
			array(
				'You dirty apple',
				'<rt>You dirty <CENSOR>apple</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('*pple');
				}
			),
			array(
				'You dirty apple',
				'<rt>You dirty <CENSOR>apple</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('ap*e');
				}
			),
			array(
				'You dirty apple',
				'<rt>You dirty <CENSOR>apple</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('app*');
				}
			),
			array(
				'You dirty apple',
				'<rt>You dirty <CENSOR>apple</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('*apple*');
				}
			),
			array(
				'You dirty Pokéman',
				'<rt>You dirty <CENSOR>Pokéman</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('pok*man');
				}
			),
			array(
				'You dirty Pok3man',
				'<rt>You dirty <CENSOR>Pok3man</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('pok?man');
				}
			),
			array(
				'You dirty Pok#man',
				'<rt>You dirty <CENSOR>Pok#man</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('pok?man');
				}
			),
			array(
				'You dirty Pokéman',
				'<rt>You dirty <CENSOR with="digiman">Pokéman</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('pok?man', 'digiman');
				}
			),
			array(
				'You dirty apple',
				'<rt>You dirty <CENSOR>apple</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('?pple');
				}
			),
			array(
				'You dirty pineapple',
				'<pt>You dirty pineapple</pt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('?pple');
				}
			),
			array(
				'You dirty $0',
				'<rt>You dirty <CENSOR>$0</CENSOR></rt>',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('$0');
				}
			),
		);
	}

	public function getRenderingTests()
	{
		return array(
			array(
				'You dirty apple',
				'You dirty ****',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('apple');
				}
			),
			array(
				'You dirty apple',
				'You dirty orange',
				array(),
				function ($constructor)
				{
					$constructor->Censor->add('apple', 'orange');
				}
			),
			array(
				'You dirty apple',
				'You dirty ****',
				array('tagName' => 'FOO'),
				function ($constructor)
				{
					$constructor->Censor->add('apple');
				}
			),
			array(
				'You dirty apple',
				'You dirty orange',
				array('attrName' => 'replacement'),
				function ($constructor)
				{
					$constructor->Censor->add('apple', 'orange');
				}
			),
		);
	}
}


text:
set(DOCUMENTATION "This module contains classes that perform operations on the
itk::QuadEdgeMesh. This is a data structure designed to represent a
2-dimensional manifold embedded in a 3-dimensional space. That's typically the
case of an iso-surface extracted from a 3D image data set. The itk::QuadEdgeMesh
ensures the proper topological orientation of the surface. Filters in this
module include: smoothing, decimation, curvature computation (mean, gaussian,
min, max, principal), and normal computation, among others.")

itk_module(ITKQuadEdgeMeshFiltering
  DEPENDS
    ITKMesh
  COMPILE_DEPENDS
    ITKQuadEdgeMesh
  TEST_DEPENDS
    ITKTestKernel
    ITKIOMesh
  DESCRIPTION
    "${DOCUMENTATION}"
)


text:
<?php

$account_id = filter_input(INPUT_GET, "account_id");
$token = filter_input(INPUT_GET, "token");

$session = da_session::GetAndValidateSession($account_id, $token);

if ($session == NULL) {
    die("Invalid Session");
}


text:
namespace AjTalk.Language
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    public class ExecutionContext
    {
        public int InstructionPointer;
        public object LastReceiver = null;
        public bool HasReturnValue;
        public object ReturnValue;
        public ExecutionContext Sender;
        public IList Stack;

        private Block block;
        private Machine machine;
        private IObject self;
        private object[] arguments;
        private object[] locals;
        private object nativeSelf;

        public ExecutionContext(Machine machine, IObject self, Block block, object[] arguments)
            : this(block, arguments)
        {
            // this.self = receiver; // TODO review
            this.machine = machine;
            this.self = self;
        }

        public ExecutionContext(Machine machine, object nativeself, Block block, object[] arguments)
            : this(block, arguments)
        {
            this.machine = machine;
            this.nativeSelf = nativeself;
        }

        private ExecutionContext(Block block, object[] arguments)
        {
            this.block = block;
            this.Stack = new ArrayList(5);

            this.arguments = arguments;
            if (this.block.NoLocals > 0)
                this.locals = new object[this.block.NoLocals];
            else
                this.locals = null;

            // TODO refactor to no copy of arguments and locals
            this.arguments = arguments;

            if (block.Closure != null)
            {
                this.self = block.Closure.Self;
                this.nativeSelf = block.Closure.NativeSelf;

                int nlocs = block.NoLocals - block.Closure.NoLocals;

                if (nlocs > 0)
                    this.locals = new object[nlocs];
                else
                    this.locals = null;
            }
            else
            {
                if (this.block.NoLocals > 0)
                    this.locals = new object[this.block.NoLocals];
                else
                    this.locals = null;
            }
        }

        public IObject Self { get { return this.self; } }

        public ExecutionContext TopClosure { get { return this.block.TopClosure; } }

        public ExecutionContext ReturnExecutionContext
        {
            get
            {
                var value = this.TopClosure;

                if (value != null)
                    return value.Sender;

                return this.Sender;
            }
        }

        public object NativeSelf { get { return this.nativeSelf; } }

        public int NoLocals { get { return this.NoParentLocals + (this.locals == null ? 0 : this.locals.Length); } }

        public int NoParentLocals { get { return this.block.Closure == null ? 0 : this.block.Closure.NoLocals; } }

        public int NoArguments { get { return this.NoParentArguments + (this.arguments == null ? 0 : this.arguments.Length); } }

        public int NoParentArguments { get { return this.block.Closure == null ? 0 : this.block.Closure.NoArguments; } }

        public Block Block { get { return this.block; } }

        public Machine Machine { get { return this.machine; } }

        public IObject Receiver
        {
            get
            {
                if (this.self != null)
                    return this.self;

                if (this.block.Closure != null)
                    return this.block.Closure.Receiver;

                return null;
            }
        }

        internal object GetLocal(int nlocal)
        {
            if (nlocal < this.NoParentLocals)
                return this.GetParentLocal(nlocal);
            return this.locals[nlocal - this.NoParentLocals];
        }

        internal object GetParentLocal(int nlocal)
        {
            return this.block.Closure.GetLocal(nlocal);
        }

        internal void SetLocal(int nlocal, object value)
        {
            if (nlocal < this.NoParentLocals)
                this.SetParentLocal(nlocal, value);
            else
                this.locals[nlocal - this.NoParentLocals] = value;
        }

        internal void SetArgument(int nargument, object value)
        {
            if (nargument < this.NoParentArguments)
                this.SetParentArgument(nargument, value);
            else
                this.arguments[nargument - this.NoParentArguments] = value;
        }

        internal void SetParentArgument(int nargument, object value)
        {
            this.block.Closure.SetArgument(nargument, value);
        }

        internal void SetParentLocal(int nlocal, object value)
        {
            this.block.Closure.SetLocal(nlocal, value);
        }

        internal object GetArgument(int nargument)
        {
            if (nargument < this.NoParentArguments)
                return this.GetParentArgument(nargument);
            return this.arguments[nargument - this.NoParentArguments];
        }

        internal object GetParentArgument(int nargument)
        {
            return this.block.Closure.GetArgument(nargument);
        }

        internal void Push(object obj)
        {
            this.Stack.Add(obj);
        }

        internal object Pop()
        {
            object obj = this.Stack[this.Stack.Count - 1];
            this.Stack.RemoveAt(this.Stack.Count - 1);
            return obj;
        }
    }
}


text:
//////////////////////////////////////////////////////////////////////////////
///                                                                        ///
/// ccs_twitter.c - CCS Twitter Driver                                     ///
///                                                                        ///
/// This driver provides the functions and state machine needed to send a  ///
/// tweet to Twitter using a PIC capable of connecting to the internet.    ///
/// The keys, tokens, and secrets from your Twitter API application are    ///
/// passed into the TwitterInit(...) function.                             ///
///                                                                        ///
/// FUNCTIONS:                                                             ///
/// TwitterInit(...) - Initializes the driver and sets the pointers to the ///
///                 keys, tokens, and secrets for use when sending         ///
///                                                                        ///
/// TwitterTask() - State machine for connecting to the Twitter API and    ///
///                 handles the sending of tweets                          ///
///                                                                        ///
/// int1 TwitterIsBusy() - Determines if this driver is busy connecting,   ///
///                 sending a tweet, or if an NTP connection is being found///
///                                                                        ///
/// TwitterSend(char *str) - if the driver is not busy, this will start the///
///                 tweet process, sending 'str' as a tweet to the API     ///
///                                                                        ///
/// TwitterCancel() - disconnects the socket and resets the state machine  ///
///                                                                        ///
/// TwitterIsError() - Returns if an error occured on the last tweet       ///
///                                                                        ///
//////////////////////////////////////////////////////////////////////////////
////        (C) Copyright 1996,2006 Custom Computer Services              ////
//// This source code may only be used by licensed users of the CCS C     ////
//// compiler.  This source code may only be distributed to other         ////
//// licensed users of the CCS C compiler.  No other use, reproduction    ////
//// or distribution is permitted without written permission.             ////
//// Derivative programs created using this software in object code       ////
//// form are not restricted in any way.                                  ////
//////////////////////////////////////////////////////////////////////////////

// THESE MUST BE DEFINED IN THE MAIN PROGRAM BEFORE
// INCLUDING "ccstcpip.c".
//define STACK_USE_TWITTER
//#define STACK_USE_ICMP_SERVER
//#define STACK_USE_TCP
//#define STACK_USE_UDP
//#define STACK_USE_DNS
//#define STACK_USE_CCS_SNTP_CLIENT

//#define TCP_ETH_RAM_SIZE   550

#ifndef TWITTER_HOST
#define TWITTER_HOST "api.twitter.com"
#endif

#ifndef TWITTER_PORT
#define TWITTER_PORT   (unsigned int16)80
#endif

#include "OAuth.c"

// global pointer to keys used by Twitter task
static char* ConsKey;
static char* ConsSecr;
static char* Token;
static char* TokenSecr;
static char* Status;

int1 isError,send;

static TICK lastTick;        // tick timer
static TCP_SOCKET socket;    // socket for connecting to Twitter
int1 receivingStatus;        // flag for receiving
int8 countReceiving;         // counter for checking if we are receiving the response status code
int8 countResponse;          // counter for the actual response code
static char response[25];    // response received from Twitter
static char SendSuccess[] = "200 OK"; // this is the response Twitter will give when a tweet was successful

// TCP connection states
static enum {
      TWITTER_STATE_CONNECT=0, TWITTER_STATE_CONNECT_WAIT,
      TWITTER_STATE_CONNECTED
   } ConnectState=0;

// Message Sending States
static enum {
      STATE_SEND_0=0, STATE_SEND_1, STATE_SEND_2, STATE_SEND_3,
      STATE_SEND_4, STATE_SEND_5, STATE_SEND_6, STATE_SEND_7,
      STATE_SEND_8, STATE_SEND_9, STATE_SEND_10, STATE_SEND_11,
      STATE_SEND_12, STATE_SEND_13, STATE_SEND_14, STATE_SEND_15,
   } SendState=0;

void HTTPPut(char c) {
   TCPPut(socket, c);
}

/* Initialize the driver with the keys/tokens,
 * Reset the statemachine
 */
void TwitterInit(char *ConsumerKey, char *ConsumerSecret, char *AccessToken, char *AccessTokenSecret){
   ConsKey = ConsumerKey;
   ConsSecr = ConsumerSecret;
   Token = AccessToken;
   TokenSecr = AccessTokenSecret;
   isError = FALSE;
   send = FALSE;
   TCPDisconnect(socket);
   ConnectState = TWITTER_STATE_CONNECT;
   SendState = STATE_SEND_0;
   socket = INVALID_SOCKET;
   receivingStatus = FALSE;
   countReceiving = 0;
   countResponse = 0;
   response[0] = '\0';
}

void TwitterTask(void){

   TICK currTick;
   int8 dis;
   char c;
   static char server[] = TWITTER_HOST;

   currTick=TickGet();

   switch (ConnectState)
   {
      case TWITTER_STATE_CONNECT:
         //lcdMessage = LCD_CONNECTING;
         //isBusy = TRUE;
         socket = TCPOpen(server, TCP_OPEN_RAM_HOST, TWITTER_PORT, TCP_PURPOSE_DEFAULT);
         if (socket!=INVALID_SOCKET) {
            lastTick=TickGet();
            ConnectState=TWITTER_STATE_CONNECT_WAIT;
         }
         break;

      case TWITTER_STATE_CONNECT_WAIT:
         if (TCPIsConnected(socket))
         {
            ConnectState=TWITTER_STATE_CONNECTED;
            //lcdMessage = LCD_TWEET_READY;
         }
         else if (TickGetDiff(currTick, lastTick) > (TICKS_PER_SECOND * 10))
         {
            TCPDisconnect(socket);
            ConnectState=TWITTER_STATE_CONNECT;
         }
         break;

      case TWITTER_STATE_CONNECTED:
         if (TCPIsConnected(socket)) {

            // first check if there is anything to receive
            if (TCPIsGetReady(socket)) {
               //lcdMessage = LCD_RECEIVING;
               // This will parse errors from the incoming xml reply from Twitter.
               // Nothing will be printed if no error was found.
               // If you want to view all of the xml data, comment out everything
               // within this loop and uncomment the first line.
               while (TCPGet(socket, &c)) {
                  //printf("%c",c);
                  // find the response status message.
                  // 200 = OK (sent successfully)
                  // 401 = Unauthorized (error in sending process or with user information)
                  // 403 = Forbidden (usually caused by a duplicate tweet)
                  if((c == 'S' && (countReceiving == 0)) || (c == 't' && (countReceiving == 1)) ||
                     (c == 'a' && (countReceiving == 2)) || (c == 't' && (countReceiving == 3)) ||
                     (c == 'u' && (countReceiving == 4)) || (c == 's' && (countReceiving == 5)) ||
                     (c == ':' && (countReceiving == 6)) || (c == ' ' && (countReceiving == 7)))
                  {
                     countReceiving++;
                     if(countReceiving == 8){  // we are now receiving the response code
                        receivingStatus = TRUE;
                        printf("\n\rStatus: ");
                     }
                  }
                  else
                     countReceiving = 0;

                  if(receivingStatus && ((c == '\n')||(c == '\r'))){ // end of response line
                     receivingStatus = FALSE;
                     printf("\r\n\n");
                     response[countResponse] = '\0'; // terminate the string
                     if (strcmp(SendSuccess,response) != 0)
                     {
                        isError = TRUE;
                        printf("ERROR!\r\n\n");
                     }
                  }

                  if(receivingStatus && (countReceiving != 8)){
                     printf("%c",c);
                     response[countResponse] = c; // save response character
                     countResponse++;
                  }
               }
            } // end of if IsGetReady

            // we want to send a message and still have a connection
            if(send && TCPIsConnected(socket)){
               switch(SendState){
                  case STATE_SEND_0:
                     isError = FALSE;
                     countResponse = 0;
                     response[0] = '\0';

                     printf(HTTPPut,"POST /1/statuses/update.xml?include_entities=true HTTP/1.1");
                     printf("\r\n\n*** SENDING ***\r\n%s\r\n",Status);
                     delay_ms(80);
                     SendState++;
                     break;
                  case STATE_SEND_1:
                     printf(HTTPPut,"\r\nAccept: */*");
                     delay_ms(30);
                     SendState++;
                     break;
                  case STATE_SEND_2:
                     printf(HTTPPut,"\r\nConnection: close");
                     delay_ms(30);
                     SendState++;
                     break;
                  case STATE_SEND_3:
                     printf(HTTPPut,"\r\nUser-Agent: OAuth gem v0.4.4");
                     delay_ms(40);
                     SendState++;
                     break;
                  case STATE_SEND_4:
                     printf(HTTPPut,"\r\nContent-Type: application/x-www-form-urlencoded");
                     delay_ms(60);
                     SendState++;
                     break;
                  case STATE_SEND_5:
                     printf(HTTPPut,"\r\nAuthorization: OAuth ");
                     delay_ms(40);
                     SendState++;
                     break;
                  case STATE_SEND_6:
                     printf(HTTPPut,"oauth_consumer_key=\"%s\", ",ConsKey);
                     delay_ms(80);
                     SendState++;
                     break;
                  case STATE_SEND_7:
                     generate_nonce();
                     printf(HTTPPut,"oauth_nonce=\"%s\", ", get_nonce());
                     delay_ms(80);
                     SendState++;
                     break;
                  case STATE_SEND_8:
                     generate_timestamp();
                     printf(HTTPPut,"oauth_signature=\"%s\", ", generate_signature(ConsKey,ConsSecr,get_nonce(),get_timestamp(),Token,TokenSecr,Status));
                     delay_ms(80);
                     SendState++;
                     break;
                  case STATE_SEND_9:
                     printf(HTTPPut,"oauth_signature_method=\"HMAC-SHA1\", ");
                     delay_ms(60);
                     SendState++;
                     break;
                  case STATE_SEND_10:
                     printf(HTTPPut,"oauth_timestamp=\"%s\", ",get_timestamp());
                     delay_ms(60);
                     SendState++;
                     break;
                  case STATE_SEND_11:
                     printf(HTTPPut,"oauth_token=\"%s\", ",Token);
                     delay_ms(80);
                     SendState++;
                     break;
                  case STATE_SEND_12:
                     printf(HTTPPut,"oauth_version=\"1.0\"");
                     delay_ms(40);
                     SendState++;
                     break;
                  case STATE_SEND_13:
                     // find the length of the percent encoded status
                     int8 len = 0;
                     char *d = Status;
                     while(*d != 0){
                        if(!reserved(*d))
                           len +=3;
                        else
                           len++;
                        d++;
                     }
                     printf(HTTPPut,"\r\nContent-Length: %u", (7+len));
                     delay_ms(40);
                     SendState++;
                     break;
                  case STATE_SEND_14:
                     printf(HTTPPut,"\r\nHost: ");
                     printf(HTTPPut, TWITTER_HOST);
                     delay_ms(40);
                     SendState++;
                     break;
                  case STATE_SEND_15:
                     printf(HTTPPut,"\r\n\r\nstatus=");
                     delay_ms(20);
                     // status needs to be percent encoded before sending
                     char *e = Status;
                     while(*e != 0){
                        if(!reserved(*e)){
                           char res[4];
                           sprintf(res,"%%%02X", *e);
                           printf(HTTPPut,"%s",res);
                           delay_ms(10);
                        }
                        // if reserved, just append
                        else{
                           printf(HTTPPut,"%c",*e);
                           delay_ms(5);
                        }
                        e++;
                     }
                     printf("\r\n\n*** RESPONSE ***\r\n");
                     TCPFlush(socket);
                     SendState = STATE_SEND_0;
                     send = FALSE;
                     break;

               }
            }
         }
         else { // lost TCP connection
            if(SendState > STATE_SEND_0) // lost connection while sending - Error
               isError = TRUE;
            ConnectState=TWITTER_STATE_CONNECT; // lost connection, reconnect
         }
         break;
   }
}

/* Determines if the system is busy
 * The system is not busy when a connection is made
 */
int1 TwitterIsBusy(void){
   if
   (
      (ConnectState != TWITTER_STATE_CONNECTED) ||
      (SendState != STATE_SEND_0) ||
      !NTPOk()
   )
      return TRUE;
   else
      return FALSE;
}

/* If TwitterIsBusy() is FALSE, then this starts the statemachine
 * for sending a Twitter update
 */
void TwitterSend(char *str){
   if (!TwitterIsBusy()){
      Status = str;
      send = TRUE;
   }
}

/* Cancels all Twitter operations and resets the
 * statemachine and socket
 */
void TwitterCancel(void){
   isError = FALSE;
   send = FALSE;
   TCPDisconnect(socket);
   ConnectState = TWITTER_STATE_CONNECT;
   SendState = STATE_SEND_0;
   socket = INVALID_SOCKET;
   receivingStatus = FALSE;
   countReceiving = 0;
   countResponse = 0;
   response[0] = '\0';
}

/* Determines if a post had an error.
 * Returns TRUE if an error occured, FALSE otherwise
 */
int1 TwitterIsError(void){
   return isError;
}