bug+codestyle: Fix compile bugs and adjust code style

Change-Id: I008bb538441c099fa25b8b967fbf23ffce13a220
diff --git a/src/add-contact-panel.cpp b/src/add-contact-panel.cpp
index 639c113..9e0db74 100644
--- a/src/add-contact-panel.cpp
+++ b/src/add-contact-panel.cpp
@@ -8,12 +8,14 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "add-contact-panel.h"
+#include "add-contact-panel.hpp"
 #include "ui_add-contact-panel.h"
 
 #ifndef Q_MOC_RUN
 #endif
 
+namespace chronos {
+
 AddContactPanel::AddContactPanel(QWidget *parent)
   : QDialog(parent)
   , ui(new Ui::AddContactPanel)
@@ -57,7 +59,7 @@
 AddContactPanel::onSearchClicked()
 {
   // ui->infoView->clear();
-  for(int i = ui->infoView->rowCount() - 1; i >= 0 ; i--)
+  for (int i = ui->infoView->rowCount() - 1; i >= 0 ; i--)
     ui->infoView->removeRow(i);
 
   m_searchIdentity = ui->contactInput->text();
@@ -72,24 +74,28 @@
 }
 
 void
-AddContactPanel::onContactEndorseInfoReady(const chronos::EndorseInfo& endorseInfo)
+AddContactPanel::onContactEndorseInfoReady(const Chronos::EndorseInfo& endorseInfo)
 {
   int entrySize = endorseInfo.endorsement_size();
 
-  for(int rowCount = 0; rowCount < entrySize; rowCount++)
-    {
-      ui->infoView->insertRow(rowCount);
-      QTableWidgetItem* type = new QTableWidgetItem(QString::fromStdString(endorseInfo.endorsement(rowCount).type()));
-      ui->infoView->setItem(rowCount, 0, type);
+  for (int rowCount = 0; rowCount < entrySize; rowCount++) {
+    ui->infoView->insertRow(rowCount);
+    QTableWidgetItem* type =
+      new QTableWidgetItem(QString::fromStdString(endorseInfo.endorsement(rowCount).type()));
+    ui->infoView->setItem(rowCount, 0, type);
 
-      QTableWidgetItem* value = new QTableWidgetItem(QString::fromStdString(endorseInfo.endorsement(rowCount).value()));
-      ui->infoView->setItem(rowCount, 1, value);
+    QTableWidgetItem* value =
+      new QTableWidgetItem(QString::fromStdString(endorseInfo.endorsement(rowCount).value()));
+    ui->infoView->setItem(rowCount, 1, value);
 
-      QTableWidgetItem* endorse = new QTableWidgetItem(QString::fromStdString(endorseInfo.endorsement(rowCount).endorse()));
-      ui->infoView->setItem(rowCount, 2, endorse);
-    }
+    QTableWidgetItem* endorse =
+      new QTableWidgetItem(QString::fromStdString(endorseInfo.endorsement(rowCount).endorse()));
+    ui->infoView->setItem(rowCount, 2, endorse);
+  }
 }
 
+} // namespace chronos
+
 
 #if WAF
 #include "add-contact-panel.moc"
diff --git a/src/add-contact-panel.h b/src/add-contact-panel.hpp
similarity index 75%
rename from src/add-contact-panel.h
rename to src/add-contact-panel.hpp
index 5b99558..545cd02 100644
--- a/src/add-contact-panel.h
+++ b/src/add-contact-panel.hpp
@@ -8,8 +8,8 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef ADD_CONTACT_PANEL_H
-#define ADD_CONTACT_PANEL_H
+#ifndef CHRONOS_ADD_CONTACT_PANEL_HPP
+#define CHRONOS_ADD_CONTACT_PANEL_HPP
 
 #include <QDialog>
 #include <QTableWidgetItem>
@@ -22,19 +22,21 @@
 class AddContactPanel;
 }
 
+namespace chronos {
+
 class AddContactPanel : public QDialog
 {
   Q_OBJECT
 
 public:
   explicit
-  AddContactPanel(QWidget *parent = 0);
+  AddContactPanel(QWidget* parent = 0);
 
   ~AddContactPanel();
 
 public slots:
   void
-  onContactEndorseInfoReady(const chronos::EndorseInfo& endorseInfo);
+  onContactEndorseInfoReady(const Chronos::EndorseInfo& endorseInfo);
 
 private slots:
   void
@@ -54,7 +56,7 @@
   addContact(const QString& identity);
 
 private:
-  Ui::AddContactPanel *ui;
+  Ui::AddContactPanel* ui;
   QString m_searchIdentity;
 
   QTableWidgetItem* m_typeHeader;
@@ -62,4 +64,6 @@
   QTableWidgetItem* m_endorseHeader;
 };
 
-#endif // ADD_CONTACT_PANEL_H
+} // namespace chronos
+
+#endif // CHRONOS_ADD_CONTACT_PANEL_HPP
diff --git a/src/browse-contact-dialog.cpp b/src/browse-contact-dialog.cpp
index c12d040..f437eeb 100644
--- a/src/browse-contact-dialog.cpp
+++ b/src/browse-contact-dialog.cpp
@@ -9,15 +9,17 @@
  */
 
 
-#include "browse-contact-dialog.h"
+#include "browse-contact-dialog.hpp"
 #include "ui_browse-contact-dialog.h"
 
 #ifndef Q_MOC_RUN
-#include "profile.h"
+#include "profile.hpp"
 #endif
 
-using namespace ndn;
-using namespace chronos;
+
+namespace chronos {
+
+using ndn::IdentityCertificate;
 
 BrowseContactDialog::BrowseContactDialog(QWidget *parent)
   : QDialog(parent)
@@ -33,8 +35,10 @@
 
   ui->ContactList->setModel(m_contactListModel);
 
-  connect(ui->ContactList->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
-          this, SLOT(onSelectionChanged(const QItemSelection &, const QItemSelection &)));
+  connect(ui->ContactList->selectionModel(),
+          SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
+          this,
+          SLOT(onSelectionChanged(const QItemSelection &, const QItemSelection &)));
   connect(ui->AddButton, SIGNAL(clicked()),
           this, SLOT(onAddClicked()));
   connect(ui->DirectAddButton, SIGNAL(clicked()),
@@ -62,8 +66,8 @@
 {
   QItemSelectionModel* selectionModel = ui->ContactList->selectionModel();
   QModelIndexList selectedList = selectionModel->selectedIndexes();
-  QModelIndexList::iterator it = selectedList.begin();
-  for(; it != selectedList.end(); it++)
+
+  for (QModelIndexList::iterator it = selectedList.begin(); it != selectedList.end(); it++)
     emit addContact(m_contactNameList[it->row()]);
 
   this->close();
@@ -80,7 +84,7 @@
 BrowseContactDialog::closeEvent(QCloseEvent *e)
 {
   ui->InfoTable->clear();
-  for(int i = ui->InfoTable->rowCount() - 1; i >= 0 ; i--)
+  for (int i = ui->InfoTable->rowCount() - 1; i >= 0 ; i--)
       ui->InfoTable->removeRow(i);
   ui->InfoTable->horizontalHeader()->hide();
 
@@ -108,27 +112,27 @@
 
   ui->InfoTable->clear();
 
-  for(int i = ui->InfoTable->rowCount() - 1; i >= 0 ; i--)
+  for (int i = ui->InfoTable->rowCount() - 1; i >= 0 ; i--)
     ui->InfoTable->removeRow(i);
 
   ui->InfoTable->horizontalHeader()->show();
   ui->InfoTable->setColumnCount(2);
 
-  Profile::const_iterator proIt = profile.begin();
-  Profile::const_iterator proEnd = profile.end();
+
   int rowCount = 0;
+  for (Profile::const_iterator proIt = profile.begin();
+       proIt != profile.end(); proIt++, rowCount++) {
+    ui->InfoTable->insertRow(rowCount);
+    QTableWidgetItem* type = new QTableWidgetItem(QString::fromStdString(proIt->first));
+    ui->InfoTable->setItem(rowCount, 0, type);
 
-  for(; proIt != proEnd; proIt++, rowCount++)
-    {
-      ui->InfoTable->insertRow(rowCount);
-      QTableWidgetItem* type = new QTableWidgetItem(QString::fromStdString(proIt->first));
-      ui->InfoTable->setItem(rowCount, 0, type);
-
-      QTableWidgetItem* value = new QTableWidgetItem(QString::fromStdString(proIt->second));
-      ui->InfoTable->setItem(rowCount, 1, value);
-    }
+    QTableWidgetItem* value = new QTableWidgetItem(QString::fromStdString(proIt->second));
+    ui->InfoTable->setItem(rowCount, 1, value);
+  }
 }
 
+} // namespace chronos
+
 #if WAF
 #include "browse-contact-dialog.moc"
 #include "browse-contact-dialog.cpp.moc"
diff --git a/src/browse-contact-dialog.h b/src/browse-contact-dialog.hpp
similarity index 80%
rename from src/browse-contact-dialog.h
rename to src/browse-contact-dialog.hpp
index 54cdcb2..c1250a8 100644
--- a/src/browse-contact-dialog.h
+++ b/src/browse-contact-dialog.hpp
@@ -8,8 +8,8 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef BROWSE_CONTACT_DIALOG_H
-#define BROWSE_CONTACT_DIALOG_H
+#ifndef CHRONOS_BROWSE_CONTACT_DIALOG_HPP
+#define CHRONOS_BROWSE_CONTACT_DIALOG_HPP
 
 #include <QDialog>
 #include <QStringListModel>
@@ -26,6 +26,8 @@
 class BrowseContactDialog;
 }
 
+namespace chronos {
+
 class BrowseContactDialog : public QDialog
 {
   Q_OBJECT
@@ -38,12 +40,12 @@
 
 protected:
   void
-  closeEvent(QCloseEvent *e);
+  closeEvent(QCloseEvent* e);
 
 private slots:
   void
-  onSelectionChanged(const QItemSelection &selected,
-                     const QItemSelection &deselected);
+  onSelectionChanged(const QItemSelection& selected,
+                     const QItemSelection& deselected);
 
   void
   onAddClicked();
@@ -76,7 +78,7 @@
   typedef boost::recursive_mutex RecLock;
   typedef boost::unique_lock<RecLock> UniqueRecLock;
 
-  Ui::BrowseContactDialog *ui;
+  Ui::BrowseContactDialog* ui;
 
   QTableWidgetItem* m_typeHeader;
   QTableWidgetItem* m_valueHeader;
@@ -87,4 +89,6 @@
   QStringList m_contactCertNameList;
 };
 
-#endif // BROWSE_CONTACT_DIALOG_H
+} // namespace chronos
+
+#endif // CHRONOS_BROWSE_CONTACT_DIALOG_HPP
diff --git a/src/chat-dialog.cpp b/src/chat-dialog.cpp
index aabbcc2..407349a 100644
--- a/src/chat-dialog.cpp
+++ b/src/chat-dialog.cpp
@@ -10,7 +10,7 @@
  *         Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "chat-dialog.h"
+#include "chat-dialog.hpp"
 #include "ui_chat-dialog.h"
 
 #include <QScrollBar>
@@ -22,26 +22,39 @@
 #include <boost/random/random_device.hpp>
 #include <boost/random/uniform_int_distribution.hpp>
 #include <ndn-cxx/util/random.hpp>
-#include <cryptopp/hex.h>
-#include <cryptopp/files.h>
+#include <ndn-cxx/encoding/buffer-stream.hpp>
+#include "cryptopp.hpp"
 #include <queue>
 #include "logging.h"
 #endif
 
-using namespace ndn;
-using ndn::shared_ptr;
-using namespace chronos;
 
-INIT_LOGGER("ChatDialog");
-
-static const int HELLO_INTERVAL = FRESHNESS * 3 / 4;
-static const uint8_t CHRONOS_RP_SEPARATOR[2] = {0xF0, 0x2E}; // %F0.
+// INIT_LOGGER("ChatDialog");
 
 Q_DECLARE_METATYPE(std::vector<Sync::MissingDataInfo> )
 Q_DECLARE_METATYPE(ndn::shared_ptr<const ndn::Data>)
 Q_DECLARE_METATYPE(ndn::Interest)
 Q_DECLARE_METATYPE(size_t)
 
+
+namespace chronos {
+
+using std::vector;
+using std::string;
+using std::map;
+using std::queue;
+
+using ndn::IdentityCertificate;
+using ndn::SecRuleRelative;
+using ndn::Face;
+using ndn::OBufferStream;
+using ndn::OnDataValidated;
+using ndn::OnDataValidationFailed;
+
+
+static const int HELLO_INTERVAL = FRESHNESS * 3 / 4;
+static const uint8_t CHRONOS_RP_SEPARATOR[2] = {0xF0, 0x2E}; // %F0.
+
 ChatDialog::ChatDialog(ContactManager* contactManager,
                        shared_ptr<Face> face,
                        const IdentityCertificate& myCertificate,
@@ -55,7 +68,7 @@
   , m_contactManager(contactManager)
   , m_face(face)
   , m_myCertificate(myCertificate)
-  , m_chatroomName(chatroomPrefix.get(-1).toEscapedString())
+  , m_chatroomName(chatroomPrefix.get(-1).toUri())
   , m_chatroomPrefix(chatroomPrefix)
   , m_localPrefix(localPrefix)
   , m_useRoutablePrefix(false)
@@ -85,7 +98,8 @@
   ui->trustTreeViewer->hide();
   ui->listView->setModel(m_rosterModel);
 
-  m_identity = IdentityCertificate::certificateNameToPublicKeyName(m_myCertificate.getName()).getPrefix(-1);
+  m_identity =
+    IdentityCertificate::certificateNameToPublicKeyName(m_myCertificate.getName()).getPrefix(-1);
   updatePrefix();
   updateLabels();
 
@@ -109,8 +123,12 @@
           this, SLOT(onProcessData(const ndn::shared_ptr<const ndn::Data>&, bool, bool)));
   connect(this, SIGNAL(processTreeUpdate(const std::vector<Sync::MissingDataInfo>)),
           this, SLOT(onProcessTreeUpdate(const std::vector<Sync::MissingDataInfo>)));
-  connect(this, SIGNAL(reply(const ndn::Interest&, const ndn::shared_ptr<const ndn::Data>&, size_t, bool)),
-          this, SLOT(onReply(const ndn::Interest&, const ndn::shared_ptr<const ndn::Data>&, size_t, bool)));
+  connect(this, SIGNAL(reply(const ndn::Interest&,
+                             const ndn::shared_ptr<const ndn::Data>&,
+                             size_t, bool)),
+          this, SLOT(onReply(const ndn::Interest&,
+                             const ndn::shared_ptr<const ndn::Data>&,
+                             size_t, bool)));
   connect(this, SIGNAL(replyTimeout(const ndn::Interest&, size_t)),
           this, SLOT(onReplyTimeout(const ndn::Interest&, size_t)));
   connect(this, SIGNAL(introCert(const ndn::Interest&, const ndn::shared_ptr<const ndn::Data>&)),
@@ -118,28 +136,26 @@
   connect(this, SIGNAL(introCertTimeout(const ndn::Interest&, int, const QString&)),
           this, SLOT(onIntroCertTimeout(const ndn::Interest&, int, const QString&)));
 
-  if(withSecurity)
-    {
+  if (withSecurity) {
+    m_invitationValidator = make_shared<chronos::ValidatorInvitation>();
+    m_dataRule = make_shared<SecRuleRelative>("([^<CHRONOCHAT-DATA>]*)<CHRONOCHAT-DATA><>",
+                                              "^([^<KEY>]*)<KEY>(<>*)<><ID-CERT>$",
+                                              "==", "\\1", "\\1", true);
 
-      m_invitationValidator = make_shared<chronos::ValidatorInvitation>();
-      m_dataRule = make_shared<SecRuleRelative>("([^<CHRONOCHAT-DATA>]*)<CHRONOCHAT-DATA><>",
-                                                "^([^<KEY>]*)<KEY>(<>*)<><ID-CERT>$",
-                                                "==", "\\1", "\\1", true);
+    ui->inviteButton->setEnabled(true);
+    ui->trustTreeButton->setEnabled(true);
 
-      ui->inviteButton->setEnabled(true);
-      ui->trustTreeButton->setEnabled(true);
-
-      connect(ui->inviteButton, SIGNAL(clicked()),
-              this, SLOT(onInviteListDialogRequested()));
-      connect(m_inviteListDialog, SIGNAL(sendInvitation(const QString&)),
-              this, SLOT(onSendInvitation(const QString&)));
-      connect(this, SIGNAL(waitForContactList()),
-              m_contactManager, SLOT(onWaitForContactList()));
-      connect(m_contactManager, SIGNAL(contactAliasListReady(const QStringList&)),
-              m_inviteListDialog, SLOT(onContactAliasListReady(const QStringList&)));
-      connect(m_contactManager, SIGNAL(contactIdListReady(const QStringList&)),
-              m_inviteListDialog, SLOT(onContactIdListReady(const QStringList&)));
-    }
+    connect(ui->inviteButton, SIGNAL(clicked()),
+            this, SLOT(onInviteListDialogRequested()));
+    connect(m_inviteListDialog, SIGNAL(sendInvitation(const QString&)),
+            this, SLOT(onSendInvitation(const QString&)));
+    connect(this, SIGNAL(waitForContactList()),
+            m_contactManager, SLOT(onWaitForContactList()));
+    connect(m_contactManager, SIGNAL(contactAliasListReady(const QStringList&)),
+            m_inviteListDialog, SLOT(onContactAliasListReady(const QStringList&)));
+    connect(m_contactManager, SIGNAL(contactIdListReady(const QStringList&)),
+            m_inviteListDialog, SLOT(onContactIdListReady(const QStringList&)));
+  }
 
   initializeSync();
 }
@@ -147,46 +163,48 @@
 
 ChatDialog::~ChatDialog()
 {
-  if(m_certListPrefixId)
+  if (m_certListPrefixId)
     m_face->unsetInterestFilter(m_certListPrefixId);
 
-  if(m_certSinglePrefixId)
+  if (m_certSinglePrefixId)
     m_face->unsetInterestFilter(m_certSinglePrefixId);
 
-  if(m_sock != NULL)
-    {
-      sendLeave();
-      delete m_sock;
-      m_sock = NULL;
-    }
+  if (m_sock != NULL) {
+    sendLeave();
+    delete m_sock;
+    m_sock = NULL;
+  }
 }
 
 // public methods:
 void
 ChatDialog::addSyncAnchor(const Invitation& invitation)
 {
-  _LOG_DEBUG("Add sync anchor from invation");
+  // _LOG_DEBUG("Add sync anchor from invation");
   // Add inviter certificate as trust anchor.
   m_sock->addParticipant(invitation.getInviterCertificate());
   plotTrustTree();
 
   // Ask inviter for IntroCertificate
-  Name inviterNameSpace = IdentityCertificate::certificateNameToPublicKeyName(invitation.getInviterCertificate().getName()).getPrefix(-1);
+  Name inviterNameSpace =
+    IdentityCertificate::certificateNameToPublicKeyName(
+      invitation.getInviterCertificate().getName()).getPrefix(-1);
   fetchIntroCert(inviterNameSpace, invitation.getInviterRoutingPrefix());
 }
 
 void
-ChatDialog::processTreeUpdateWrapper(const std::vector<Sync::MissingDataInfo>& v, Sync::SyncSocket *sock)
+ChatDialog::processTreeUpdateWrapper(const vector<Sync::MissingDataInfo>& v,
+                                     Sync::SyncSocket *sock)
 {
   emit processTreeUpdate(v);
-  _LOG_DEBUG("<<< Tree update signal emitted");
+  // _LOG_DEBUG("<<< Tree update signal emitted");
 }
 
 void
 ChatDialog::processDataWrapper(const shared_ptr<const Data>& data)
 {
   emit processData(data, true, false);
-  _LOG_DEBUG("<<< " << data->getName() << " fetched");
+  // _LOG_DEBUG("<<< " << data->getName() << " fetched");
 }
 
 void
@@ -196,9 +214,9 @@
 }
 
 void
-ChatDialog::processRemoveWrapper(std::string prefix)
+ChatDialog::processRemoveWrapper(const string& prefix)
 {
-  _LOG_DEBUG("Sync REMOVE signal received for prefix: " << prefix);
+  // _LOG_DEBUG("Sync REMOVE signal received for prefix: " << prefix);
 }
 
 // protected methods:
@@ -217,11 +235,9 @@
 void
 ChatDialog::changeEvent(QEvent *e)
 {
-  switch(e->type())
-  {
+  switch(e->type()) {
   case QEvent::ActivationChange:
-    if (isActiveWindow())
-    {
+    if (isActiveWindow()) {
       emit resetIcon();
     }
     break;
@@ -250,29 +266,35 @@
   m_certSinglePrefix.clear();
   m_localChatPrefix.clear();
   m_chatPrefix.clear();
-  m_chatPrefix.append(m_identity).append("CHRONOCHAT-DATA").append(m_chatroomName).append(getRandomString());
-  if(!m_localPrefix.isPrefixOf(m_identity))
-    {
-      m_useRoutablePrefix = true;
-      m_certListPrefix.append(m_localPrefix).append(CHRONOS_RP_SEPARATOR, 2);
-      m_certSinglePrefix.append(m_localPrefix).append(CHRONOS_RP_SEPARATOR, 2);
-      m_localChatPrefix.append(m_localPrefix).append(CHRONOS_RP_SEPARATOR, 2);
-    }
+  m_chatPrefix.append(m_identity)
+    .append("CHRONOCHAT-DATA")
+    .append(m_chatroomName)
+    .append(getRandomString());
+  if (!m_localPrefix.isPrefixOf(m_identity)) {
+    m_useRoutablePrefix = true;
+    m_certListPrefix.append(m_localPrefix).append(CHRONOS_RP_SEPARATOR, 2);
+    m_certSinglePrefix.append(m_localPrefix).append(CHRONOS_RP_SEPARATOR, 2);
+    m_localChatPrefix.append(m_localPrefix).append(CHRONOS_RP_SEPARATOR, 2);
+  }
   m_certListPrefix.append(m_identity).append("CHRONOCHAT-CERT-LIST").append(m_chatroomName);
   m_certSinglePrefix.append(m_identity).append("CHRONOCHAT-CERT-SINGLE").append(m_chatroomName);
   m_localChatPrefix.append(m_chatPrefix);
 
-  if(m_certListPrefixId)
+  if (m_certListPrefixId)
     m_face->unsetInterestFilter(m_certListPrefixId);
-  m_certListPrefixId = m_face->setInterestFilter (m_certListPrefix,
-                                                  bind(&ChatDialog::onCertListInterest, this, _1, _2),
-                                                  bind(&ChatDialog::onCertListRegisterFailed, this, _1, _2));
+  m_certListPrefixId = m_face->setInterestFilter(m_certListPrefix,
+                                                 bind(&ChatDialog::onCertListInterest,
+                                                      this, _1, _2),
+                                                 bind(&ChatDialog::onCertListRegisterFailed,
+                                                      this, _1, _2));
 
-  if(m_certSinglePrefixId)
+  if (m_certSinglePrefixId)
     m_face->unsetInterestFilter(m_certSinglePrefixId);
-  m_certSinglePrefixId = m_face->setInterestFilter (m_certSinglePrefix,
-                                                    bind(&ChatDialog::onCertSingleInterest, this, _1, _2),
-                                                    bind(&ChatDialog::onCertSingleRegisterFailed, this, _1, _2));
+  m_certSinglePrefixId = m_face->setInterestFilter(m_certSinglePrefix,
+                                                   bind(&ChatDialog::onCertSingleInterest,
+                                                        this, _1, _2),
+                                                   bind(&ChatDialog::onCertSingleRegisterFailed,
+                                                        this, _1, _2));
 }
 
 void
@@ -283,19 +305,20 @@
   ui->infoLabel->setText(settingDisp);
   QString prefixDisp;
   Name privatePrefix("/private/local");
-  if(privatePrefix.isPrefixOf(m_localChatPrefix))
-    {
-      prefixDisp =
-        QString("<Warning: no connection to hub or hub does not support prefix autoconfig.>\n <Prefix = %1>")
-        .arg(QString::fromStdString(m_localChatPrefix.toUri()));
-      ui->prefixLabel->setStyleSheet("QLabel {color: red; font-size: 12px; font: bold \"Verdana\";}");
-    }
-  else
-    {
-      prefixDisp = QString("<Prefix = %1>")
-        .arg(QString::fromStdString(m_localChatPrefix.toUri()));
-      ui->prefixLabel->setStyleSheet("QLabel {color: Green; font-size: 12px; font: bold \"Verdana\";}");
-    }
+  if (privatePrefix.isPrefixOf(m_localChatPrefix)) {
+    prefixDisp =
+      QString("<Warning: no connection to hub or hub does not support prefix autoconfig.>\n"
+              "<Prefix = %1>")
+      .arg(QString::fromStdString(m_localChatPrefix.toUri()));
+    ui->prefixLabel->setStyleSheet(
+      "QLabel {color: red; font-size: 12px; font: bold \"Verdana\";}");
+  }
+  else {
+    prefixDisp = QString("<Prefix = %1>")
+      .arg(QString::fromStdString(m_localChatPrefix.toUri()));
+    ui->prefixLabel->setStyleSheet(
+      "QLabel {color: Green; font-size: 12px; font: bold \"Verdana\";}");
+  }
   ui->prefixLabel->setText(prefixDisp);
 }
 
@@ -337,28 +360,30 @@
   Interest tmpInterest(invitation.getUnsignedInterestName());
   m_keyChain.sign(tmpInterest, m_myCertificate.getName());
 
-  // Get invitee's routable prefix (ideally it will do some DNS lookup, but we assume everyone use /ndn/broadcast
+  // Get invitee's routable prefix
+  // (ideally it will do some DNS lookup, but we assume everyone use /ndn/broadcast
   Name routablePrefix = getInviteeRoutablePrefix(contact->getNameSpace());
 
   // Check if we need to prepend the routable prefix to the interest name.
   bool requireRoutablePrefix = false;
   Name interestName;
   size_t routablePrefixOffset = 0;
-  if(!routablePrefix.isPrefixOf(tmpInterest.getName()))
-    {
-      interestName.append(routablePrefix).append(CHRONOS_RP_SEPARATOR, 2);
-      requireRoutablePrefix = true;
-      routablePrefixOffset = routablePrefix.size() + 1;
-    }
+  if (!routablePrefix.isPrefixOf(tmpInterest.getName())) {
+    interestName.append(routablePrefix).append(CHRONOS_RP_SEPARATOR, 2);
+    requireRoutablePrefix = true;
+    routablePrefixOffset = routablePrefix.size() + 1;
+  }
   interestName.append(tmpInterest.getName());
 
   // Send the invitation out
   Interest interest(interestName);
   interest.setMustBeFresh(true);
-  _LOG_DEBUG("sendInvitation: " << interest.getName());
+  // _LOG_DEBUG("sendInvitation: " << interest.getName());
   m_face->expressInterest(interest,
-                          bind(&ChatDialog::replyWrapper, this, _1, _2, routablePrefixOffset, isIntroducer),
-                          bind(&ChatDialog::replyTimeoutWrapper, this, _1, routablePrefixOffset));
+                          bind(&ChatDialog::replyWrapper,
+                               this, _1, _2, routablePrefixOffset, isIntroducer),
+                          bind(&ChatDialog::replyTimeoutWrapper,
+                               this, _1, routablePrefixOffset));
 }
 
 void
@@ -367,16 +392,16 @@
                          size_t routablePrefixOffset,
                          bool isIntroducer)
 {
-  _LOG_DEBUG("ChatDialog::replyWrapper");
+  // _LOG_DEBUG("ChatDialog::replyWrapper");
   emit reply(interest, data.shared_from_this(), routablePrefixOffset, isIntroducer);
-  _LOG_DEBUG("OK?");
+  // _LOG_DEBUG("OK?");
 }
 
 void
 ChatDialog::replyTimeoutWrapper(const Interest& interest,
                                 size_t routablePrefixOffset)
 {
-  _LOG_DEBUG("ChatDialog::replyTimeoutWrapper");
+  // _LOG_DEBUG("ChatDialog::replyTimeoutWrapper");
   emit replyTimeout(interest, routablePrefixOffset);
 }
 
@@ -385,26 +410,25 @@
                              size_t inviteeRoutablePrefixOffset,
                              bool isIntroducer)
 {
-  if(data->getName().size() <= inviteeRoutablePrefixOffset)
-    {
-      Invitation invitation(data->getName());
-      invitationRejected(invitation.getInviteeNameSpace());
-    }
-  else
-    {
-      Name inviteePrefix;
-      inviteePrefix.wireDecode(data->getName().get(inviteeRoutablePrefixOffset).blockFromValue());
-      IdentityCertificate inviteeCert;
-      inviteeCert.wireDecode(data->getContent().blockFromValue());
-      invitationAccepted(inviteeCert, inviteePrefix, isIntroducer);
-    }
+  if (data->getName().size() <= inviteeRoutablePrefixOffset) {
+    Invitation invitation(data->getName());
+    invitationRejected(invitation.getInviteeNameSpace());
+  }
+  else {
+    Name inviteePrefix;
+    inviteePrefix.wireDecode(data->getName().get(inviteeRoutablePrefixOffset).blockFromValue());
+    IdentityCertificate inviteeCert;
+    inviteeCert.wireDecode(data->getContent().blockFromValue());
+    invitationAccepted(inviteeCert, inviteePrefix, isIntroducer);
+  }
 }
 
 void
 ChatDialog::onReplyValidationFailed(const shared_ptr<const Data>& data,
-                                    const std::string& failureInfo)
+                                    const string& failureInfo)
 {
-  _LOG_DEBUG("Invitation reply cannot be validated: " + failureInfo + " ==> " + data->getName().toUri());
+  // _LOG_DEBUG("Invitation reply cannot be validated: " + failureInfo + " ==> " +
+  //            data->getName().toUri());
 }
 
 void
@@ -424,7 +448,8 @@
   plotTrustTree();
 
   // Ask invitee for IntroCertificate.
-  Name inviteeNameSpace = IdentityCertificate::certificateNameToPublicKeyName(inviteeCert.getName()).getPrefix(-1);
+  Name inviteeNameSpace =
+    IdentityCertificate::certificateNameToPublicKeyName(inviteeCert.getName()).getPrefix(-1);
   fetchIntroCert(inviteeNameSpace, inviteePrefix);
 }
 
@@ -433,7 +458,7 @@
 {
   Name interestName;
 
-  if(!prefix.isPrefixOf(identity))
+  if (!prefix.isPrefixOf(identity))
     interestName.append(prefix).append(CHRONOS_RP_SEPARATOR, 2);
 
   interestName.append(identity)
@@ -454,33 +479,34 @@
 ChatDialog::onIntroCertList(const Interest& interest, const Data& data)
 {
   Chronos::IntroCertListMsg introCertList;
-  if(!introCertList.ParseFromArray(data.getContent().value(), data.getContent().value_size()))
+  if (!introCertList.ParseFromArray(data.getContent().value(), data.getContent().value_size()))
     return;
 
-  for(int i = 0; i < introCertList.certname_size(); i++)
-    {
-      Name certName(introCertList.certname(i));
-      Interest interest(certName);
-      interest.setMustBeFresh(true);
+  for (int i = 0; i < introCertList.certname_size(); i++) {
+    Name certName(introCertList.certname(i));
+    Interest interest(certName);
+    interest.setMustBeFresh(true);
 
-      _LOG_DEBUG("onIntroCertList: to fetch " << certName);
+    // _LOG_DEBUG("onIntroCertList: to fetch " << certName);
 
-      m_face->expressInterest(interest,
-                              bind(&ChatDialog::introCertWrapper, this, _1, _2),
-                              bind(&ChatDialog::introCertTimeoutWrapper, this, _1, 0,
-                                   QString("IntroCert: %1").arg(introCertList.certname(i).c_str())));
-    }
+    m_face->expressInterest(interest,
+                            bind(&ChatDialog::introCertWrapper, this, _1, _2),
+                            bind(&ChatDialog::introCertTimeoutWrapper, this, _1, 0,
+                                 QString("IntroCert: %1").arg(introCertList.certname(i).c_str())));
+  }
 }
 
 void
-ChatDialog::onIntroCertListTimeout(const Interest& interest, int retry, const std::string& msg)
+ChatDialog::onIntroCertListTimeout(const Interest& interest, int retry, const string& msg)
 {
-  if(retry > 0)
+  if (retry > 0) {
     m_face->expressInterest(interest,
                             bind(&ChatDialog::onIntroCertList, this, _1, _2),
                             bind(&ChatDialog::onIntroCertListTimeout, this, _1, retry - 1, msg));
-  else
-    _LOG_DEBUG(msg << " TIMEOUT!");
+  }
+  else {
+    // _LOG_DEBUG(msg << " TIMEOUT!");
+  }
 }
 
 void
@@ -496,21 +522,18 @@
 }
 
 void
-ChatDialog::onCertListInterest(const Name& prefix, const ndn::Interest& interest)
+ChatDialog::onCertListInterest(const Name& prefix, const Interest& interest)
 {
-  std::vector<Name> certNameList;
+  vector<Name> certNameList;
   m_sock->getIntroCertNames(certNameList);
 
   Chronos::IntroCertListMsg msg;
 
-  std::vector<Name>::const_iterator it  = certNameList.begin();
-  std::vector<Name>::const_iterator end = certNameList.end();
-  for(; it != end; it++)
-    {
-      Name certName;
-      certName.append(m_certSinglePrefix).append(*it);
-      msg.add_certname(certName.toUri());
-    }
+  for (vector<Name>::const_iterator it = certNameList.begin(); it != certNameList.end(); it++) {
+    Name certName;
+    certName.append(m_certSinglePrefix).append(*it);
+    msg.add_certname(certName.toUri());
+  }
   OBufferStream os;
   msg.SerializeToOstream(&os);
 
@@ -522,33 +545,31 @@
 }
 
 void
-ChatDialog::onCertListRegisterFailed(const Name& prefix, const std::string& msg)
+ChatDialog::onCertListRegisterFailed(const Name& prefix, const string& msg)
 {
-  _LOG_DEBUG("ChatDialog::onCertListRegisterFailed failed: " + msg);
+  // _LOG_DEBUG("ChatDialog::onCertListRegisterFailed failed: " + msg);
 }
 
 void
-ChatDialog::onCertSingleInterest(const Name& prefix, const ndn::Interest& interest)
+ChatDialog::onCertSingleInterest(const Name& prefix, const Interest& interest)
 {
-  try
-    {
-      Name certName = interest.getName().getSubName(prefix.size());
-      const Sync::IntroCertificate& introCert = m_sock->getIntroCertificate(certName);
-      Data data(interest.getName());
-      data.setContent(introCert.wireEncode());
-      m_keyChain.sign(data,  m_myCertificate.getName());
-      m_face->put(data);
-    }
-  catch(Sync::SyncSocket::Error& e)
-    {
-      return;
-    }
+  try {
+    Name certName = interest.getName().getSubName(prefix.size());
+    const Sync::IntroCertificate& introCert = m_sock->getIntroCertificate(certName);
+    Data data(interest.getName());
+    data.setContent(introCert.wireEncode());
+    m_keyChain.sign(data,  m_myCertificate.getName());
+    m_face->put(data);
+  }
+  catch(Sync::SyncSocket::Error& e) {
+    return;
+  }
 }
 
 void
-ChatDialog::onCertSingleRegisterFailed(const Name& prefix, const std::string& msg)
+ChatDialog::onCertSingleRegisterFailed(const Name& prefix, const string& msg)
 {
-  _LOG_DEBUG("ChatDialog::onCertListRegisterFailed failed: " + msg);
+  // _LOG_DEBUG("ChatDialog::onCertListRegisterFailed failed: " + msg);
 }
 
 void
@@ -558,9 +579,9 @@
   OBufferStream os;
   msg.SerializeToOstream(&os);
 
-  if (!msg.IsInitialized())
-  {
-    _LOG_DEBUG("Errrrr.. msg was not probally initialized "<<__FILE__ <<":"<<__LINE__<<". what is happening?");
+  if (!msg.IsInitialized()) {
+    // _LOG_DEBUG("Errrrr.. msg was not probally initialized " << __FILE__ <<
+    //            ":" << __LINE__ << ". what is happening?");
     abort();
   }
   uint64_t nextSequence = m_sock->getNextSeq();
@@ -568,8 +589,10 @@
 
   m_lastMsgTime = time::toUnixTimestamp(time::system_clock::now()).count();
 
-  Sync::MissingDataInfo mdi = {m_localChatPrefix.toUri(), Sync::SeqNo(0), Sync::SeqNo(nextSequence)};
-  std::vector<Sync::MissingDataInfo> v;
+  Sync::MissingDataInfo mdi = {m_localChatPrefix.toUri(),
+                               Sync::SeqNo(0),
+                               Sync::SeqNo(nextSequence)};
+  vector<Sync::MissingDataInfo> v;
   v.push_back(mdi);
   {
     boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
@@ -591,21 +614,16 @@
 {
   boost::recursive_mutex::scoped_lock lock(m_msgMutex);
 
-  if (msg.type() == SyncDemo::ChatMessage::CHAT)
-  {
-
-    if (!msg.has_data())
-    {
+  if (msg.type() == SyncDemo::ChatMessage::CHAT) {
+    if (!msg.has_data()) {
       return;
     }
 
-    if (msg.from().empty() || msg.data().empty())
-    {
+    if (msg.from().empty() || msg.data().empty()) {
       return;
     }
 
-    if (!msg.has_timestamp())
-    {
+    if (!msg.has_timestamp()) {
       return;
     }
 
@@ -639,14 +657,12 @@
     nextCursor.movePosition(QTextCursor::End);
     table = nextCursor.insertTable(1, 1, tableFormat);
     table->cellAt(0, 0).firstCursorPosition().insertText(QString::fromUtf8(msg.data().c_str()));
-    if (!isHistory)
-    {
+    if (!isHistory) {
       showMessage(from, QString::fromUtf8(msg.data().c_str()));
     }
   }
 
-  if (msg.type() == SyncDemo::ChatMessage::JOIN || msg.type() == SyncDemo::ChatMessage::LEAVE)
-  {
+  if (msg.type() == SyncDemo::ChatMessage::JOIN || msg.type() == SyncDemo::ChatMessage::LEAVE) {
     QTextCharFormat nickFormat;
     nickFormat.setForeground(Qt::gray);
     nickFormat.setFontWeight(QFont::Bold);
@@ -659,12 +675,10 @@
     tableFormat.setBorder(0);
     QTextTable *table = cursor.insertTable(1, 2, tableFormat);
     QString action;
-    if (msg.type() == SyncDemo::ChatMessage::JOIN)
-    {
+    if (msg.type() == SyncDemo::ChatMessage::JOIN) {
       action = "enters room";
     }
-    else
-    {
+    else {
       action = "leaves room";
     }
 
@@ -684,11 +698,10 @@
 void
 ChatDialog::processRemove(QString prefix)
 {
-  _LOG_DEBUG("<<< remove node for prefix" << prefix.toStdString());
+  // _LOG_DEBUG("<<< remove node for prefix" << prefix.toStdString());
 
   bool removed = m_scene->removeNode(prefix);
-  if (removed)
-  {
+  if (removed) {
     boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
     m_scene->plot(m_sock->getRootDigest().c_str());
   }
@@ -697,7 +710,7 @@
 Name
 ChatDialog::getInviteeRoutablePrefix(const Name& invitee)
 {
-  return ndn::Name("/ndn/broadcast");
+  return Name("/ndn/broadcast");
 }
 
 void
@@ -705,17 +718,20 @@
   msg.set_from(m_nick);
   msg.set_to(m_chatroomName);
   msg.set_data(text.toStdString());
-  int32_t seconds = static_cast<int32_t>(time::toUnixTimestamp(time::system_clock::now()).count()/1000000000);
+  int32_t seconds =
+    static_cast<int32_t>(time::toUnixTimestamp(time::system_clock::now()).count()/1000000000);
   msg.set_timestamp(seconds);
   msg.set_type(SyncDemo::ChatMessage::CHAT);
 }
 
 void
-ChatDialog::formControlMessage(SyncDemo::ChatMessage &msg, SyncDemo::ChatMessage::ChatMessageType type)
+ChatDialog::formControlMessage(SyncDemo::ChatMessage &msg,
+                               SyncDemo::ChatMessage::ChatMessageType type)
 {
   msg.set_from(m_nick);
   msg.set_to(m_chatroomName);
-  int32_t seconds = static_cast<int32_t>(time::toUnixTimestamp(time::system_clock::now()).count()/1000000000);
+  int32_t seconds =
+    static_cast<int32_t>(time::toUnixTimestamp(time::system_clock::now()).count()/1000000000);
   msg.set_timestamp(seconds);
   msg.set_type(type);
 }
@@ -726,22 +742,20 @@
   struct tm *tm_time = localtime(&timestamp);
   int hour = tm_time->tm_hour;
   QString amOrPM;
-  if (hour > 12)
-  {
+  if (hour > 12) {
     hour -= 12;
     amOrPM = "PM";
   }
-  else
-  {
+  else {
     amOrPM = "AM";
-    if (hour == 0)
-    {
+    if (hour == 0) {
       hour = 12;
     }
   }
 
   char textTime[12];
-  sprintf(textTime, "%d:%02d:%02d %s", hour, tm_time->tm_min, tm_time->tm_sec, amOrPM.toStdString().c_str());
+  sprintf(textTime, "%d:%02d:%02d %s",
+          hour, tm_time->tm_min, tm_time->tm_sec, amOrPM.toStdString().c_str());
   return QString(textTime);
 }
 
@@ -757,10 +771,10 @@
   timeCell.firstCursorPosition().insertText(formatTime(timestamp));
 }
 
-std::string
+string
 ChatDialog::getRandomString()
 {
-  uint32_t r = random::generateWord32();
+  uint32_t r = ndn::random::generateWord32();
   std::stringstream ss;
   {
     using namespace CryptoPP;
@@ -797,32 +811,27 @@
 ChatDialog::summonReaper()
 {
   Sync::SyncLogic &logic = m_sock->getLogic ();
-  std::map<std::string, bool> branches = logic.getBranchPrefixes();
+  map<string, bool> branches = logic.getBranchPrefixes();
   QMap<QString, DisplayUserPtr> roster = m_scene->getRosterFull();
 
   m_zombieList.clear();
 
   QMapIterator<QString, DisplayUserPtr> it(roster);
-  std::map<std::string, bool>::iterator mapIt;
-  while(it.hasNext())
-  {
+  map<string, bool>::iterator mapIt;
+  while (it.hasNext()) {
     it.next();
     DisplayUserPtr p = it.value();
-    if (p != DisplayUserNullPtr)
-    {
+    if (p != DisplayUserNullPtr) {
       mapIt = branches.find(p->getPrefix().toStdString());
-      if (mapIt != branches.end())
-      {
+      if (mapIt != branches.end()) {
         mapIt->second = true;
       }
     }
   }
 
-  for (mapIt = branches.begin(); mapIt != branches.end(); ++mapIt)
-  {
+  for (mapIt = branches.begin(); mapIt != branches.end(); ++mapIt) {
     // this is zombie. all active users should have been marked true
-    if (! mapIt->second)
-    {
+    if (! mapIt->second) {
       m_zombieList.append(mapIt->first.c_str());
     }
   }
@@ -836,77 +845,70 @@
 void
 ChatDialog::getTree(TrustTreeNodeList& nodeList)
 {
-  typedef std::map<Name, shared_ptr<TrustTreeNode> > NodeMap;
+  typedef map<Name, shared_ptr<TrustTreeNode> > NodeMap;
 
-  std::vector<Name> certNameList;
+  vector<Name> certNameList;
   NodeMap nodeMap;
 
   m_sock->getIntroCertNames(certNameList);
 
-  std::vector<Name>::const_iterator it  = certNameList.begin();
-  std::vector<Name>::const_iterator end = certNameList.end();
-  for(; it != end; it++)
-    {
-      Name introducerCertName;
-      Name introduceeCertName;
+  for (vector<Name>::const_iterator it = certNameList.begin(); it != certNameList.end(); it++) {
+    Name introducerCertName;
+    Name introduceeCertName;
 
-      introducerCertName.wireDecode(it->get(-2).blockFromValue());
-      introduceeCertName.wireDecode(it->get(-3).blockFromValue());
+    introducerCertName.wireDecode(it->get(-2).blockFromValue());
+    introduceeCertName.wireDecode(it->get(-3).blockFromValue());
 
-      Name introducerName = IdentityCertificate::certificateNameToPublicKeyName(introducerCertName).getPrefix(-1);
-      Name introduceeName = IdentityCertificate::certificateNameToPublicKeyName(introduceeCertName).getPrefix(-1);
+    Name introducerName =
+      IdentityCertificate::certificateNameToPublicKeyName(introducerCertName).getPrefix(-1);
+    Name introduceeName =
+      IdentityCertificate::certificateNameToPublicKeyName(introduceeCertName).getPrefix(-1);
 
-      NodeMap::iterator introducerIt = nodeMap.find(introducerName);
-      if(introducerIt == nodeMap.end())
-        {
-          shared_ptr<TrustTreeNode> introducerNode(new TrustTreeNode(introducerName));
-          nodeMap[introducerName] = introducerNode;
-        }
-      shared_ptr<TrustTreeNode> erNode = nodeMap[introducerName];
-
-      NodeMap::iterator introduceeIt = nodeMap.find(introduceeName);
-      if(introduceeIt == nodeMap.end())
-        {
-          shared_ptr<TrustTreeNode> introduceeNode(new TrustTreeNode(introduceeName));
-          nodeMap[introduceeName] = introduceeNode;
-        }
-      shared_ptr<TrustTreeNode> eeNode = nodeMap[introduceeName];
-
-      erNode->addIntroducee(eeNode);
-      eeNode->addIntroducer(erNode);
+    NodeMap::iterator introducerIt = nodeMap.find(introducerName);
+    if (introducerIt == nodeMap.end()) {
+      shared_ptr<TrustTreeNode> introducerNode(new TrustTreeNode(introducerName));
+      nodeMap[introducerName] = introducerNode;
     }
+    shared_ptr<TrustTreeNode> erNode = nodeMap[introducerName];
+
+    NodeMap::iterator introduceeIt = nodeMap.find(introduceeName);
+    if (introduceeIt == nodeMap.end()) {
+      shared_ptr<TrustTreeNode> introduceeNode(new TrustTreeNode(introduceeName));
+      nodeMap[introduceeName] = introduceeNode;
+    }
+    shared_ptr<TrustTreeNode> eeNode = nodeMap[introduceeName];
+
+    erNode->addIntroducee(eeNode);
+    eeNode->addIntroducer(erNode);
+  }
 
   nodeList.clear();
-  std::queue<shared_ptr<TrustTreeNode> > nodeQueue;
+  queue<shared_ptr<TrustTreeNode> > nodeQueue;
 
   NodeMap::iterator nodeIt = nodeMap.find(m_identity);
-  if(nodeIt == nodeMap.end())
+  if (nodeIt == nodeMap.end())
     return;
 
   nodeQueue.push(nodeIt->second);
   nodeIt->second->setLevel(0);
-  while(!nodeQueue.empty())
-    {
-      shared_ptr<TrustTreeNode>& node = nodeQueue.front();
-      node->setVisited();
+  while (!nodeQueue.empty()) {
+    shared_ptr<TrustTreeNode>& node = nodeQueue.front();
+    node->setVisited();
 
-      TrustTreeNodeList& introducees = node->getIntroducees();
-      TrustTreeNodeList::iterator eeIt  = introducees.begin();
-      TrustTreeNodeList::iterator eeEnd = introducees.end();
-
-      for(; eeIt != eeEnd; eeIt++)
-        {
-          _LOG_DEBUG("introducee: " << (*eeIt)->name() << " visited: " << boolalpha << (*eeIt)->visited());
-          if(!(*eeIt)->visited())
-            {
-              nodeQueue.push(*eeIt);
-              (*eeIt)->setLevel(node->level()+1);
-            }
-        }
-
-      nodeList.push_back(node);
-      nodeQueue.pop();
+    TrustTreeNodeList& introducees = node->getIntroducees();
+    for (TrustTreeNodeList::iterator eeIt = introducees.begin();
+         eeIt != introducees.end(); eeIt++) {
+      // _LOG_DEBUG("introducee: " << (*eeIt)->name() <<
+      //            " visited: " << std::boolalpha << (*eeIt)->visited());
+      if (!(*eeIt)->visited()) {
+        nodeQueue.push(*eeIt);
+        (*eeIt)->setLevel(node->level()+1);
+      }
     }
+
+    nodeList.push_back(node);
+    nodeQueue.pop();
+  }
 }
 
 void
@@ -927,53 +929,50 @@
 ChatDialog::onLocalPrefixUpdated(const QString& localPrefix)
 {
   Name newLocalPrefix(localPrefix.toStdString());
-  if(!newLocalPrefix.empty() && newLocalPrefix != m_localPrefix)
-    {
-      // Update localPrefix
-      m_localPrefix = newLocalPrefix;
+  if (!newLocalPrefix.empty() && newLocalPrefix != m_localPrefix) {
+    // Update localPrefix
+    m_localPrefix = newLocalPrefix;
 
-      updatePrefix();
-      updateLabels();
-      m_scene->setCurrentPrefix(QString(m_localChatPrefix.toUri().c_str()));
+    updatePrefix();
+    updateLabels();
+    m_scene->setCurrentPrefix(QString(m_localChatPrefix.toUri().c_str()));
 
-      if(m_sock != NULL)
-        {
-          {
-            boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
-            m_scene->clearAll();
-            m_scene->plot("Empty");
-          }
+    if (m_sock != NULL) {
+      {
+        boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
+        m_scene->clearAll();
+        m_scene->plot("Empty");
+      }
 
-          ui->textEdit->clear();
+      ui->textEdit->clear();
 
-          if (m_joined)
-            {
-              sendLeave();
-            }
+      if (m_joined) {
+        sendLeave();
+      }
 
-          delete m_sock;
-          m_sock = NULL;
+      delete m_sock;
+      m_sock = NULL;
 
-          usleep(100000);
-          m_sock = new Sync::SyncSocket(m_chatroomPrefix,
-                                        m_chatPrefix,
-                                        m_session,
-                                        m_useRoutablePrefix,
-                                        m_localPrefix,
-                                        m_face,
-                                        m_myCertificate,
-                                        m_dataRule,
-                                        bind(&ChatDialog::processTreeUpdateWrapper, this, _1, _2),
-                                        bind(&ChatDialog::processRemoveWrapper, this, _1));
-          usleep(100000);
-          QTimer::singleShot(600, this, SLOT(sendJoin()));
-          m_timer->start(FRESHNESS * 1000);
-          disableSyncTreeDisplay();
-          QTimer::singleShot(2200, this, SLOT(enableSyncTreeDisplay()));
-        }
-      else
-        initializeSync();
+      usleep(100000);
+      m_sock = new Sync::SyncSocket(m_chatroomPrefix,
+                                    m_chatPrefix,
+                                    m_session,
+                                    m_useRoutablePrefix,
+                                    m_localPrefix,
+                                    m_face,
+                                    m_myCertificate,
+                                    m_dataRule,
+                                    bind(&ChatDialog::processTreeUpdateWrapper, this, _1, _2),
+                                    bind(&ChatDialog::processRemoveWrapper, this, _1));
+      usleep(100000);
+      QTimer::singleShot(600, this, SLOT(sendJoin()));
+      m_timer->start(FRESHNESS * 1000);
+      disableSyncTreeDisplay();
+      QTimer::singleShot(2200, this, SLOT(enableSyncTreeDisplay()));
     }
+    else
+      initializeSync();
+  }
   else
     if (m_sock == NULL)
       initializeSync();
@@ -999,16 +998,14 @@
 
   ui->lineEdit->clear();
 
-  if (text.startsWith("boruoboluomi"))
-  {
+  if (text.startsWith("boruoboluomi")) {
     summonReaper ();
     // reapButton->show();
     fitView();
     return;
   }
 
-  if (text.startsWith("minimanihong"))
-  {
+  if (text.startsWith("minimanihong")) {
     // reapButton->hide();
     fitView();
     return;
@@ -1027,13 +1024,11 @@
 void
 ChatDialog::onSyncTreeButtonPressed()
 {
-  if (ui->syncTreeViewer->isVisible())
-  {
+  if (ui->syncTreeViewer->isVisible()) {
     ui->syncTreeViewer->hide();
     ui->syncTreeButton->setText("Show ChronoSync Tree");
   }
-  else
-  {
+  else {
     ui->syncTreeViewer->show();
     ui->syncTreeButton->setText("Hide ChronoSync Tree");
   }
@@ -1044,13 +1039,11 @@
 void
 ChatDialog::onTrustTreeButtonPressed()
 {
-  if (ui->trustTreeViewer->isVisible())
-  {
+  if (ui->trustTreeViewer->isVisible()) {
     ui->trustTreeViewer->hide();
     ui->trustTreeButton->setText("Show Trust Tree");
   }
-  else
-  {
+  else {
     ui->trustTreeViewer->show();
     ui->trustTreeButton->setText("Hide Trust Tree");
   }
@@ -1063,9 +1056,9 @@
 {
   SyncDemo::ChatMessage msg;
   bool corrupted = false;
-  if (!msg.ParseFromArray(data->getContent().value(), data->getContent().value_size()))
-  {
-    _LOG_DEBUG("Errrrr.. Can not parse msg with name: " << data->getName() << ". what is happening?");
+  if (!msg.ParseFromArray(data->getContent().value(), data->getContent().value_size())) {
+    // _LOG_DEBUG("Errrrr.. Can not parse msg with name: " <<
+    //            data->getName() << ". what is happening?");
     // nasty stuff: as a remedy, we'll form some standard msg for inparsable msgs
     msg.set_from("inconnu");
     msg.set_type(SyncDemo::ChatMessage::OTHER);
@@ -1077,22 +1070,18 @@
   // so if we call appendMsg directly
   // Qt crash as "QObject: Cannot create children for a parent that is in a different thread"
   // the "cannonical" way to is use signal-slot
-  if (show && !corrupted)
-  {
+  if (show && !corrupted) {
     appendMessage(msg, isHistory);
   }
 
-  if (!isHistory)
-  {
+  if (!isHistory) {
     // update the tree view
-    std::string prefix = data->getName().getPrefix(-2).toUri();
-    _LOG_DEBUG("<<< updating scene for" << prefix << ": " << msg.from());
-    if (msg.type() == SyncDemo::ChatMessage::LEAVE)
-    {
+    string prefix = data->getName().getPrefix(-2).toUri();
+    // _LOG_DEBUG("<<< updating scene for" << prefix << ": " << msg.from());
+    if (msg.type() == SyncDemo::ChatMessage::LEAVE) {
       processRemove(prefix.c_str());
     }
-    else
-    {
+    else {
       boost::recursive_mutex::scoped_lock lock(m_sceneMutex);
       m_scene->msgReceived(prefix.c_str(), msg.from().c_str());
     }
@@ -1101,12 +1090,11 @@
 }
 
 void
-ChatDialog::onProcessTreeUpdate(const std::vector<Sync::MissingDataInfo>& v)
+ChatDialog::onProcessTreeUpdate(const vector<Sync::MissingDataInfo>& v)
 {
-  _LOG_DEBUG("<<< processing Tree Update");
+  // _LOG_DEBUG("<<< processing Tree Update");
 
-  if (v.empty())
-  {
+  if (v.empty()) {
     return;
   }
 
@@ -1118,24 +1106,20 @@
 
   int n = v.size();
   int totalMissingPackets = 0;
-  for (int i = 0; i < n; i++)
-  {
+  for (int i = 0; i < n; i++) {
     totalMissingPackets += v[i].high.getSeq() - v[i].low.getSeq() + 1;
   }
 
-  for (int i = 0; i < n; i++)
-  {
-    if (totalMissingPackets < 4)
-    {
-      for (Sync::SeqNo seq = v[i].low; seq <= v[i].high; ++seq)
-      {
+  for (int i = 0; i < n; i++) {
+    if (totalMissingPackets < 4) {
+      for (Sync::SeqNo seq = v[i].low; seq <= v[i].high; ++seq) {
         m_sock->fetchData(v[i].prefix, seq, bind(&ChatDialog::processDataWrapper, this, _1), 2);
-        _LOG_DEBUG("<<< Fetching " << v[i].prefix << "/" <<seq.getSession() <<"/" << seq.getSeq());
+        // _LOG_DEBUG("<<< Fetching " << v[i].prefix << "/" <<seq.getSession() <<"/" << seq.getSeq());
       }
     }
-    else
-    {
-        m_sock->fetchData(v[i].prefix, v[i].high, bind(&ChatDialog::processDataNoShowWrapper, this, _1), 2);
+    else {
+      m_sock->fetchData(v[i].prefix, v[i].high,
+                        bind(&ChatDialog::processDataNoShowWrapper, this, _1), 2);
     }
   }
   // adjust the view
@@ -1158,9 +1142,8 @@
   m_rosterModel->setStringList(rosterList);
   QString user;
   QStringListIterator it(staleUserList);
-  while(it.hasNext())
-  {
-    std::string nick = it.next().toStdString();
+  while (it.hasNext()) {
+    string nick = it.next().toStdString();
     if (nick.empty())
       continue;
 
@@ -1198,8 +1181,7 @@
 {
   int64_t now = time::toUnixTimestamp(time::system_clock::now()).count();
   int elapsed = (now - m_lastMsgTime) / 1000000000;
-  if (elapsed >= m_randomizedInterval / 1000)
-  {
+  if (elapsed >= m_randomizedInterval / 1000) {
     SyncDemo::ChatMessage msg;
     formControlMessage(msg, SyncDemo::ChatMessage::HELLO);
     sendMsg(msg);
@@ -1208,8 +1190,7 @@
     m_randomizedInterval = HELLO_INTERVAL * 1000 + uniform(rng);
     QTimer::singleShot(m_randomizedInterval, this, SLOT(sendHello()));
   }
-  else
-  {
+  else {
     QTimer::singleShot((m_randomizedInterval - elapsed * 1000), this, SLOT(sendHello()));
   }
 }
@@ -1224,7 +1205,7 @@
   m_sock->leave();
   usleep(5000);
   m_joined = false;
-  _LOG_DEBUG("Sync REMOVE signal sent");
+  // _LOG_DEBUG("Sync REMOVE signal sent");
 }
 
 void ChatDialog::enableSyncTreeDisplay()
@@ -1237,11 +1218,10 @@
 void
 ChatDialog::reap()
 {
-  if (m_zombieIndex < m_zombieList.size())
-  {
-    std::string prefix = m_zombieList.at(m_zombieIndex).toStdString();
+  if (m_zombieIndex < m_zombieList.size()) {
+    string prefix = m_zombieList.at(m_zombieIndex).toStdString();
     m_sock->remove(prefix);
-    _LOG_DEBUG("Reaped: prefix = " << prefix);
+    // _LOG_DEBUG("Reaped: prefix = " << prefix);
     m_zombieIndex++;
     // reap again in 10 seconds
     QTimer::singleShot(10000, this, SLOT(reap()));
@@ -1264,19 +1244,19 @@
 {
   OnDataValidated onValidated = bind(&ChatDialog::onReplyValidated,
                                      this, _1,
-                                     interest.getName().size()-routablePrefixOffset, //RoutablePrefix will be removed before data is passed to the validator
+                                     //RoutablePrefix will be removed before passing to validator
+                                     interest.getName().size()-routablePrefixOffset,
                                      isIntroducer);
 
   OnDataValidationFailed onFailed = bind(&ChatDialog::onReplyValidationFailed,
                                          this, _1, _2);
 
-  if(routablePrefixOffset > 0)
-    {
-      // It is an encapsulated packet, we only validate the inner packet.
-      shared_ptr<Data> innerData = make_shared<Data>();
-      innerData->wireDecode(data->getContent().blockFromValue());
-      m_invitationValidator->validate(*innerData, onValidated, onFailed);
-    }
+  if (routablePrefixOffset > 0) {
+    // It is an encapsulated packet, we only validate the inner packet.
+    shared_ptr<Data> innerData = make_shared<Data>();
+    innerData->wireDecode(data->getContent().blockFromValue());
+    m_invitationValidator->validate(*innerData, onValidated, onFailed);
+  }
   else
     m_invitationValidator->validate(*data, onValidated, onFailed);
 }
@@ -1286,14 +1266,15 @@
                            size_t routablePrefixOffset)
 {
   Name interestName;
-  if(routablePrefixOffset > 0)
+  if (routablePrefixOffset > 0)
     interestName = interest.getName().getSubName(routablePrefixOffset);
   else
     interestName = interest.getName();
 
   Invitation invitation(interestName);
 
-  QString msg = QString::fromUtf8("Your invitation to ") + QString::fromStdString(invitation.getInviteeNameSpace().toUri()) + " times out!";
+  QString msg = QString::fromUtf8("Your invitation to ") +
+    QString::fromStdString(invitation.getInviteeNameSpace().toUri()) + " times out!";
   emit inivationRejection(msg);
 }
 
@@ -1310,9 +1291,10 @@
 void
 ChatDialog::onIntroCertTimeout(const Interest& interest, int retry, const QString& msg)
 {
-  _LOG_DEBUG("onIntroCertTimeout: " << msg.toStdString());
+  // _LOG_DEBUG("onIntroCertTimeout: " << msg.toStdString());
 }
 
+} // namespace chronos
 
 #if WAF
 #include "chat-dialog.moc"
diff --git a/src/chat-dialog.h b/src/chat-dialog.h
deleted file mode 100644
index 7902e09..0000000
--- a/src/chat-dialog.h
+++ /dev/null
@@ -1,359 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
- *         Alexander Afanasyev <alexander.afanasyev@ucla.edu>
- *         Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef CHAT_DIALOG_H
-#define CHAT_DIALOG_H
-
-#include <QDialog>
-#include <QTextTable>
-#include <QStringListModel>
-#include <QSystemTrayIcon>
-#include <QMenu>
-#include <QTimer>
-
-#include "invite-list-dialog.h"
-
-#ifndef Q_MOC_RUN
-#include "contact-manager.h"
-#include "invitation.h"
-#include "contact.h"
-#include "chatbuf.pb.h"
-#include "intro-cert-list.pb.h"
-#include "digest-tree-scene.h"
-#include "trust-tree-scene.h"
-#include "trust-tree-node.h"
-#include <sync-socket.h>
-#include <sync-seq-no.h>
-#include <ndn-cxx/security/key-chain.hpp>
-#include "validator-invitation.h"
-#include <boost/thread/locks.hpp>
-#include <boost/thread/recursive_mutex.hpp>
-#include <boost/thread/thread.hpp>
-#endif
-
-#define MAX_HISTORY_ENTRY   20
-
-namespace Ui {
-class ChatDialog;
-}
-
-class ChatDialog : public QDialog
-{
-  Q_OBJECT
-
-public:
-  explicit
-  ChatDialog(chronos::ContactManager* contactManager,
-             ndn::shared_ptr<ndn::Face> face,
-             const ndn::IdentityCertificate& myCertificate,
-             const ndn::Name& chatroomPrefix,
-             const ndn::Name& localPrefix,
-             const std::string& nick,
-             bool witSecurity,
-             QWidget* parent = 0);
-
-  ~ChatDialog();
-
-  void
-  addSyncAnchor(const chronos::Invitation& invitation);
-
-  void
-  processTreeUpdateWrapper(const std::vector<Sync::MissingDataInfo>&, Sync::SyncSocket *);
-
-  void
-  processDataWrapper(const ndn::shared_ptr<const ndn::Data>& data);
-
-  void
-  processDataNoShowWrapper(const ndn::shared_ptr<const ndn::Data>& data);
-
-  void
-  processRemoveWrapper(std::string);
-
-protected:
-  void
-  closeEvent(QCloseEvent *e);
-
-  void
-  changeEvent(QEvent *e);
-
-  void
-  resizeEvent(QResizeEvent *);
-
-  void
-  showEvent(QShowEvent *);
-
-private:
-  void
-  updatePrefix();
-
-  void
-  updateLabels();
-
-  void
-  initializeSync();
-
-  void
-  sendInvitation(ndn::shared_ptr<chronos::Contact> contact, bool isIntroducer);
-
-  void
-  replyWrapper(const ndn::Interest& interest,
-               ndn::Data& data,
-               size_t routablePrefixOffset,
-               bool isIntroducer);
-
-  void
-  replyTimeoutWrapper(const ndn::Interest& interest,
-                      size_t routablePrefixOffset);
-
-  void
-  onReplyValidated(const ndn::shared_ptr<const ndn::Data>& data,
-                   size_t inviteeRoutablePrefixOffset,
-                   bool isIntroduce);
-
-  void
-  onReplyValidationFailed(const ndn::shared_ptr<const ndn::Data>& data,
-                          const std::string& failureInfo);
-
-  void
-  invitationRejected(const ndn::Name& identity);
-
-  void
-  invitationAccepted(const ndn::IdentityCertificate& inviteeCert,
-                     const ndn::Name& inviteePrefix,
-                     bool isIntroducer);
-
-  void
-  fetchIntroCert(const ndn::Name& identity, const ndn::Name& prefix);
-
-  void
-  onIntroCertList(const ndn::Interest& interest, const ndn::Data& data);
-
-  void
-  onIntroCertListTimeout(const ndn::Interest& interest, int retry, const std::string& msg);
-
-  void
-  introCertWrapper(const ndn::Interest& interest, ndn::Data& data);
-
-  void
-  introCertTimeoutWrapper(const ndn::Interest& interest, int retry, const QString& msg);
-
-  void
-  onCertListInterest(const ndn::Name& prefix, const ndn::Interest& interest);
-
-  void
-  onCertListRegisterFailed(const ndn::Name& prefix, const std::string& msg);
-
-  void
-  onCertSingleInterest(const ndn::Name& prefix, const ndn::Interest& interest);
-
-  void
-  onCertSingleRegisterFailed(const ndn::Name& prefix, const std::string& msg);
-
-
-  void
-  sendMsg(SyncDemo::ChatMessage &msg);
-
-  void
-  disableSyncTreeDisplay();
-
-  void
-  appendMessage(const SyncDemo::ChatMessage msg, bool isHistory = false);
-
-  void
-  processRemove(QString prefix);
-
-  ndn::Name
-  getInviteeRoutablePrefix(const ndn::Name& invitee);
-
-  void
-  formChatMessage(const QString &text, SyncDemo::ChatMessage &msg);
-
-  void
-  formControlMessage(SyncDemo::ChatMessage &msg, SyncDemo::ChatMessage::ChatMessageType type);
-
-  QString
-  formatTime(time_t);
-
-  void
-  printTimeInCell(QTextTable *, time_t);
-
-  std::string
-  getRandomString();
-
-  void
-  showMessage(const QString&, const QString&);
-
-  void
-  fitView();
-
-  void
-  summonReaper();
-
-  void
-  getTree(TrustTreeNodeList& nodeList);
-
-  void
-  plotTrustTree();
-
-signals:
-  void
-  processData(const ndn::shared_ptr<const ndn::Data>& data, bool show, bool isHistory);
-
-  void
-  processTreeUpdate(const std::vector<Sync::MissingDataInfo>);
-
-  void
-  closeChatDialog(const QString& chatroomName);
-
-  void
-  inivationRejection(const QString& msg);
-
-  void
-  showChatMessage(const QString& chatroomName, const QString& from, const QString& data);
-
-  void
-  resetIcon();
-
-  void
-  reply(const ndn::Interest& interest,
-        const ndn::shared_ptr<const ndn::Data>& data,
-        size_t routablePrefixOffset, bool isIntroducer);
-
-  void
-  replyTimeout(const ndn::Interest& interest,
-               size_t routablePrefixOffset);
-
-  void
-  introCert(const ndn::Interest& interest,
-            const ndn::shared_ptr<const ndn::Data>& data);
-
-  void
-  introCertTimeout(const ndn::Interest& interest,
-                   int retry, const QString& msg);
-
-  void
-  waitForContactList();
-
-public slots:
-  void
-  onLocalPrefixUpdated(const QString& localPrefix);
-
-  void
-  onClose();
-
-private slots:
-  void
-  onReturnPressed();
-
-  void
-  onSyncTreeButtonPressed();
-
-  void
-  onTrustTreeButtonPressed();
-
-  void
-  onProcessData(const ndn::shared_ptr<const ndn::Data>& data,
-                bool show, bool isHistory);
-
-  void
-  onProcessTreeUpdate(const std::vector<Sync::MissingDataInfo>&);
-
-  void
-  onReplot();
-
-  void
-  onRosterChanged(QStringList);
-
-  void
-  onInviteListDialogRequested();
-
-  void
-  sendJoin();
-
-  void
-  sendHello();
-
-  void
-  sendLeave();
-
-  void
-  enableSyncTreeDisplay();
-
-  void
-  reap();
-
-  void
-  onSendInvitation(QString);
-
-  void
-  onReply(const ndn::Interest& interest,
-          const ndn::shared_ptr<const ndn::Data>& data,
-          size_t routablePrefixOffset, bool isIntroducer);
-
-  void
-  onReplyTimeout(const ndn::Interest& interest,
-                 size_t routablePrefixOffset);
-
-  void
-  onIntroCert(const ndn::Interest& interest,
-              const ndn::shared_ptr<const ndn::Data>& data);
-
-  void
-  onIntroCertTimeout(const ndn::Interest& interest,
-                     int retry, const QString& msg);
-
-private:
-  Ui::ChatDialog *ui;
-  ndn::KeyChain m_keyChain;
-
-  chronos::ContactManager* m_contactManager;
-  ndn::shared_ptr<ndn::Face> m_face;
-
-  ndn::IdentityCertificate m_myCertificate;
-  ndn::Name m_identity;
-
-  ndn::Name m_certListPrefix;
-  const ndn::RegisteredPrefixId* m_certListPrefixId;
-  ndn::Name m_certSinglePrefix;
-  const ndn::RegisteredPrefixId* m_certSinglePrefixId;
-
-  std::string m_chatroomName;
-  ndn::Name m_chatroomPrefix;
-  ndn::Name m_localPrefix;
-  bool m_useRoutablePrefix;
-  ndn::Name m_chatPrefix;
-  ndn::Name m_localChatPrefix;
-  std::string m_nick;
-  DigestTreeScene *m_scene;
-  TrustTreeScene *m_trustScene;
-  QStringListModel *m_rosterModel;
-  QTimer* m_timer;
-
-
-  int64_t m_lastMsgTime;
-  int m_randomizedInterval;
-  bool m_joined;
-
-  Sync::SyncSocket *m_sock;
-  uint64_t m_session;
-  ndn::shared_ptr<ndn::SecRuleRelative> m_dataRule;
-
-  InviteListDialog* m_inviteListDialog;
-  ndn::shared_ptr<chronos::ValidatorInvitation> m_invitationValidator;
-
-  boost::recursive_mutex m_msgMutex;
-  boost::recursive_mutex m_sceneMutex;
-  QList<QString> m_zombieList;
-  int m_zombieIndex;
-};
-
-#endif // CHAT_DIALOG_H
diff --git a/src/chat-dialog.hpp b/src/chat-dialog.hpp
new file mode 100644
index 0000000..12051f1
--- /dev/null
+++ b/src/chat-dialog.hpp
@@ -0,0 +1,352 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ *         Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ *         Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_CHAT_DIALOG_HPP
+#define CHRONOS_CHAT_DIALOG_HPP
+
+#include <QDialog>
+#include <QTextTable>
+#include <QStringListModel>
+#include <QSystemTrayIcon>
+#include <QMenu>
+#include <QTimer>
+
+#ifndef Q_MOC_RUN
+#include "common.hpp"
+#include "contact-manager.hpp"
+#include "invitation.hpp"
+#include "contact.hpp"
+#include "chatbuf.pb.h"
+#include "intro-cert-list.pb.h"
+#include "digest-tree-scene.hpp"
+#include "trust-tree-scene.hpp"
+#include "trust-tree-node.hpp"
+#include "validator-invitation.hpp"
+#include <sync-socket.h>
+#include <sync-seq-no.h>
+#include <ndn-cxx/security/key-chain.hpp>
+#include <boost/thread/locks.hpp>
+#include <boost/thread/recursive_mutex.hpp>
+#include <boost/thread/thread.hpp>
+#endif
+
+#include "invite-list-dialog.hpp"
+
+
+#define MAX_HISTORY_ENTRY   20
+
+namespace Ui {
+class ChatDialog;
+}
+
+namespace chronos {
+
+class ChatDialog : public QDialog
+{
+  Q_OBJECT
+
+public:
+  explicit
+  ChatDialog(ContactManager* contactManager,
+             shared_ptr<ndn::Face> face,
+             const ndn::IdentityCertificate& myCertificate,
+             const Name& chatroomPrefix,
+             const Name& localPrefix,
+             const std::string& nick,
+             bool witSecurity,
+             QWidget* parent = 0);
+
+  ~ChatDialog();
+
+  void
+  addSyncAnchor(const Invitation& invitation);
+
+  void
+  processTreeUpdateWrapper(const std::vector<Sync::MissingDataInfo>&, Sync::SyncSocket *);
+
+  void
+  processDataWrapper(const shared_ptr<const Data>& data);
+
+  void
+  processDataNoShowWrapper(const shared_ptr<const Data>& data);
+
+  void
+  processRemoveWrapper(const std::string& prefix);
+
+protected:
+  void
+  closeEvent(QCloseEvent* e);
+
+  void
+  changeEvent(QEvent* e);
+
+  void
+  resizeEvent(QResizeEvent* e);
+
+  void
+  showEvent(QShowEvent* e);
+
+private:
+  void
+  updatePrefix();
+
+  void
+  updateLabels();
+
+  void
+  initializeSync();
+
+  void
+  sendInvitation(shared_ptr<Contact> contact, bool isIntroducer);
+
+  void
+  replyWrapper(const Interest& interest, Data& data,
+               size_t routablePrefixOffset, bool isIntroducer);
+
+  void
+  replyTimeoutWrapper(const Interest& interest,
+                      size_t routablePrefixOffset);
+
+  void
+  onReplyValidated(const shared_ptr<const Data>& data,
+                   size_t inviteeRoutablePrefixOffset,
+                   bool isIntroduce);
+
+  void
+  onReplyValidationFailed(const shared_ptr<const Data>& data,
+                          const std::string& failureInfo);
+
+  void
+  invitationRejected(const Name& identity);
+
+  void
+  invitationAccepted(const ndn::IdentityCertificate& inviteeCert,
+                     const Name& inviteePrefix, bool isIntroducer);
+
+  void
+  fetchIntroCert(const Name& identity, const Name& prefix);
+
+  void
+  onIntroCertList(const Interest& interest, const Data& data);
+
+  void
+  onIntroCertListTimeout(const Interest& interest, int retry, const std::string& msg);
+
+  void
+  introCertWrapper(const Interest& interest, Data& data);
+
+  void
+  introCertTimeoutWrapper(const Interest& interest, int retry, const QString& msg);
+
+  void
+  onCertListInterest(const Name& prefix, const Interest& interest);
+
+  void
+  onCertListRegisterFailed(const Name& prefix, const std::string& msg);
+
+  void
+  onCertSingleInterest(const Name& prefix, const Interest& interest);
+
+  void
+  onCertSingleRegisterFailed(const Name& prefix, const std::string& msg);
+
+
+  void
+  sendMsg(SyncDemo::ChatMessage& msg);
+
+  void
+  disableSyncTreeDisplay();
+
+  void
+  appendMessage(const SyncDemo::ChatMessage msg, bool isHistory = false);
+
+  void
+  processRemove(QString prefix);
+
+  ndn::Name
+  getInviteeRoutablePrefix(const Name& invitee);
+
+  void
+  formChatMessage(const QString& text, SyncDemo::ChatMessage& msg);
+
+  void
+  formControlMessage(SyncDemo::ChatMessage &msg, SyncDemo::ChatMessage::ChatMessageType type);
+
+  QString
+  formatTime(time_t timestamp);
+
+  void
+  printTimeInCell(QTextTable* table, time_t timestamp);
+
+  std::string
+  getRandomString();
+
+  void
+  showMessage(const QString&, const QString&);
+
+  void
+  fitView();
+
+  void
+  summonReaper();
+
+  void
+  getTree(TrustTreeNodeList& nodeList);
+
+  void
+  plotTrustTree();
+
+signals:
+  void
+  processData(const shared_ptr<const Data>& data, bool show, bool isHistory);
+
+  void
+  processTreeUpdate(const std::vector<Sync::MissingDataInfo>);
+
+  void
+  closeChatDialog(const QString& chatroomName);
+
+  void
+  inivationRejection(const QString& msg);
+
+  void
+  showChatMessage(const QString& chatroomName, const QString& from, const QString& data);
+
+  void
+  resetIcon();
+
+  void
+  reply(const Interest& interest, const shared_ptr<const Data>& data,
+        size_t routablePrefixOffset, bool isIntroducer);
+
+  void
+  replyTimeout(const Interest& interest, size_t routablePrefixOffset);
+
+  void
+  introCert(const Interest& interest, const shared_ptr<const Data>& data);
+
+  void
+  introCertTimeout(const Interest& interest, int retry, const QString& msg);
+
+  void
+  waitForContactList();
+
+public slots:
+  void
+  onLocalPrefixUpdated(const QString& localPrefix);
+
+  void
+  onClose();
+
+private slots:
+  void
+  onReturnPressed();
+
+  void
+  onSyncTreeButtonPressed();
+
+  void
+  onTrustTreeButtonPressed();
+
+  void
+  onProcessData(const shared_ptr<const Data>& data, bool show, bool isHistory);
+
+  void
+  onProcessTreeUpdate(const std::vector<Sync::MissingDataInfo>&);
+
+  void
+  onReplot();
+
+  void
+  onRosterChanged(QStringList staleUserList);
+
+  void
+  onInviteListDialogRequested();
+
+  void
+  sendJoin();
+
+  void
+  sendHello();
+
+  void
+  sendLeave();
+
+  void
+  enableSyncTreeDisplay();
+
+  void
+  reap();
+
+  void
+  onSendInvitation(QString invitee);
+
+  void
+  onReply(const Interest& interest, const shared_ptr<const Data>& data,
+          size_t routablePrefixOffset, bool isIntroducer);
+
+  void
+  onReplyTimeout(const Interest& interest, size_t routablePrefixOffset);
+
+  void
+  onIntroCert(const Interest& interest, const shared_ptr<const Data>& data);
+
+  void
+  onIntroCertTimeout(const Interest& interest, int retry, const QString& msg);
+
+private:
+  Ui::ChatDialog *ui;
+  ndn::KeyChain m_keyChain;
+
+  ContactManager* m_contactManager;
+  shared_ptr<ndn::Face> m_face;
+
+  ndn::IdentityCertificate m_myCertificate;
+  Name m_identity;
+
+  Name m_certListPrefix;
+  const ndn::RegisteredPrefixId* m_certListPrefixId;
+  Name m_certSinglePrefix;
+  const ndn::RegisteredPrefixId* m_certSinglePrefixId;
+
+  std::string m_chatroomName;
+  Name m_chatroomPrefix;
+  Name m_localPrefix;
+  bool m_useRoutablePrefix;
+  Name m_chatPrefix;
+  Name m_localChatPrefix;
+  std::string m_nick;
+  DigestTreeScene *m_scene;
+  TrustTreeScene *m_trustScene;
+  QStringListModel *m_rosterModel;
+  QTimer* m_timer;
+
+
+  int64_t m_lastMsgTime;
+  int m_randomizedInterval;
+  bool m_joined;
+
+  Sync::SyncSocket *m_sock;
+  uint64_t m_session;
+  shared_ptr<ndn::SecRuleRelative> m_dataRule;
+
+  InviteListDialog* m_inviteListDialog;
+  shared_ptr<ValidatorInvitation> m_invitationValidator;
+
+  boost::recursive_mutex m_msgMutex;
+  boost::recursive_mutex m_sceneMutex;
+  QList<QString> m_zombieList;
+  int m_zombieIndex;
+};
+
+} // namespace chronos
+
+#endif // CHRONOS_CHAT_DIALOG_HPP
diff --git a/src/common.hpp b/src/common.hpp
new file mode 100644
index 0000000..22e5de4
--- /dev/null
+++ b/src/common.hpp
@@ -0,0 +1,77 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * COPYRIGHT MSG GOES HERE...
+ */
+
+#ifndef CHRONOS_COMMON_HPP
+#define CHRONOS_COMMON_HPP
+
+#include "config.h"
+
+#ifdef WITH_TESTS
+#define VIRTUAL_WITH_TESTS virtual
+#define PUBLIC_WITH_TESTS_ELSE_PROTECTED public
+#define PUBLIC_WITH_TESTS_ELSE_PRIVATE public
+#define PROTECTED_WITH_TESTS_ELSE_PRIVATE protected
+#else
+#define VIRTUAL_WITH_TESTS
+#define PUBLIC_WITH_TESTS_ELSE_PROTECTED protected
+#define PUBLIC_WITH_TESTS_ELSE_PRIVATE private
+#define PROTECTED_WITH_TESTS_ELSE_PRIVATE private
+#endif
+
+#include <cstddef>
+#include <list>
+#include <set>
+#include <map>
+#include <queue>
+#include <vector>
+#include <string>
+
+#include <ndn-cxx/common.hpp>
+#include <ndn-cxx/interest.hpp>
+#include <ndn-cxx/data.hpp>
+
+#include <boost/algorithm/string.hpp>
+#include <boost/asio.hpp>
+#include <boost/assert.hpp>
+#include <boost/lexical_cast.hpp>
+#include <boost/noncopyable.hpp>
+#include <boost/property_tree/ptree.hpp>
+
+namespace chronos {
+
+using std::size_t;
+
+using boost::noncopyable;
+
+using ndn::shared_ptr;
+using ndn::weak_ptr;
+using ndn::enable_shared_from_this;
+using ndn::make_shared;
+using ndn::static_pointer_cast;
+using ndn::dynamic_pointer_cast;
+using ndn::const_pointer_cast;
+using ndn::function;
+using ndn::bind;
+using ndn::ref;
+using ndn::cref;
+
+using ndn::Interest;
+using ndn::Data;
+using ndn::Name;
+using ndn::Exclude;
+using ndn::Block;
+using ndn::Signature;
+using ndn::KeyLocator;
+
+namespace tlv {
+using namespace ndn::Tlv;
+}
+
+namespace name = ndn::name;
+namespace time = ndn::time;
+
+} // namespace chronos
+
+#endif // CHRONOS_COMMON_HPP
diff --git a/src/contact-manager.cpp b/src/contact-manager.cpp
index fb792db..7653cd0 100644
--- a/src/contact-manager.cpp
+++ b/src/contact-manager.cpp
@@ -12,7 +12,7 @@
 #pragma clang diagnostic ignored "-Wtautological-compare"
 #endif
 
-#include "contact-manager.h"
+#include "contact-manager.hpp"
 #include <QStringList>
 #include <QFile>
 
@@ -21,24 +21,33 @@
 #include <ndn-cxx/util/io.hpp>
 #include <ndn-cxx/security/sec-rule-relative.hpp>
 #include <ndn-cxx/security/validator-regex.hpp>
-#include <cryptopp/base64.h>
-#include <cryptopp/files.h>
-#include <cryptopp/sha.h>
-#include <cryptopp/filters.h>
+#include "cryptopp.hpp"
 #include <boost/asio.hpp>
 #include <boost/tokenizer.hpp>
 #include <boost/filesystem.hpp>
 #include "logging.h"
 #endif
 
-using namespace ndn;
 namespace fs = boost::filesystem;
 
-INIT_LOGGER("chronos.ContactManager");
+// INIT_LOGGER("chronos.ContactManager");
 
 namespace chronos{
 
-using ndn::shared_ptr;
+using std::string;
+using std::map;
+using std::vector;
+
+using ndn::Face;
+using ndn::OBufferStream;
+using ndn::IdentityCertificate;
+using ndn::Validator;
+using ndn::ValidatorRegex;
+using ndn::SecRuleRelative;
+using ndn::OnDataValidated;
+using ndn::OnDataValidationFailed;
+using ndn::OnInterestValidated;
+using ndn::OnInterestValidationFailed;
 
 static const uint8_t DNS_RP_SEPARATOR[2] = {0xF0, 0x2E}; // %F0.
 
@@ -52,7 +61,8 @@
 }
 
 ContactManager::~ContactManager()
-{}
+{
+}
 
 // private methods
 shared_ptr<IdentityCertificate>
@@ -62,38 +72,33 @@
 
   QFile anchorFile(":/security/anchor.cert");
 
-  if (!anchorFile.open(QIODevice::ReadOnly))
-    {
-      emit warning(QString("Cannot load trust anchor!"));
-
-      return anchor;
-    }
+  if (!anchorFile.open(QIODevice::ReadOnly)) {
+    emit warning(QString("Cannot load trust anchor!"));
+    return anchor;
+  }
 
   qint64 fileSize = anchorFile.size();
   char* buf = new char[fileSize];
   anchorFile.read(buf, fileSize);
 
-  try
-    {
-      using namespace CryptoPP;
+  try {
+    using namespace CryptoPP;
 
-      OBufferStream os;
-      StringSource(reinterpret_cast<const uint8_t*>(buf), fileSize, true, new Base64Decoder(new FileSink(os)));
-      anchor = make_shared<IdentityCertificate>();
-      anchor->wireDecode(Block(os.buf()));
-    }
-  catch(CryptoPP::Exception& e)
-    {
-      emit warning(QString("Cannot load trust anchor!"));
-    }
-  catch(IdentityCertificate::Error& e)
-    {
-      emit warning(QString("Cannot load trust anchor!"));
-    }
-  catch(Block::Error& e)
-    {
-      emit warning(QString("Cannot load trust anchor!"));
-    }
+    OBufferStream os;
+    StringSource(reinterpret_cast<const uint8_t*>(buf), fileSize, true,
+                 new Base64Decoder(new FileSink(os)));
+    anchor = make_shared<IdentityCertificate>();
+    anchor->wireDecode(Block(os.buf()));
+  }
+  catch (CryptoPP::Exception& e) {
+    emit warning(QString("Cannot load trust anchor!"));
+  }
+  catch (IdentityCertificate::Error& e) {
+    emit warning(QString("Cannot load trust anchor!"));
+  }
+  catch(Block::Error& e) {
+    emit warning(QString("Cannot load trust anchor!"));
+  }
 
   delete [] buf;
 
@@ -141,9 +146,12 @@
   interest.setInterestLifetime(time::milliseconds(1000));
   interest.setMustBeFresh(true);
 
-  OnDataValidated onValidated = bind(&ContactManager::onDnsCollectEndorseValidated, this, _1, identity);
-  OnDataValidationFailed onValidationFailed = bind(&ContactManager::onDnsCollectEndorseValidationFailed, this, _1, _2, identity);
-  TimeoutNotify timeoutNotify = bind(&ContactManager::onDnsCollectEndorseTimeoutNotify, this, _1, identity);
+  OnDataValidated onValidated =
+    bind(&ContactManager::onDnsCollectEndorseValidated, this, _1, identity);
+  OnDataValidationFailed onValidationFailed =
+    bind(&ContactManager::onDnsCollectEndorseValidationFailed, this, _1, _2, identity);
+  TimeoutNotify timeoutNotify =
+    bind(&ContactManager::onDnsCollectEndorseTimeoutNotify, this, _1, identity);
 
   sendInterest(interest, onValidated, onValidationFailed, timeoutNotify, 0);
 }
@@ -151,7 +159,8 @@
 void
 ContactManager::fetchEndorseCertificateInternal(const Name& identity, int certIndex)
 {
-  shared_ptr<EndorseCollection> endorseCollection = m_bufferedContacts[identity].m_endorseCollection;
+  shared_ptr<EndorseCollection> endorseCollection =
+    m_bufferedContacts[identity].m_endorseCollection;
 
   if(certIndex >= endorseCollection->endorsement_size())
     prepareEndorseInfo(identity);
@@ -176,58 +185,51 @@
   // _LOG_DEBUG("prepareEndorseInfo");
   const Profile& profile = m_bufferedContacts[identity].m_selfEndorseCert->getProfile();
 
-  shared_ptr<EndorseInfo> endorseInfo = make_shared<EndorseInfo>();
+  shared_ptr<Chronos::EndorseInfo> endorseInfo = make_shared<Chronos::EndorseInfo>();
   m_bufferedContacts[identity].m_endorseInfo = endorseInfo;
 
-  Profile::const_iterator pIt  = profile.begin();
-  Profile::const_iterator pEnd = profile.end();
-
-  std::map<std::string, int> endorseCount;
-  for(; pIt != pEnd; pIt++)
-    {
-      // _LOG_DEBUG("prepareEndorseInfo: profile[" << pIt->first << "]: " << pIt->second);
-      endorseCount[pIt->first] = 0;
-    }
+  map<string, int> endorseCount;
+  for (Profile::const_iterator pIt = profile.begin(); pIt != profile.end(); pIt++) {
+    // _LOG_DEBUG("prepareEndorseInfo: profile[" << pIt->first << "]: " << pIt->second);
+    endorseCount[pIt->first] = 0;
+  }
 
   int endorseCertCount = 0;
 
-  std::vector<shared_ptr<EndorseCertificate> >::const_iterator cIt  = m_bufferedContacts[identity].m_endorseCertList.begin();
-  std::vector<shared_ptr<EndorseCertificate> >::const_iterator cEnd = m_bufferedContacts[identity].m_endorseCertList.end();
+  vector<shared_ptr<EndorseCertificate> >::const_iterator cIt =
+    m_bufferedContacts[identity].m_endorseCertList.begin();
+  vector<shared_ptr<EndorseCertificate> >::const_iterator cEnd =
+    m_bufferedContacts[identity].m_endorseCertList.end();
 
-  for(; cIt != cEnd; cIt++, endorseCertCount++)
-    {
-      shared_ptr<Contact> contact = getContact((*cIt)->getSigner().getPrefix(-1));
-      if(!static_cast<bool>(contact))
-        continue;
+  for (; cIt != cEnd; cIt++, endorseCertCount++) {
+    shared_ptr<Contact> contact = getContact((*cIt)->getSigner().getPrefix(-1));
+    if (!static_cast<bool>(contact))
+      continue;
 
-      if(!contact->isIntroducer()
-         || !contact->canBeTrustedFor(profile.getIdentityName()))
-        continue;
+    if (!contact->isIntroducer() ||
+        !contact->canBeTrustedFor(profile.getIdentityName()))
+      continue;
 
-      if(!Validator::verifySignature(**cIt, contact->getPublicKey()))
-        continue;
+    if (!Validator::verifySignature(**cIt, contact->getPublicKey()))
+      continue;
 
-      const Profile& tmpProfile = (*cIt)->getProfile();
-      if(tmpProfile != profile)
-        continue;
+    const Profile& tmpProfile = (*cIt)->getProfile();
+    if (tmpProfile != profile)
+      continue;
 
-      const std::vector<std::string>& endorseList = (*cIt)->getEndorseList();
-      std::vector<std::string>::const_iterator eIt = endorseList.begin();
-      for(; eIt != endorseList.end(); eIt++)
-        endorseCount[*eIt] += 1;
-    }
+    const vector<string>& endorseList = (*cIt)->getEndorseList();
+    for (vector<string>::const_iterator eIt = endorseList.begin(); eIt != endorseList.end(); eIt++)
+      endorseCount[*eIt] += 1;
+  }
 
-  pIt  = profile.begin();
-  pEnd = profile.end();
-  for(; pIt != pEnd; pIt++)
-    {
-      EndorseInfo::Endorsement* endorsement = endorseInfo->add_endorsement();
-      endorsement->set_type(pIt->first);
-      endorsement->set_value(pIt->second);
-      std::stringstream ss;
-      ss << endorseCount[pIt->first] << "/" << endorseCertCount;
-      endorsement->set_endorse(ss.str());
-    }
+  for (Profile::const_iterator pIt = profile.begin(); pIt != profile.end(); pIt++) {
+    Chronos::EndorseInfo::Endorsement* endorsement = endorseInfo->add_endorsement();
+    endorsement->set_type(pIt->first);
+    endorsement->set_value(pIt->second);
+    std::stringstream ss;
+    ss << endorseCount[pIt->first] << "/" << endorseCertCount;
+    endorsement->set_endorse(ss.str());
+  }
 
   emit contactEndorseInfoReady (*endorseInfo);
 }
@@ -236,36 +238,32 @@
 ContactManager::onDnsSelfEndorseCertValidated(const shared_ptr<const Data>& data,
                                               const Name& identity)
 {
-  try
-    {
-      Data plainData;
-      plainData.wireDecode(data->getContent().blockFromValue());
-      shared_ptr<EndorseCertificate> selfEndorseCertificate = make_shared<EndorseCertificate>(boost::cref(plainData));
-      if(Validator::verifySignature(plainData, selfEndorseCertificate->getPublicKeyInfo()))
-        {
-          m_bufferedContacts[identity].m_selfEndorseCert = selfEndorseCertificate;
-          fetchCollectEndorse(identity);
-        }
-      else
-        emit contactInfoFetchFailed(QString::fromStdString(identity.toUri()));
+  try {
+    Data plainData;
+    plainData.wireDecode(data->getContent().blockFromValue());
+    shared_ptr<EndorseCertificate> selfEndorseCertificate =
+      make_shared<EndorseCertificate>(boost::cref(plainData));
+    if (Validator::verifySignature(plainData, selfEndorseCertificate->getPublicKeyInfo())) {
+      m_bufferedContacts[identity].m_selfEndorseCert = selfEndorseCertificate;
+      fetchCollectEndorse(identity);
     }
-  catch(Block::Error& e)
-    {
+    else
       emit contactInfoFetchFailed(QString::fromStdString(identity.toUri()));
-    }
-  catch(Data::Error& e)
-    {
-      emit contactInfoFetchFailed(QString::fromStdString(identity.toUri()));
-    }
-  catch(EndorseCertificate::Error& e)
-    {
-      emit contactInfoFetchFailed(QString::fromStdString(identity.toUri()));
-    }
+  }
+  catch(Block::Error& e) {
+    emit contactInfoFetchFailed(QString::fromStdString(identity.toUri()));
+  }
+  catch(Data::Error& e) {
+    emit contactInfoFetchFailed(QString::fromStdString(identity.toUri()));
+  }
+  catch(EndorseCertificate::Error& e) {
+    emit contactInfoFetchFailed(QString::fromStdString(identity.toUri()));
+  }
 }
 
 void
 ContactManager::onDnsSelfEndorseCertValidationFailed(const shared_ptr<const Data>& data,
-                                                     const std::string& failInfo,
+                                                     const string& failInfo,
                                                      const Name& identity)
 {
   // If we cannot validate the Self-Endorse-Certificate, we may retry or fetch id-cert,
@@ -287,37 +285,33 @@
                                              const Name& identity)
 {
   shared_ptr<EndorseCollection> endorseCollection = make_shared<EndorseCollection>();
-  if(!endorseCollection->ParseFromArray(data->getContent().value(), data->getContent().value_size()))
-    {
-      m_bufferedContacts[identity].m_endorseCollection = endorseCollection;
-      fetchEndorseCertificateInternal(identity, 0);
-    }
+  if (!endorseCollection->ParseFromArray(data->getContent().value(),
+                                         data->getContent().value_size())) {
+    m_bufferedContacts[identity].m_endorseCollection = endorseCollection;
+    fetchEndorseCertificateInternal(identity, 0);
+  }
   else
     prepareEndorseInfo(identity);
 }
 
 void
 ContactManager::onDnsCollectEndorseValidationFailed(const shared_ptr<const Data>& data,
-                                                    const std::string& failInfo,
+                                                    const string& failInfo,
                                                     const Name& identity)
 {
   prepareEndorseInfo(identity);
 }
 
 void
-ContactManager::onDnsCollectEndorseTimeoutNotify(const Interest& interest,
-                                                 const Name& identity)
+ContactManager::onDnsCollectEndorseTimeoutNotify(const Interest& interest, const Name& identity)
 {
   // _LOG_DEBUG("onDnsCollectEndorseTimeoutNotify: " << interest.getName());
   prepareEndorseInfo(identity);
 }
 
 void
-ContactManager::onEndorseCertificateInternal(const Interest& interest,
-                                             Data& data,
-                                             const Name& identity,
-                                             int certIndex,
-                                             std::string hash)
+ContactManager::onEndorseCertificateInternal(const Interest& interest, Data& data,
+                                             const Name& identity, int certIndex, string hash)
 {
   std::stringstream ss;
   {
@@ -328,11 +322,11 @@
                  new HashFilter(hash, new FileSink(ss)));
   }
 
-  if(ss.str() == hash)
-    {
-      shared_ptr<EndorseCertificate> endorseCertificate = make_shared<EndorseCertificate>(boost::cref(data));
-      m_bufferedContacts[identity].m_endorseCertList.push_back(endorseCertificate);
-    }
+  if (ss.str() == hash) {
+    shared_ptr<EndorseCertificate> endorseCertificate =
+      make_shared<EndorseCertificate>(boost::cref(data));
+    m_bufferedContacts[identity].m_endorseCertList.push_back(endorseCertificate);
+  }
 
   fetchEndorseCertificateInternal(identity, certIndex+1);
 }
@@ -352,23 +346,20 @@
     boost::recursive_mutex::scoped_lock lock(m_collectCountMutex);
     m_collectCount = m_contactList.size();
 
-    ContactList::iterator it  = m_contactList.begin();
-    ContactList::iterator end = m_contactList.end();
+    for (ContactList::iterator it  = m_contactList.begin(); it != m_contactList.end(); it++) {
+      Name interestName = (*it)->getNameSpace();
+      interestName.append("DNS").append(m_identity.wireEncode()).append("ENDORSEE");
 
-    for(; it != end ; it++)
-      {
-        Name interestName = (*it)->getNameSpace();
-        interestName.append("DNS").append(m_identity.wireEncode()).append("ENDORSEE");
+      Interest interest(interestName);
+      interest.setInterestLifetime(time::milliseconds(1000));
 
-        Interest interest(interestName);
-        interest.setInterestLifetime(time::milliseconds(1000));
+      OnDataValidated onValidated = bind(&ContactManager::onDnsEndorseeValidated, this, _1);
+      OnDataValidationFailed onValidationFailed =
+        bind(&ContactManager::onDnsEndorseeValidationFailed, this, _1, _2);
+      TimeoutNotify timeoutNotify = bind(&ContactManager::onDnsEndorseeTimeoutNotify, this, _1);
 
-        OnDataValidated onValidated = bind(&ContactManager::onDnsEndorseeValidated, this, _1);
-        OnDataValidationFailed onValidationFailed = bind(&ContactManager::onDnsEndorseeValidationFailed, this, _1, _2);
-        TimeoutNotify timeoutNotify = bind(&ContactManager::onDnsEndorseeTimeoutNotify, this, _1);
-
-        sendInterest(interest, onValidated, onValidationFailed, timeoutNotify, 0);
-      }
+      sendInterest(interest, onValidated, onValidationFailed, timeoutNotify, 0);
+    }
   }
 }
 
@@ -385,7 +376,8 @@
 }
 
 void
-ContactManager::onDnsEndorseeValidationFailed(const shared_ptr<const Data>& data, const std::string& failInfo)
+ContactManager::onDnsEndorseeValidationFailed(const shared_ptr<const Data>& data,
+                                              const string& failInfo)
 {
   decreaseCollectStatus();
 }
@@ -441,16 +433,17 @@
 }
 
 void
-ContactManager::onIdentityCertValidationFailed(const shared_ptr<const Data>& data, const std::string& failInfo)
+ContactManager::onIdentityCertValidationFailed(const shared_ptr<const Data>& data,
+                                               const string& failInfo)
 {
-  _LOG_DEBUG("ContactManager::onIdentityCertValidationFailed " << data->getName());
+  // _LOG_DEBUG("ContactManager::onIdentityCertValidationFailed " << data->getName());
   decreaseIdCertCount();
 }
 
 void
 ContactManager::onIdentityCertTimeoutNotify(const Interest& interest)
 {
-  _LOG_DEBUG("ContactManager::onIdentityCertTimeoutNotify: " << interest.getName());
+  // _LOG_DEBUG("ContactManager::onIdentityCertTimeoutNotify: " << interest.getName());
   decreaseIdCertCount();
 }
 
@@ -464,23 +457,20 @@
     count = m_idCertCount;
   }
 
-  if(count == 0)
-    {
-      QStringList certNameList;
-      QStringList nameList;
+  if (count == 0) {
+    QStringList certNameList;
+    QStringList nameList;
 
-      BufferedIdCerts::const_iterator it  = m_bufferedIdCerts.begin();
-      BufferedIdCerts::const_iterator end = m_bufferedIdCerts.end();
-      for(; it != end; it++)
-        {
-          certNameList << QString::fromStdString(it->second->getName().toUri());
-          Profile profile(*(it->second));
-          nameList << QString::fromStdString(profile.get("name"));
-        }
-
-      emit idCertNameListReady(certNameList);
-      emit nameListReady(nameList);
+    for(BufferedIdCerts::const_iterator it = m_bufferedIdCerts.begin();
+        it != m_bufferedIdCerts.end(); it++) {
+      certNameList << QString::fromStdString(it->second->getName().toUri());
+      Profile profile(*(it->second));
+      nameList << QString::fromStdString(profile.get("name"));
     }
+
+    emit idCertNameListReady(certNameList);
+    emit nameListReady(nameList);
+  }
 }
 
 shared_ptr<EndorseCertificate>
@@ -490,13 +480,14 @@
 
   shared_ptr<IdentityCertificate> signingCert = m_keyChain.getCertificate(certificateName);
 
-  std::vector<std::string> endorseList;
-  Profile::const_iterator it = profile.begin();
-  for(; it != profile.end(); it++)
+  vector<string> endorseList;
+  for (Profile::const_iterator it = profile.begin(); it != profile.end(); it++)
     endorseList.push_back(it->first);
 
   shared_ptr<EndorseCertificate> selfEndorseCertificate =
-    shared_ptr<EndorseCertificate>(new EndorseCertificate(*signingCert, profile, endorseList));
+    make_shared<EndorseCertificate>(boost::cref(*signingCert),
+                                    boost::cref(profile),
+                                    boost::cref(endorseList));
 
   m_keyChain.sign(*selfEndorseCertificate, certificateName);
 
@@ -524,12 +515,12 @@
 ContactManager::generateEndorseCertificate(const Name& identity)
 {
   shared_ptr<Contact> contact = getContact(identity);
-  if(!static_cast<bool>(contact))
+  if (!static_cast<bool>(contact))
     return shared_ptr<EndorseCertificate>();
 
   Name signerKeyName = m_keyChain.getDefaultKeyNameForIdentity(m_identity);
 
-  std::vector<std::string> endorseList;
+  vector<string> endorseList;
   m_contactStorage->getEndorseList(identity, endorseList);
 
   shared_ptr<EndorseCertificate> cert =
@@ -561,7 +552,7 @@
 
   m_keyChain.signByIdentity(data, m_identity);
 
-  m_contactStorage->updateDnsEndorseOthers(data, dnsName.get(-3).toEscapedString());
+  m_contactStorage->updateDnsEndorseOthers(data, dnsName.get(-3).toUri());
   m_face->put(data);
 }
 
@@ -597,7 +588,7 @@
                                 const TimeoutNotify& timeoutNotify)
 {
   // _LOG_DEBUG("On interest timeout: " << interest.getName());
-  if(retry > 0)
+  if (retry > 0)
     sendInterest(interest, onValidated, onValidationFailed, timeoutNotify, retry-1);
   else
     timeoutNotify(interest);
@@ -609,25 +600,23 @@
   const Name& interestName = interest.getName();
   shared_ptr<Data> data;
 
-  if(interestName.size() <= prefix.size())
+  if (interestName.size() <= prefix.size())
     return;
 
-  if(interestName.size() == (prefix.size()+1))
-    {
-      data = m_contactStorage->getDnsData("N/A", interestName.get(prefix.size()).toEscapedString());
-      if(static_cast<bool>(data))
-        m_face->put(*data);
-      return;
-    }
+  if (interestName.size() == (prefix.size()+1)) {
+    data = m_contactStorage->getDnsData("N/A", interestName.get(prefix.size()).toUri());
+    if (static_cast<bool>(data))
+      m_face->put(*data);
+    return;
+  }
 
-  if(interestName.size() == (prefix.size()+2))
-    {
-      data = m_contactStorage->getDnsData(interestName.get(prefix.size()).toEscapedString(),
-                                          interestName.get(prefix.size()+1).toEscapedString());
-      if(static_cast<bool>(data))
-        m_face->put(*data);
-      return;
-    }
+  if (interestName.size() == (prefix.size()+2)) {
+    data = m_contactStorage->getDnsData(interestName.get(prefix.size()).toUri(),
+                                        interestName.get(prefix.size()+1).toUri());
+    if (static_cast<bool>(data))
+      m_face->put(*data);
+    return;
+  }
 }
 
 void
@@ -645,14 +634,16 @@
 
   m_contactStorage = make_shared<ContactStorage>(m_identity);
 
-  if(m_dnsListenerId)
+  if (m_dnsListenerId)
     m_face->unsetInterestFilter(m_dnsListenerId);
 
   Name dnsPrefix;
   dnsPrefix.append(m_identity).append("DNS");
   m_dnsListenerId = m_face->setInterestFilter(dnsPrefix,
-                                              bind(&ContactManager::onDnsInterest, this, _1, _2),
-                                              bind(&ContactManager::onDnsRegisterFailed, this, _1, _2));
+                                              bind(&ContactManager::onDnsInterest,
+                                                   this, _1, _2),
+                                              bind(&ContactManager::onDnsRegisterFailed,
+                                                   this, _1, _2));
 
   m_contactList.clear();
   m_contactStorage->getAllContacts(m_contactList);
@@ -676,9 +667,12 @@
   interest.setInterestLifetime(time::milliseconds(1000));
   interest.setMustBeFresh(true);
 
-  OnDataValidated onValidated = bind(&ContactManager::onDnsSelfEndorseCertValidated, this, _1, identityName);
-  OnDataValidationFailed onValidationFailed = bind(&ContactManager::onDnsSelfEndorseCertValidationFailed, this, _1, _2, identityName);
-  TimeoutNotify timeoutNotify = bind(&ContactManager::onDnsSelfEndorseCertTimeoutNotify, this, _1, identityName);
+  OnDataValidated onValidated =
+    bind(&ContactManager::onDnsSelfEndorseCertValidated, this, _1, identityName);
+  OnDataValidationFailed onValidationFailed =
+    bind(&ContactManager::onDnsSelfEndorseCertValidationFailed, this, _1, _2, identityName);
+  TimeoutNotify timeoutNotify =
+    bind(&ContactManager::onDnsSelfEndorseCertTimeoutNotify, this, _1, identityName);
 
   sendInterest(interest, onValidated, onValidationFailed, timeoutNotify, 0);
 }
@@ -691,29 +685,24 @@
   Name identityName(identity.toStdString());
 
   BufferedContacts::const_iterator it = m_bufferedContacts.find(identityName);
-  if(it != m_bufferedContacts.end())
-    {
-      Contact contact(*(it->second.m_selfEndorseCert));
-      // _LOG_DEBUG("onAddFetchedContact: contact ready");
-      try
-        {
-          m_contactStorage->addContact(contact);
-          m_bufferedContacts.erase(identityName);
+  if (it != m_bufferedContacts.end()) {
+    Contact contact(*(it->second.m_selfEndorseCert));
+    // _LOG_DEBUG("onAddFetchedContact: contact ready");
+    try {
+      m_contactStorage->addContact(contact);
+      m_bufferedContacts.erase(identityName);
 
-          m_contactList.clear();
-          m_contactStorage->getAllContacts(m_contactList);
+      m_contactList.clear();
+      m_contactStorage->getAllContacts(m_contactList);
 
-          onWaitForContactList();
-        }
-      catch(ContactStorage::Error& e)
-        {
-          emit warning(QString::fromStdString(e.what()));
-        }
+      onWaitForContactList();
     }
+    catch(ContactStorage::Error& e) {
+      emit warning(QString::fromStdString(e.what()));
+    }
+  }
   else
-    {
-      emit warning(QString("Failure: no information of %1").arg(identity));
-    }
+    emit warning(QString("Failure: no information of %1").arg(identity));
 }
 
 void
@@ -721,12 +710,13 @@
 {
   // Get current profile;
   shared_ptr<Profile> newProfile = m_contactStorage->getSelfProfile();
-  if(!static_cast<bool>(newProfile))
+  if (!static_cast<bool>(newProfile))
     return;
 
-  _LOG_DEBUG("ContactManager::onUpdateProfile: getProfile");
+  // _LOG_DEBUG("ContactManager::onUpdateProfile: getProfile");
 
-  shared_ptr<EndorseCertificate> newEndorseCertificate = getSignedSelfEndorseCertificate(*newProfile);
+  shared_ptr<EndorseCertificate> newEndorseCertificate =
+    getSignedSelfEndorseCertificate(*newProfile);
 
   m_contactStorage->addSelfEndorseCertificate(*newEndorseCertificate);
 
@@ -736,102 +726,98 @@
 void
 ContactManager::onRefreshBrowseContact()
 {
-  std::vector<std::string> bufferedIdCertNames;
-  try
-    {
-      using namespace boost::asio::ip;
-      tcp::iostream request_stream;
-      request_stream.expires_from_now(boost::posix_time::milliseconds(5000));
-      request_stream.connect("ndncert.named-data.net","80");
-      if(!request_stream)
-        {
-          emit warning(QString::fromStdString("Fail to fetch certificate directory! #1"));
-          return;
-        }
-
-      request_stream << "GET /cert/list/ HTTP/1.0\r\n";
-      request_stream << "Host: ndncert.named-data.net\r\n\r\n";
-      request_stream.flush();
-
-      std::string line1;
-      std::getline(request_stream,line1);
-      if (!request_stream)
-        {
-          emit warning(QString::fromStdString("Fail to fetch certificate directory! #2"));
-          return;
-        }
-
-      std::stringstream response_stream(line1);
-      std::string http_version;
-      response_stream >> http_version;
-      unsigned int status_code;
-      response_stream >> status_code;
-      std::string status_message;
-      std::getline(response_stream,status_message);
-
-      if (!response_stream||http_version.substr(0,5)!="HTTP/")
-        {
-          emit warning(QString::fromStdString("Fail to fetch certificate directory! #3"));
-          return;
-        }
-      if (status_code!=200)
-        {
-          emit warning(QString::fromStdString("Fail to fetch certificate directory! #4"));
-          return;
-        }
-      std::vector<std::string> headers;
-      std::string header;
-      while (std::getline(request_stream, header) && header != "\r")
-        headers.push_back(header);
-
-      std::istreambuf_iterator<char> stream_iter (request_stream);
-      std::istreambuf_iterator<char> end_of_stream;
-
-      typedef boost::tokenizer< boost::escaped_list_separator<char>, std::istreambuf_iterator<char> > tokenizer_t;
-      tokenizer_t certItems (stream_iter, end_of_stream,boost::escaped_list_separator<char>('\\', '\n', '"'));
-
-      for (tokenizer_t::iterator it = certItems.begin(); it != certItems.end (); it++)
-        if (!it->empty())
-          bufferedIdCertNames.push_back(*it);
+  vector<string> bufferedIdCertNames;
+  try {
+    using namespace boost::asio::ip;
+    tcp::iostream request_stream;
+    request_stream.expires_from_now(boost::posix_time::milliseconds(5000));
+    request_stream.connect("ndncert.named-data.net","80");
+    if (!request_stream) {
+      emit warning(QString::fromStdString("Fail to fetch certificate directory! #1"));
+      return;
     }
-  catch(std::exception &e)
-    {
-      emit warning(QString::fromStdString("Fail to fetch certificate directory! #N"));
+
+    request_stream << "GET /cert/list/ HTTP/1.0\r\n";
+    request_stream << "Host: ndncert.named-data.net\r\n\r\n";
+    request_stream.flush();
+
+    string line1;
+    std::getline(request_stream,line1);
+    if (!request_stream) {
+      emit warning(QString::fromStdString("Fail to fetch certificate directory! #2"));
+      return;
     }
 
+    std::stringstream response_stream(line1);
+    string http_version;
+    response_stream >> http_version;
+    unsigned int status_code;
+    response_stream >> status_code;
+    string status_message;
+    std::getline(response_stream,status_message);
+
+    if (!response_stream ||
+        http_version.substr(0,5) != "HTTP/") {
+      emit warning(QString::fromStdString("Fail to fetch certificate directory! #3"));
+      return;
+    }
+    if (status_code!=200) {
+      emit warning(QString::fromStdString("Fail to fetch certificate directory! #4"));
+      return;
+    }
+    vector<string> headers;
+    string header;
+    while (std::getline(request_stream, header) && header != "\r")
+      headers.push_back(header);
+
+    std::istreambuf_iterator<char> stream_iter (request_stream);
+    std::istreambuf_iterator<char> end_of_stream;
+
+    typedef boost::tokenizer< boost::escaped_list_separator<char>,
+                              std::istreambuf_iterator<char> > tokenizer_t;
+    tokenizer_t certItems (stream_iter,
+                           end_of_stream,
+                           boost::escaped_list_separator<char>('\\', '\n', '"'));
+
+    for (tokenizer_t::iterator it = certItems.begin(); it != certItems.end (); it++)
+      if (!it->empty())
+        bufferedIdCertNames.push_back(*it);
+  }
+  catch(std::exception &e) {
+    emit warning(QString::fromStdString("Fail to fetch certificate directory! #N"));
+  }
+
   {
     boost::recursive_mutex::scoped_lock lock(m_idCertCountMutex);
     m_idCertCount = bufferedIdCertNames.size();
   }
   m_bufferedIdCerts.clear();
 
-  std::vector<std::string>::const_iterator it  = bufferedIdCertNames.begin();
-  std::vector<std::string>::const_iterator end = bufferedIdCertNames.end();
-  for(; it != end; it++)
-    {
-      Name certName(*it);
+  for (vector<string>::const_iterator it = bufferedIdCertNames.begin();
+       it != bufferedIdCertNames.end(); it++) {
+    Name certName(*it);
 
-      Interest interest(certName);
-      interest.setInterestLifetime(time::milliseconds(1000));
-      interest.setMustBeFresh(true);
+    Interest interest(certName);
+    interest.setInterestLifetime(time::milliseconds(1000));
+    interest.setMustBeFresh(true);
 
-      OnDataValidated onValidated = bind(&ContactManager::onIdentityCertValidated, this, _1);
-      OnDataValidationFailed onValidationFailed = bind(&ContactManager::onIdentityCertValidationFailed, this, _1, _2);
-      TimeoutNotify timeoutNotify = bind(&ContactManager::onIdentityCertTimeoutNotify, this, _1);
+    OnDataValidated onValidated =
+    bind(&ContactManager::onIdentityCertValidated, this, _1);
+    OnDataValidationFailed onValidationFailed =
+    bind(&ContactManager::onIdentityCertValidationFailed, this, _1, _2);
+    TimeoutNotify timeoutNotify =
+    bind(&ContactManager::onIdentityCertTimeoutNotify, this, _1);
 
-      sendInterest(interest, onValidated, onValidationFailed, timeoutNotify, 0);
-    }
-
+    sendInterest(interest, onValidated, onValidationFailed, timeoutNotify, 0);
+  }
 }
 
 void
 ContactManager::onFetchIdCert(const QString& qCertName)
 {
   Name certName(qCertName.toStdString());
-  if(m_bufferedIdCerts.find(certName) != m_bufferedIdCerts.end())
-    {
-      emit idCertReady(*m_bufferedIdCerts[certName]);
-    }
+  if (m_bufferedIdCerts.find(certName) != m_bufferedIdCerts.end())
+    emit idCertReady(*m_bufferedIdCerts[certName]);
 }
 
 void
@@ -841,41 +827,35 @@
   Name identity = IdentityCertificate::certificateNameToPublicKeyName(certName).getPrefix(-1);
 
   BufferedIdCerts::const_iterator it = m_bufferedIdCerts.find(certName);
-  if(it != m_bufferedIdCerts.end())
-    {
-      Contact contact(*it->second);
-      try
-        {
-          m_contactStorage->addContact(contact);
-          m_bufferedIdCerts.erase(certName);
+  if (it != m_bufferedIdCerts.end()) {
+    Contact contact(*it->second);
+    try {
+      m_contactStorage->addContact(contact);
+      m_bufferedIdCerts.erase(certName);
 
-          m_contactList.clear();
-          m_contactStorage->getAllContacts(m_contactList);
+      m_contactList.clear();
+      m_contactStorage->getAllContacts(m_contactList);
 
-          onWaitForContactList();
-        }
-      catch(ContactStorage::Error& e)
-        {
-          emit warning(QString::fromStdString(e.what()));
-        }
+      onWaitForContactList();
     }
+    catch(ContactStorage::Error& e) {
+      emit warning(QString::fromStdString(e.what()));
+    }
+  }
   else
-    emit warning(QString("Failure: no information of %1").arg(QString::fromStdString(identity.toUri())));
+    emit warning(QString("Failure: no information of %1")
+                 .arg(QString::fromStdString(identity.toUri())));
 }
 
 void
 ContactManager::onWaitForContactList()
 {
-  ContactList::const_iterator it  = m_contactList.begin();
-  ContactList::const_iterator end = m_contactList.end();
-
   QStringList aliasList;
   QStringList idList;
-  for(; it != end; it++)
-    {
-      aliasList << QString((*it)->getAlias().c_str());
-      idList << QString((*it)->getNameSpace().toUri().c_str());
-    }
+  for (ContactList::const_iterator it = m_contactList.begin(); it != m_contactList.end(); it++) {
+    aliasList << QString((*it)->getAlias().c_str());
+    idList << QString((*it)->getNameSpace().toUri().c_str());
+  }
 
   emit contactAliasListReady(aliasList);
   emit contactIdListReady(idList);
@@ -884,11 +864,8 @@
 void
 ContactManager::onWaitForContactInfo(const QString& identity)
 {
-  ContactList::const_iterator it  = m_contactList.begin();
-  ContactList::const_iterator end = m_contactList.end();
-
-  for(; it != end; it++)
-    if((*it)->getNameSpace().toUri() == identity.toStdString())
+  for (ContactList::const_iterator it = m_contactList.begin(); it != m_contactList.end(); it++)
+    if ((*it)->getNameSpace().toUri() == identity.toStdString())
       emit contactInfoReady(QString((*it)->getNameSpace().toUri().c_str()),
                             QString((*it)->getName().c_str()),
                             QString((*it)->getInstitution().c_str()),
@@ -927,7 +904,7 @@
   Name identityName(identity.toStdString());
   shared_ptr<EndorseCertificate> newEndorseCertificate = generateEndorseCertificate(identityName);
 
-  if(!static_cast<bool>(newEndorseCertificate))
+  if (!static_cast<bool>(newEndorseCertificate))
     return;
 
   m_contactStorage->addEndorseCertificate(*newEndorseCertificate, identityName);
diff --git a/src/contact-manager.h b/src/contact-manager.h
deleted file mode 100644
index 8ab7e81..0000000
--- a/src/contact-manager.h
+++ /dev/null
@@ -1,300 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef CHRONOS_CONTACT_MANAGER_H
-#define CHRONOS_CONTACT_MANAGER_H
-
-#include <QObject>
-
-#ifndef Q_MOC_RUN
-#include "contact-storage.h"
-#include "endorse-certificate.h"
-#include "profile.h"
-#include "endorse-info.pb.h"
-#include "endorse-collection.pb.h"
-#include <ndn-cxx/face.hpp>
-#include <ndn-cxx/security/key-chain.hpp>
-#include <ndn-cxx/security/validator.hpp>
-#include <boost/thread/locks.hpp>
-#include <boost/thread/recursive_mutex.hpp>
-#endif
-
-namespace chronos{
-
-typedef ndn::function<void(const ndn::Interest&)> TimeoutNotify;
-typedef std::vector<ndn::shared_ptr<Contact> > ContactList;
-
-class ContactManager : public QObject
-{
-  Q_OBJECT
-
-public:
-  ContactManager(ndn::shared_ptr<ndn::Face> m_face,
-                 QObject* parent = 0);
-
-  ~ContactManager();
-
-  ndn::shared_ptr<Contact>
-  getContact(const ndn::Name& identity)
-  {
-    return m_contactStorage->getContact(identity);
-  }
-
-  void
-  getContactList(ContactList& contactList)
-  {
-    contactList.clear();
-    contactList.insert(contactList.end(), m_contactList.begin(), m_contactList.end());
-  }
-private:
-  ndn::shared_ptr<ndn::IdentityCertificate>
-  loadTrustAnchor();
-
-  void
-  initializeSecurity();
-
-  void
-  fetchCollectEndorse(const ndn::Name& identity);
-
-  void
-  fetchEndorseCertificateInternal(const ndn::Name& identity, int certIndex);
-
-  void
-  prepareEndorseInfo(const ndn::Name& identity);
-
-  // PROFILE: self-endorse-certificate
-  void
-  onDnsSelfEndorseCertValidated(const ndn::shared_ptr<const ndn::Data>& selfEndorseCertificate,
-                                const ndn::Name& identity);
-
-  void
-  onDnsSelfEndorseCertValidationFailed(const ndn::shared_ptr<const ndn::Data>& selfEndorseCertificate,
-                                       const std::string& failInfo,
-                                       const ndn::Name& identity);
-
-  void
-  onDnsSelfEndorseCertTimeoutNotify(const ndn::Interest& interest,
-                                    const ndn::Name& identity);
-
-  // ENDORSED: endorse-collection
-  void
-  onDnsCollectEndorseValidated(const ndn::shared_ptr<const ndn::Data>& data,
-                               const ndn::Name& identity);
-
-  void
-  onDnsCollectEndorseValidationFailed(const ndn::shared_ptr<const ndn::Data>& data,
-                                      const std::string& failInfo,
-                                      const ndn::Name& identity);
-
-  void
-  onDnsCollectEndorseTimeoutNotify(const ndn::Interest& interest,
-                                   const ndn::Name& identity);
-
-  // PROFILE-CERT: endorse-certificate
-  void
-  onEndorseCertificateInternal(const ndn::Interest& interest,
-                               ndn::Data& data,
-                               const ndn::Name& identity,
-                               int certIndex,
-                               std::string hash);
-
-  void
-  onEndorseCertificateInternalTimeout(const ndn::Interest& interest,
-                                      const ndn::Name& identity,
-                                      int certIndex);
-
-  // Collect endorsement
-  void
-  collectEndorsement();
-
-  void
-  onDnsEndorseeValidated(const ndn::shared_ptr<const ndn::Data>& data);
-
-  void
-  onDnsEndorseeValidationFailed(const ndn::shared_ptr<const ndn::Data>& data,
-                                const std::string& failInfo);
-
-  void
-  onDnsEndorseeTimeoutNotify(const ndn::Interest& interest);
-
-  void
-  decreaseCollectStatus();
-
-  void
-  publishCollectEndorsedDataInDNS();
-
-  // Identity certificate
-  void
-  onIdentityCertValidated(const ndn::shared_ptr<const ndn::Data>& data);
-
-  void
-  onIdentityCertValidationFailed(const ndn::shared_ptr<const ndn::Data>& data,
-                                 const std::string& failInfo);
-
-  void
-  onIdentityCertTimeoutNotify(const ndn::Interest& interest);
-
-  void
-  decreaseIdCertCount();
-
-  // Publish self-endorse certificate
-  ndn::shared_ptr<EndorseCertificate>
-  getSignedSelfEndorseCertificate(const Profile& profile);
-
-  void
-  publishSelfEndorseCertificateInDNS(const EndorseCertificate& selfEndorseCertificate);
-
-  // Publish endorse certificate
-  ndn::shared_ptr<EndorseCertificate>
-  generateEndorseCertificate(const ndn::Name& identity);
-
-  void
-  publishEndorseCertificateInDNS(const EndorseCertificate& endorseCertificate);
-
-  // Communication
-  void
-  sendInterest(const ndn::Interest& interest,
-               const ndn::OnDataValidated& onValidated,
-               const ndn::OnDataValidationFailed& onValidationFailed,
-               const TimeoutNotify& timeoutNotify,
-               int retry = 1);
-
-  void
-  onTargetData(const ndn::Interest& interest,
-               const ndn::Data& data,
-               const ndn::OnDataValidated& onValidated,
-               const ndn::OnDataValidationFailed& onValidationFailed);
-
-  void
-  onTargetTimeout(const ndn::Interest& interest,
-                  int retry,
-                  const ndn::OnDataValidated& onValidated,
-                  const ndn::OnDataValidationFailed& onValidationFailed,
-                  const TimeoutNotify& timeoutNotify);
-
-  // DNS listener
-  void
-  onDnsInterest(const ndn::Name& prefix, const ndn::Interest& interest);
-
-  void
-  onDnsRegisterFailed(const ndn::Name& prefix, const std::string& failInfo);
-
-signals:
-  void
-  contactEndorseInfoReady(const chronos::EndorseInfo& endorseInfo);
-
-  void
-  contactInfoFetchFailed(const QString& identity);
-
-  void
-  idCertNameListReady(const QStringList& certNameList);
-
-  void
-  nameListReady(const QStringList& certNameList);
-
-  void
-  idCertReady(const ndn::IdentityCertificate& idCert);
-
-  void
-  contactAliasListReady(const QStringList& aliasList);
-
-  void
-  contactIdListReady(const QStringList& idList);
-
-  void
-  contactInfoReady(const QString& identity,
-                   const QString& name,
-                   const QString& institute,
-                   bool isIntro);
-
-  void
-  warning(const QString& msg);
-
-public slots:
-  void
-  onIdentityUpdated(const QString& identity);
-
-  void
-  onFetchContactInfo(const QString& identity);
-
-  void
-  onAddFetchedContact(const QString& identity);
-
-  void
-  onUpdateProfile();
-
-  void
-  onRefreshBrowseContact();
-
-  void
-  onFetchIdCert(const QString& certName);
-
-  void
-  onAddFetchedContactIdCert(const QString& identity);
-
-  void
-  onWaitForContactList();
-
-  void
-  onWaitForContactInfo(const QString& identity);
-
-  void
-  onRemoveContact(const QString& identity);
-
-  void
-  onUpdateAlias(const QString& identity, const QString& alias);
-
-  void
-  onUpdateIsIntroducer(const QString& identity, bool isIntro);
-
-  void
-  onUpdateEndorseCertificate(const QString& identity);
-
-private:
-
-  class FetchedInfo {
-  public:
-    ndn::shared_ptr<EndorseCertificate> m_selfEndorseCert;
-    ndn::shared_ptr<EndorseCollection> m_endorseCollection;
-    std::vector<ndn::shared_ptr<EndorseCertificate> > m_endorseCertList;
-    ndn::shared_ptr<EndorseInfo> m_endorseInfo;
-  };
-
-  typedef std::map<ndn::Name, FetchedInfo> BufferedContacts;
-  typedef std::map<ndn::Name, ndn::shared_ptr<ndn::IdentityCertificate> > BufferedIdCerts;
-
-  typedef boost::recursive_mutex RecLock;
-  typedef boost::unique_lock<RecLock> UniqueRecLock;
-
-  // Conf
-  ndn::shared_ptr<ContactStorage> m_contactStorage;
-  ndn::shared_ptr<ndn::Validator> m_validator;
-  ndn::shared_ptr<ndn::Face> m_face;
-  ndn::KeyChain m_keyChain;
-  ndn::Name m_identity;
-  ContactList m_contactList;
-
-  // Buffer
-  BufferedContacts m_bufferedContacts;
-  BufferedIdCerts m_bufferedIdCerts;
-
-  // Tmp Dns
-  const ndn::RegisteredPrefixId* m_dnsListenerId;
-
-  RecLock m_collectCountMutex;
-  int m_collectCount;
-
-  RecLock m_idCertCountMutex;
-  int m_idCertCount;
-};
-
-} // namespace chronos
-
-#endif //CHRONOS_CONTACT_MANAGER_H
diff --git a/src/contact-manager.hpp b/src/contact-manager.hpp
new file mode 100644
index 0000000..d9254d9
--- /dev/null
+++ b/src/contact-manager.hpp
@@ -0,0 +1,293 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_CONTACT_MANAGER_HPP
+#define CHRONOS_CONTACT_MANAGER_HPP
+
+#include <QObject>
+
+#ifndef Q_MOC_RUN
+#include "common.hpp"
+#include "contact-storage.hpp"
+#include "endorse-certificate.hpp"
+#include "profile.hpp"
+#include "endorse-info.pb.h"
+#include "endorse-collection.pb.h"
+#include <ndn-cxx/security/key-chain.hpp>
+#include <ndn-cxx/security/validator.hpp>
+#include <boost/thread/locks.hpp>
+#include <boost/thread/recursive_mutex.hpp>
+#endif
+
+namespace chronos{
+
+typedef function<void(const Interest&)> TimeoutNotify;
+typedef std::vector<shared_ptr<Contact> > ContactList;
+
+class ContactManager : public QObject
+{
+  Q_OBJECT
+
+public:
+  ContactManager(shared_ptr<ndn::Face> m_face, QObject* parent = 0);
+
+  ~ContactManager();
+
+  shared_ptr<Contact>
+  getContact(const Name& identity)
+  {
+    return m_contactStorage->getContact(identity);
+  }
+
+  void
+  getContactList(ContactList& contactList)
+  {
+    contactList.clear();
+    contactList.insert(contactList.end(), m_contactList.begin(), m_contactList.end());
+  }
+private:
+  shared_ptr<ndn::IdentityCertificate>
+  loadTrustAnchor();
+
+  void
+  initializeSecurity();
+
+  void
+  fetchCollectEndorse(const Name& identity);
+
+  void
+  fetchEndorseCertificateInternal(const Name& identity, int certIndex);
+
+  void
+  prepareEndorseInfo(const Name& identity);
+
+  // PROFILE: self-endorse-certificate
+  void
+  onDnsSelfEndorseCertValidated(const shared_ptr<const Data>& selfEndorseCertificate,
+                                const Name& identity);
+
+  void
+  onDnsSelfEndorseCertValidationFailed(const shared_ptr<const Data>& selfEndorseCertificate,
+                                       const std::string& failInfo,
+                                       const Name& identity);
+
+  void
+  onDnsSelfEndorseCertTimeoutNotify(const Interest& interest, const Name& identity);
+
+  // ENDORSED: endorse-collection
+  void
+  onDnsCollectEndorseValidated(const shared_ptr<const Data>& data, const Name& identity);
+
+  void
+  onDnsCollectEndorseValidationFailed(const shared_ptr<const Data>& data,
+                                      const std::string& failInfo,
+                                      const Name& identity);
+
+  void
+  onDnsCollectEndorseTimeoutNotify(const Interest& interest,
+                                   const Name& identity);
+
+  // PROFILE-CERT: endorse-certificate
+  void
+  onEndorseCertificateInternal(const Interest& interest, Data& data,
+                               const Name& identity, int certIndex, std::string hash);
+
+  void
+  onEndorseCertificateInternalTimeout(const Interest& interest,
+                                      const Name& identity,
+                                      int certIndex);
+
+  // Collect endorsement
+  void
+  collectEndorsement();
+
+  void
+  onDnsEndorseeValidated(const shared_ptr<const Data>& data);
+
+  void
+  onDnsEndorseeValidationFailed(const shared_ptr<const Data>& data,
+                                const std::string& failInfo);
+
+  void
+  onDnsEndorseeTimeoutNotify(const Interest& interest);
+
+  void
+  decreaseCollectStatus();
+
+  void
+  publishCollectEndorsedDataInDNS();
+
+  // Identity certificate
+  void
+  onIdentityCertValidated(const shared_ptr<const Data>& data);
+
+  void
+  onIdentityCertValidationFailed(const shared_ptr<const Data>& data, const std::string& failInfo);
+
+  void
+  onIdentityCertTimeoutNotify(const Interest& interest);
+
+  void
+  decreaseIdCertCount();
+
+  // Publish self-endorse certificate
+  shared_ptr<EndorseCertificate>
+  getSignedSelfEndorseCertificate(const Profile& profile);
+
+  void
+  publishSelfEndorseCertificateInDNS(const EndorseCertificate& selfEndorseCertificate);
+
+  // Publish endorse certificate
+  shared_ptr<EndorseCertificate>
+  generateEndorseCertificate(const Name& identity);
+
+  void
+  publishEndorseCertificateInDNS(const EndorseCertificate& endorseCertificate);
+
+  // Communication
+  void
+  sendInterest(const Interest& interest,
+               const ndn::OnDataValidated& onValidated,
+               const ndn::OnDataValidationFailed& onValidationFailed,
+               const TimeoutNotify& timeoutNotify,
+               int retry = 1);
+
+  void
+  onTargetData(const Interest& interest,
+               const Data& data,
+               const ndn::OnDataValidated& onValidated,
+               const ndn::OnDataValidationFailed& onValidationFailed);
+
+  void
+  onTargetTimeout(const Interest& interest,
+                  int retry,
+                  const ndn::OnDataValidated& onValidated,
+                  const ndn::OnDataValidationFailed& onValidationFailed,
+                  const TimeoutNotify& timeoutNotify);
+
+  // DNS listener
+  void
+  onDnsInterest(const Name& prefix, const Interest& interest);
+
+  void
+  onDnsRegisterFailed(const Name& prefix, const std::string& failInfo);
+
+signals:
+  void
+  contactEndorseInfoReady(const Chronos::EndorseInfo& endorseInfo);
+
+  void
+  contactInfoFetchFailed(const QString& identity);
+
+  void
+  idCertNameListReady(const QStringList& certNameList);
+
+  void
+  nameListReady(const QStringList& certNameList);
+
+  void
+  idCertReady(const ndn::IdentityCertificate& idCert);
+
+  void
+  contactAliasListReady(const QStringList& aliasList);
+
+  void
+  contactIdListReady(const QStringList& idList);
+
+  void
+  contactInfoReady(const QString& identity,
+                   const QString& name,
+                   const QString& institute,
+                   bool isIntro);
+
+  void
+  warning(const QString& msg);
+
+public slots:
+  void
+  onIdentityUpdated(const QString& identity);
+
+  void
+  onFetchContactInfo(const QString& identity);
+
+  void
+  onAddFetchedContact(const QString& identity);
+
+  void
+  onUpdateProfile();
+
+  void
+  onRefreshBrowseContact();
+
+  void
+  onFetchIdCert(const QString& certName);
+
+  void
+  onAddFetchedContactIdCert(const QString& identity);
+
+  void
+  onWaitForContactList();
+
+  void
+  onWaitForContactInfo(const QString& identity);
+
+  void
+  onRemoveContact(const QString& identity);
+
+  void
+  onUpdateAlias(const QString& identity, const QString& alias);
+
+  void
+  onUpdateIsIntroducer(const QString& identity, bool isIntro);
+
+  void
+  onUpdateEndorseCertificate(const QString& identity);
+
+private:
+
+  class FetchedInfo {
+  public:
+    shared_ptr<EndorseCertificate> m_selfEndorseCert;
+    shared_ptr<EndorseCollection> m_endorseCollection;
+    std::vector<shared_ptr<EndorseCertificate> > m_endorseCertList;
+    shared_ptr<Chronos::EndorseInfo> m_endorseInfo;
+  };
+
+  typedef std::map<Name, FetchedInfo> BufferedContacts;
+  typedef std::map<Name, shared_ptr<ndn::IdentityCertificate> > BufferedIdCerts;
+
+  typedef boost::recursive_mutex RecLock;
+  typedef boost::unique_lock<RecLock> UniqueRecLock;
+
+  // Conf
+  shared_ptr<ContactStorage> m_contactStorage;
+  shared_ptr<ndn::Validator> m_validator;
+  shared_ptr<ndn::Face> m_face;
+  ndn::KeyChain m_keyChain;
+  Name m_identity;
+  ContactList m_contactList;
+
+  // Buffer
+  BufferedContacts m_bufferedContacts;
+  BufferedIdCerts m_bufferedIdCerts;
+
+  // Tmp Dns
+  const ndn::RegisteredPrefixId* m_dnsListenerId;
+
+  RecLock m_collectCountMutex;
+  int m_collectCount;
+
+  RecLock m_idCertCountMutex;
+  int m_idCertCount;
+};
+
+} // namespace chronos
+
+#endif //CHRONOS_CONTACT_MANAGER_HPP
diff --git a/src/contact-panel.cpp b/src/contact-panel.cpp
index 323667b..4b8dee8 100644
--- a/src/contact-panel.cpp
+++ b/src/contact-panel.cpp
@@ -8,7 +8,7 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "contact-panel.h"
+#include "contact-panel.hpp"
 #include "ui_contact-panel.h"
 
 #include <QMenu>
@@ -22,7 +22,9 @@
 #include "logging.h"
 #endif
 
-INIT_LOGGER("ContactPanel");
+// INIT_LOGGER("ContactPanel");
+
+namespace chronos {
 
 ContactPanel::ContactPanel(QWidget *parent)
   : QDialog(parent)
@@ -38,8 +40,10 @@
   m_menuAlias  = new QAction("Set Alias", this);
   m_menuDelete = new QAction("Delete", this);
 
-  connect(ui->ContactList->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
-          this, SLOT(onSelectionChanged(const QItemSelection &, const QItemSelection &)));
+  connect(ui->ContactList->selectionModel(),
+          SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
+          this,
+          SLOT(onSelectionChanged(const QItemSelection &, const QItemSelection &)));
   connect(ui->ContactList, SIGNAL(customContextMenuRequested(const QPoint&)),
           this, SLOT(onContextMenuRequested(const QPoint&)));
   connect(ui->isIntroducer, SIGNAL(stateChanged(int)),
@@ -58,9 +62,12 @@
 
 ContactPanel::~ContactPanel()
 {
-  if(m_contactListModel) delete m_contactListModel;
-  if(m_trustScopeModel)  delete m_trustScopeModel;
-  if(m_endorseDataModel) delete m_endorseDataModel;
+  if (m_contactListModel)
+    delete m_contactListModel;
+  if (m_trustScopeModel)
+    delete m_trustScopeModel;
+  if (m_endorseDataModel)
+    delete m_endorseDataModel;
 
   delete m_setAliasDialog;
   delete m_endorseComboBoxDelegate;
@@ -122,17 +129,15 @@
 void
 ContactPanel::onCloseDBModule()
 {
-  _LOG_DEBUG("close db module");
-  if(m_trustScopeModel)
-    {
-      delete m_trustScopeModel;
-      _LOG_DEBUG("trustScopeModel closed");
-    }
-  if(m_endorseDataModel)
-    {
-      delete m_endorseDataModel;
-      _LOG_DEBUG("endorseDataModel closed");
-    }
+  // _LOG_DEBUG("close db module");
+  if (m_trustScopeModel) {
+    delete m_trustScopeModel;
+    // _LOG_DEBUG("trustScopeModel closed");
+  }
+  if (m_endorseDataModel) {
+    delete m_endorseDataModel;
+    // _LOG_DEBUG("endorseDataModel closed");
+  }
 }
 
 void
@@ -177,20 +182,18 @@
   ui->trustScopeList->setColumnHidden(1, true);
   ui->trustScopeList->show();
 
-  if(isIntro)
-    {
-      ui->isIntroducer->setChecked(true);
-      ui->addScope->setEnabled(true);
-      ui->deleteScope->setEnabled(true);
-      ui->trustScopeList->setEnabled(true);
-    }
-  else
-    {
-      ui->isIntroducer->setChecked(false);
-      ui->addScope->setEnabled(false);
-      ui->deleteScope->setEnabled(false);
-      ui->trustScopeList->setEnabled(false);
-    }
+  if (isIntro) {
+    ui->isIntroducer->setChecked(true);
+    ui->addScope->setEnabled(true);
+    ui->deleteScope->setEnabled(true);
+    ui->trustScopeList->setEnabled(true);
+  }
+  else {
+    ui->isIntroducer->setChecked(false);
+    ui->addScope->setEnabled(false);
+    ui->deleteScope->setEnabled(false);
+    ui->trustScopeList->setEnabled(false);
+  }
 
   QString filter2 = QString("profile_identity = '%1'").arg(identity);
   m_endorseDataModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
@@ -215,21 +218,18 @@
   QString alias = m_contactListModel->data(items.first(), Qt::DisplayRole).toString();
 
   bool contactFound = false;
-  for(int i = 0; i < m_contactAliasList.size(); i++)
-    {
-      if(alias == m_contactAliasList[i])
-        {
-          contactFound = true;
-          m_currentSelectedContact = m_contactIdList[i];
-          break;
-        }
+  for (int i = 0; i < m_contactAliasList.size(); i++) {
+    if (alias == m_contactAliasList[i]) {
+      contactFound = true;
+      m_currentSelectedContact = m_contactIdList[i];
+      break;
     }
+  }
 
-  if(!contactFound)
-    {
-      emit warning("This should not happen: ContactPanel::updateSelection #1");
-      return;
-    }
+  if (!contactFound) {
+    emit warning("This should not happen: ContactPanel::updateSelection #1");
+    return;
+  }
 
   emit waitForContactInfo(m_currentSelectedContact);
 }
@@ -253,13 +253,12 @@
 void
 ContactPanel::onSetAliasDialogRequested()
 {
-  for(int i = 0; i < m_contactIdList.size(); i++)
-    if(m_contactIdList[i] == m_currentSelectedContact)
-      {
-        m_setAliasDialog->setTargetIdentity(m_currentSelectedContact, m_contactAliasList[i]);
-        m_setAliasDialog->show();
-        return;
-      }
+  for (int i = 0; i < m_contactIdList.size(); i++)
+    if (m_contactIdList[i] == m_currentSelectedContact) {
+      m_setAliasDialog->setTargetIdentity(m_currentSelectedContact, m_contactAliasList[i]);
+      m_setAliasDialog->show();
+      return;
+    }
 }
 
 void
@@ -267,36 +266,32 @@
 {
   QItemSelectionModel* selectionModel = ui->ContactList->selectionModel();
   QModelIndexList selectedList = selectionModel->selectedIndexes();
-  QModelIndexList::iterator it = selectedList.begin();
-  for(; it != selectedList.end(); it++)
-    {
-      QString alias =  m_contactListModel->data(*it, Qt::DisplayRole).toString();
-      for(int i = 0; i < m_contactAliasList.size(); i++)
-        if(m_contactAliasList[i] == alias)
-          {
-            emit removeContact(m_contactIdList[i]);
-            return;
-          }
-    }
+
+  for (QModelIndexList::iterator it = selectedList.begin(); it != selectedList.end(); it++) {
+    QString alias =  m_contactListModel->data(*it, Qt::DisplayRole).toString();
+    for (int i = 0; i < m_contactAliasList.size(); i++)
+      if (m_contactAliasList[i] == alias) {
+        emit removeContact(m_contactIdList[i]);
+        return;
+      }
+  }
 }
 
 void
 ContactPanel::onIsIntroducerChanged(int state)
 {
-  if(state == Qt::Checked)
-    {
-      ui->addScope->setEnabled(true);
-      ui->deleteScope->setEnabled(true);
-      ui->trustScopeList->setEnabled(true);
-      emit updateIsIntroducer(m_currentSelectedContact, true);
-    }
-  else
-    {
-      ui->addScope->setEnabled(false);
-      ui->deleteScope->setEnabled(false);
-      ui->trustScopeList->setEnabled(false);
-      emit updateIsIntroducer(m_currentSelectedContact, false);
-    }
+  if (state == Qt::Checked) {
+    ui->addScope->setEnabled(true);
+    ui->deleteScope->setEnabled(true);
+    ui->trustScopeList->setEnabled(true);
+    emit updateIsIntroducer(m_currentSelectedContact, true);
+  }
+  else {
+    ui->addScope->setEnabled(false);
+    ui->deleteScope->setEnabled(false);
+    ui->trustScopeList->setEnabled(false);
+    emit updateIsIntroducer(m_currentSelectedContact, false);
+  }
 }
 
 void
@@ -317,8 +312,7 @@
   QItemSelectionModel* selectionModel = ui->trustScopeList->selectionModel();
   QModelIndexList indexList = selectionModel->selectedIndexes();
 
-  int i = indexList.size() - 1;
-  for(; i >= 0; i--)
+  for (int i = indexList.size() - 1; i >= 0; i--)
     m_trustScopeModel->removeRow(indexList[i].row());
 
   m_trustScopeModel->submitAll();
@@ -343,6 +337,8 @@
   emit updateAlias(identity, alias);
 }
 
+} // namespace chronos
+
 #if WAF
 #include "contact-panel.moc"
 #include "contact-panel.cpp.moc"
diff --git a/src/contact-panel.h b/src/contact-panel.hpp
similarity index 85%
rename from src/contact-panel.h
rename to src/contact-panel.hpp
index f47287f..a7a3241 100644
--- a/src/contact-panel.h
+++ b/src/contact-panel.hpp
@@ -8,15 +8,15 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef CONTACT_PANEL_H
-#define CONTACT_PANEL_H
+#ifndef CHRONOS_CONTACT_PANEL_HPP
+#define CHRONOS_CONTACT_PANEL_HPP
 
 #include <QDialog>
 #include <QStringListModel>
 #include <QSqlTableModel>
 
-#include "set-alias-dialog.h"
-#include "endorse-combobox-delegate.h"
+#include "set-alias-dialog.hpp"
+#include "endorse-combobox-delegate.hpp"
 
 #ifndef Q_MOC_RUN
 #endif
@@ -25,13 +25,15 @@
 class ContactPanel;
 }
 
+namespace chronos {
+
 class ContactPanel : public QDialog
 {
   Q_OBJECT
 
 public:
   explicit
-  ContactPanel(QWidget *parent = 0);
+  ContactPanel(QWidget* parent = 0);
 
   virtual
   ~ContactPanel();
@@ -83,8 +85,8 @@
 
 private slots:
   void
-  onSelectionChanged(const QItemSelection &selected,
-                     const QItemSelection &deselected);
+  onSelectionChanged(const QItemSelection& selected,
+                     const QItemSelection& deselected);
 
   void
   onContextMenuRequested(const QPoint& pos);
@@ -137,4 +139,6 @@
   QString     m_currentSelectedContact;
 };
 
-#endif // CONTACT_PANEL_H
+} // namespace chronos
+
+#endif // CHRONOS_CONTACT_PANEL_HPP
diff --git a/src/contact-storage.cpp b/src/contact-storage.cpp
index aaf8b79..8f37079 100644
--- a/src/contact-storage.cpp
+++ b/src/contact-storage.cpp
@@ -8,133 +8,168 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "contact-storage.h"
+#include "contact-storage.hpp"
 
 #include <boost/filesystem.hpp>
-#include <cryptopp/sha.h>
-#include <cryptopp/filters.h>
-#include <cryptopp/hex.h>
-#include <cryptopp/files.h>
+#include "cryptopp.hpp"
 #include "logging.h"
 
-using namespace ndn;
+
+// INIT_LOGGER ("chronos.ContactStorage");
+
+namespace chronos {
+
 namespace fs = boost::filesystem;
 
-INIT_LOGGER ("chronos.ContactStorage");
+using std::string;
+using std::vector;
 
-namespace chronos{
+using ndn::PublicKey;
 
-using ndn::shared_ptr;
+// user's own profile;
+const string INIT_SP_TABLE =
+  "CREATE TABLE IF NOT EXISTS                          "
+  "  SelfProfile(                                      "
+  "      profile_type      BLOB NOT NULL,              "
+  "      profile_value     BLOB NOT NULL,              "
+  "      PRIMARY KEY (profile_type)                    "
+  "  );                                                "
+  "CREATE INDEX sp_index ON SelfProfile(profile_type); ";
 
-const std::string INIT_SP_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  SelfProfile(                                                       \n \
-      profile_type      BLOB NOT NULL,                               \n \
-      profile_value     BLOB NOT NULL,                               \n \
-                                                                     \
-      PRIMARY KEY (profile_type)                                     \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX sp_index ON SelfProfile(profile_type);                  \n \
-"; // user's own profile;
+// user's self endorse cert;
+const string INIT_SE_TABLE =
+  "CREATE TABLE IF NOT EXISTS                      "
+  "  SelfEndorse(                                  "
+  "      identity          BLOB NOT NULL UNIQUE,   "
+  "      endorse_data      BLOB NOT NULL,          "
+  "      PRIMARY KEY (identity)                    "
+  "  );                                            "
+  "CREATE INDEX se_index ON SelfEndorse(identity); ";
 
-const std::string INIT_SE_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  SelfEndorse(                                                       \n \
-      identity          BLOB NOT NULL UNIQUE,                        \n \
-      endorse_data      BLOB NOT NULL,                               \n \
-                                                                     \
-      PRIMARY KEY (identity)                                         \n \
-  );                                                                 \n \
-CREATE INDEX se_index ON SelfEndorse(identity);                      \n \
-"; // user's self endorse cert;
+// contact's basic info
+const string INIT_CONTACT_TABLE =
+  "CREATE TABLE IF NOT EXISTS                                "
+  "  Contact(                                                "
+  "      contact_namespace BLOB NOT NULL,                    "
+  "      contact_alias     BLOB NOT NULL,                    "
+  "      contact_keyName   BLOB NOT NULL,                    "
+  "      contact_key       BLOB NOT NULL,                    "
+  "      notBefore         INTEGER DEFAULT 0,                "
+  "      notAfter          INTEGER DEFAULT 0,                "
+  "      is_introducer     INTEGER DEFAULT 0,                "
+  "      PRIMARY KEY (contact_namespace)                     "
+  "  );                                                      "
+  "CREATE INDEX contact_index ON Contact(contact_namespace); ";
 
-const std::string INIT_CONTACT_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  Contact(                                                           \n \
-      contact_namespace BLOB NOT NULL,                               \n \
-      contact_alias     BLOB NOT NULL,                               \n \
-      contact_keyName   BLOB NOT NULL,                               \n \
-      contact_key       BLOB NOT NULL,                               \n \
-      notBefore         INTEGER DEFAULT 0,                           \n \
-      notAfter          INTEGER DEFAULT 0,                           \n \
-      is_introducer     INTEGER DEFAULT 0,                           \n \
-                                                                     \
-      PRIMARY KEY (contact_namespace)                                \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX contact_index ON Contact(contact_namespace);            \n \
-"; // contact's basic info
+// contact's trust scope;
+const string INIT_TS_TABLE =
+  "CREATE TABLE IF NOT EXISTS                                 "
+  "  TrustScope(                                              "
+  "      id                INTEGER PRIMARY KEY AUTOINCREMENT, "
+  "      contact_namespace BLOB NOT NULL,                     "
+  "      trust_scope       BLOB NOT NULL                      "
+  "  );                                                       "
+  "CREATE INDEX ts_index ON TrustScope(contact_namespace);    ";
 
-const std::string INIT_TS_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  TrustScope(                                                        \n \
-      id                INTEGER PRIMARY KEY AUTOINCREMENT,           \n \
-      contact_namespace BLOB NOT NULL,                               \n \
-      trust_scope       BLOB NOT NULL                                \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX ts_index ON TrustScope(contact_namespace);              \n \
-"; // contact's trust scope;
+// contact's profile
+const string INIT_CP_TABLE =
+  "CREATE TABLE IF NOT EXISTS                                 "
+  "  ContactProfile(                                          "
+  "      profile_identity  BLOB NOT NULL,                     "
+  "      profile_type      BLOB NOT NULL,                     "
+  "      profile_value     BLOB NOT NULL,                     "
+  "      endorse           INTEGER NOT NULL,                  "
+  "      PRIMARY KEY (profile_identity, profile_type)         "
+  "  );                                                       "
+  "CREATE INDEX cp_index ON ContactProfile(profile_identity); ";
 
-const std::string INIT_CP_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  ContactProfile(                                                    \n \
-      profile_identity  BLOB NOT NULL,                               \n \
-      profile_type      BLOB NOT NULL,                               \n \
-      profile_value     BLOB NOT NULL,                               \n \
-      endorse           INTEGER NOT NULL,                            \n \
-                                                                     \
-      PRIMARY KEY (profile_identity, profile_type)                   \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX cp_index ON ContactProfile(profile_identity);           \n \
-"; // contact's profile
+// user's endorsement on contacts
+const string INIT_PE_TABLE =
+  "CREATE TABLE IF NOT EXISTS                         "
+  "  ProfileEndorse(                                  "
+  "      identity          BLOB NOT NULL UNIQUE,      "
+  "      endorse_data      BLOB NOT NULL,             "
+  "      PRIMARY KEY (identity)                       "
+  "  );                                               "
+  "CREATE INDEX pe_index ON ProfileEndorse(identity); ";
 
-const std::string INIT_PE_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  ProfileEndorse(                                                    \n \
-      identity          BLOB NOT NULL UNIQUE,                        \n \
-      endorse_data      BLOB NOT NULL,                               \n \
-                                                                     \
-      PRIMARY KEY (identity)                                         \n \
-  );                                                                 \n \
-                                                                     \
-CREATE INDEX pe_index ON ProfileEndorse(identity);                   \n \
-"; // user's endorsement on contacts
+// contact's endorsements on the user
+const string INIT_CE_TABLE =
+  "CREATE TABLE IF NOT EXISTS               "
+  "  CollectEndorse(                        "
+  "      endorser          BLOB NOT NULL,   "
+  "      endorse_name      BLOB NOT NULL,   "
+  "      endorse_data      BLOB NOT NULL,   "
+  "      PRIMARY KEY (endorser)             "
+  "  );                                     ";
 
-const std::string INIT_CE_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  CollectEndorse(                                                    \n \
-      endorser          BLOB NOT NULL,                               \n \
-      endorse_name      BLOB NOT NULL,                               \n \
-      endorse_data      BLOB NOT NULL,                               \n \
-                                                                     \
-      PRIMARY KEY (endorser)                                         \n \
-  );                                                                 \n \
-"; // contact's endorsements on the user
+// dns data;
+const string INIT_DD_TABLE =
+  "CREATE TABLE IF NOT EXISTS                             "
+  "  DnsData(                                             "
+  "      dns_name      BLOB NOT NULL,                     "
+  "      dns_type      BLOB NOT NULL,                     "
+  "      data_name     BLOB NOT NULL,                     "
+  "      dns_value     BLOB NOT NULL,                     "
+  "      PRIMARY KEY (dns_name, dns_type)                 "
+  "  );                                                   "
+  "CREATE INDEX dd_index ON DnsData(dns_name, dns_type);  "
+  "CREATE INDEX dd_index2 ON DnsData(data_name);          ";
 
-const std::string INIT_DD_TABLE = "\
-CREATE TABLE IF NOT EXISTS                                           \n \
-  DnsData(                                                           \n \
-      dns_name      BLOB NOT NULL,                                   \n \
-      dns_type      BLOB NOT NULL,                                   \n \
-      data_name     BLOB NOT NULL,                                   \n	\
-      dns_value     BLOB NOT NULL,                                   \n \
-                                                                     \
-      PRIMARY KEY (dns_name, dns_type)                               \n \
-  );                                                                 \
-CREATE INDEX dd_index ON DnsData(dns_name, dns_type);                \n \
-CREATE INDEX dd_index2 ON DnsData(data_name);                        \n \
-"; // dns data;
+/**
+ * A utility function to call the normal sqlite3_bind_text where the value and length are
+ * value.c_str() and value.size().
+ */
+static int
+sqlite3_bind_string(sqlite3_stmt* statement,
+                    int index,
+                    const string& value,
+                    void(*destructor)(void*))
+{
+  return sqlite3_bind_text(statement, index, value.c_str(), value.size(), destructor);
+}
+
+/**
+ * A utility function to call the normal sqlite3_bind_blob where the value and length are
+ * block.wire() and block.size().
+ */
+static int
+sqlite3_bind_block(sqlite3_stmt* statement,
+                   int index,
+                   const Block& block,
+                   void(*destructor)(void*))
+{
+  return sqlite3_bind_blob(statement, index, block.wire(), block.size(), destructor);
+}
+
+/**
+ * A utility function to generate string by calling the normal sqlite3_column_text.
+ */
+static string
+sqlite3_column_string(sqlite3_stmt* statement, int column)
+{
+  return string(reinterpret_cast<const char*>(sqlite3_column_text(statement, column)),
+                sqlite3_column_bytes(statement, column));
+}
+
+/**
+ * A utility function to generate block by calling the normal sqlite3_column_text.
+ */
+static Block
+sqlite3_column_block(sqlite3_stmt* statement, int column)
+{
+  return Block(reinterpret_cast<const char*>(sqlite3_column_blob(statement, column)),
+               sqlite3_column_bytes(statement, column));
+}
+
 
 ContactStorage::ContactStorage(const Name& identity)
   : m_identity(identity)
 {
   fs::path chronosDir = fs::path(getenv("HOME")) / ".chronos";
-  fs::create_directories (chronosDir);
+  fs::create_directories(chronosDir);
 
-  int res = sqlite3_open((chronosDir / getDBName()).c_str (), &m_db);
+  int res = sqlite3_open((chronosDir / getDBName()).c_str(), &m_db);
   if (res != SQLITE_OK)
     throw Error("Chronos DB cannot be open/created");
 
@@ -149,10 +184,10 @@
 
 }
 
-std::string
+string
 ContactStorage::getDBName()
 {
-  std::string dbName("chronos-");
+  string dbName("chronos-");
 
   std::stringstream ss;
   {
@@ -168,25 +203,26 @@
 }
 
 void
-ContactStorage::initializeTable(const std::string& tableName, const std::string& sqlCreateStmt)
+ContactStorage::initializeTable(const string& tableName, const string& sqlCreateStmt)
 {
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT name FROM sqlite_master WHERE type='table' And name=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, tableName.c_str(), tableName.size(), SQLITE_TRANSIENT);
-  int res = sqlite3_step (stmt);
+  sqlite3_prepare_v2(m_db,
+                     "SELECT name FROM sqlite_master WHERE type='table' And name=?",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, tableName, SQLITE_TRANSIENT);
+  int res = sqlite3_step(stmt);
 
   bool tableExist = false;
   if (res == SQLITE_ROW)
-      tableExist = true;
-  sqlite3_finalize (stmt);
+    tableExist = true;
+  sqlite3_finalize(stmt);
 
-  if(!tableExist)
-    {
-      char *errmsg = 0;
-      res = sqlite3_exec (m_db, sqlCreateStmt.c_str (), NULL, NULL, &errmsg);
-      if (res != SQLITE_OK && errmsg != 0)
-        throw Error("Init \"error\" in " + tableName);
-    }
+  if (!tableExist) {
+    char *errmsg = 0;
+    res = sqlite3_exec(m_db, sqlCreateStmt.c_str (), NULL, NULL, &errmsg);
+    if (res != SQLITE_OK && errmsg != 0)
+      throw Error("Init \"error\" in " + tableName);
+  }
 }
 
 shared_ptr<Profile>
@@ -194,15 +230,13 @@
 {
   shared_ptr<Profile> profile = make_shared<Profile>(m_identity);
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT profile_type, profile_value FROM SelfProfile", -1, &stmt, 0);
+  sqlite3_prepare_v2(m_db, "SELECT profile_type, profile_value FROM SelfProfile", -1, &stmt, 0);
 
-  while( sqlite3_step (stmt) == SQLITE_ROW)
-    {
-      std::string profileType(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0));
-      std::string profileValue(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1)), sqlite3_column_bytes (stmt, 1));
-      (*profile)[profileType] = profileValue;
-    }
-
+  while (sqlite3_step(stmt) == SQLITE_ROW) {
+    string profileType = sqlite3_column_string(stmt, 0);
+    string profileValue = sqlite3_column_string (stmt, 1);
+    (*profile)[profileType] = profileValue;
+  }
   sqlite3_finalize(stmt);
 
   return profile;
@@ -211,29 +245,31 @@
 void
 ContactStorage::addSelfEndorseCertificate(const EndorseCertificate& newEndorseCertificate)
 {
-  const Block& newEndorseCertificateBlock = newEndorseCertificate.wireEncode();
-
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "INSERT OR REPLACE INTO SelfEndorse (identity, endorse_data) values (?, ?)", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, m_identity.toUri().c_str(), m_identity.toUri().size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, reinterpret_cast<const char*>(newEndorseCertificateBlock.wire()), newEndorseCertificateBlock.size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db,
+                     "INSERT OR REPLACE INTO SelfEndorse (identity, endorse_data) values (?, ?)",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, m_identity.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_block(stmt, 2, newEndorseCertificate.wireEncode(), SQLITE_TRANSIENT);
   int res = sqlite3_step(stmt);
 
-  sqlite3_finalize (stmt);
+  sqlite3_finalize(stmt);
 }
 
 void
-ContactStorage::addEndorseCertificate(const EndorseCertificate& endorseCertificate, const Name& identity)
+ContactStorage::addEndorseCertificate(const EndorseCertificate& endorseCertificate,
+                                      const Name& identity)
 {
-  const Block& newEndorseCertificateBlock = endorseCertificate.wireEncode();
-
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "INSERT OR REPLACE INTO ProfileEndorse (identity, endorse_data) values (?, ?)", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.toUri().c_str(), identity.toUri().size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, reinterpret_cast<const char*>(newEndorseCertificateBlock.wire()), newEndorseCertificateBlock.size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db,
+                     "INSERT OR REPLACE INTO ProfileEndorse \
+                      (identity, endorse_data) values (?, ?)",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, identity.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_block(stmt, 2, endorseCertificate.wireEncode(), SQLITE_TRANSIENT);
   sqlite3_step(stmt);
 
-  sqlite3_finalize (stmt);
+  sqlite3_finalize(stmt);
 }
 
 void
@@ -243,13 +279,17 @@
   Name certName = endorseCertificate.getName();
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "INSERT OR REPLACE INTO CollectEndorse (endorser, endorse_name, endorse_data) VALUES (?, ?, ?, ?)", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, endorserName.toUri().c_str(), endorserName.toUri().size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, certName.toUri().c_str(), certName.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db,
+                     "INSERT OR REPLACE INTO CollectEndorse \
+                      (endorser, endorse_name, endorse_data) \
+                      VALUES (?, ?, ?, ?)",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, endorserName.toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, certName.toUri(), SQLITE_TRANSIENT);
   const Block &block = endorseCertificate.wireEncode();
-  sqlite3_bind_text(stmt, 3, reinterpret_cast<const char*>(block.wire()), block.size(), SQLITE_TRANSIENT);
-  int res = sqlite3_step (stmt);
-  sqlite3_finalize (stmt);
+  sqlite3_bind_block(stmt, 3, endorseCertificate.wireEncode(), SQLITE_TRANSIENT);
+  int res = sqlite3_step(stmt);
+  sqlite3_finalize(stmt);
   return;
 }
 
@@ -257,131 +297,125 @@
 ContactStorage::getCollectEndorse(EndorseCollection& endorseCollection)
 {
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT endorse_name, endorse_data FROM CollectEndorse", -1, &stmt, 0);
+  sqlite3_prepare_v2(m_db, "SELECT endorse_name, endorse_data FROM CollectEndorse", -1, &stmt, 0);
 
-  while(sqlite3_step (stmt) == SQLITE_ROW)
+  while (sqlite3_step(stmt) == SQLITE_ROW) {
+    string certName = sqlite3_column_string(stmt, 0);
+    std::stringstream ss;
     {
-      std::string certName(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes(stmt, 1));
-      std::stringstream ss;
-      {
-        using namespace CryptoPP;
-        SHA256 hash;
+      using namespace CryptoPP;
+      SHA256 hash;
 
-        StringSource(sqlite3_column_text(stmt, 1), sqlite3_column_bytes (stmt, 0), true,
-                     new HashFilter(hash, new FileSink(ss)));
-      }
-      EndorseCollection::Endorsement* endorsement = endorseCollection.add_endorsement();
-      endorsement->set_certname(certName);
-      endorsement->set_hash(ss.str());
+      StringSource(sqlite3_column_text(stmt, 1), sqlite3_column_bytes (stmt, 1), true,
+                   new HashFilter(hash, new FileSink(ss)));
     }
+    EndorseCollection::Endorsement* endorsement = endorseCollection.add_endorsement();
+    endorsement->set_certname(certName);
+    endorsement->set_hash(ss.str());
+  }
 
-  sqlite3_finalize (stmt);
+  sqlite3_finalize(stmt);
 }
 
 void
-ContactStorage::getEndorseList(const Name& identity, std::vector<std::string>& endorseList)
+ContactStorage::getEndorseList(const Name& identity, vector<string>& endorseList)
 {
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT profile_type FROM ContactProfile WHERE profile_identity=? AND endorse=1 ORDER BY profile_type", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.toUri().c_str(), identity.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db,
+                     "SELECT profile_type FROM ContactProfile \
+                      WHERE profile_identity=? AND endorse=1 ORDER BY profile_type",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, identity.toUri(), SQLITE_TRANSIENT);
 
-  while( sqlite3_step (stmt) == SQLITE_ROW)
-    {
-      std::string profileType(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0));
-      endorseList.push_back(profileType);
-    }
-  sqlite3_finalize (stmt);
+  while (sqlite3_step(stmt) == SQLITE_ROW) {
+    string profileType = sqlite3_column_string(stmt, 0);
+    endorseList.push_back(profileType);
+  }
+  sqlite3_finalize(stmt);
 }
 
 
 void
 ContactStorage::removeContact(const Name& identityName)
 {
-  std::string identity = identityName.toUri();
+  string identity = identityName.toUri();
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "DELETE FROM Contact WHERE contact_namespace=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size (), SQLITE_TRANSIENT);
-  int res = sqlite3_step (stmt);
-  sqlite3_finalize (stmt);
+  sqlite3_prepare_v2(m_db, "DELETE FROM Contact WHERE contact_namespace=?", -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+  int res = sqlite3_step(stmt);
+  sqlite3_finalize(stmt);
 
-  sqlite3_prepare_v2 (m_db, "DELETE FROM ContactProfile WHERE profile_identity=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(),  identity.size (), SQLITE_TRANSIENT);
-  res = sqlite3_step (stmt);
-  sqlite3_finalize (stmt);
+  sqlite3_prepare_v2(m_db, "DELETE FROM ContactProfile WHERE profile_identity=?", -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+  res = sqlite3_step(stmt);
+  sqlite3_finalize(stmt);
 
-  sqlite3_prepare_v2 (m_db, "DELETE FROM TrustScope WHERE contact_namespace=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, identity.c_str(),  identity.size (), SQLITE_TRANSIENT);
-  res = sqlite3_step (stmt);
-  sqlite3_finalize (stmt);
+  sqlite3_prepare_v2(m_db, "DELETE FROM TrustScope WHERE contact_namespace=?", -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+  res = sqlite3_step(stmt);
+  sqlite3_finalize(stmt);
 }
 
 void
 ContactStorage::addContact(const Contact& contact)
 {
-  if(doesContactExist(contact.getNameSpace()))
+  if (doesContactExist(contact.getNameSpace()))
     throw Error("Normal Contact has already existed");
 
-  std::string identity = contact.getNameSpace().toUri();
+  string identity = contact.getNameSpace().toUri();
   bool isIntroducer = contact.isIntroducer();
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db,
-                      "INSERT INTO Contact (contact_namespace, contact_alias, contact_keyName, contact_key, notBefore, notAfter, is_introducer) values (?, ?, ?, ?, ?, ?, ?)",
-                      -1,
-                      &stmt,
-                      0);
+  sqlite3_prepare_v2(m_db,
+                     "INSERT INTO Contact (contact_namespace, contact_alias, contact_keyName, \
+                      contact_key, notBefore, notAfter, is_introducer) \
+                      values (?, ?, ?, ?, ?, ?, ?)",
+                     -1, &stmt, 0);
 
-  sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size (), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, contact.getAlias().c_str(), contact.getAlias().size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 3, contact.getPublicKeyName().toUri().c_str(), contact.getPublicKeyName().toUri().size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 4, reinterpret_cast<const char*>(contact.getPublicKey().get().buf()), contact.getPublicKey().get().size(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, contact.getAlias(), SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 3, contact.getPublicKeyName().toUri(), SQLITE_TRANSIENT);
+  sqlite3_bind_text(stmt, 4,
+                    reinterpret_cast<const char*>(contact.getPublicKey().get().buf()),
+                    contact.getPublicKey().get().size(), SQLITE_TRANSIENT);
   sqlite3_bind_int64(stmt, 5, time::toUnixTimestamp(contact.getNotBefore()).count());
   sqlite3_bind_int64(stmt, 6, time::toUnixTimestamp(contact.getNotAfter()).count());
   sqlite3_bind_int(stmt, 7, (isIntroducer ? 1 : 0));
 
-  int res = sqlite3_step (stmt);
+  int res = sqlite3_step(stmt);
 
-  // _LOG_DEBUG("addContact: " << res);
-
-  sqlite3_finalize (stmt);
+  sqlite3_finalize(stmt);
 
   const Profile& profile = contact.getProfile();
-  Profile::const_iterator it = profile.begin();
+  for (Profile::const_iterator it = profile.begin(); it != profile.end(); it++) {
+    sqlite3_prepare_v2(m_db,
+                       "INSERT INTO ContactProfile \
+                        (profile_identity, profile_type, profile_value, endorse) \
+                        values (?, ?, ?, 0)",
+                       -1, &stmt, 0);
+    sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+    sqlite3_bind_string(stmt, 2, it->first, SQLITE_TRANSIENT);
+    sqlite3_bind_string(stmt, 3, it->second, SQLITE_TRANSIENT);
+    res = sqlite3_step(stmt);
+    sqlite3_finalize(stmt);
+  }
 
-  for(; it != profile.end(); it++)
-    {
-      sqlite3_prepare_v2 (m_db,
-                          "INSERT INTO ContactProfile (profile_identity, profile_type, profile_value, endorse) values (?, ?, ?, 0)",
-                          -1,
-                          &stmt,
-                          0);
-      sqlite3_bind_text(stmt, 1, identity.c_str(),  identity.size (), SQLITE_TRANSIENT);
-      sqlite3_bind_text(stmt, 2, it->first.c_str(), it->first.size(), SQLITE_TRANSIENT);
-      sqlite3_bind_text(stmt, 3, it->second.c_str(), it->second.size(), SQLITE_TRANSIENT);
-      res = sqlite3_step (stmt);
-      sqlite3_finalize (stmt);
+  if (isIntroducer) {
+    Contact::const_iterator it  = contact.trustScopeBegin();
+    Contact::const_iterator end = contact.trustScopeEnd();
+
+    while (it != end) {
+      sqlite3_prepare_v2(m_db,
+                         "INSERT INTO TrustScope (contact_namespace, trust_scope) values (?, ?)",
+                         -1, &stmt, 0);
+      sqlite3_bind_string(stmt, 1, identity, SQLITE_TRANSIENT);
+      sqlite3_bind_string(stmt, 2, it->first.toUri(), SQLITE_TRANSIENT);
+      res = sqlite3_step(stmt);
+      sqlite3_finalize(stmt);
+      it++;
     }
-
-  if(isIntroducer)
-    {
-      Contact::const_iterator it  = contact.trustScopeBegin();
-      Contact::const_iterator end = contact.trustScopeEnd();
-
-      while(it != end)
-        {
-          sqlite3_prepare_v2 (m_db,
-                              "INSERT INTO TrustScope (contact_namespace, trust_scope) values (?, ?)",
-                              -1,
-                              &stmt,
-                              0);
-          sqlite3_bind_text(stmt, 1, identity.c_str(), identity.size (), SQLITE_TRANSIENT);
-          sqlite3_bind_text(stmt, 2, it->first.toUri().c_str(), it->first.toUri().size(), SQLITE_TRANSIENT);
-          res = sqlite3_step (stmt);
-          sqlite3_finalize (stmt);
-          it++;
-        }
-    }
+  }
 }
 
 
@@ -392,46 +426,53 @@
   Profile profile;
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT contact_alias, contact_keyName, contact_key, notBefore, notAfter, is_introducer FROM Contact where contact_namespace=?", -1, &stmt, 0);
-  sqlite3_bind_text (stmt, 1, identity.toUri().c_str(), identity.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db,
+                     "SELECT contact_alias, contact_keyName, contact_key, notBefore, notAfter, \
+                      is_introducer FROM Contact where contact_namespace=?",
+                      -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, identity.toUri(), SQLITE_TRANSIENT);
 
-  if(sqlite3_step (stmt) == SQLITE_ROW)
-    {
-      std::string alias(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0));
-      std::string keyName(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)), sqlite3_column_bytes (stmt, 1));
-      PublicKey key(sqlite3_column_text(stmt, 2), sqlite3_column_bytes (stmt, 2));
-      time::system_clock::TimePoint notBefore = time::fromUnixTimestamp(time::milliseconds(sqlite3_column_int64 (stmt, 3)));
-      time::system_clock::TimePoint notAfter = time::fromUnixTimestamp(time::milliseconds(sqlite3_column_int64 (stmt, 4)));
-      int isIntroducer = sqlite3_column_int (stmt, 5);
+  if (sqlite3_step(stmt) == SQLITE_ROW) {
+    string alias = sqlite3_column_string(stmt, 0);
+    string keyName = sqlite3_column_string(stmt, 1);
+    PublicKey key(sqlite3_column_text(stmt, 2), sqlite3_column_bytes (stmt, 2));
+    time::system_clock::TimePoint notBefore =
+      time::fromUnixTimestamp(time::milliseconds(sqlite3_column_int64 (stmt, 3)));
+    time::system_clock::TimePoint notAfter =
+      time::fromUnixTimestamp(time::milliseconds(sqlite3_column_int64 (stmt, 4)));
+    int isIntroducer = sqlite3_column_int (stmt, 5);
 
-      contact = shared_ptr<Contact>(new Contact(identity, alias, Name(keyName), notBefore, notAfter, key, isIntroducer));
-    }
-  sqlite3_finalize (stmt);
+    contact = make_shared<Contact>(identity, alias, Name(keyName),
+                                   notBefore, notAfter, key, isIntroducer);
+  }
+  sqlite3_finalize(stmt);
 
-  sqlite3_prepare_v2 (m_db, "SELECT profile_type, profile_value FROM ContactProfile where profile_identity=?", -1, &stmt, 0);
-  sqlite3_bind_text (stmt, 1, identity.toUri().c_str(), identity.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db,
+                     "SELECT profile_type, profile_value FROM ContactProfile \
+                      where profile_identity=?",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, identity.toUri(), SQLITE_TRANSIENT);
 
-  while(sqlite3_step (stmt) == SQLITE_ROW)
-    {
-      std::string type(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0));
-      std::string value(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)), sqlite3_column_bytes (stmt, 1));
-      profile[type] = value;
-    }
-  sqlite3_finalize (stmt);
+  while (sqlite3_step(stmt) == SQLITE_ROW) {
+    string type = sqlite3_column_string(stmt, 0);
+    string value = sqlite3_column_string(stmt, 1);
+    profile[type] = value;
+  }
+  sqlite3_finalize(stmt);
   contact->setProfile(profile);
 
-  if(contact->isIntroducer())
-    {
-      sqlite3_prepare_v2 (m_db, "SELECT trust_scope FROM TrustScope WHERE contact_namespace=?", -1, &stmt, 0);
-      sqlite3_bind_text(stmt, 1, identity.toUri().c_str(), identity.toUri().size(), SQLITE_TRANSIENT);
+  if (contact->isIntroducer()) {
+    sqlite3_prepare_v2(m_db,
+                       "SELECT trust_scope FROM TrustScope WHERE contact_namespace=?",
+                       -1, &stmt, 0);
+    sqlite3_bind_string(stmt, 1, identity.toUri(), SQLITE_TRANSIENT);
 
-      while(sqlite3_step (stmt) == SQLITE_ROW)
-        {
-          Name scope(std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0)));
-          contact->addTrustScope(scope);
-        }
-      sqlite3_finalize (stmt);
+    while (sqlite3_step(stmt) == SQLITE_ROW) {
+      Name scope(sqlite3_column_string(stmt, 0));
+      contact->addTrustScope(scope);
     }
+    sqlite3_finalize(stmt);
+  }
 
   return contact;
 }
@@ -441,23 +482,25 @@
 ContactStorage::updateIsIntroducer(const Name& identity, bool isIntroducer)
 {
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "UPDATE Contact SET is_introducer=? WHERE contact_namespace=?", -1, &stmt, 0);
+  sqlite3_prepare_v2(m_db, "UPDATE Contact SET is_introducer=? WHERE contact_namespace=?",
+                     -1, &stmt, 0);
   sqlite3_bind_int(stmt, 1, (isIntroducer ? 1 : 0));
-  sqlite3_bind_text(stmt, 2, identity.toUri().c_str(),  identity.toUri().size (), SQLITE_TRANSIENT);
-  int res = sqlite3_step (stmt);
-  sqlite3_finalize (stmt);
+  sqlite3_bind_string(stmt, 2, identity.toUri(), SQLITE_TRANSIENT);
+  int res = sqlite3_step(stmt);
+  sqlite3_finalize(stmt);
   return;
 }
 
 void
-ContactStorage::updateAlias(const Name& identity, std::string alias)
+ContactStorage::updateAlias(const Name& identity, const string& alias)
 {
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "UPDATE Contact SET contact_alias=? WHERE contact_namespace=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, alias.c_str(), alias.size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, identity.toUri().c_str(),  identity.toUri().size (), SQLITE_TRANSIENT);
-  int res = sqlite3_step (stmt);
-  sqlite3_finalize (stmt);
+  sqlite3_prepare_v2(m_db, "UPDATE Contact SET contact_alias=? WHERE contact_namespace=?",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, alias, SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, identity.toUri(), SQLITE_TRANSIENT);
+  int res = sqlite3_step(stmt);
+  sqlite3_finalize(stmt);
   return;
 }
 
@@ -467,61 +510,57 @@
   bool result = false;
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT count(*) FROM Contact WHERE contact_namespace=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, name.toUri().c_str(), name.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db, "SELECT count(*) FROM Contact WHERE contact_namespace=?", -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, name.toUri(), SQLITE_TRANSIENT);
 
-  int res = sqlite3_step (stmt);
+  int res = sqlite3_step(stmt);
 
-  if (res == SQLITE_ROW)
-    {
-      int countAll = sqlite3_column_int (stmt, 0);
-      if (countAll > 0)
-        result = true;
-    }
-  sqlite3_finalize (stmt);
+  if (res == SQLITE_ROW) {
+    int countAll = sqlite3_column_int (stmt, 0);
+    if (countAll > 0)
+      result = true;
+  }
+
+  sqlite3_finalize(stmt);
   return result;
 }
 
 void
-ContactStorage::getAllContacts(std::vector<shared_ptr<Contact> >& contacts) const
+ContactStorage::getAllContacts(vector<shared_ptr<Contact> >& contacts) const
 {
-  std::vector<Name> contactNames;
+  vector<Name> contactNames;
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT contact_namespace FROM Contact", -1, &stmt, 0);
+  sqlite3_prepare_v2(m_db, "SELECT contact_namespace FROM Contact", -1, &stmt, 0);
 
-  while(sqlite3_step (stmt) == SQLITE_ROW)
-    {
-      std::string identity(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes(stmt, 0));
-      contactNames.push_back(Name(identity));
-    }
-  sqlite3_finalize (stmt);
+  while (sqlite3_step(stmt) == SQLITE_ROW) {
+    string identity = sqlite3_column_string(stmt, 0);
+    contactNames.push_back(Name(identity));
+  }
+  sqlite3_finalize(stmt);
 
-  std::vector<Name>::iterator it  = contactNames.begin();
-  std::vector<Name>::iterator end = contactNames.end();
-  for(; it != end; it++)
-    {
-      shared_ptr<Contact> contact = getContact(*it);
-      if(static_cast<bool>(contact))
-        contacts.push_back(contact);
-    }
+  for (vector<Name>::iterator it = contactNames.begin(); it != contactNames.end(); it++) {
+    shared_ptr<Contact> contact = getContact(*it);
+    if (static_cast<bool>(contact))
+      contacts.push_back(contact);
+  }
 }
 
 void
-ContactStorage::updateDnsData(const Block& data,
-                              const std::string& name,
-                              const std::string& type,
-                              const std::string& dataName)
+ContactStorage::updateDnsData(const Block& data, const string& name,
+                              const string& type, const string& dataName)
 {
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "INSERT OR REPLACE INTO DnsData (dns_name, dns_type, dns_value, data_name) VALUES (?, ?, ?, ?)", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, name.c_str(), name.size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, type.c_str(), type.size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 3, reinterpret_cast<const char*>(data.wire()), data.size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 4, dataName.c_str(), dataName.size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db,
+                     "INSERT OR REPLACE INTO DnsData (dns_name, dns_type, dns_value, data_name) \
+                      VALUES (?, ?, ?, ?)",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, name, SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, type, SQLITE_TRANSIENT);
+  sqlite3_bind_block(stmt, 3, data, SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 4, dataName, SQLITE_TRANSIENT);
   int res = sqlite3_step(stmt);
 
-  // _LOG_DEBUG("updateDnsData " << res);
   sqlite3_finalize(stmt);
 }
 
@@ -531,37 +570,36 @@
   shared_ptr<Data> data;
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT dns_value FROM DnsData where data_name=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, dataName.toUri().c_str(), dataName.toUri().size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db, "SELECT dns_value FROM DnsData where data_name=?", -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, dataName.toUri(), SQLITE_TRANSIENT);
 
-  if(sqlite3_step (stmt) == SQLITE_ROW)
-    {
-      data = make_shared<Data>();
-      data->wireDecode(Block(reinterpret_cast<const uint8_t*>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0)));
-    }
+  if (sqlite3_step(stmt) == SQLITE_ROW) {
+    data = make_shared<Data>();
+    data->wireDecode(sqlite3_column_block(stmt, 0));
+  }
   sqlite3_finalize(stmt);
 
   return data;
 }
 
 shared_ptr<Data>
-ContactStorage::getDnsData(const std::string& name, const std::string& type)
+ContactStorage::getDnsData(const string& name, const string& type)
 {
   shared_ptr<Data> data;
 
   sqlite3_stmt *stmt;
-  sqlite3_prepare_v2 (m_db, "SELECT dns_value FROM DnsData where dns_name=? and dns_type=?", -1, &stmt, 0);
-  sqlite3_bind_text(stmt, 1, name.c_str(), name.size(), SQLITE_TRANSIENT);
-  sqlite3_bind_text(stmt, 2, type.c_str(), type.size(), SQLITE_TRANSIENT);
+  sqlite3_prepare_v2(m_db, "SELECT dns_value FROM DnsData where dns_name=? and dns_type=?",
+                     -1, &stmt, 0);
+  sqlite3_bind_string(stmt, 1, name, SQLITE_TRANSIENT);
+  sqlite3_bind_string(stmt, 2, type, SQLITE_TRANSIENT);
 
-  if(sqlite3_step (stmt) == SQLITE_ROW)
-    {
-      data = make_shared<Data>();
-      data->wireDecode(Block(reinterpret_cast<const uint8_t*>(sqlite3_column_text(stmt, 0)), sqlite3_column_bytes (stmt, 0)));
-    }
+  if (sqlite3_step(stmt) == SQLITE_ROW) {
+    data = make_shared<Data>();
+    data->wireDecode(sqlite3_column_block(stmt, 0));
+  }
   sqlite3_finalize(stmt);
 
   return data;
 }
 
-}//chronos
+} // namespace chronos
diff --git a/src/contact-storage.h b/src/contact-storage.h
deleted file mode 100644
index 1dd4804..0000000
--- a/src/contact-storage.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef CHRONOS_CONTACT_STORAGE_H
-#define CHRONOS_CONTACT_STORAGE_H
-
-#include "contact.h"
-#include "endorse-collection.pb.h"
-#include <sqlite3.h>
-
-namespace chronos{
-
-class ContactStorage
-{
-
-public:
-  struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };
-
-  ContactStorage(const ndn::Name& identity);
-
-  ~ContactStorage()
-  {
-    sqlite3_close(m_db);
-  }
-
-  ndn::shared_ptr<Profile>
-  getSelfProfile();
-
-  void
-  addSelfEndorseCertificate(const EndorseCertificate& endorseCertificate);
-
-  void
-  addEndorseCertificate(const EndorseCertificate& endorseCertificate, const ndn::Name& identity);
-
-  void
-  updateCollectEndorse(const EndorseCertificate& endorseCertificate);
-
-  void
-  getCollectEndorse(EndorseCollection& endorseCollection);
-
-  void
-  getEndorseList(const ndn::Name& identity, std::vector<std::string>& endorseList);
-
-
-
-  void
-  removeContact(const ndn::Name& identity);
-
-  void
-  addContact(const Contact& contact);
-
-  ndn::shared_ptr<Contact>
-  getContact(const ndn::Name& identity) const;
-
-  void
-  updateIsIntroducer(const ndn::Name& identity, bool isIntroducer);
-
-  void
-  updateAlias(const ndn::Name& identity, std::string alias);
-
-  void
-  getAllContacts(std::vector<ndn::shared_ptr<Contact> >& contacts) const;
-
-  void
-  updateDnsSelfProfileData(const ndn::Data& data)
-  {
-    updateDnsData(data.wireEncode(), "N/A", "PROFILE", data.getName().toUri());
-  }
-
-  void
-  updateDnsEndorseOthers(const ndn::Data& data, const std::string& endorsee)
-  {
-    updateDnsData(data.wireEncode(), endorsee, "ENDORSEE", data.getName().toUri());
-  }
-
-  void
-  updateDnsOthersEndorse(const ndn::Data& data)
-  {
-    updateDnsData(data.wireEncode(), "N/A", "ENDORSED", data.getName().toUri());
-  }
-
-  ndn::shared_ptr<ndn::Data>
-  getDnsData(const ndn::Name& name);
-
-  ndn::shared_ptr<ndn::Data>
-  getDnsData(const std::string& name, const std::string& type);
-
-private:
-  std::string
-  getDBName();
-
-  void
-  initializeTable(const std::string& tableName, const std::string& sqlCreateStmt);
-
-  bool
-  doesContactExist(const ndn::Name& name);
-
-  void
-  updateDnsData(const ndn::Block& data, const std::string& name, const std::string& type, const std::string& dataName);
-
-private:
-  ndn::Name m_identity;
-
-  sqlite3 *m_db;
-};
-
-}//chronos
-#endif
diff --git a/src/contact-storage.hpp b/src/contact-storage.hpp
new file mode 100644
index 0000000..da13d4b
--- /dev/null
+++ b/src/contact-storage.hpp
@@ -0,0 +1,124 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_CONTACT_STORAGE_HPP
+#define CHRONOS_CONTACT_STORAGE_HPP
+
+#include "contact.hpp"
+#include "endorse-collection.pb.h"
+#include <sqlite3.h>
+
+namespace chronos{
+
+class ContactStorage
+{
+
+public:
+  class Error : public std::runtime_error
+  {
+  public:
+    Error(const std::string &what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+  ContactStorage(const Name& identity);
+
+  ~ContactStorage()
+  {
+    sqlite3_close(m_db);
+  }
+
+  shared_ptr<Profile>
+  getSelfProfile();
+
+  void
+  addSelfEndorseCertificate(const EndorseCertificate& endorseCertificate);
+
+  void
+  addEndorseCertificate(const EndorseCertificate& endorseCertificate, const Name& identity);
+
+  void
+  updateCollectEndorse(const EndorseCertificate& endorseCertificate);
+
+  void
+  getCollectEndorse(EndorseCollection& endorseCollection);
+
+  void
+  getEndorseList(const Name& identity, std::vector<std::string>& endorseList);
+
+  void
+  removeContact(const Name& identity);
+
+  void
+  addContact(const Contact& contact);
+
+  shared_ptr<Contact>
+  getContact(const Name& identity) const;
+
+  void
+  updateIsIntroducer(const Name& identity, bool isIntroducer);
+
+  void
+  updateAlias(const Name& identity, const std::string& alias);
+
+  void
+  getAllContacts(std::vector<shared_ptr<Contact> >& contacts) const;
+
+  void
+  updateDnsSelfProfileData(const Data& data)
+  {
+    updateDnsData(data.wireEncode(), "N/A", "PROFILE", data.getName().toUri());
+  }
+
+  void
+  updateDnsEndorseOthers(const Data& data, const std::string& endorsee)
+  {
+    updateDnsData(data.wireEncode(), endorsee, "ENDORSEE", data.getName().toUri());
+  }
+
+  void
+  updateDnsOthersEndorse(const Data& data)
+  {
+    updateDnsData(data.wireEncode(), "N/A", "ENDORSED", data.getName().toUri());
+  }
+
+  shared_ptr<Data>
+  getDnsData(const Name& name);
+
+  shared_ptr<Data>
+  getDnsData(const std::string& name, const std::string& type);
+
+private:
+  std::string
+  getDBName();
+
+  void
+  initializeTable(const std::string& tableName, const std::string& sqlCreateStmt);
+
+  bool
+  doesContactExist(const Name& name);
+
+  void
+  updateDnsData(const Block& data,
+                const std::string& name,
+                const std::string& type,
+                const std::string& dataName);
+
+private:
+  Name m_identity;
+
+  sqlite3 *m_db;
+};
+
+}//chronos
+
+#endif // CHRONOS_CONTACT_STORAGE_HPP
diff --git a/src/contact.h b/src/contact.hpp
similarity index 77%
rename from src/contact.h
rename to src/contact.hpp
index a95ad42..8052ac7 100644
--- a/src/contact.h
+++ b/src/contact.hpp
@@ -8,21 +8,21 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef CHRONOS_CONTACT_H
-#define CHRONOS_CONTACT_H
+#ifndef CHRONOS_CONTACT_HPP
+#define CHRONOS_CONTACT_HPP
 
+#include "common.hpp"
 #include <ndn-cxx/security/identity-certificate.hpp>
 #include <ndn-cxx/util/regex.hpp>
-#include "endorse-certificate.h"
-#include <vector>
+#include "endorse-certificate.hpp"
 
-namespace chronos{
+namespace chronos {
 
 class Contact
 {
 public:
-  typedef std::map<ndn::Name, ndn::shared_ptr<ndn::Regex> >::const_iterator const_iterator;
-  typedef std::map<ndn::Name, ndn::shared_ptr<ndn::Regex> >::iterator iterator;
+  typedef std::map<Name, shared_ptr<ndn::Regex> >::const_iterator const_iterator;
+  typedef std::map<Name, shared_ptr<ndn::Regex> >::iterator iterator;
 
   Contact(const ndn::IdentityCertificate& identityCertificate,
           bool isIntroducer = false,
@@ -59,11 +59,11 @@
     m_publicKey = endorseCertificate.getPublicKeyInfo();
   }
 
-  Contact(const ndn::Name& identity,
+  Contact(const Name& identity,
           const std::string& alias,
-          const ndn::Name& keyName,
-          const ndn::time::system_clock::TimePoint& notBefore,
-          const ndn::time::system_clock::TimePoint& notAfter,
+          const Name& keyName,
+          const time::system_clock::TimePoint& notBefore,
+          const time::system_clock::TimePoint& notAfter,
           const ndn::PublicKey& key,
           bool isIntroducer)
     : m_namespace(identity)
@@ -88,13 +88,15 @@
     , m_isIntroducer(contact.m_isIntroducer)
     , m_profile(contact.m_profile)
     , m_trustScope(contact.m_trustScope)
-  {}
+  {
+  }
 
   virtual
   ~Contact()
-  {}
+  {
+  }
 
-  const ndn::Name&
+  const Name&
   getNameSpace() const
   {
     return m_namespace;
@@ -118,7 +120,7 @@
     return m_institution;
   }
 
-  const ndn::Name&
+  const Name&
   getPublicKeyName() const
   {
     return m_keyName;
@@ -130,13 +132,13 @@
     return m_publicKey;
   }
 
-  const ndn::time::system_clock::TimePoint&
+  const time::system_clock::TimePoint&
   getNotBefore() const
   {
     return m_notBefore;
   }
 
-  const ndn::time::system_clock::TimePoint&
+  const time::system_clock::TimePoint&
   getNotAfter() const
   {
     return m_notAfter;
@@ -169,24 +171,23 @@
   }
 
   void
-  addTrustScope(const ndn::Name& nameSpace)
+  addTrustScope(const Name& nameSpace)
   {
     m_trustScope[nameSpace] = ndn::Regex::fromName(nameSpace);
   }
 
   void
-  deleteTrustScope(const ndn::Name& nameSpace)
+  deleteTrustScope(const Name& nameSpace)
   {
     m_trustScope.erase(nameSpace);
   }
 
   bool
-  canBeTrustedFor(const ndn::Name& name)
+  canBeTrustedFor(const Name& name)
   {
-    std::map<ndn::Name, ndn::shared_ptr<ndn::Regex> >::iterator it = m_trustScope.begin();
-
-    for(; it != m_trustScope.end(); it++)
-      if(it->second->match(name))
+    for (std::map<Name, shared_ptr<ndn::Regex> >::iterator it = m_trustScope.begin();
+         it != m_trustScope.end(); it++)
+      if (it->second->match(name))
         return true;
     return false;
   }
@@ -216,16 +217,16 @@
   }
 
 protected:
-  typedef std::map<ndn::Name, ndn::shared_ptr<ndn::Regex> > TrustScopes;
+  typedef std::map<Name, shared_ptr<ndn::Regex> > TrustScopes;
 
-  ndn::Name m_namespace;
+  Name m_namespace;
   std::string m_alias;
   std::string m_name;
   std::string m_institution;
-  ndn::Name m_keyName;
+  Name m_keyName;
   ndn::PublicKey m_publicKey;
-  ndn::time::system_clock::TimePoint m_notBefore;
-  ndn::time::system_clock::TimePoint m_notAfter;
+  time::system_clock::TimePoint m_notBefore;
+  time::system_clock::TimePoint m_notAfter;
 
   bool m_isIntroducer;
   Profile m_profile;
@@ -235,4 +236,4 @@
 
 } // namespace chronos
 
-#endif // CHRONOS_CONTACT_H
+#endif // CHRONOS_CONTACT_HPP
diff --git a/src/controller.cpp b/src/controller.cpp
index 7517a4e..915e3d8 100644
--- a/src/controller.cpp
+++ b/src/controller.cpp
@@ -12,34 +12,34 @@
 #include <QMessageBox>
 #include <QDir>
 #include <QTimer>
-#include "controller.h"
+#include "controller.hpp"
 
 #ifndef Q_MOC_RUN
 #include <boost/filesystem.hpp>
 #include <boost/lexical_cast.hpp>
 #include <ndn-cxx/util/random.hpp>
-#include <cryptopp/sha.h>
-#include <cryptopp/hex.h>
-#include <cryptopp/files.h>
-#include <cryptopp/filters.h>
+#include "cryptopp.hpp"
 #include "config.pb.h"
 #include "endorse-info.pb.h"
 #include "logging.h"
 #endif
 
-INIT_LOGGER("chronos.Controller");
-
-using namespace ndn;
+// INIT_LOGGER("chronos.Controller");
 
 Q_DECLARE_METATYPE(ndn::Name)
 Q_DECLARE_METATYPE(ndn::IdentityCertificate)
-Q_DECLARE_METATYPE(chronos::EndorseInfo)
+Q_DECLARE_METATYPE(Chronos::EndorseInfo)
 Q_DECLARE_METATYPE(ndn::Interest)
 Q_DECLARE_METATYPE(size_t)
 
 namespace chronos {
 
-using ndn::shared_ptr;
+using std::string;
+
+using ndn::Face;
+using ndn::IdentityCertificate;
+using ndn::OnInterestValidated;
+using ndn::OnInterestValidationFailed;
 
 static const uint8_t ROUTING_PREFIX_SEPARATOR[2] = {0xF0, 0x2E};
 
@@ -60,7 +60,7 @@
 {
   qRegisterMetaType<ndn::Name>("ndn.Name");
   qRegisterMetaType<ndn::IdentityCertificate>("ndn.IdentityCertificate");
-  qRegisterMetaType<chronos::EndorseInfo>("chronos.EndorseInfo");
+  qRegisterMetaType<Chronos::EndorseInfo>("Chronos.EndorseInfo");
   qRegisterMetaType<ndn::Interest>("ndn.Interest");
   qRegisterMetaType<size_t>("size_t");
 
@@ -110,8 +110,8 @@
           &m_contactManager, SLOT(onFetchContactInfo(const QString&)));
   connect(m_addContactPanel, SIGNAL(addContact(const QString&)),
           &m_contactManager, SLOT(onAddFetchedContact(const QString&)));
-  connect(&m_contactManager, SIGNAL(contactEndorseInfoReady(const chronos::EndorseInfo&)),
-          m_addContactPanel, SLOT(onContactEndorseInfoReady(const chronos::EndorseInfo&)));
+  connect(&m_contactManager, SIGNAL(contactEndorseInfoReady(const Chronos::EndorseInfo&)),
+          m_addContactPanel, SLOT(onContactEndorseInfoReady(const Chronos::EndorseInfo&)));
 
 
   // Connection to BrowseContactDialog
@@ -151,8 +151,10 @@
           m_contactPanel, SLOT(onContactAliasListReady(const QStringList&)));
   connect(&m_contactManager, SIGNAL(contactIdListReady(const QStringList&)),
           m_contactPanel, SLOT(onContactIdListReady(const QStringList&)));
-  connect(&m_contactManager, SIGNAL(contactInfoReady(const QString&, const QString&, const QString&, bool)),
-          m_contactPanel, SLOT(onContactInfoReady(const QString&, const QString&, const QString&, bool)));
+  connect(&m_contactManager, SIGNAL(contactInfoReady(const QString&, const QString&,
+                                                     const QString&, bool)),
+          m_contactPanel, SLOT(onContactInfoReady(const QString&, const QString&,
+                                                  const QString&, bool)));
 
   initialize();
 
@@ -170,10 +172,10 @@
 
 
 // private methods
-std::string
+string
 Controller::getDBName()
 {
-  std::string dbName("chronos-");
+  string dbName("chronos-");
 
   std::stringstream ss;
   {
@@ -193,11 +195,14 @@
 {
   m_db = QSqlDatabase::addDatabase("QSQLITE");
   QString path = (QDir::home().path());
-  path.append(QDir::separator()).append(".chronos").append(QDir::separator()).append(getDBName().c_str());
+  path.append(QDir::separator())
+    .append(".chronos")
+    .append(QDir::separator())
+    .append(getDBName().c_str());
   m_db.setDatabaseName(path);
   bool ok = m_db.open();
 
-  _LOG_DEBUG("DB opened: " << std::boolalpha << ok );
+  // _LOG_DEBUG("DB opened: " << std::boolalpha << ok );
 }
 
 void
@@ -217,22 +222,23 @@
 void
 Controller::setInvitationListener()
 {
-  if(m_invitationListenerId != 0)
+  if (m_invitationListenerId != 0)
     m_face->unsetInterestFilter(m_invitationListenerId);
 
   Name invitationPrefix;
   Name routingPrefix = getInvitationRoutingPrefix();
   size_t offset = 0;
-  if(!routingPrefix.isPrefixOf(m_identity))
-    {
-      invitationPrefix.append(routingPrefix).append(ROUTING_PREFIX_SEPARATOR, 2);
-      offset = routingPrefix.size() + 1;
-    }
+  if (!routingPrefix.isPrefixOf(m_identity)) {
+    invitationPrefix.append(routingPrefix).append(ROUTING_PREFIX_SEPARATOR, 2);
+    offset = routingPrefix.size() + 1;
+  }
   invitationPrefix.append(m_identity).append("CHRONOCHAT-INVITATION");
 
   m_invitationListenerId = m_face->setInterestFilter(invitationPrefix,
-                                                     bind(&Controller::onInvitationInterestWrapper, this, _1, _2, offset),
-                                                     bind(&Controller::onInvitationRegisterFailed, this, _1, _2));
+                                                     bind(&Controller::onInvitationInterestWrapper,
+                                                          this, _1, _2, offset),
+                                                     bind(&Controller::onInvitationRegisterFailed,
+                                                          this, _1, _2));
 }
 
 void
@@ -245,24 +251,22 @@
 
   std::ifstream is((chronosDir / "config").c_str ());
   ChronoChat::Conf conf;
-  if(conf.ParseFromIstream(&is))
-    {
-      m_identity.clear();
-      m_identity.append(conf.identity());
-      if(conf.has_nick())
-        m_nick = conf.nick();
-      else
-        m_nick = m_identity.get(-1).toUri();
-    }
-  else
-    {
-      m_identity.clear();
-      // TODO: change below to system default;
-      m_identity.append("chronochat-tmp-identity")
-        .append(getRandomString());
-
+  if (conf.ParseFromIstream(&is)) {
+    m_identity.clear();
+    m_identity.append(conf.identity());
+    if (conf.has_nick())
+      m_nick = conf.nick();
+    else
       m_nick = m_identity.get(-1).toUri();
-    }
+  }
+  else {
+    m_identity.clear();
+    // TODO: change below to system default;
+    m_identity.append("chronochat-tmp-identity")
+      .append(getRandomString());
+
+    m_nick = m_identity.get(-1).toUri();
+  }
 }
 
 void
@@ -276,7 +280,7 @@
   std::ofstream os((chronosDir / "config").c_str ());
   ChronoChat::Conf conf;
   conf.set_identity(m_identity.toUri());
-  if(!m_nick.empty())
+  if (!m_nick.empty())
     conf.set_nick(m_nick);
   conf.SerializeToOstream(&os);
 
@@ -358,12 +362,11 @@
   {
     ChatActionList::const_iterator it = m_chatActionList.begin();
     ChatActionList::const_iterator end = m_chatActionList.end();
-    if(it != end)
-      {
-        for(; it != end; it++)
-          menu->addAction(it->second);
-        menu->addSeparator();
-      }
+    if (it != end) {
+      for (; it != end; it++)
+        menu->addAction(it->second);
+      menu->addSeparator();
+    }
   }
   menu->addAction(m_updateLocalPrefixAction);
   menu->addSeparator();
@@ -372,15 +375,11 @@
   {
     ChatActionList::const_iterator it = m_closeActionList.begin();
     ChatActionList::const_iterator end = m_closeActionList.end();
-    if(it == end)
-      {
-        closeMenu->setEnabled(false);
-      }
+    if (it == end)
+      closeMenu->setEnabled(false);
     else
-      {
-        for(; it != end; it++)
-          closeMenu->addAction(it->second);
-      }
+      for (; it != end; it++)
+        closeMenu->addAction(it->second);
   }
   menu->addSeparator();
   menu->addAction(m_quitAction);
@@ -399,7 +398,7 @@
     .trimmed();
 
   Name localPrefix(localPrefixStr.toStdString());
-  if(m_localPrefix.empty() || m_localPrefix != localPrefix)
+  if (m_localPrefix.empty() || m_localPrefix != localPrefix)
     emit localPrefixUpdated(localPrefixStr);
 }
 
@@ -409,42 +408,47 @@
   QString localPrefixStr("/private/local");
 
   Name localPrefix(localPrefixStr.toStdString());
-  if(m_localPrefix.empty() || m_localPrefix != localPrefix)
+  if (m_localPrefix.empty() || m_localPrefix != localPrefix)
     emit localPrefixUpdated(localPrefixStr);
 }
 
 void
-Controller::onInvitationInterestWrapper(const Name& prefix, const Interest& interest, size_t routingPrefixOffset)
+Controller::onInvitationInterestWrapper(const Name& prefix,
+                                        const Interest& interest,
+                                        size_t routingPrefixOffset)
 {
   emit invitationInterest(prefix, interest, routingPrefixOffset);
 }
 
 void
-Controller::onInvitationRegisterFailed(const Name& prefix, const std::string& failInfo)
+Controller::onInvitationRegisterFailed(const Name& prefix, const string& failInfo)
 {
-  _LOG_DEBUG("Controller::onInvitationRegisterFailed: " << failInfo);
+  // _LOG_DEBUG("Controller::onInvitationRegisterFailed: " << failInfo);
 }
 
 void
 Controller::onInvitationValidated(const shared_ptr<const Interest>& interest)
 {
   Invitation invitation(interest->getName());
-  std::string alias = invitation.getInviterCertificate().getPublicKeyName().getPrefix(-1).toUri(); // Should be obtained via a method of ContactManager.
+  // Should be obtained via a method of ContactManager.
+  string alias = invitation.getInviterCertificate().getPublicKeyName().getPrefix(-1).toUri();
 
   m_invitationDialog->setInvitation(alias, invitation.getChatroom(), interest->getName());
   m_invitationDialog->show();
 }
 
 void
-Controller::onInvitationValidationFailed(const shared_ptr<const Interest>& interest, std::string failureInfo)
+Controller::onInvitationValidationFailed(const shared_ptr<const Interest>& interest,
+                                         string failureInfo)
 {
-  _LOG_DEBUG("Invitation: " << interest->getName() << " cannot not be validated due to: " << failureInfo);
+  // _LOG_DEBUG("Invitation: " << interest->getName() <<
+  //            " cannot not be validated due to: " << failureInfo);
 }
 
-std::string
+string
 Controller::getRandomString()
 {
-  uint32_t r = random::generateWord32();
+  uint32_t r = ndn::random::generateWord32();
   std::stringstream ss;
   {
     using namespace CryptoPP;
@@ -452,10 +456,10 @@
                  new HexEncoder(new FileSink(ss), false));
 
   }
-  // for(int i = 0; i < 8; i++)
+  // for (int i = 0; i < 8; i++)
   //   {
   //     uint32_t t = r & mask;
-  //     if(t < 10)
+  //     if (t < 10)
   //       ss << static_cast<char>(t + 0x30);
   //     else
   //       ss << static_cast<char>(t + 0x57);
@@ -501,11 +505,10 @@
 {
   Name identityName(identity.toStdString());
 
-  while(!m_chatDialogList.empty())
-    {
-      ChatDialogList::const_iterator it = m_chatDialogList.begin();
-      onRemoveChatDialog(QString::fromStdString(it->first));
-    }
+  while (!m_chatDialogList.empty()) {
+    ChatDialogList::const_iterator it = m_chatDialogList.begin();
+    onRemoveChatDialog(QString::fromStdString(it->first));
+  }
 
   m_identity = identityName;
   m_keyChain.createIdentity(m_identity);
@@ -538,10 +541,7 @@
   m_contactManager.getContactList(contactList);
   m_validator.cleanTrustAnchor();
 
-  ContactList::const_iterator it  = contactList.begin();
-  ContactList::const_iterator end = contactList.end();
-
-  for(; it != end; it++)
+  for (ContactList::const_iterator it  = contactList.begin(); it != contactList.end(); it++)
     m_validator.addTrustAnchor((*it)->getPublicKeyName(), (*it)->getPublicKey());
 
 }
@@ -561,7 +561,7 @@
 void
 Controller::onStartChatAction()
 {
-  std::string chatroom = "chatroom-" + getRandomString();
+  string chatroom = "chatroom-" + getRandomString();
 
   m_startChatDialog->setChatroom(chatroom);
   m_startChatDialog->show();
@@ -629,20 +629,19 @@
 
   ChatDialogList::iterator it = m_chatDialogList.begin();
   ChatDialogList::iterator end = m_chatDialogList.end();
-  for(; it != end; it++)
+  for (; it != end; it++)
     it->second->hide();
 }
 
 void
 Controller::onQuitAction()
 {
-  while(!m_chatDialogList.empty())
-    {
-      ChatDialogList::const_iterator it = m_chatDialogList.begin();
-      onRemoveChatDialog(QString::fromStdString(it->first));
-    }
+  while (!m_chatDialogList.empty()) {
+    ChatDialogList::const_iterator it = m_chatDialogList.begin();
+    onRemoveChatDialog(QString::fromStdString(it->first));
+  }
 
-  if(m_invitationListenerId != 0)
+  if (m_invitationListenerId != 0)
     m_face->unsetInterestFilter(m_invitationListenerId);
 
   delete m_settingDialog;
@@ -652,7 +651,7 @@
   delete m_browseContactDialog;
   delete m_addContactPanel;
 
-  m_face->ioService()->stop();
+  m_face->getIoService().stop();
 
   QApplication::quit();
 }
@@ -667,13 +666,12 @@
     .append(chatroomName.toStdString());
 
   // check if the chatroom exists
-  if(m_chatDialogList.find(chatroomName.toStdString()) != m_chatDialogList.end())
-    {
-      QMessageBox::information(this, tr("ChronoChat"),
-                               tr("You are creating an existing chatroom."
-                                  "You can check it in the context memu."));
-      return;
-    }
+  if (m_chatDialogList.find(chatroomName.toStdString()) != m_chatDialogList.end()) {
+    QMessageBox::information(this, tr("ChronoChat"),
+                             tr("You are creating an existing chatroom."
+                                "You can check it in the context memu."));
+    return;
+  }
 
   // TODO: We should create a chatroom specific key/cert (which should be created in the first half of this method, but let's use the default one for now.
   shared_ptr<IdentityCertificate> idCert = m_keyChain.getCertificate(m_keyChain.getDefaultCertificateNameForIdentity(m_identity));
@@ -690,67 +688,62 @@
   shared_ptr<IdentityCertificate> chatroomCert;
 
   // generate reply;
-  if(accepted)
-    {
-      Name responseName = invitationName;
-      responseName.append(m_localPrefix.wireEncode());
+  if (accepted) {
+    Name responseName = invitationName;
+    responseName.append(m_localPrefix.wireEncode());
 
-      response.setName(responseName);
+    response.setName(responseName);
 
-      // We should create a particular certificate for this chatroom, but let's use default one for now.
-      chatroomCert = m_keyChain.getCertificate(m_keyChain.getDefaultCertificateNameForIdentity(m_identity));
+    // We should create a particular certificate for this chatroom, but let's use default one for now.
+    chatroomCert = m_keyChain.getCertificate(m_keyChain.getDefaultCertificateNameForIdentity(m_identity));
 
-      response.setContent(chatroomCert->wireEncode());
-      response.setFreshnessPeriod(time::milliseconds(1000));
-    }
-  else
-    {
-      response.setName(invitationName);
-      response.setFreshnessPeriod(time::milliseconds(1000));
-    }
+    response.setContent(chatroomCert->wireEncode());
+    response.setFreshnessPeriod(time::milliseconds(1000));
+  }
+  else {
+    response.setName(invitationName);
+    response.setFreshnessPeriod(time::milliseconds(1000));
+  }
+
   m_keyChain.signByIdentity(response, m_identity);
 
   // Check if we need a wrapper
   Name invitationRoutingPrefix = getInvitationRoutingPrefix();
-  if(invitationRoutingPrefix.isPrefixOf(m_identity))
-    {
-      m_face->put(response);
-    }
-  else
-    {
-      Name wrappedName;
-      wrappedName.append(invitationRoutingPrefix)
-        .append(ROUTING_PREFIX_SEPARATOR, 2)
-        .append(response.getName());
+  if (invitationRoutingPrefix.isPrefixOf(m_identity))
+    m_face->put(response);
+  else {
+    Name wrappedName;
+    wrappedName.append(invitationRoutingPrefix)
+      .append(ROUTING_PREFIX_SEPARATOR, 2)
+      .append(response.getName());
 
-      _LOG_DEBUG("onInvitationResponded: prepare reply " << wrappedName);
+    // _LOG_DEBUG("onInvitationResponded: prepare reply " << wrappedName);
 
-      Data wrappedData(wrappedName);
-      wrappedData.setContent(response.wireEncode());
-      wrappedData.setFreshnessPeriod(time::milliseconds(1000));
+    Data wrappedData(wrappedName);
+    wrappedData.setContent(response.wireEncode());
+    wrappedData.setFreshnessPeriod(time::milliseconds(1000));
 
-      m_keyChain.signByIdentity(wrappedData, m_identity);
-      m_face->put(wrappedData);
-    }
+    m_keyChain.signByIdentity(wrappedData, m_identity);
+    m_face->put(wrappedData);
+  }
 
   // create chatroom
-  if(accepted)
-    {
-      Invitation invitation(invitationName);
-      Name chatroomPrefix;
-      chatroomPrefix.append("ndn")
-        .append("broadcast")
-        .append("ChronoChat")
-        .append(invitation.getChatroom());
+  if (accepted) {
+    Invitation invitation(invitationName);
+    Name chatroomPrefix;
+    chatroomPrefix.append("ndn")
+      .append("broadcast")
+      .append("ChronoChat")
+      .append(invitation.getChatroom());
 
-      //We should create a chatroom specific key/cert (which should be created in the first half of this method, but let's use the default one for now.
-      shared_ptr<IdentityCertificate> idCert = m_keyChain.getCertificate(m_keyChain.getDefaultCertificateNameForIdentity(m_identity));
-      ChatDialog* chatDialog = new ChatDialog(&m_contactManager, m_face, *idCert, chatroomPrefix, m_localPrefix, m_nick, true);
-      chatDialog->addSyncAnchor(invitation);
+    //We should create a chatroom specific key/cert (which should be created in the first half of this method, but let's use the default one for now.
+    shared_ptr<IdentityCertificate> idCert = m_keyChain.getCertificate(m_keyChain.getDefaultCertificateNameForIdentity(m_identity));
+    ChatDialog* chatDialog = new ChatDialog(&m_contactManager, m_face, *idCert, chatroomPrefix, m_localPrefix, m_nick, true);
+    chatDialog->addSyncAnchor(invitation);
 
-      addChatDialog(QString::fromStdString(invitation.getChatroom()), chatDialog);
-      chatDialog->show();
-    }
+    addChatDialog(QString::fromStdString(invitation.getChatroom()), chatDialog);
+    chatDialog->show();
+  }
 }
 
 void
@@ -773,25 +766,24 @@
 {
   ChatDialogList::iterator it = m_chatDialogList.find(chatroomName.toStdString());
 
-  if(it != m_chatDialogList.end())
-    {
-      ChatDialog* deletedChat = it->second;
-      if(deletedChat)
-        delete deletedChat;
-      m_chatDialogList.erase(it);
+  if (it != m_chatDialogList.end()) {
+    ChatDialog* deletedChat = it->second;
+    if (deletedChat)
+      delete deletedChat;
+    m_chatDialogList.erase(it);
 
-      QAction* chatAction = m_chatActionList[chatroomName.toStdString()];
-      QAction* closeAction = m_closeActionList[chatroomName.toStdString()];
-      if(chatAction)
-        delete chatAction;
-      if(closeAction)
-        delete closeAction;
+    QAction* chatAction = m_chatActionList[chatroomName.toStdString()];
+    QAction* closeAction = m_closeActionList[chatroomName.toStdString()];
+    if (chatAction)
+      delete chatAction;
+    if (closeAction)
+      delete closeAction;
 
-      m_chatActionList.erase(chatroomName.toStdString());
-      m_closeActionList.erase(chatroomName.toStdString());
+    m_chatActionList.erase(chatroomName.toStdString());
+    m_closeActionList.erase(chatroomName.toStdString());
 
-      updateMenu();
-    }
+    updateMenu();
+  }
 }
 
 void
@@ -808,26 +800,28 @@
 }
 
 void
-Controller::onInvitationInterest(const Name& prefix, const Interest& interest, size_t routingPrefixOffset)
+Controller::onInvitationInterest(const Name& prefix,
+                                 const Interest& interest,
+                                 size_t routingPrefixOffset)
 {
-  _LOG_DEBUG("onInvitationInterest: " << interest.getName());
-  shared_ptr<Interest> invitationInterest = make_shared<Interest>(boost::cref(interest.getName().getSubName(routingPrefixOffset)));
+  // _LOG_DEBUG("onInvitationInterest: " << interest.getName());
+  shared_ptr<Interest> invitationInterest =
+    make_shared<Interest>(boost::cref(interest.getName().getSubName(routingPrefixOffset)));
 
   // check if the chatroom already exists;
-  try
-    {
+  try {
       Invitation invitation(invitationInterest->getName());
-      if(m_chatDialogList.find(invitation.getChatroom()) != m_chatDialogList.end())
+      if (m_chatDialogList.find(invitation.getChatroom()) != m_chatDialogList.end())
         return;
-    }
-  catch(Invitation::Error& e)
-    {
-      // Cannot parse the invitation;
-      return;
-    }
+  }
+  catch (Invitation::Error& e) {
+    // Cannot parse the invitation;
+    return;
+  }
 
   OnInterestValidated onValidated = bind(&Controller::onInvitationValidated, this, _1);
-  OnInterestValidationFailed onValidationFailed = bind(&Controller::onInvitationValidationFailed, this, _1, _2);
+  OnInterestValidationFailed onValidationFailed = bind(&Controller::onInvitationValidationFailed,
+                                                       this, _1, _2);
   m_validator.validate(*invitationInterest, onValidated, onValidationFailed);
 }
 
diff --git a/src/controller.h b/src/controller.hpp
similarity index 68%
rename from src/controller.h
rename to src/controller.hpp
index 77828d0..d445171 100644
--- a/src/controller.h
+++ b/src/controller.hpp
@@ -8,27 +8,27 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef CHRONOS_CONTROLLER_H
-#define CHRONOS_CONTROLLER_H
+#ifndef CHRONOS_CONTROLLER_HPP
+#define CHRONOS_CONTROLLER_HPP
 
 #include <QDialog>
 #include <QMenu>
 #include <QSystemTrayIcon>
 #include <QtSql/QSqlDatabase>
 
-#include "setting-dialog.h"
-#include "start-chat-dialog.h"
-#include "profile-editor.h"
-#include "invitation-dialog.h"
-#include "contact-panel.h"
-#include "browse-contact-dialog.h"
-#include "add-contact-panel.h"
-#include "chat-dialog.h"
+#include "setting-dialog.hpp"
+#include "start-chat-dialog.hpp"
+#include "profile-editor.hpp"
+#include "invitation-dialog.hpp"
+#include "contact-panel.hpp"
+#include "browse-contact-dialog.hpp"
+#include "add-contact-panel.hpp"
+#include "chat-dialog.hpp"
 
 #ifndef Q_MOC_RUN
-#include "contact-manager.h"
-#include "validator-invitation.h"
-#include <ndn-cxx/face.hpp>
+#include "common.hpp"
+#include "contact-manager.hpp"
+#include "validator-invitation.hpp"
 #include <ndn-cxx/security/key-chain.hpp>
 #endif
 
@@ -39,8 +39,7 @@
   Q_OBJECT
 
 public: // public methods
-  Controller(ndn::shared_ptr<ndn::Face> face,
-             QWidget* parent = 0);
+  Controller(shared_ptr<ndn::Face> face, QWidget* parent = 0);
 
   virtual
   ~Controller();
@@ -74,22 +73,24 @@
   updateMenu();
 
   void
-  onLocalPrefix(const ndn::Interest& interest, ndn::Data& data);
+  onLocalPrefix(const Interest& interest, Data& data);
 
   void
-  onLocalPrefixTimeout(const ndn::Interest& interest);
+  onLocalPrefixTimeout(const Interest& interest);
 
   void
-  onInvitationInterestWrapper(const ndn::Name& prefix, const ndn::Interest& interest, size_t routingPrefixOffset);
+  onInvitationInterestWrapper(const Name& prefix, const Interest& interest,
+                              size_t routingPrefixOffset);
 
   void
-  onInvitationRegisterFailed(const ndn::Name& prefix, const std::string& failInfo);
+  onInvitationRegisterFailed(const Name& prefix, const std::string& failInfo);
 
   void
-  onInvitationValidated(const ndn::shared_ptr<const ndn::Interest>& interest);
+  onInvitationValidated(const shared_ptr<const Interest>& interest);
 
   void
-  onInvitationValidationFailed(const ndn::shared_ptr<const ndn::Interest>& interest, std::string failureInfo);
+  onInvitationValidationFailed(const shared_ptr<const Interest>& interest,
+                               std::string failureInfo);
 
   std::string
   getRandomString();
@@ -114,7 +115,7 @@
   refreshBrowseContact();
 
   void
-  invitationInterest(const ndn::Name& prefix, const ndn::Interest& interest, size_t routingPrefixOffset);
+  invitationInterest(const Name& prefix, const Interest& interest, size_t routingPrefixOffset);
 
 private slots:
   void
@@ -163,7 +164,7 @@
   onStartChatroom(const QString& chatroom, bool secured);
 
   void
-  onInvitationResponded(const ndn::Name& invitationName, bool accepted);
+  onInvitationResponded(const Name& invitationName, bool accepted);
 
   void
   onShowChatMessage(const QString& chatroomName, const QString& from, const QString& data);
@@ -181,15 +182,15 @@
   onError(const QString& msg);
 
   void
-  onInvitationInterest(const ndn::Name& prefix, const ndn::Interest& interest, size_t routingPrefixOffset);
+  onInvitationInterest(const Name& prefix, const Interest& interest, size_t routingPrefixOffset);
 
 private: // private member
   typedef std::map<std::string, QAction*> ChatActionList;
   typedef std::map<std::string, ChatDialog*> ChatDialogList;
 
   // Communication
-  ndn::shared_ptr<ndn::Face>     m_face;
-  ndn::Name                      m_localPrefix;
+  shared_ptr<ndn::Face> m_face;
+  Name m_localPrefix;
   const ndn::RegisteredPrefixId* m_invitationListenerId;
 
   // Contact Manager
@@ -221,15 +222,15 @@
   ChatDialogList       m_chatDialogList;
 
   // Conf
-  ndn::Name   m_identity;
+  Name m_identity;
   std::string m_nick;
   QSqlDatabase m_db;
 
   // Security related;
-  ndn::KeyChain                m_keyChain;
-  chronos::ValidatorInvitation m_validator;
+  ndn::KeyChain m_keyChain;
+  ValidatorInvitation m_validator;
 };
 
 } // namespace chronos
 
-#endif //CHRONOS_CONTROLLER_H
+#endif //CHRONOS_CONTROLLER_HPP
diff --git a/src/cryptopp.hpp b/src/cryptopp.hpp
new file mode 100644
index 0000000..f49ebb2
--- /dev/null
+++ b/src/cryptopp.hpp
@@ -0,0 +1,23 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_CRYPTOPP_HPP
+#define CHRONOS_CRYPTOPP_HPP
+
+// suppress CryptoPP warnings
+#pragma GCC system_header
+#pragma clang system_header
+
+#include <cryptopp/hex.h>
+#include <cryptopp/files.h>
+#include <cryptopp/base64.h>
+#include <cryptopp/sha.h>
+#include <cryptopp/filters.h>
+
+#endif // CHRONOS_CRYPTOPP_HPP
diff --git a/src/digest-tree-scene.cpp b/src/digest-tree-scene.cpp
index 88315b1..65204df 100644
--- a/src/digest-tree-scene.cpp
+++ b/src/digest-tree-scene.cpp
@@ -9,7 +9,7 @@
  *         Alexander Afanasyev <alexander.afanasyev@ucla.edu>
  */
 
-#include "digest-tree-scene.h"
+#include "digest-tree-scene.hpp"
 
 #include <QtGui>
 
@@ -21,6 +21,8 @@
 #include <memory>
 #endif
 
+namespace chronos {
+
 static const double Pi = 3.14159265358979323846264338327950288419717;
 
 //DisplayUserPtr DisplayUserNullPtr;
@@ -36,38 +38,32 @@
 {
   int n = v.size();
   bool rePlot = false;
-  for (int i = 0; i < n; i++)
-  {
+  for (int i = 0; i < n; i++) {
     QString routablePrefix(v[i].prefix.c_str());
     QString prefix = trimRoutablePrefix(routablePrefix);
 
     Roster_iterator it = m_roster.find(prefix);
-    if (it == m_roster.end())
-    {
+    if (it == m_roster.end()) {
       // std::cout << "processUpdate v[" << i << "]: " << prefix.toStdString() << std::endl;
       rePlot = true;
       DisplayUserPtr p(new DisplayUser());
-      time_t tempTime = time(NULL) - FRESHNESS + 1;
+      time_t tempTime = ::time(NULL) - FRESHNESS + 1;
       p->setReceived(tempTime);
       p->setPrefix(prefix);
       p->setSeq(v[i].high);
       m_roster.insert(p->getPrefix(), p);
     }
-    else
-    {
+    else {
       it.value()->setSeq(v[i].high);
     }
   }
 
-  if (rePlot)
-  {
+  if (rePlot) {
     plot(digest);
     QTimer::singleShot(2100, this, SLOT(emitReplot()));
   }
-  else
-  {
-    for (int i = 0; i < n; i++)
-    {
+  else {
+    for (int i = 0; i < n; i++) {
       QString routablePrefix(v[i].prefix.c_str());
       QString prefix = trimRoutablePrefix(routablePrefix);
 
@@ -80,7 +76,8 @@
         item->setPlainText(s.c_str());
         QRectF textBR = item->boundingRect();
         QRectF rectBR = rectItem->boundingRect();
-        item->setPos(rectBR.x() + (rectBR.width() - textBR.width())/2, rectBR.y() + (rectBR.height() - textBR.height())/2);
+        item->setPos(rectBR.x() + (rectBR.width() - textBR.width())/2,
+                     rectBR.y() + (rectBR.height() - textBR.height())/2);
       }
     }
     m_rootDigest->setPlainText(digest);
@@ -98,12 +95,10 @@
 {
   QStringList rosterList;
   RosterIterator it(m_roster);
-  while(it.hasNext())
-  {
+  while (it.hasNext()) {
     it.next();
     DisplayUserPtr p = it.value();
-    if (p != DisplayUserNullPtr)
-    {
+    if (p != DisplayUserNullPtr) {
       rosterList << "- " + p->getNick();
     }
   }
@@ -116,33 +111,31 @@
   QString prefix = trimRoutablePrefix(routablePrefix);
   Roster_iterator it = m_roster.find(prefix);
   // std::cout << "msgReceived prefix: " << prefix.toStdString() << std::endl;
-  if (it != m_roster.end())
-    {
-      // std::cout << "Updating for prefix = " << prefix.toStdString() << " nick = " << nick.toStdString() << std::endl;
-      DisplayUserPtr p = it.value();
-      p->setReceived(time(NULL));
-      if (nick != p->getNick())
-        {
-          // std::cout << "old nick = " << p->getNick().toStdString() << std::endl;
-          p->setNick(nick);
-          QGraphicsTextItem *nickItem = p->getNickTextItem();
-          QGraphicsRectItem *nickRectItem = p->getNickRectItem();
-          nickItem->setPlainText(p->getNick());
-          QRectF rectBR = nickRectItem->boundingRect();
-          QRectF nickBR = nickItem->boundingRect();
-          nickItem->setPos(rectBR.x() + (rectBR.width() - nickBR.width())/2, rectBR.y() + 5);
-          emit rosterChanged(QStringList());
-        }
-
-      reDrawNode(p, Qt::red);
-
-      if (previouslyUpdatedUser != DisplayUserNullPtr && previouslyUpdatedUser != p)
-        {
-          reDrawNode(previouslyUpdatedUser, Qt::darkBlue);
-        }
-
-      previouslyUpdatedUser = p;
+  if (it != m_roster.end()) {
+    // std::cout << "Updating for prefix = " << prefix.toStdString() <<
+    // " nick = " << nick.toStdString() << std::endl;
+    DisplayUserPtr p = it.value();
+    p->setReceived(::time(NULL));
+    if (nick != p->getNick()) {
+      // std::cout << "old nick = " << p->getNick().toStdString() << std::endl;
+      p->setNick(nick);
+      QGraphicsTextItem *nickItem = p->getNickTextItem();
+      QGraphicsRectItem *nickRectItem = p->getNickRectItem();
+      nickItem->setPlainText(p->getNick());
+      QRectF rectBR = nickRectItem->boundingRect();
+      QRectF nickBR = nickItem->boundingRect();
+      nickItem->setPos(rectBR.x() + (rectBR.width() - nickBR.width())/2, rectBR.y() + 5);
+      emit rosterChanged(QStringList());
     }
+
+    reDrawNode(p, Qt::red);
+
+    if (previouslyUpdatedUser != DisplayUserNullPtr && previouslyUpdatedUser != p) {
+      reDrawNode(previouslyUpdatedUser, Qt::darkBlue);
+    }
+
+    previouslyUpdatedUser = p;
+  }
 }
 
 void
@@ -163,7 +156,7 @@
 DigestTreeScene::plot(QString digest)
 {
 #ifdef _DEBUG
-  std::cout << "Plotting at time: " << time(NULL) << std::endl;
+  std::cout << "Plotting at time: " << ::time(NULL) << std::endl;
 #endif
   clear();
 
@@ -177,14 +170,11 @@
   // do some cleaning, get rid of stale member info
   Roster_iterator it = m_roster.begin();
   QStringList staleUserList;
-  while (it != m_roster.end())
-  {
+  while (it != m_roster.end()) {
     DisplayUserPtr p = it.value();
-    if (p != DisplayUserNullPtr)
-    {
-      time_t now = time(NULL);
-      if (now - p->getReceived() >= FRESHNESS)
-      {
+    if (p != DisplayUserNullPtr) {
+      time_t now = ::time(NULL);
+      if (now - p->getReceived() >= FRESHNESS) {
 #ifdef _DEBUG
         std::cout << "Removing user: " << p->getNick().toStdString() << std::endl;
         std::cout << "now - last = " << now - p->getReceived() << std::endl;
@@ -193,10 +183,9 @@
         p = DisplayUserNullPtr;
         it = m_roster.erase(it);
       }
-      else
-      {
-        if (!m_currentPrefix.startsWith("/private/local") && p->getPrefix().startsWith("/private/local"))
-        {
+      else {
+        if (!m_currentPrefix.startsWith("/private/local") &&
+            p->getPrefix().startsWith("/private/local")) {
 #ifdef _DEBUG
           std::cout << "erasing: " << p->getPrefix().toStdString() << std::endl;
 #endif
@@ -208,8 +197,7 @@
         ++it;
       }
     }
-    else
-    {
+    else {
       it = m_roster.erase(it);
     }
   }
@@ -243,19 +231,22 @@
     double angle = ::acos(line.dx() / line.length());
 
     double arrowSize = 10;
-    QPointF sourceArrowP0 = src + QPointF((nodeSize/2 + 10) * line.dx() / line.length(),  (nodeSize/2 +10) * line.dy() / line.length());
+    QPointF sourceArrowP0 = src + QPointF((nodeSize/2 + 10) * line.dx() / line.length(),
+                                          (nodeSize/2 +10) * line.dy() / line.length());
     QPointF sourceArrowP1 = sourceArrowP0 + QPointF(cos(angle + Pi / 3 - Pi/2) * arrowSize,
                                                     sin(angle + Pi / 3 - Pi/2) * arrowSize);
     QPointF sourceArrowP2 = sourceArrowP0 + QPointF(cos(angle + Pi - Pi / 3 - Pi/2) * arrowSize,
-                                                         sin(angle + Pi - Pi / 3 - Pi/2) * arrowSize);
+                                                    sin(angle + Pi - Pi / 3 - Pi/2) * arrowSize);
 
     addLine(QLineF(sourceArrowP0, dest), QPen(Qt::black));
-    addPolygon(QPolygonF() << sourceArrowP0<< sourceArrowP1 << sourceArrowP2, QPen(Qt::black), QBrush(Qt::black));
+    addPolygon(QPolygonF() << sourceArrowP0<< sourceArrowP1 <<
+               sourceArrowP2, QPen(Qt::black), QBrush(Qt::black));
   }
 }
 
 void
-DigestTreeScene::plotNode(const std::vector<TreeLayout::Coordinate> &childNodesCo, QString digest, int nodeSize)
+DigestTreeScene::plotNode(const std::vector<TreeLayout::Coordinate>& childNodesCo,
+                          QString digest, int nodeSize)
 {
   RosterIterator it(m_roster);
   int n = childNodesCo.size();
@@ -273,20 +264,16 @@
   QRectF digestBoundingRect = digestItem->boundingRect();
   digestItem->setDefaultTextColor(Qt::black);
   digestItem->setFont(QFont("Cursive", 12, QFont::Bold));
-  digestItem->setPos(- 4.5 * nodeSize + (12 * nodeSize - digestBoundingRect.width()) / 2, - nodeSize + 5);
+  digestItem->setPos(- 4.5 * nodeSize + (12 * nodeSize - digestBoundingRect.width()) / 2,
+                     - nodeSize + 5);
   m_rootDigest = digestItem;
 
   // plot child nodes
-  for (int i = 0; i < n; i++)
-  {
+  for (int i = 0; i < n; i++) {
     if (it.hasNext())
-    {
       it.next();
-    }
     else
-    {
       abort();
-    }
 
     double x = childNodesCo[i].x;
     double y = childNodesCo[i].y;
@@ -296,14 +283,17 @@
     QGraphicsRectItem *rectItem = addRect(boundingRect, QPen(Qt::black), QBrush(Qt::darkBlue));
     p->setRimRectItem(rectItem);
 
-    QGraphicsRectItem *innerRectItem = addRect(innerBoundingRect, QPen(Qt::black), QBrush(Qt::lightGray));
+    QGraphicsRectItem *innerRectItem = addRect(innerBoundingRect,
+                                               QPen(Qt::black),
+                                               QBrush(Qt::lightGray));
     p->setInnerRectItem(innerRectItem);
 
     std::string s = boost::lexical_cast<std::string>(p->getSeqNo().getSeq());
     QGraphicsTextItem *seqItem = addText(s.c_str());
     seqItem->setFont(QFont("Cursive", 12, QFont::Bold));
     QRectF seqBoundingRect = seqItem->boundingRect();
-    seqItem->setPos(x + nodeSize / 2 - seqBoundingRect.width() / 2, y + nodeSize / 2 - seqBoundingRect.height() / 2);
+    seqItem->setPos(x + nodeSize / 2 - seqBoundingRect.width() / 2,
+                    y + nodeSize / 2 - seqBoundingRect.height() / 2);
     p->setSeqTextItem(seqItem);
 
     QRectF textRect(x - nodeSize / 2, y + nodeSize, 2 * nodeSize, 30);
@@ -331,7 +321,8 @@
     seqTextItem->setPlainText(s.c_str());
     QRectF textBR = seqTextItem->boundingRect();
     QRectF innerBR = innerItem->boundingRect();
-    seqTextItem->setPos(innerBR.x() + (innerBR.width() - textBR.width())/2, innerBR.y() + (innerBR.height() - textBR.height())/2);
+    seqTextItem->setPos(innerBR.x() + (innerBR.width() - textBR.width())/2,
+                        innerBR.y() + (innerBR.height() - textBR.height())/2);
 }
 
 QString
@@ -340,27 +331,22 @@
   bool encaped = false;
   ndn::Name prefixName(prefix.toStdString());
 
-  ndn::Name::const_iterator it  = prefixName.begin();
-  ndn::Name::const_iterator end = prefixName.end();
   size_t offset = 0;
-
-  for(; it != end; it++, offset++)
-    {
-      if(it->toEscapedString() == "%F0.")
-        {
-          encaped = true;
-          break;
-        }
+  for (ndn::Name::const_iterator it  = prefixName.begin(); it != prefixName.end(); it++, offset++) {
+    if (it->toUri() == "%F0.") {
+      encaped = true;
+      break;
     }
+  }
 
-  if(!encaped)
+  if (!encaped)
     return prefix;
   else
-    {
-      return QString(prefixName.getSubName(offset+1).toUri().c_str());
-    }
+    return QString(prefixName.getSubName(offset+1).toUri().c_str());
 }
 
+} // namespace chronos
+
 #if WAF
 #include "digest-tree-scene.moc"
 #include "digest-tree-scene.cpp.moc"
diff --git a/src/digest-tree-scene.h b/src/digest-tree-scene.h
deleted file mode 100644
index 06befa8..0000000
--- a/src/digest-tree-scene.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
- *         Alexander Afanasyev <alexander.afanasyev@ucla.edu>
- */
-
-#ifndef DIGEST_TREE_SCENE_H
-#define DIGEST_TREE_SCENE_H
-
-#include <QtGui/QGraphicsScene>
-#include <QColor>
-#include <QMap>
-
-#ifndef Q_MOC_RUN
-#include "tree-layout.h"
-#include <sync-seq-no.h>
-#include <sync-logic.h>
-#include <ctime>
-#include <vector>
-#include <boost/shared_ptr.hpp>
-#endif
-
-const int FRESHNESS = 60;
-
-class QGraphicsTextItem;
-
-class User;
-class DisplayUser;
-typedef boost::shared_ptr<DisplayUser> DisplayUserPtr;
-static DisplayUserPtr DisplayUserNullPtr;
-
-class DigestTreeScene : public QGraphicsScene
-{
-  Q_OBJECT
-
-typedef QMap<QString, DisplayUserPtr> Roster;
-typedef QMap<QString, DisplayUserPtr>::iterator Roster_iterator;
-typedef QMapIterator<QString, DisplayUserPtr> RosterIterator;
-
-public:
-  DigestTreeScene(QWidget *parent = 0);
-  void processUpdate(const std::vector<Sync::MissingDataInfo> &v, QString digest);
-  void msgReceived(QString prefix, QString nick);
-  void clearAll();
-  bool removeNode(const QString prefix);
-  void plot(QString digest);
-  QStringList getRosterList();
-  void setCurrentPrefix(QString prefix) {m_currentPrefix = prefix;}
-  QMap<QString, DisplayUserPtr> getRosterFull() { return m_roster;}
-
-signals:
-  void replot();
-  void rosterChanged(QStringList);
-
-private slots:
-  void emitReplot();
-
-private:
-  void plotEdge(const std::vector<TreeLayout::Coordinate> &v, int nodeSize);
-  void plotNode(const std::vector<TreeLayout::Coordinate> &v, QString digest, int nodeSize);
-  void reDrawNode(DisplayUserPtr p, QColor rimColor);
-
-  QString trimRoutablePrefix(QString prefix);
-
-private:
-  Roster m_roster;
-  QGraphicsTextItem *m_rootDigest;
-  DisplayUserPtr previouslyUpdatedUser;
-  QString m_currentPrefix;
-};
-
-class User
-{
-public:
-  User():m_received(time(NULL)) {}
-  User(QString n, QString p, QString c): m_nick(n), m_prefix(p), m_chatroom(c), m_received(time(NULL)) {}
-  void setNick(QString nick) {m_nick = nick;}
-  void setPrefix(QString prefix) {m_prefix = prefix;}
-  void setChatroom(QString chatroom) {m_chatroom = chatroom;}
-  void setSeq(Sync::SeqNo seq) {m_seq = seq;}
-  void setReceived(time_t t) {m_received = t;}
-  void setOriginPrefix(QString originPrefix) { m_originPrefix = originPrefix;}
-  QString getNick() { return m_nick;}
-  QString getPrefix() { return m_prefix;}
-  QString getChatroom() { return m_chatroom;}
-  QString getOriginPrefix() { return m_originPrefix;}
-  Sync::SeqNo getSeqNo() { return m_seq;}
-  time_t getReceived() { return m_received;}
-private:
-  QString m_nick;
-  QString m_prefix;
-  QString m_chatroom;
-  QString m_originPrefix;
-  Sync::SeqNo m_seq;
-  time_t m_received;
-};
-
-class DisplayUser : public User
-{
-public:
-  DisplayUser():m_seqTextItem(NULL), m_nickTextItem(NULL), m_rimRectItem(NULL) {}
-  DisplayUser(QString n, QString p , QString c): User(n, p, c), m_seqTextItem(NULL), m_nickTextItem(NULL), m_rimRectItem(NULL) {}
-  QGraphicsTextItem *getSeqTextItem() {return m_seqTextItem;}
-  QGraphicsTextItem *getNickTextItem() {return m_nickTextItem;}
-  QGraphicsRectItem *getRimRectItem() {return m_rimRectItem;}
-  QGraphicsRectItem *getInnerRectItem() {return m_innerRectItem;}
-  QGraphicsRectItem *getNickRectItem() {return m_nickRectItem;}
-  void setSeqTextItem(QGraphicsTextItem *item) { m_seqTextItem = item;}
-  void setNickTextItem(QGraphicsTextItem *item) { m_nickTextItem = item;}
-  void setRimRectItem(QGraphicsRectItem *item) {m_rimRectItem = item;}
-  void setInnerRectItem(QGraphicsRectItem *item) {m_innerRectItem = item;}
-  void setNickRectItem(QGraphicsRectItem *item) {m_nickRectItem = item;}
-private:
-  QGraphicsTextItem *m_seqTextItem;
-  QGraphicsTextItem *m_nickTextItem;
-  QGraphicsRectItem *m_rimRectItem;
-  QGraphicsRectItem *m_innerRectItem;
-  QGraphicsRectItem *m_nickRectItem;
-};
-
-#endif // DIGEST_TREE_SCENE_H
diff --git a/src/digest-tree-scene.hpp b/src/digest-tree-scene.hpp
new file mode 100644
index 0000000..434ee07
--- /dev/null
+++ b/src/digest-tree-scene.hpp
@@ -0,0 +1,291 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ *         Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef CHRONOS_DIGEST_TREE_SCENE_HPP
+#define CHRONOS_DIGEST_TREE_SCENE_HPP
+
+#include <QtGui/QGraphicsScene>
+#include <QColor>
+#include <QMap>
+
+#ifndef Q_MOC_RUN
+#include "tree-layout.hpp"
+#include <sync-seq-no.h>
+#include <sync-logic.h>
+#include <ctime>
+#include <vector>
+#include <boost/shared_ptr.hpp>
+#endif
+
+const int FRESHNESS = 60;
+
+class QGraphicsTextItem;
+
+namespace chronos {
+
+class User;
+class DisplayUser;
+typedef boost::shared_ptr<DisplayUser> DisplayUserPtr;
+static DisplayUserPtr DisplayUserNullPtr;
+
+class DigestTreeScene : public QGraphicsScene
+{
+  Q_OBJECT
+
+typedef QMap<QString, DisplayUserPtr> Roster;
+typedef QMap<QString, DisplayUserPtr>::iterator Roster_iterator;
+typedef QMapIterator<QString, DisplayUserPtr> RosterIterator;
+
+public:
+  DigestTreeScene(QWidget *parent = 0);
+
+  void
+  processUpdate(const std::vector<Sync::MissingDataInfo>& v, QString digest);
+
+  void
+  msgReceived(QString prefix, QString nick);
+
+  void
+  clearAll();
+
+  bool
+  removeNode(const QString prefix);
+
+  void
+  plot(QString digest);
+
+  QStringList
+  getRosterList();
+
+  void
+  setCurrentPrefix(QString prefix)
+  {
+    m_currentPrefix = prefix;
+  }
+
+  QMap<QString, DisplayUserPtr> getRosterFull()
+  {
+    return m_roster;
+  }
+
+signals:
+  void
+  replot();
+
+  void
+  rosterChanged(QStringList);
+
+private slots:
+  void
+  emitReplot();
+
+private:
+  void
+  plotEdge(const std::vector<chronos::TreeLayout::Coordinate>& v, int nodeSize);
+
+  void
+  plotNode(const std::vector<chronos::TreeLayout::Coordinate>& v, QString digest, int nodeSize);
+
+  void
+  reDrawNode(DisplayUserPtr p, QColor rimColor);
+
+  QString
+  trimRoutablePrefix(QString prefix);
+
+private:
+  Roster m_roster;
+  QGraphicsTextItem* m_rootDigest;
+  DisplayUserPtr previouslyUpdatedUser;
+  QString m_currentPrefix;
+};
+
+class User
+{
+public:
+  User()
+    :m_received(::time(NULL))
+  {
+  }
+
+  User(QString n, QString p, QString c)
+    : m_nick(n)
+    , m_prefix(p)
+    , m_chatroom(c)
+    , m_received(::time(NULL))
+  {
+  }
+
+  void
+  setNick(QString nick)
+  {
+    m_nick = nick;
+  }
+
+  void
+  setPrefix(QString prefix)
+  {
+    m_prefix = prefix;
+  }
+
+  void
+  setChatroom(QString chatroom)
+  {
+    m_chatroom = chatroom;
+  }
+
+  void
+  setSeq(Sync::SeqNo seq)
+  {
+    m_seq = seq;
+  }
+
+  void
+  setReceived(time_t t)
+  {
+    m_received = t;
+  }
+
+  void
+  setOriginPrefix(QString originPrefix)
+  {
+    m_originPrefix = originPrefix;
+  }
+
+  QString
+  getNick()
+  {
+    return m_nick;
+  }
+
+  QString getPrefix()
+  {
+    return m_prefix;
+  }
+
+  QString getChatroom()
+  {
+    return m_chatroom;
+  }
+
+  QString getOriginPrefix()
+  {
+    return m_originPrefix;
+  }
+
+  Sync::SeqNo
+  getSeqNo()
+  {
+    return m_seq;
+  }
+
+  time_t getReceived()
+  {
+    return m_received;
+  }
+
+private:
+  QString m_nick;
+  QString m_prefix;
+  QString m_chatroom;
+  QString m_originPrefix;
+  Sync::SeqNo m_seq;
+  time_t m_received;
+};
+
+class DisplayUser : public User
+{
+public:
+  DisplayUser()
+    : m_seqTextItem(NULL)
+    , m_nickTextItem(NULL)
+    , m_rimRectItem(NULL)
+  {
+  }
+
+  DisplayUser(QString n, QString p , QString c)
+    : User(n, p, c)
+    , m_seqTextItem(NULL)
+    , m_nickTextItem(NULL)
+    , m_rimRectItem(NULL)
+  {
+  }
+
+  QGraphicsTextItem*
+  getSeqTextItem()
+  {
+    return m_seqTextItem;
+  }
+
+  QGraphicsTextItem*
+  getNickTextItem()
+  {
+    return m_nickTextItem;
+  }
+
+  QGraphicsRectItem*
+  getRimRectItem()
+  {
+    return m_rimRectItem;
+  }
+
+  QGraphicsRectItem*
+  getInnerRectItem()
+  {
+    return m_innerRectItem;
+  }
+
+  QGraphicsRectItem*
+  getNickRectItem()
+  {
+    return m_nickRectItem;
+  }
+
+  void
+  setSeqTextItem(QGraphicsTextItem* item)
+  {
+    m_seqTextItem = item;
+  }
+
+  void
+  setNickTextItem(QGraphicsTextItem* item)
+  {
+    m_nickTextItem = item;
+  }
+
+  void
+  setRimRectItem(QGraphicsRectItem* item)
+  {
+    m_rimRectItem = item;
+  }
+
+  void
+  setInnerRectItem(QGraphicsRectItem* item)
+  {
+    m_innerRectItem = item;
+  }
+
+  void
+  setNickRectItem(QGraphicsRectItem* item)
+  {
+    m_nickRectItem = item;
+  }
+
+private:
+  QGraphicsTextItem* m_seqTextItem;
+  QGraphicsTextItem* m_nickTextItem;
+  QGraphicsRectItem* m_rimRectItem;
+  QGraphicsRectItem* m_innerRectItem;
+  QGraphicsRectItem* m_nickRectItem;
+};
+
+} // namespace chronos
+
+#endif // CHRONOS_DIGEST_TREE_SCENE_HPP
diff --git a/src/endorse-certificate.cpp b/src/endorse-certificate.cpp
index faa0972..8fc8dec 100644
--- a/src/endorse-certificate.cpp
+++ b/src/endorse-certificate.cpp
@@ -8,33 +8,41 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "endorse-certificate.h"
+#include "endorse-certificate.hpp"
 #include "endorse-extension.pb.h"
 #include <boost/iostreams/stream.hpp>
+#include <ndn-cxx/encoding/buffer-stream.hpp>
 
-using namespace ndn;
+namespace chronos {
 
-namespace chronos{
+using std::vector;
+using std::string;
+
+using ndn::PublicKey;
+using ndn::IdentityCertificate;
+using ndn::CertificateSubjectDescription;
+using ndn::CertificateExtension;
+using ndn::OID;
+using ndn::OBufferStream;
 
 const OID EndorseCertificate::PROFILE_EXT_OID("1.3.6.1.5.32.2.1");
 const OID EndorseCertificate::ENDORSE_EXT_OID("1.3.6.1.5.32.2.2");
 
-const std::vector<std::string> EndorseCertificate::DEFAULT_ENDORSE_LIST = std::vector<std::string>();
+const vector<string> EndorseCertificate::DEFAULT_ENDORSE_LIST;
 
 Chronos::EndorseExtensionMsg&
-operator << (Chronos::EndorseExtensionMsg& endorseExtension, const std::vector<std::string>& endorseList)
+operator<<(Chronos::EndorseExtensionMsg& endorseExtension, const vector<string>& endorseList)
 {
-  std::vector<std::string>::const_iterator it = endorseList.begin();
-  for(; it != endorseList.end(); it++)
+  for (vector<string>::const_iterator it = endorseList.begin(); it != endorseList.end(); it++)
     endorseExtension.add_endorseentry()->set_name(*it);
 
   return endorseExtension;
 }
 
 Chronos::EndorseExtensionMsg&
-operator >> (Chronos::EndorseExtensionMsg& endorseExtension, std::vector<std::string>& endorseList)
+operator>>(Chronos::EndorseExtensionMsg& endorseExtension, vector<string>& endorseList)
 {
-  for(int i = 0; i < endorseExtension.endorseentry_size(); i ++)
+  for (int i = 0; i < endorseExtension.endorseentry_size(); i ++)
     endorseList.push_back(endorseExtension.endorseentry(i).name());
 
   return endorseExtension;
@@ -42,7 +50,7 @@
 
 EndorseCertificate::EndorseCertificate(const IdentityCertificate& kskCertificate,
                                        const Profile& profile,
-                                       const std::vector<std::string>& endorseList)
+                                       const vector<string>& endorseList)
   : Certificate()
   , m_profile(profile)
   , m_endorseList(endorseList)
@@ -56,7 +64,7 @@
 
   setNotBefore(kskCertificate.getNotBefore());
   setNotAfter(kskCertificate.getNotAfter());
-  addSubjectDescription(CertificateSubjectDescription("2.5.4.41", m_keyName.toUri()));
+  addSubjectDescription(CertificateSubjectDescription(OID("2.5.4.41"), m_keyName.toUri()));
   setPublicKeyInfo(kskCertificate.getPublicKeyInfo());
 
   OBufferStream profileStream;
@@ -74,7 +82,7 @@
 
 EndorseCertificate::EndorseCertificate(const EndorseCertificate& endorseCertificate,
                                        const Name& signer,
-                                       const std::vector<std::string>& endorseList)
+                                       const vector<string>& endorseList)
   : Certificate()
   , m_keyName(endorseCertificate.m_keyName)
   , m_signer(signer)
@@ -87,7 +95,7 @@
 
   setNotBefore(endorseCertificate.getNotBefore());
   setNotAfter(endorseCertificate.getNotAfter());
-  addSubjectDescription(CertificateSubjectDescription("2.5.4.41", m_keyName.toUri()));
+  addSubjectDescription(CertificateSubjectDescription(OID("2.5.4.41"), m_keyName.toUri()));
   setPublicKeyInfo(endorseCertificate.getPublicKeyInfo());
 
   OBufferStream profileStream;
@@ -109,7 +117,7 @@
                                        const time::system_clock::TimePoint& notAfter,
                                        const Name& signer,
                                        const Profile& profile,
-                                       const std::vector<std::string>& endorseList)
+                                       const vector<string>& endorseList)
   : Certificate()
   , m_keyName(keyName)
   , m_signer(signer)
@@ -122,7 +130,7 @@
 
   setNotBefore(notBefore);
   setNotAfter(notAfter);
-  addSubjectDescription(CertificateSubjectDescription("2.5.4.41", m_keyName.toUri()));
+  addSubjectDescription(CertificateSubjectDescription(OID("2.5.4.41"), m_keyName.toUri()));
   setPublicKeyInfo(key);
 
   OBufferStream profileStream;
@@ -144,39 +152,37 @@
   , m_signer(endorseCertificate.m_signer)
   , m_profile(endorseCertificate.m_profile)
   , m_endorseList(endorseCertificate.m_endorseList)
-{}
+{
+}
 
 EndorseCertificate::EndorseCertificate(const Data& data)
   : Certificate(data)
 {
   const Name& dataName = data.getName();
 
-  if(dataName.size() < 3 || dataName.get(-3).toEscapedString() != "PROFILE-CERT")
+  if(dataName.size() < 3 || dataName.get(-3).toUri() != "PROFILE-CERT")
     throw Error("No PROFILE-CERT component in data name!");
 
   m_keyName = dataName.getPrefix(-3);
   m_signer.wireDecode(dataName.get(-2).blockFromValue());
 
-  ExtensionList::iterator it = m_extensionList.begin();
-  for(; it != m_extensionList.end(); it++)
-    {
-      if(PROFILE_EXT_OID == it->getOid())
-	{
-          boost::iostreams::stream<boost::iostreams::array_source> is
-            (reinterpret_cast<const char*>(it->getValue().buf()), it->getValue().size());
-	  m_profile.decode(is);
-	}
-      if(ENDORSE_EXT_OID == it->getOid())
-        {
-          Chronos::EndorseExtensionMsg endorseExtension;
 
-          boost::iostreams::stream<boost::iostreams::array_source> is
-            (reinterpret_cast<const char*>(it->getValue().buf()), it->getValue().size());
-          endorseExtension.ParseFromIstream(&is);
-
-          endorseExtension >> m_endorseList;
-        }
+  for (ExtensionList::iterator it = m_extensionList.begin() ; it != m_extensionList.end(); it++) {
+    if (PROFILE_EXT_OID == it->getOid()) {
+      boost::iostreams::stream<boost::iostreams::array_source> is
+        (reinterpret_cast<const char*>(it->getValue().buf()), it->getValue().size());
+      m_profile.decode(is);
     }
+    if (ENDORSE_EXT_OID == it->getOid()) {
+      Chronos::EndorseExtensionMsg endorseExtension;
+
+      boost::iostreams::stream<boost::iostreams::array_source> is
+        (reinterpret_cast<const char*>(it->getValue().buf()), it->getValue().size());
+      endorseExtension.ParseFromIstream(&is);
+
+      endorseExtension >> m_endorseList;
+    }
+  }
 }
 
-}//chronos
+} // namespace chronos
diff --git a/src/endorse-certificate.h b/src/endorse-certificate.hpp
similarity index 61%
rename from src/endorse-certificate.h
rename to src/endorse-certificate.hpp
index 970b5b7..6a73edf 100644
--- a/src/endorse-certificate.h
+++ b/src/endorse-certificate.hpp
@@ -8,19 +8,24 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef CHRONOS_ENDORSE_CERTIFICATE_H
-#define CHRONOS_ENDORSE_CERTIFICATE_H
+#ifndef CHRONOS_ENDORSE_CERTIFICATE_HPP
+#define CHRONOS_ENDORSE_CERTIFICATE_HPP
 
-#include "profile.h"
-#include <vector>
-#include <ndn-cxx/security/identity-certificate.hpp>
+#include "profile.hpp"
 
-namespace chronos{
+namespace chronos {
 
 class EndorseCertificate : public ndn::Certificate
 {
 public:
-  struct Error : public ndn::Certificate::Error { Error(const std::string &what) : ndn::Certificate::Error(what) {} };
+  class Error : public ndn::Certificate::Error
+  {
+  public:
+    Error(const std::string& what)
+      : ndn::Certificate::Error(what)
+    {
+    }
+  };
 
   static const std::vector<std::string> DEFAULT_ENDORSE_LIST;
 
@@ -31,51 +36,61 @@
                      const std::vector<std::string>& endorseList = DEFAULT_ENDORSE_LIST);
 
   EndorseCertificate(const EndorseCertificate& endorseCertificate,
-                     const ndn::Name& signer,
+                     const Name& signer,
                      const std::vector<std::string>& endorseList = DEFAULT_ENDORSE_LIST);
 
-  EndorseCertificate(const ndn::Name& keyName,
+  EndorseCertificate(const Name& keyName,
                      const ndn::PublicKey& key,
-                     const ndn::time::system_clock::TimePoint& notBefore,
-                     const ndn::time::system_clock::TimePoint& notAfter,
-                     const ndn::Name& signer,
+                     const time::system_clock::TimePoint& notBefore,
+                     const time::system_clock::TimePoint& notAfter,
+                     const Name& signer,
                      const Profile& profile,
                      const std::vector<std::string>& endorseList = DEFAULT_ENDORSE_LIST);
 
   EndorseCertificate(const EndorseCertificate& endorseCertificate);
 
-  EndorseCertificate(const ndn::Data& data);
+  EndorseCertificate(const Data& data);
 
   virtual
   ~EndorseCertificate()
-  {}
+  {
+  }
 
-  const ndn::Name&
+  const Name&
   getSigner() const
-  { return m_signer; }
+  {
+    return m_signer;
+  }
 
   const Profile&
   getProfile() const
-  { return m_profile; }
+  {
+    return m_profile;
+  }
 
   const std::vector<std::string>&
   getEndorseList() const
-  { return m_endorseList; }
+  {
+    return m_endorseList;
+  }
 
-  const ndn::Name&
+  const Name&
   getPublicKeyName () const
-  { return m_keyName; }
+  {
+    return m_keyName;
+  }
 
 private:
   static const ndn::OID PROFILE_EXT_OID;
   static const ndn::OID ENDORSE_EXT_OID;
 
-  ndn::Name m_keyName;
-  ndn::Name m_signer; // signing key name
+  Name m_keyName;
+  Name m_signer; // signing key name
   Profile m_profile;
   std::vector<std::string> m_endorseList;
+
 };
 
-}//chronos
+} // namespace chronos
 
-#endif
+#endif // CHRONOS_ENDORSE_CERTIFICATE_HPP
diff --git a/src/endorse-combobox-delegate.cpp b/src/endorse-combobox-delegate.cpp
index 906020a..d881f18 100644
--- a/src/endorse-combobox-delegate.cpp
+++ b/src/endorse-combobox-delegate.cpp
@@ -8,7 +8,7 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "endorse-combobox-delegate.h"
+#include "endorse-combobox-delegate.hpp"
 
 #include <QComboBox>
 #include <QApplication>
@@ -17,9 +17,9 @@
 #include "logging.h"
 #endif
 
-INIT_LOGGER("EndorseComboBoxDelegate");
+namespace chronos {
 
-EndorseComboBoxDelegate::EndorseComboBoxDelegate(QObject *parent)
+EndorseComboBoxDelegate::EndorseComboBoxDelegate(QObject* parent)
  : QItemDelegate(parent)
 {
   m_items.push_back("Not Endorsed");
@@ -28,43 +28,45 @@
 
 
 QWidget*
-EndorseComboBoxDelegate::createEditor(QWidget *parent,
-                                      const QStyleOptionViewItem &/* option */,
-                                      const QModelIndex &/* index */) const
+EndorseComboBoxDelegate::createEditor(QWidget* parent,
+                                      const QStyleOptionViewItem& /* option */,
+                                      const QModelIndex& /* index */) const
 {
   QComboBox* editor = new QComboBox(parent);
-  for(unsigned int i = 0; i < m_items.size(); ++i)
-      editor->addItem(m_items[i].c_str());
+  for (unsigned int i = 0; i < m_items.size(); ++i)
+    editor->addItem(m_items[i].c_str());
   return editor;
 }
 
 void
-EndorseComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
+EndorseComboBoxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
 {
-  QComboBox *comboBox = static_cast<QComboBox*>(editor);
+  QComboBox* comboBox = static_cast<QComboBox*>(editor);
   int value = index.model()->data(index, Qt::EditRole).toUInt();
   comboBox->setCurrentIndex(value);
 }
 
 void
-EndorseComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
+EndorseComboBoxDelegate::setModelData(QWidget* editor,
+                                      QAbstractItemModel* model,
+                                      const QModelIndex& index) const
 {
-  QComboBox *comboBox = static_cast<QComboBox*>(editor);
+  QComboBox* comboBox = static_cast<QComboBox*>(editor);
   model->setData(index, comboBox->currentIndex(), Qt::EditRole);
 }
 
 void
-EndorseComboBoxDelegate::updateEditorGeometry(QWidget *editor,
-                                              const QStyleOptionViewItem &option,
-                                              const QModelIndex &/* index */) const
+EndorseComboBoxDelegate::updateEditorGeometry(QWidget* editor,
+                                              const QStyleOptionViewItem& option,
+                                              const QModelIndex& /* index */) const
 {
   editor->setGeometry(option.rect);
 }
 
 void
-EndorseComboBoxDelegate::paint(QPainter *painter,
-                               const QStyleOptionViewItem &option,
-                               const QModelIndex &index) const
+EndorseComboBoxDelegate::paint(QPainter* painter,
+                               const QStyleOptionViewItem& option,
+                               const QModelIndex& index) const
 {
   QStyleOptionViewItemV4 myOption = option;
   QString text = m_items[index.model()->data(index, Qt::EditRole).toUInt()].c_str();
@@ -74,6 +76,8 @@
   QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &myOption, painter);
 }
 
+} // namespace chronos
+
 #if WAF
 #include "endorse-combobox-delegate.moc"
 #include "endorse-combobox-delegate.cpp.moc"
diff --git a/src/endorse-combobox-delegate.h b/src/endorse-combobox-delegate.h
deleted file mode 100644
index 424a8f7..0000000
--- a/src/endorse-combobox-delegate.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef ENDORSE_COMBOBOX_DELEGATE_H
-#define ENDORSE_COMBOBOX_DELEGATE_H
-
-#include <QItemDelegate>
-#include <string>
-#include <vector>
-
-class EndorseComboBoxDelegate : public QItemDelegate
-{
-  Q_OBJECT
-public:
-  EndorseComboBoxDelegate(QObject *parent = 0);
-
-  // virtual
-  // ~ComboBoxDelegate() {}
-
-  QWidget*
-  createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
-  void
-  setEditorData(QWidget *editor, const QModelIndex &index) const;
-
-  void
-  setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
-
-  void
-  updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
-  void
-  paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
-private:
-  std::vector<std::string> m_items;
-
-};
-
-#endif
diff --git a/src/endorse-combobox-delegate.hpp b/src/endorse-combobox-delegate.hpp
new file mode 100644
index 0000000..92e26d1
--- /dev/null
+++ b/src/endorse-combobox-delegate.hpp
@@ -0,0 +1,53 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_ENDORSE_COMBOBOX_DELEGATE_HPP
+#define CHRONOS_ENDORSE_COMBOBOX_DELEGATE_HPP
+
+#include <QItemDelegate>
+#include <string>
+#include <vector>
+
+namespace chronos {
+
+class EndorseComboBoxDelegate : public QItemDelegate
+{
+  Q_OBJECT
+public:
+  EndorseComboBoxDelegate(QObject* parent = 0);
+
+  // virtual
+  // ~ComboBoxDelegate() {}
+
+  QWidget*
+  createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+
+  void
+  setEditorData(QWidget* editor, const QModelIndex& index) const;
+
+  void
+  setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const;
+
+  void
+  updateEditorGeometry(QWidget* editor,
+                       const QStyleOptionViewItem& option,
+                       const QModelIndex& index) const;
+
+  void
+  paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
+
+private:
+  std::vector<std::string> m_items;
+
+};
+
+} // namespace chronos
+
+#endif // CHRONOS_ENDORSE_COMBOBOX_DELEGATE_HPP
diff --git a/src/endorse-info.proto b/src/endorse-info.proto
index a0612d0..41aa6f2 100644
--- a/src/endorse-info.proto
+++ b/src/endorse-info.proto
@@ -1,4 +1,4 @@
-package chronos;
+package Chronos;
 
 message EndorseInfo
 {
diff --git a/src/invitation-dialog.cpp b/src/invitation-dialog.cpp
index 17977f2..a847b93 100644
--- a/src/invitation-dialog.cpp
+++ b/src/invitation-dialog.cpp
@@ -8,12 +8,12 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "invitation-dialog.h"
+#include "invitation-dialog.hpp"
 #include "ui_invitation-dialog.h"
 
-using namespace ndn;
+namespace chronos {
 
-InvitationDialog::InvitationDialog(QWidget *parent)
+InvitationDialog::InvitationDialog(QWidget* parent)
   : QDialog(parent)
   , ui(new Ui::InvitationDialog)
 {
@@ -61,6 +61,8 @@
   m_invitationInterest.clear();
 }
 
+} // namespace chronos
+
 #if WAF
 #include "invitation-dialog.moc"
 #include "invitation-dialog.cpp.moc"
diff --git a/src/invitation-dialog.h b/src/invitation-dialog.hpp
similarity index 75%
rename from src/invitation-dialog.h
rename to src/invitation-dialog.hpp
index e6a9e97..0dab90f 100644
--- a/src/invitation-dialog.h
+++ b/src/invitation-dialog.hpp
@@ -8,25 +8,29 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef INVITATION_DIALOG_H
-#define INVITATION_DIALOG_H
+#ifndef CHRONOS_INVITATION_DIALOG_HPP
+#define CHRONOS_INVITATION_DIALOG_HPP
 
 #include <QDialog>
 
 #ifndef Q_MOC_RUN
-#include <ndn-cxx/name.hpp>
+#include "common.hpp"
 #endif
 
 namespace Ui {
 class InvitationDialog;
 }
 
+namespace chronos{
+
 class InvitationDialog : public QDialog
 {
     Q_OBJECT
 
 public:
-  explicit InvitationDialog(QWidget *parent = 0);
+  explicit
+  InvitationDialog(QWidget* parent = 0);
+
   ~InvitationDialog();
 
   void
@@ -47,8 +51,10 @@
 
 
 private:
-  Ui::InvitationDialog *ui;
+  Ui::InvitationDialog* ui;
   ndn::Name m_invitationInterest;
 };
 
-#endif // INVITATION_DIALOG_H
+} // namespace chronos
+
+#endif // CHRONOS_INVITATION_DIALOG_HPP
diff --git a/src/invitation.cpp b/src/invitation.cpp
index ae39761..97b3855 100644
--- a/src/invitation.cpp
+++ b/src/invitation.cpp
@@ -8,20 +8,18 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "invitation.h"
+#include "invitation.hpp"
 
-#include <ndn-cxx/security/identity-certificate.hpp>
 #include <ndn-cxx/security/signature-sha256-with-rsa.hpp>
 
 #include "logging.h"
 
-using namespace ndn;
-
-INIT_LOGGER("Invitation");
-
-
 namespace chronos{
 
+using std::string;
+
+using ndn::IdentityCertificate;
+
 const size_t  Invitation::NAME_SIZE_MIN         = 7;
 const ssize_t Invitation::SIGNATURE             = -1;
 const ssize_t Invitation::KEY_LOCATOR           = -2;
@@ -36,22 +34,22 @@
 {
   size_t nameSize = interestName.size();
 
-  if(nameSize < NAME_SIZE_MIN)
+  if (nameSize < NAME_SIZE_MIN)
     throw Error("Wrong Invitation Name: Wrong length");
 
-  if(interestName.get(CHRONOCHAT_INVITATION).toEscapedString() != "CHRONOCHAT-INVITATION")
+  if (interestName.get(CHRONOCHAT_INVITATION).toUri() != "CHRONOCHAT-INVITATION")
     throw Error("Wrong Invitation Name: Wrong application tags");
 
   m_interestName = interestName.getPrefix(KEY_LOCATOR);
   m_timestamp = interestName.get(TIMESTAMP).toNumber();
   m_inviterCertificate.wireDecode(interestName.get(INVITER_CERT).blockFromValue());
   m_inviterRoutingPrefix.wireDecode(interestName.get(INVITER_PREFIX).blockFromValue());
-  m_chatroom = interestName.get(CHATROOM).toEscapedString();
+  m_chatroom = interestName.get(CHATROOM).toUri();
   m_inviteeNameSpace = interestName.getPrefix(CHRONOCHAT_INVITATION);
 }
 
 Invitation::Invitation(const Name& inviteeNameSpace,
-                       const std::string& chatroom,
+                       const string& chatroom,
                        const Name& inviterRoutingPrefix,
                        const IdentityCertificate& inviterCertificate)
   : m_inviteeNameSpace(inviteeNameSpace)
@@ -78,4 +76,4 @@
 {
 }
 
-}//chronos
+} // namespace chronos
diff --git a/src/invitation.h b/src/invitation.hpp
similarity index 62%
rename from src/invitation.h
rename to src/invitation.hpp
index 6a53019..c724661 100644
--- a/src/invitation.h
+++ b/src/invitation.hpp
@@ -8,19 +8,19 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef CHRONOS_INVITATION_H
-#define CHRONOS_INVITATION_H
+#ifndef CHRONOS_INVITATION_HPP
+#define CHRONOS_INVITATION_HPP
 
 
-#include <ndn-cxx/name.hpp>
-#include <ndn-cxx/signature.hpp>
+#include "common.hpp"
+
 #include <ndn-cxx/security/identity-certificate.hpp>
 
-namespace chronos{
+namespace chronos {
 
 class Invitation
 {
-  public:
+public:
   /*
    *  /[invitee_namespace]
    *  /CHRONOCHAT-INVITATION
@@ -40,56 +40,79 @@
   static const ssize_t CHATROOM;
   static const ssize_t CHRONOCHAT_INVITATION;
 
-  struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };
+  class Error : public std::runtime_error
+  {
+  public:
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
 
-  Invitation() {}
+  Invitation()
+  {
+  }
 
-  Invitation(const ndn::Name& interestName);
+  Invitation(const Name& interestName);
 
-  Invitation(const ndn::Name& inviteeNameSpace,
+  Invitation(const Name& inviteeNameSpace,
              const std::string& chatroom,
-             const ndn::Name& inviterRoutingPrefix,
+             const Name& inviterRoutingPrefix,
              const ndn::IdentityCertificate& inviterCertificate);
 
   Invitation(const Invitation& invitation);
 
   virtual
-  ~Invitation() {};
+  ~Invitation()
+  {
+  }
 
-  const ndn::Name&
+  const Name&
   getInviteeNameSpace() const
-  { return m_inviteeNameSpace; }
+  {
+    return m_inviteeNameSpace;
+  }
 
   const std::string&
   getChatroom() const
-  { return m_chatroom; }
+  {
+    return m_chatroom;
+  }
 
-  const ndn::Name&
+  const Name&
   getInviterRoutingPrefix() const
-  { return m_inviterRoutingPrefix; }
+  {
+    return m_inviterRoutingPrefix;
+  }
 
   const ndn::IdentityCertificate&
   getInviterCertificate() const
-  { return m_inviterCertificate; }
+  {
+    return m_inviterCertificate;
+  }
 
   const uint64_t
   getTimestamp() const
-  { return m_timestamp; }
+  {
+    return m_timestamp;
+  }
 
-  const ndn::Name&
+  const Name&
   getUnsignedInterestName() const
-  { return m_interestName; }
+  {
+    return m_interestName;
+  }
 
 private:
-  ndn::Name m_interestName;
+  Name m_interestName;
 
-  ndn::Name m_inviteeNameSpace;
+  Name m_inviteeNameSpace;
   std::string m_chatroom;
-  ndn::Name m_inviterRoutingPrefix;
+  Name m_inviterRoutingPrefix;
   ndn::IdentityCertificate m_inviterCertificate;
   uint64_t m_timestamp;
 };
 
-}//chronos
+} // namespace chronos
 
-#endif
+#endif // CHRONOS_INVITATION_HPP
diff --git a/src/invite-list-dialog.cpp b/src/invite-list-dialog.cpp
index 6f62c5a..ccac3ed 100644
--- a/src/invite-list-dialog.cpp
+++ b/src/invite-list-dialog.cpp
@@ -8,10 +8,12 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "invite-list-dialog.h"
+#include "invite-list-dialog.hpp"
 #include "ui_invite-list-dialog.h"
 
-InviteListDialog::InviteListDialog(QWidget *parent)
+namespace chronos {
+
+InviteListDialog::InviteListDialog(QWidget* parent)
   :QDialog(parent)
   , ui(new Ui::InviteListDialog)
   , m_contactListModel(new QStringListModel)
@@ -46,14 +48,13 @@
   QModelIndexList selected = ui->contactListView->selectionModel()->selectedIndexes();
   QString alias = m_contactListModel->data(selected.first(), Qt::DisplayRole).toString();
 
-  for(int i = 0; i < m_contactAliasList.size(); i++) // TODO:: could be optimized without using for loop.
-    {
-      if(alias == m_contactAliasList[i])
-        {
-          emit sendInvitation(m_contactIdList[i]);
-          break;
-        }
+  // TODO:: could be optimized without using for loop.
+  for (int i = 0; i < m_contactAliasList.size(); i++) {
+    if (alias == m_contactAliasList[i]) {
+      emit sendInvitation(m_contactIdList[i]);
+      break;
     }
+  }
 
   this->close();
 }
@@ -77,6 +78,8 @@
   m_contactIdList = idList;
 }
 
+} // namespace chronos
+
 #if WAF
 #include "invite-list-dialog.moc"
 #include "invite-list-dialog.cpp.moc"
diff --git a/src/invite-list-dialog.h b/src/invite-list-dialog.hpp
similarity index 79%
rename from src/invite-list-dialog.h
rename to src/invite-list-dialog.hpp
index bf62ec0..848e07f 100644
--- a/src/invite-list-dialog.h
+++ b/src/invite-list-dialog.hpp
@@ -8,8 +8,8 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef INVITE_LIST_DIALOG_H
-#define INVITE_LIST_DIALOG_H
+#ifndef CHRONOS_INVITE_LIST_DIALOG_HPP
+#define CHRONOS_INVITE_LIST_DIALOG_HPP
 
 #include <QDialog>
 #include <QStringListModel>
@@ -21,13 +21,15 @@
 class InviteListDialog;
 }
 
+namespace chronos {
+
 class InviteListDialog : public QDialog
 {
   Q_OBJECT
 
 public:
   explicit
-  InviteListDialog(QWidget *parent = 0);
+  InviteListDialog(QWidget* parent = 0);
 
   ~InviteListDialog();
 
@@ -53,10 +55,12 @@
   onCancelClicked();
 
 private:
-  Ui::InviteListDialog *ui;
+  Ui::InviteListDialog* ui;
   QStringListModel* m_contactListModel;
   QStringList m_contactAliasList;
   QStringList m_contactIdList;
 };
 
-#endif // INVITE_LIST_DIALOG_H
+} // namespace chronos
+
+#endif // CHRONOS_INVITE_LIST_DIALOG_HPP
diff --git a/src/main.cpp b/src/main.cpp
index 6ad597b..afa3665 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -11,29 +11,26 @@
 #include <QApplication>
 // #include <QSystemTrayIcon>
 
-#include "controller.h"
+#include "controller.hpp"
 #include "logging.h"
 #include <ndn-cxx/face.hpp>
 #include <boost/thread/thread.hpp>
 
-INIT_LOGGER("MAIN");
-
-using namespace ndn;
-using ndn::shared_ptr;
-
 class NewApp : public QApplication
 {
 public:
-  NewApp(int & argc, char ** argv)
+  NewApp(int& argc, char** argv)
     : QApplication(argc, argv)
-  { }
+  {
+  }
 
-  bool notify(QObject * receiver, QEvent * event)
+  bool
+  notify(QObject* receiver, QEvent* event)
   {
     try {
         return QApplication::notify(receiver, event);
     }
-    catch(std::exception& e){
+    catch (std::exception& e) {
       std::cerr << "Exception thrown:" << e.what() << std::endl;
       return false;
     }
@@ -41,11 +38,13 @@
   }
 };
 
-void runIO(shared_ptr<boost::asio::io_service> ioService)
+void
+runIO(boost::asio::io_service& ioService)
 {
-  try{
-    ioService->run();
-  }catch(std::runtime_error& e){
+  try {
+    ioService.run();
+  }
+  catch (std::runtime_error& e) {
     std::cerr << e.what() << std::endl;
   }
 }
@@ -54,12 +53,12 @@
 {
   NewApp app(argc, argv);
 
-  shared_ptr<Face> face = make_shared<Face>();
+  ndn::shared_ptr<ndn::Face> face = ndn::make_shared<ndn::Face>();
   chronos::Controller controller(face);
 
   app.setQuitOnLastWindowClosed(false);
 
-  boost::thread (runIO, face->ioService());
+  boost::thread(runIO, boost::ref(face->getIoService()));
 
   return app.exec();
 }
diff --git a/src/profile-editor.cpp b/src/profile-editor.cpp
index 9488f47..4e91a56 100644
--- a/src/profile-editor.cpp
+++ b/src/profile-editor.cpp
@@ -8,7 +8,7 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "profile-editor.h"
+#include "profile-editor.hpp"
 #include "ui_profile-editor.h"
 #include <QtSql/QSqlRecord>
 #include <QtSql/QSqlField>
@@ -18,7 +18,9 @@
 #include "logging.h"
 #endif
 
-INIT_LOGGER("ProfileEditor")
+// INIT_LOGGER("ProfileEditor")
+
+namespace chronos {
 
 ProfileEditor::ProfileEditor(QWidget *parent)
   : QDialog(parent)
@@ -44,12 +46,11 @@
 void
 ProfileEditor::onCloseDBModule()
 {
-  _LOG_DEBUG("close db module");
-  if(m_tableModel)
-    {
-      delete m_tableModel;
-      _LOG_DEBUG("tableModel closed");
-    }
+  // _LOG_DEBUG("close db module");
+  if (m_tableModel) {
+    delete m_tableModel;
+    // _LOG_DEBUG("tableModel closed");
+  }
 }
 
 void
@@ -85,8 +86,7 @@
   QItemSelectionModel* selectionModel = ui->profileTable->selectionModel();
   QModelIndexList indexList = selectionModel->selectedIndexes();
 
-  int i = indexList.size() - 1;
-  for(; i >= 0; i--)
+  for (int i = indexList.size() - 1; i >= 0; i--)
     m_tableModel->removeRow(indexList[i].row());
 
   m_tableModel->submitAll();
@@ -100,6 +100,8 @@
   this->hide();
 }
 
+} // namespace chronos
+
 #if WAF
 #include "profile-editor.moc"
 #include "profile-editor.cpp.moc"
diff --git a/src/profile-editor.h b/src/profile-editor.hpp
similarity index 77%
rename from src/profile-editor.h
rename to src/profile-editor.hpp
index 8ec9713..1dc5f5e 100644
--- a/src/profile-editor.h
+++ b/src/profile-editor.hpp
@@ -8,8 +8,8 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef PROFILE_EDITOR_H
-#define PROFILE_EDITOR_H
+#ifndef CHRONOS_PROFILE_EDITOR_HPP
+#define CHRONOS_PROFILE_EDITOR_HPP
 
 #include <QDialog>
 #include <QtSql/QSqlTableModel>
@@ -21,12 +21,14 @@
 class ProfileEditor;
 }
 
+namespace chronos {
+
 class ProfileEditor : public QDialog
 {
     Q_OBJECT
 
 public:
-  explicit ProfileEditor(QWidget *parent = 0);
+  explicit ProfileEditor(QWidget* parent = 0);
 
   ~ProfileEditor();
 
@@ -52,9 +54,11 @@
   updateProfile();
 
 private:
-  Ui::ProfileEditor *ui;
+  Ui::ProfileEditor* ui;
   QSqlTableModel* m_tableModel;
   QString m_identity;
 };
 
-#endif // PROFILE_EDITOR_H
+} // namespace chronos
+
+#endif // CHRONOS_PROFILE_EDITOR_HPP
diff --git a/src/profile.cpp b/src/profile.cpp
index e6044fa..cd69849 100644
--- a/src/profile.cpp
+++ b/src/profile.cpp
@@ -8,15 +8,18 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "profile.h"
+#include "profile.hpp"
 #include "logging.h"
 
-using namespace ndn;
-
-INIT_LOGGER("Profile");
-
 namespace chronos{
 
+using std::vector;
+using std::string;
+using std::map;
+
+using ndn::IdentityCertificate;
+using ndn::CertificateSubjectDescription;
+
 const std::string Profile::OID_NAME("2.5.4.41");
 const std::string Profile::OID_ORG("2.5.4.11");
 const std::string Profile::OID_GROUP("2.5.4.1");
@@ -28,29 +31,30 @@
 {
   Name keyName = IdentityCertificate::certificateNameToPublicKeyName(identityCertificate.getName());
 
-  m_entries[std::string("IDENTITY")] = keyName.getPrefix(-1).toUri();
+  m_entries[string("IDENTITY")] = keyName.getPrefix(-1).toUri();
 
-  const std::vector<CertificateSubjectDescription>& subList = identityCertificate.getSubjectDescriptionList();
-  std::vector<CertificateSubjectDescription>::const_iterator it = subList.begin();
-  for(; it != subList.end(); it++)
-    {
-      const std::string oidStr = it->getOidString();
-      std::string valueStr = it->getValue();
-      if(oidStr == OID_NAME)
-        m_entries["name"] = valueStr;
-      else if(oidStr == OID_ORG)
-        m_entries["institution"] = valueStr;
-      else if(oidStr == OID_GROUP)
-        m_entries["group"] = valueStr;
-      else if(oidStr == OID_HOMEPAGE)
-        m_entries["homepage"] = valueStr;
-      else if(oidStr == OID_ADVISOR)
-        m_entries["advisor"] = valueStr;
-      else if(oidStr == OID_EMAIL)
-        m_entries["email"] = valueStr;
-      else
-        m_entries[oidStr] = valueStr;
-    }
+  const vector<CertificateSubjectDescription>& subList =
+    identityCertificate.getSubjectDescriptionList();
+
+  for (vector<CertificateSubjectDescription>::const_iterator it = subList.begin();
+       it != subList.end(); it++) {
+    const string oidStr = it->getOidString();
+    string valueStr = it->getValue();
+    if (oidStr == OID_NAME)
+      m_entries["name"] = valueStr;
+    else if (oidStr == OID_ORG)
+      m_entries["institution"] = valueStr;
+    else if (oidStr == OID_GROUP)
+      m_entries["group"] = valueStr;
+    else if (oidStr == OID_HOMEPAGE)
+      m_entries["homepage"] = valueStr;
+    else if (oidStr == OID_ADVISOR)
+      m_entries["advisor"] = valueStr;
+    else if (oidStr == OID_EMAIL)
+      m_entries["email"] = valueStr;
+    else
+      m_entries[oidStr] = valueStr;
+  }
 }
 
 Profile::Profile(const Name& identityName)
@@ -59,8 +63,8 @@
 }
 
 Profile::Profile(const Name& identityName,
-                 const std::string& name,
-                 const std::string& institution)
+                 const string& name,
+                 const string& institution)
 {
   m_entries["IDENTITY"] = identityName.toUri();
   m_entries["name"] = name;
@@ -69,7 +73,8 @@
 
 Profile::Profile(const Profile& profile)
   : m_entries(profile.m_entries)
-{}
+{
+}
 
 void
 Profile::encode(std::ostream& os) const
@@ -87,29 +92,50 @@
   profileMsg >> (*this);
 }
 
-Chronos::ProfileMsg&
-operator << (Chronos::ProfileMsg& profileMsg, const Profile& profile)
+bool
+Profile::operator==(const Profile& profile) const
 {
-  std::map<std::string, std::string>::const_iterator it = profile.begin();
-  for(; it != profile.end(); it++)
-    {
-      Chronos::ProfileMsg::ProfileEntry* profileEntry = profileMsg.add_entry();
-      profileEntry->set_oid(it->first);
-      profileEntry->set_data(it->second);
-    }
+  if (m_entries.size() != profile.m_entries.size())
+    return false;
+
+  for(map<string, string>::const_iterator it = m_entries.begin(); it != m_entries.end(); it++) {
+    map<string, string>::const_iterator found = profile.m_entries.find(it->first);
+    if (found == profile.m_entries.end())
+      return false;
+    if (found->second != it->second)
+      return false;
+  }
+
+  return true;
+}
+
+bool
+Profile::operator!=(const Profile& profile) const
+{
+  return !(*this == profile);
+}
+
+Chronos::ProfileMsg&
+operator<<(Chronos::ProfileMsg& profileMsg, const Profile& profile)
+{
+;
+  for (map<string, string>::const_iterator it = profile.begin(); it != profile.end(); it++) {
+    Chronos::ProfileMsg::ProfileEntry* profileEntry = profileMsg.add_entry();
+    profileEntry->set_oid(it->first);
+    profileEntry->set_data(it->second);
+  }
   return profileMsg;
 }
 
 Chronos::ProfileMsg&
-operator >> (Chronos::ProfileMsg& profileMsg, Profile& profile)
+operator>>(Chronos::ProfileMsg& profileMsg, Profile& profile)
 {
-  for(int i = 0; i < profileMsg.entry_size(); i++)
-    {
-      const Chronos::ProfileMsg::ProfileEntry& profileEntry = profileMsg.entry(i);
-      profile[profileEntry.oid()] = profileEntry.data();
-    }
+  for (int i = 0; i < profileMsg.entry_size(); i++) {
+    const Chronos::ProfileMsg::ProfileEntry& profileEntry = profileMsg.entry(i);
+    profile[profileEntry.oid()] = profileEntry.data();
+  }
 
   return profileMsg;
 }
 
-}//chronos
+} // namespace chronos
diff --git a/src/profile.h b/src/profile.h
deleted file mode 100644
index 17b8d6c..0000000
--- a/src/profile.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef CHRONOS_PROFILE_H
-#define CHRONOS_PROFILE_H
-
-#include "config.h"
-#include <ndn-cxx/name.hpp>
-#include <ndn-cxx/security/identity-certificate.hpp>
-#include <map>
-#include <string>
-#include "profile.pb.h"
-
-namespace chronos{
-
-class Profile
-{
-public:
-  typedef std::map<std::string, std::string>::iterator iterator;
-  typedef std::map<std::string, std::string>::const_iterator const_iterator;
-
-  Profile() {}
-
-  Profile(const ndn::IdentityCertificate& identityCertificate);
-
-  Profile(const ndn::Name& identityName);
-
-  Profile(const ndn::Name& identityName,
-          const std::string& name,
-          const std::string& institution);
-
-  Profile(const Profile& profile);
-
-  ~Profile() {}
-
-  std::string&
-  operator [] (const std::string& profileKey)
-  { return m_entries[profileKey]; }
-
-  std::string
-  get (const std::string& profileKey) const
-  {
-    std::map<std::string, std::string>::const_iterator it = m_entries.find(profileKey);
-    if(it != m_entries.end())
-      return it->second;
-    else
-      return std::string();
-  }
-
-  inline Profile::iterator
-  begin()
-  { return m_entries.begin(); }
-
-  inline Profile::const_iterator
-  begin() const
-  { return m_entries.begin(); }
-
-  inline Profile::iterator
-  end()
-  { return m_entries.end(); }
-
-  inline Profile::const_iterator
-  end() const
-  { return m_entries.end(); }
-
-  void
-  encode(std::ostream& os) const;
-
-  void
-  decode(std::istream& is);
-
-  ndn::Name
-  getIdentityName() const
-  { return ndn::Name(m_entries.at("IDENTITY")); }
-
-  inline bool
-  operator == (const Profile& profile) const;
-
-  inline bool
-  operator != (const Profile& profile) const;
-
-private:
-  static const std::string OID_NAME;
-  static const std::string OID_ORG;
-  static const std::string OID_GROUP;
-  static const std::string OID_HOMEPAGE;
-  static const std::string OID_ADVISOR;
-  static const std::string OID_EMAIL;
-
-  std::map<std::string, std::string> m_entries;
-};
-
-Chronos::ProfileMsg&
-operator << (Chronos::ProfileMsg& msg, const Profile& profile);
-
-Chronos::ProfileMsg&
-operator >> (Chronos::ProfileMsg& msg, Profile& profile);
-
-inline bool
-Profile::operator == (const Profile& profile) const
-{
-  if(m_entries.size() != profile.m_entries.size())
-    return false;
-
-  std::map<std::string, std::string>::const_iterator it = m_entries.begin();
-  for(; it != m_entries.end(); it++)
-    {
-      std::map<std::string, std::string>::const_iterator found = profile.m_entries.find(it->first);
-      if(found == profile.m_entries.end())
-        return false;
-      if(found->second != it->second)
-        return false;
-    }
-
-  return true;
-}
-
-inline bool
-Profile::operator != (const Profile& profile) const
-{
-  return !(*this == profile);
-}
-
-}//chronos
-
-#endif
diff --git a/src/profile.hpp b/src/profile.hpp
new file mode 100644
index 0000000..2f4b2cf
--- /dev/null
+++ b/src/profile.hpp
@@ -0,0 +1,122 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_PROFILE_HPP
+#define CHRONOS_PROFILE_HPP
+
+#include "common.hpp"
+
+#include <ndn-cxx/security/identity-certificate.hpp>
+#include "profile.pb.h"
+
+namespace chronos {
+
+class Profile
+{
+public:
+  typedef std::map<std::string, std::string>::iterator iterator;
+  typedef std::map<std::string, std::string>::const_iterator const_iterator;
+
+  Profile()
+  {
+  }
+
+  Profile(const ndn::IdentityCertificate& identityCertificate);
+
+  Profile(const Name& identityName);
+
+  Profile(const Name& identityName,
+          const std::string& name,
+          const std::string& institution);
+
+  Profile(const Profile& profile);
+
+  ~Profile()
+  {
+  }
+
+  std::string&
+  operator[](const std::string& profileKey)
+  {
+    return m_entries[profileKey];
+  }
+
+  std::string
+  get(const std::string& profileKey) const
+  {
+    std::map<std::string, std::string>::const_iterator it = m_entries.find(profileKey);
+    if (it != m_entries.end())
+      return it->second;
+    else
+      return std::string();
+  }
+
+  Profile::iterator
+  begin()
+  {
+    return m_entries.begin();
+  }
+
+  Profile::const_iterator
+  begin() const
+  {
+    return m_entries.begin();
+  }
+
+  Profile::iterator
+  end()
+  {
+    return m_entries.end();
+  }
+
+  Profile::const_iterator
+  end() const
+  {
+    return m_entries.end();
+  }
+
+  void
+  encode(std::ostream& os) const;
+
+  void
+  decode(std::istream& is);
+
+  Name
+  getIdentityName() const
+  {
+    return ndn::Name(m_entries.at("IDENTITY"));
+  }
+
+  bool
+  operator==(const Profile& profile) const;
+
+  bool
+  operator!=(const Profile& profile) const;
+
+private:
+  static const std::string OID_NAME;
+  static const std::string OID_ORG;
+  static const std::string OID_GROUP;
+  static const std::string OID_HOMEPAGE;
+  static const std::string OID_ADVISOR;
+  static const std::string OID_EMAIL;
+
+  std::map<std::string, std::string> m_entries;
+};
+
+Chronos::ProfileMsg&
+operator<<(Chronos::ProfileMsg& msg, const Profile& profile);
+
+Chronos::ProfileMsg&
+operator>>(Chronos::ProfileMsg& msg, Profile& profile);
+
+} // namespace chronos
+
+#endif // CHRONOS_PROFILE_HPP
diff --git a/src/set-alias-dialog.cpp b/src/set-alias-dialog.cpp
index ef21ab7..599749c 100644
--- a/src/set-alias-dialog.cpp
+++ b/src/set-alias-dialog.cpp
@@ -8,11 +8,12 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "set-alias-dialog.h"
+#include "set-alias-dialog.hpp"
 #include "ui_set-alias-dialog.h"
 
+namespace chronos {
 
-SetAliasDialog::SetAliasDialog(QWidget *parent)
+SetAliasDialog::SetAliasDialog(QWidget* parent)
   : QDialog(parent)
   , ui(new Ui::SetAliasDialog)
 {
@@ -51,6 +52,7 @@
   ui->aliasInput->setText(alias);
 }
 
+} // namespace chronos
 
 #if WAF
 #include "set-alias-dialog.moc"
diff --git a/src/set-alias-dialog.h b/src/set-alias-dialog.hpp
similarity index 76%
rename from src/set-alias-dialog.h
rename to src/set-alias-dialog.hpp
index c04ea55..dc43de6 100644
--- a/src/set-alias-dialog.h
+++ b/src/set-alias-dialog.hpp
@@ -8,8 +8,8 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef SETALIASDIALOG_H
-#define SETALIASDIALOG_H
+#ifndef CHRONOS_SET_ALIAS_DIALOG_HPP
+#define CHRONOS_SET_ALIAS_DIALOG_HPP
 
 #include <QDialog>
 
@@ -21,13 +21,15 @@
 class SetAliasDialog;
 }
 
+namespace chronos {
+
 class SetAliasDialog : public QDialog
 {
   Q_OBJECT
 
 public:
   explicit
-  SetAliasDialog(QWidget *parent = 0);
+  SetAliasDialog(QWidget* parent = 0);
 
   ~SetAliasDialog();
 
@@ -46,8 +48,10 @@
   onCancelClicked();
 
 private:
-  Ui::SetAliasDialog *ui;
+  Ui::SetAliasDialog* ui;
   QString m_targetIdentity;
 };
 
-#endif // SETALIASDIALOG_H
+} // namespace chronos
+
+#endif // CHRONOS_SET_ALIAS_DIALOG_HPP
diff --git a/src/setting-dialog.cpp b/src/setting-dialog.cpp
index c81bfdd..59c6b73 100644
--- a/src/setting-dialog.cpp
+++ b/src/setting-dialog.cpp
@@ -8,10 +8,12 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "setting-dialog.h"
+#include "setting-dialog.hpp"
 #include "ui_setting-dialog.h"
 
-SettingDialog::SettingDialog(QWidget *parent)
+namespace chronos {
+
+SettingDialog::SettingDialog(QWidget* parent)
   : QDialog(parent)
   , ui(new Ui::SettingDialog)
 {
@@ -68,6 +70,7 @@
   this->close();
 }
 
+} // namespace chronos
 
 #if WAF
 #include "setting-dialog.moc"
diff --git a/src/setting-dialog.h b/src/setting-dialog.hpp
similarity index 78%
rename from src/setting-dialog.h
rename to src/setting-dialog.hpp
index fc61fb4..443b87d 100644
--- a/src/setting-dialog.h
+++ b/src/setting-dialog.hpp
@@ -8,8 +8,8 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef SETTING_DIALOG_H
-#define SETTING_DIALOG_H
+#ifndef CHRONOS_SETTING_DIALOG_HPP
+#define CHRONOS_SETTING_DIALOG_HPP
 
 #include <QDialog>
 
@@ -20,13 +20,15 @@
 class SettingDialog;
 }
 
+namespace chronos {
+
 class SettingDialog : public QDialog
 {
   Q_OBJECT
 
 public:
   explicit
-  SettingDialog(QWidget *parent = 0);
+  SettingDialog(QWidget* parent = 0);
 
   ~SettingDialog();
 
@@ -52,9 +54,11 @@
   onCancelClicked();
 
 private:
-  Ui::SettingDialog *ui;
+  Ui::SettingDialog* ui;
   QString m_identity;
   QString m_nick;
 };
 
-#endif // SETTING_DIALOG_H
+} // namespace chronos
+
+#endif // CHRONOS_SETTING_DIALOG_HPP
diff --git a/src/start-chat-dialog.cpp b/src/start-chat-dialog.cpp
index f79e4a2..8aa7965 100644
--- a/src/start-chat-dialog.cpp
+++ b/src/start-chat-dialog.cpp
@@ -8,9 +8,11 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "start-chat-dialog.h"
+#include "start-chat-dialog.hpp"
 #include "ui_start-chat-dialog.h"
 
+namespace chronos {
+
 StartChatDialog::StartChatDialog(QWidget *parent)
   : QDialog(parent)
   , ui(new Ui::StartChatDialog)
@@ -49,6 +51,8 @@
   this->close();
 }
 
+} // namespace chronos
+
 #if WAF
 #include "start-chat-dialog.moc"
 #include "start-chat-dialog.cpp.moc"
diff --git a/src/start-chat-dialog.h b/src/start-chat-dialog.hpp
similarity index 73%
rename from src/start-chat-dialog.h
rename to src/start-chat-dialog.hpp
index 771c993..be7eafe 100644
--- a/src/start-chat-dialog.h
+++ b/src/start-chat-dialog.hpp
@@ -8,8 +8,8 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef START_CHAT_DIALOG_H
-#define START_CHAT_DIALOG_H
+#ifndef CHRONOS_START_CHAT_DIALOG_HPP
+#define CHRONOS_START_CHAT_DIALOG_HPP
 
 #include <QDialog>
 
@@ -21,12 +21,14 @@
 class StartChatDialog;
 }
 
+namespace chronos {
+
 class StartChatDialog : public QDialog
 {
   Q_OBJECT
 
 public:
-  explicit StartChatDialog(QWidget *parent = 0);
+  explicit StartChatDialog(QWidget* parent = 0);
 
   ~StartChatDialog();
 
@@ -45,7 +47,9 @@
   onCancelClicked();
 
 private:
-  Ui::StartChatDialog *ui;
+  Ui::StartChatDialog* ui;
 };
 
-#endif // START_CHAT_DIALOG_H
+} // namespace chronos
+
+#endif // CHRONOS_START_CHAT_DIALOG_HPP
diff --git a/src/tree-layout.cpp b/src/tree-layout.cpp
index 7fba509..d2c4d2c 100644
--- a/src/tree-layout.cpp
+++ b/src/tree-layout.cpp
@@ -10,23 +10,25 @@
  *         Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "tree-layout.h"
-
+#include "tree-layout.hpp"
 #include <iostream>
 
+namespace chronos {
+
+using std::vector;
+using std::map;
+
 void
-OneLevelTreeLayout::setOneLevelLayout(std::vector<Coordinate> &childNodesCo)
+OneLevelTreeLayout::setOneLevelLayout(vector<Coordinate>& childNodesCo)
 {
   if (childNodesCo.empty())
-  {
     return;
-  }
+
   double y = getLevelDistance();
   double sd = getSiblingDistance();
   int n = childNodesCo.size();
   double x = - (n - 1) * sd / 2;
-  for (int i = 0; i < n; i++)
-  {
+  for (int i = 0; i < n; i++) {
     childNodesCo[i].x = x;
     childNodesCo[i].y = y;
     x += sd;
@@ -36,36 +38,30 @@
 void
 MultipleLevelTreeLayout::setMultipleLevelTreeLayout(TrustTreeNodeList& nodeList)
 {
-  if(nodeList.empty())
+  if (nodeList.empty())
     return;
 
   double ld = getLevelDistance();
   double sd = getSiblingDistance();
 
-  std::map<int, double> layerSpan;
+  map<int, double> layerSpan;
 
-  TrustTreeNodeList::iterator it  = nodeList.begin();
-  TrustTreeNodeList::iterator end = nodeList.end();
-  for(; it != end; it++)
-    {
-      int layer = (*it)->level();
-      (*it)->y = layer * ld;
-      (*it)->x = layerSpan[layer];
-      layerSpan[layer] += sd;
-    }
+  for (TrustTreeNodeList::iterator it = nodeList.begin(); it != nodeList.end(); it++) {
+    int layer = (*it)->level();
+    (*it)->y = layer * ld;
+    (*it)->x = layerSpan[layer];
+    layerSpan[layer] += sd;
+  }
 
-  std::map<int, double>::iterator layerIt  = layerSpan.begin();
-  std::map<int, double>::iterator layerEnd = layerSpan.end();
-  for(; layerIt != layerEnd; layerIt++)
-    {
-      double shift = (layerIt->second - sd) / 2;
-      layerIt->second = shift;
-    }
+  for (map<int, double>::iterator layerIt = layerSpan.begin();
+       layerIt != layerSpan.end(); layerIt++) {
+    double shift = (layerIt->second - sd) / 2;
+    layerIt->second = shift;
+  }
 
-  it  = nodeList.begin();
-  end = nodeList.end();
-  for(; it != end; it++)
-    {
-      (*it)->x -= layerSpan[(*it)->level()];
-    }
+  for (TrustTreeNodeList::iterator it = nodeList.begin(); it != nodeList.end(); it++) {
+    (*it)->x -= layerSpan[(*it)->level()];
+  }
 }
+
+} // namespace chronos
diff --git a/src/tree-layout.h b/src/tree-layout.h
deleted file mode 100644
index aa69251..0000000
--- a/src/tree-layout.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
- *         Alexander Afanasyev <alexander.afanasyev@ucla.edu>
- *         Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef TREE_LAYOUT_H
-#define TREE_LAYOUT_H
-
-#include <vector>
-#include "trust-tree-node.h"
-
-class TreeLayout
-{
-public:
-  struct Coordinate
-  {
-    double x;
-    double y;
-  };
-  TreeLayout(){}
-  virtual void setOneLevelLayout(std::vector<Coordinate> &childNodesCo){};
-  void setSiblingDistance(int d) {m_siblingDistance = d;}
-  void setLevelDistance(int d) {m_levelDistance = d;}
-  int getSiblingDistance() {return m_siblingDistance;}
-  int getLevelDistance() {return m_levelDistance;}
-  virtual ~TreeLayout(){}
-private:
-  int m_siblingDistance;
-  int m_levelDistance;
-};
-
-class OneLevelTreeLayout : public TreeLayout
-{
-public:
-  OneLevelTreeLayout(){}
-  virtual void setOneLevelLayout(std::vector<Coordinate> &childNodesCo);
-  virtual ~OneLevelTreeLayout(){}
-};
-
-class MultipleLevelTreeLayout : public TreeLayout
-{
-public:
-  MultipleLevelTreeLayout(){}
-  virtual ~MultipleLevelTreeLayout(){}
-  virtual void setMultipleLevelTreeLayout(TrustTreeNodeList& nodeList);
-};
-
-#endif // TREE_LAYOUT_H
diff --git a/src/tree-layout.hpp b/src/tree-layout.hpp
new file mode 100644
index 0000000..a33142e
--- /dev/null
+++ b/src/tree-layout.hpp
@@ -0,0 +1,105 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ *         Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ *         Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_TREE_LAYOUT_HPP
+#define CHRONOS_TREE_LAYOUT_HPP
+
+#include "trust-tree-node.hpp"
+
+namespace chronos {
+
+class TreeLayout
+{
+public:
+  struct Coordinate
+  {
+    double x;
+    double y;
+  };
+
+  TreeLayout()
+  {
+  }
+
+  virtual
+  ~TreeLayout()
+  {
+  }
+
+  virtual void
+  setOneLevelLayout(std::vector<Coordinate>& childNodesCo)
+  {
+  }
+
+  void
+  setSiblingDistance(int d)
+  {
+    m_siblingDistance = d;
+  }
+
+  void
+  setLevelDistance(int d)
+  {
+    m_levelDistance = d;
+  }
+
+  int
+  getSiblingDistance()
+  {
+    return m_siblingDistance;
+  }
+
+  int
+  getLevelDistance()
+  {
+    return m_levelDistance;
+  }
+
+
+private:
+  int m_siblingDistance;
+  int m_levelDistance;
+};
+
+class OneLevelTreeLayout : public TreeLayout
+{
+public:
+  OneLevelTreeLayout()
+  {
+  }
+
+  virtual ~OneLevelTreeLayout()
+  {
+  }
+
+  virtual void
+  setOneLevelLayout(std::vector<Coordinate>& childNodesCo);
+
+};
+
+class MultipleLevelTreeLayout : public TreeLayout
+{
+public:
+  MultipleLevelTreeLayout()
+  {
+  }
+
+  virtual ~MultipleLevelTreeLayout()
+  {
+  }
+
+  virtual void setMultipleLevelTreeLayout(TrustTreeNodeList& nodeList);
+};
+
+} // namespace chronos
+
+#endif // CHRONOS_TREE_LAYOUT_HPP
diff --git a/src/trust-tree-node.h b/src/trust-tree-node.hpp
similarity index 72%
rename from src/trust-tree-node.h
rename to src/trust-tree-node.hpp
index 77b62e6..2fe455a 100644
--- a/src/trust-tree-node.h
+++ b/src/trust-tree-node.hpp
@@ -8,15 +8,16 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#ifndef TRUST_TREE_NODE_H
-#define TRUST_TREE_NODE_H
+#ifndef CHRONOS_TRUST_TREE_NODE_HPP
+#define CHRONOS_TRUST_TREE_NODE_HPP
 
-#include <vector>
-#include <ndn-cxx/name.hpp>
+#include "common.hpp"
+
+namespace chronos {
 
 class TrustTreeNode;
 
-typedef std::vector<ndn::shared_ptr<TrustTreeNode> > TrustTreeNodeList;
+typedef std::vector<shared_ptr<TrustTreeNode> > TrustTreeNodeList;
 
 class TrustTreeNode
 {
@@ -24,25 +25,28 @@
   TrustTreeNode()
     : m_level(-1)
     , m_visited(false)
-  {}
+  {
+  }
 
-  TrustTreeNode(const ndn::Name& name)
+  TrustTreeNode(const Name& name)
     : m_name(name)
     , m_level(-1)
     , m_visited(false)
-  {}
+  {
+  }
 
   ~TrustTreeNode()
-  {}
+  {
+  }
 
-  const ndn::Name&
+  const Name&
   name()
   {
     return m_name;
   }
 
   void
-  addIntroducee(const ndn::shared_ptr<TrustTreeNode>& introducee)
+  addIntroducee(const shared_ptr<TrustTreeNode>& introducee)
   {
     m_introducees.push_back(introducee);
   }
@@ -54,7 +58,7 @@
   }
 
   void
-  addIntroducer(const ndn::shared_ptr<TrustTreeNode>& introducer)
+  addIntroducer(const shared_ptr<TrustTreeNode>& introducer)
   {
     m_introducers.push_back(introducer);
   }
@@ -100,13 +104,13 @@
   double y;
 
 private:
-  ndn::Name m_name;
+  Name m_name;
   TrustTreeNodeList m_introducees;
   TrustTreeNodeList m_introducers;
   int m_level;
   bool m_visited;
 };
 
+} // namespace chronos
 
-
-#endif // TRUST_TREE_NODE_H
+#endif // CHRONOS_TRUST_TREE_NODE_HPP
diff --git a/src/trust-tree-scene.cpp b/src/trust-tree-scene.cpp
index d3f84b5..73643f2 100644
--- a/src/trust-tree-scene.cpp
+++ b/src/trust-tree-scene.cpp
@@ -8,23 +8,23 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "trust-tree-scene.h"
+#include "trust-tree-scene.hpp"
 
 #include <QtGui>
 
 #ifndef Q_MOC_RUN
-#include <vector>
-#include <iostream>
 #include <assert.h>
-#include <boost/lexical_cast.hpp>
 #include <memory>
 #endif
 
+namespace chronos {
+
 static const double Pi = 3.14159265358979323846264338327950288419717;
 
-TrustTreeScene::TrustTreeScene(QWidget *parent)
+TrustTreeScene::TrustTreeScene(QWidget* parent)
   : QGraphicsScene(parent)
-{}
+{
+}
 
 void
 TrustTreeScene::plotTrustTree(TrustTreeNodeList& nodeList)
@@ -32,9 +32,10 @@
   clear();
 
   int nodeSize = 40;
-  int siblingDistance = 100, levelDistance = 100;
+  int siblingDistance = 100;
+  int levelDistance = 100;
 
-  boost::shared_ptr<MultipleLevelTreeLayout> layout(new MultipleLevelTreeLayout());
+  shared_ptr<MultipleLevelTreeLayout> layout(new MultipleLevelTreeLayout());
   layout->setSiblingDistance(siblingDistance);
   layout->setLevelDistance(levelDistance);
   layout->setMultipleLevelTreeLayout(nodeList);
@@ -46,41 +47,37 @@
 void
 TrustTreeScene::plotEdge(const TrustTreeNodeList& nodeList, int nodeSize)
 {
-  TrustTreeNodeList::const_iterator it  = nodeList.begin();
-  TrustTreeNodeList::const_iterator end = nodeList.end();
-  for(; it != end; it++)
-    {
-      TrustTreeNodeList& introducees = (*it)->getIntroducees();
-      TrustTreeNodeList::iterator eeIt  = introducees.begin();
-      TrustTreeNodeList::iterator eeEnd = introducees.end();
+  for (TrustTreeNodeList::const_iterator it = nodeList.begin(); it != nodeList.end(); it++) {
+    TrustTreeNodeList& introducees = (*it)->getIntroducees();
+    for (TrustTreeNodeList::iterator eeIt = introducees.begin();
+         eeIt != introducees.end(); eeIt++) {
+      if ((*it)->level() >= (*eeIt)->level())
+        continue;
 
-      for(; eeIt != eeEnd; eeIt++)
-        {
-          if((*it)->level() >= (*eeIt)->level())
-            continue;
+      double x1 = (*it)->x;
+      double y1 = (*it)->y;
+      double x2 = (*eeIt)->x;
+      double y2 = (*eeIt)->y;
 
-          double x1 = (*it)->x;
-          double y1 = (*it)->y;
-          double x2 = (*eeIt)->x;
-          double y2 = (*eeIt)->y;
+      QPointF src(x1 + nodeSize/2, y1 + nodeSize/2);
+      QPointF dest(x2 + nodeSize/2, y2 + nodeSize/2);
+      QLineF line(src, dest);
+      double angle = ::acos(line.dx() / line.length());
 
-          QPointF src(x1 + nodeSize/2, y1 + nodeSize/2);
-          QPointF dest(x2 + nodeSize/2, y2 + nodeSize/2);
-          QLineF line(src, dest);
-          double angle = ::acos(line.dx() / line.length());
+      double arrowSize = 10;
+      QPointF endP0 = src + QPointF((nodeSize/2) * line.dx() / line.dy(), nodeSize/2);
+      QPointF sourceArrowP0 = dest + QPointF((-nodeSize/2) * line.dx() / line.dy(),
+                                             -nodeSize/2);
+      QPointF sourceArrowP1 = sourceArrowP0 + QPointF(-cos(angle - Pi / 6) * arrowSize,
+                                                      -sin(angle - Pi / 6) * arrowSize);
+      QPointF sourceArrowP2 = sourceArrowP0 + QPointF(-cos(angle + Pi / 6) * arrowSize,
+                                                      -sin(angle + Pi / 6) * arrowSize);
 
-          double arrowSize = 10;
-          QPointF endP0 = src + QPointF((nodeSize/2) * line.dx() / line.dy(), nodeSize/2);
-          QPointF sourceArrowP0 = dest + QPointF((-nodeSize/2) * line.dx() / line.dy(), -nodeSize/2);
-          QPointF sourceArrowP1 = sourceArrowP0 + QPointF(-cos(angle - Pi / 6) * arrowSize,
-                                                          -sin(angle - Pi / 6) * arrowSize);
-          QPointF sourceArrowP2 = sourceArrowP0 + QPointF(-cos(angle + Pi / 6) * arrowSize,
-                                                          -sin(angle + Pi / 6) * arrowSize);
-
-          addLine(QLineF(sourceArrowP0, endP0), QPen(Qt::black));
-          addPolygon(QPolygonF() << sourceArrowP0 << sourceArrowP1 << sourceArrowP2, QPen(Qt::black), QBrush(Qt::black));
-        }
+      addLine(QLineF(sourceArrowP0, endP0), QPen(Qt::black));
+      addPolygon(QPolygonF() << sourceArrowP0 << sourceArrowP1 << sourceArrowP2,
+                 QPen(Qt::black), QBrush(Qt::black));
     }
+  }
 }
 
 void
@@ -89,10 +86,7 @@
   int rim = 3;
 
   // plot nodes
-  TrustTreeNodeList::const_iterator it  = nodeList.begin();
-  TrustTreeNodeList::const_iterator end = nodeList.end();
-  for(; it != end; it++)
-  {
+  for (TrustTreeNodeList::const_iterator it = nodeList.begin(); it != nodeList.end(); it++) {
     double x = (*it)->x;
     double y = (*it)->y;
     QRectF boundingRect(x, y, nodeSize, nodeSize);
@@ -108,9 +102,10 @@
     nickItem->setFont(QFont("Cursive", 8, QFont::Bold));
     nickItem->setPos(x - nodeSize / 2 + 10, y + nodeSize + 5);
   }
-
 }
 
+} //namespace chronos
+
 #if WAF
 #include "trust-tree-scene.moc"
 #include "trust-tree-scene.cpp.moc"
diff --git a/src/trust-tree-scene.h b/src/trust-tree-scene.h
deleted file mode 100644
index 384c4cc..0000000
--- a/src/trust-tree-scene.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef TRUST_TREE_SCENE_H
-#define TRUST_TREE_SCENE_H
-
-#include <QtGui/QGraphicsScene>
-#include <QColor>
-#include <QMap>
-
-#ifndef Q_MOC_RUN
-#include <vector>
-#include "trust-tree-node.h"
-#include "tree-layout.h"
-#endif
-
-class QGraphicsTextItem;
-
-class TrustTreeScene : public QGraphicsScene
-{
-  Q_OBJECT
-
-public:
-  TrustTreeScene(QWidget *parent = 0);
-
-  void plotTrustTree(TrustTreeNodeList& nodeList);
-
-private:
-  void plotEdge(const TrustTreeNodeList& nodeList, int nodeSize);
-  void plotNode(const TrustTreeNodeList& nodeList, int nodeSize);
-};
-
-#endif // TRUST_TREE_SCENE_H
diff --git a/src/trust-tree-scene.hpp b/src/trust-tree-scene.hpp
new file mode 100644
index 0000000..90be20e
--- /dev/null
+++ b/src/trust-tree-scene.hpp
@@ -0,0 +1,47 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_TRUST_TREE_SCENE_HPP
+#define CHRONOS_TRUST_TREE_SCENE_HPP
+
+#include <QtGui/QGraphicsScene>
+#include <QColor>
+#include <QMap>
+
+#ifndef Q_MOC_RUN
+#include "trust-tree-node.hpp"
+#include "tree-layout.hpp"
+#endif
+
+class QGraphicsTextItem;
+
+namespace chronos {
+
+class TrustTreeScene : public QGraphicsScene
+{
+  Q_OBJECT
+
+public:
+  TrustTreeScene(QWidget* parent = 0);
+
+  void
+  plotTrustTree(chronos::TrustTreeNodeList& nodeList);
+
+private:
+  void
+  plotEdge(const chronos::TrustTreeNodeList& nodeList, int nodeSize);
+
+  void
+  plotNode(const chronos::TrustTreeNodeList& nodeList, int nodeSize);
+};
+
+} // namespace chronos
+
+#endif // CHRONOS_TRUST_TREE_SCENE_HPP
diff --git a/src/validator-invitation.cpp b/src/validator-invitation.cpp
index e311e79..3b53e26 100644
--- a/src/validator-invitation.cpp
+++ b/src/validator-invitation.cpp
@@ -8,20 +8,28 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "validator-invitation.h"
-#include "invitation.h"
+#include "validator-invitation.hpp"
+#include "invitation.hpp"
 
 #include "logging.h"
 
 using namespace ndn;
 
-INIT_LOGGER("ValidatorInvitation");
+namespace chronos {
 
-namespace chronos{
+using std::vector;
 
-using ndn::shared_ptr;
+using ndn::CertificateCache;
+using ndn::SecRuleRelative;
+using ndn::OnDataValidated;
+using ndn::OnDataValidationFailed;
+using ndn::OnInterestValidated;
+using ndn::OnInterestValidationFailed;
+using ndn::ValidationRequest;
+using ndn::IdentityCertificate;
 
-const shared_ptr<CertificateCache> ValidatorInvitation::DefaultCertificateCache = shared_ptr<CertificateCache>();
+const shared_ptr<CertificateCache> ValidatorInvitation::DefaultCertificateCache =
+  shared_ptr<CertificateCache>();
 
 ValidatorInvitation::ValidatorInvitation()
   : Validator()
@@ -34,38 +42,54 @@
 }
 
 void
+ValidatorInvitation::addTrustAnchor(const Name& keyName, const ndn::PublicKey& key)
+{
+  m_trustAnchors[keyName] = key;
+}
+
+void
+ValidatorInvitation::removeTrustAnchor(const Name& keyName)
+{
+  m_trustAnchors.erase(keyName);
+}
+
+void
+ValidatorInvitation::cleanTrustAnchor()
+{
+  m_trustAnchors.clear();
+}
+
+void
 ValidatorInvitation::checkPolicy (const Data& data,
                                   int stepCount,
                                   const OnDataValidated& onValidated,
                                   const OnDataValidationFailed& onValidationFailed,
-                                  std::vector<shared_ptr<ValidationRequest> >& nextSteps)
+                                  vector<shared_ptr<ValidationRequest> >& nextSteps)
 {
-  try
-    {
-      SignatureSha256WithRsa sig(data.getSignature());
-      const Name & keyLocatorName = sig.getKeyLocator().getName();
+  const Signature& signature = data.getSignature();
 
-      if(!m_invitationReplyRule.satisfy(data.getName(), keyLocatorName))
-        return onValidationFailed(data.shared_from_this(),
-                                  "Does not comply with the invitation rule: "
-                                  + data.getName().toUri() + " signed by: "
-                                  + keyLocatorName.toUri());
+  if (signature.getKeyLocator().getType() != KeyLocator::KeyLocator_Name)
+    return onValidationFailed(data.shared_from_this(),
+                              "Key Locator is not a name: " + data.getName().toUri());
 
-      Data innerData;
-      innerData.wireDecode(data.getContent().blockFromValue());
+  const Name & keyLocatorName = signature.getKeyLocator().getName();
 
-      return internalCheck(data.wireEncode().value(),
-                           data.wireEncode().value_size() - data.getSignature().getValue().size(),
-                           sig,
-                           innerData,
-                           bind(onValidated, data.shared_from_this()),
-                           bind(onValidationFailed, data.shared_from_this(), _1));
-    }
-   catch(SignatureSha256WithRsa::Error &e)
-     {
-       return onValidationFailed(data.shared_from_this(),
-                                 "Not SignatureSha256WithRsa signature: " + data.getName().toUri());
-     }
+  if (!m_invitationReplyRule.satisfy(data.getName(), keyLocatorName))
+    return onValidationFailed(data.shared_from_this(),
+                              "Does not comply with the invitation rule: " +
+                              data.getName().toUri() + " signed by: " +
+                              keyLocatorName.toUri());
+
+  Data innerData;
+  innerData.wireDecode(data.getContent().blockFromValue());
+
+  return internalCheck(data.wireEncode().value(),
+                       data.wireEncode().value_size() - data.getSignature().getValue().size(),
+                       signature,
+                       keyLocatorName,
+                       innerData,
+                       bind(onValidated, data.shared_from_this()),
+                       bind(onValidationFailed, data.shared_from_this(), _1));
 }
 
 void
@@ -73,74 +97,65 @@
                                   int stepCount,
                                   const OnInterestValidated& onValidated,
                                   const OnInterestValidationFailed& onValidationFailed,
-                                  std::vector<shared_ptr<ValidationRequest> >& nextSteps)
+                                  vector<shared_ptr<ValidationRequest> >& nextSteps)
 {
-  try
-    {
-      Name interestName  = interest.getName();
+  const Name& interestName  = interest.getName();
 
-      if(!m_invitationInterestRule.match(interestName))
-        return onValidationFailed(interest.shared_from_this(),
-                                  "Invalid interest name: " +  interest.getName().toUri());
+  if (!m_invitationInterestRule.match(interestName))
+    return onValidationFailed(interest.shared_from_this(),
+                              "Invalid interest name: " +  interest.getName().toUri());
 
-      Name signedName = interestName.getPrefix(-1);
-      Buffer signedBlob = Buffer(signedName.wireEncode().value(), signedName.wireEncode().value_size());
+  Name signedName = interestName.getPrefix(-1);
+  Buffer signedBlob = Buffer(signedName.wireEncode().value(),
+                             signedName.wireEncode().value_size());
 
-      Block signatureBlock = interestName.get(Invitation::SIGNATURE).blockFromValue();
-      Block signatureInfo = interestName.get(Invitation::KEY_LOCATOR).blockFromValue();
-      Signature signature(signatureInfo, signatureBlock);
-      SignatureSha256WithRsa sig(signature);
+  Block signatureBlock = interestName.get(Invitation::SIGNATURE).blockFromValue();
+  Block signatureInfo = interestName.get(Invitation::KEY_LOCATOR).blockFromValue();
+  Signature signature(signatureInfo, signatureBlock);
 
-      Data innerData;
-      innerData.wireDecode(interestName.get(Invitation::INVITER_CERT).blockFromValue());
+  if (signature.getKeyLocator().getType() != KeyLocator::KeyLocator_Name)
+    return onValidationFailed(interest.shared_from_this(),
+                              "KeyLocator is not a name: " + interest.getName().toUri());
 
-      return internalCheck(signedBlob.buf(),
-                           signedBlob.size(),
-                           sig,
-                           innerData,
-                           bind(onValidated, interest.shared_from_this()),
-                           bind(onValidationFailed, interest.shared_from_this(), _1));
-    }
-  catch(SignatureSha256WithRsa::Error& e)
-    {
-      return onValidationFailed(interest.shared_from_this(),
-                                "Not SignatureSha256WithRsa signature: " + interest.getName().toUri());
-    }
+  const Name & keyLocatorName = signature.getKeyLocator().getName();
+
+  Data innerData;
+  innerData.wireDecode(interestName.get(Invitation::INVITER_CERT).blockFromValue());
+
+  return internalCheck(signedBlob.buf(), signedBlob.size(),
+                       signature,
+                       keyLocatorName,
+                       innerData,
+                       bind(onValidated, interest.shared_from_this()),
+                       bind(onValidationFailed, interest.shared_from_this(), _1));
 }
 
 void
 ValidatorInvitation::internalCheck(const uint8_t* buf, size_t size,
-                                   const SignatureSha256WithRsa& sig,
+                                   const Signature& signature,
+                                   const Name& keyLocatorName,
                                    const Data& innerData,
                                    const OnValidated& onValidated,
                                    const OnValidationFailed& onValidationFailed)
 {
-  try
-    {
-      const Name & keyLocatorName = sig.getKeyLocator().getName();
-      Name signingKeyName = IdentityCertificate::certificateNameToPublicKeyName(keyLocatorName);
+  Name signingKeyName = IdentityCertificate::certificateNameToPublicKeyName(keyLocatorName);
 
-      if(m_trustAnchors.find(signingKeyName) == m_trustAnchors.end())
-        return onValidationFailed("Cannot reach any trust anchor");
+  TrustAnchors::const_iterator keyIt = m_trustAnchors.find(signingKeyName);
+  if (keyIt == m_trustAnchors.end())
+    return onValidationFailed("Cannot reach any trust anchor");
 
-      if(!Validator::verifySignature(buf, size, sig, m_trustAnchors[signingKeyName]))
-        return onValidationFailed("Cannot verify outer signature");
+  if (!Validator::verifySignature(buf, size, signature, keyIt->second))
+    return onValidationFailed("Cannot verify outer signature");
 
-      // Temporarily disabled, we should get it back when we create a specific key for the chatroom.
-      // if(!Validator::verifySignature(innerData, m_trustAnchors[signingKeyName]))
-      //   return onValidationFailed("Cannot verify inner signature");
+  // Temporarily disabled, we should get it back when we create a specific key for the chatroom.
+  // if(!Validator::verifySignature(innerData, m_trustAnchors[signingKeyName]))
+  //   return onValidationFailed("Cannot verify inner signature");
 
-      if(!m_innerKeyRegex.match(innerData.getName())
-          || m_innerKeyRegex.expand() != signingKeyName.getPrefix(-1))
-         return onValidationFailed("Inner certificate does not comply with the rule");
+  if (!m_innerKeyRegex.match(innerData.getName()) ||
+      m_innerKeyRegex.expand() != signingKeyName.getPrefix(-1))
+    return onValidationFailed("Inner certificate does not comply with the rule");
 
-      return onValidated();
-    }
-  catch(KeyLocator::Error& e)
-    {
-      return onValidationFailed("Key Locator is not a name");
-    }
+  return onValidated();
 }
 
-
-}//chronos
+} // namespace chronos
diff --git a/src/validator-invitation.h b/src/validator-invitation.h
deleted file mode 100644
index d7b8276..0000000
--- a/src/validator-invitation.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef CHRONOS_VALIDATOR_INVITATION_H
-#define CHRONOS_VALIDATOR_INVITATION_H
-
-#include <ndn-cxx/security/validator.hpp>
-#include <ndn-cxx/security/certificate-cache.hpp>
-#include <ndn-cxx/security/sec-rule-relative.hpp>
-#include <map>
-
-#include "endorse-certificate.h"
-
-namespace chronos{
-
-class ValidatorInvitation : public ndn::Validator
-{
-  typedef ndn::function< void (const std::string&) > OnValidationFailed;
-  typedef ndn::function< void () > OnValidated;
-
-public:
-  struct Error : public Validator::Error { Error(const std::string &what) : Validator::Error(what) {} };
-
-  static const ndn::shared_ptr<ndn::CertificateCache> DefaultCertificateCache;
-
-  ValidatorInvitation();
-
-  virtual
-  ~ValidatorInvitation() {};
-
-  void
-  addTrustAnchor(const ndn::Name& keyName, const ndn::PublicKey& key)
-  {
-    m_trustAnchors[keyName] = key;
-  }
-
-  void
-  removeTrustAnchor(const ndn::Name& keyName)
-  {
-    m_trustAnchors.erase(keyName);
-  }
-
-  void
-  cleanTrustAnchor()
-  {
-    m_trustAnchors.clear();
-  }
-
-protected:
-  void
-  checkPolicy(const ndn::Data& data,
-              int stepCount,
-              const ndn::OnDataValidated& onValidated,
-              const ndn::OnDataValidationFailed& onValidationFailed,
-              std::vector<ndn::shared_ptr<ndn::ValidationRequest> >& nextSteps);
-
-  void
-  checkPolicy(const ndn::Interest& interest,
-              int stepCount,
-              const ndn::OnInterestValidated& onValidated,
-              const ndn::OnInterestValidationFailed& onValidationFailed,
-              std::vector<ndn::shared_ptr<ndn::ValidationRequest> >& nextSteps);
-
-private:
-  void
-  internalCheck(const uint8_t* buf, size_t size,
-                const ndn::SignatureSha256WithRsa& sig,
-                const ndn::Data& innerData,
-                const OnValidated& onValidated,
-                const OnValidationFailed& onValidationFailed);
-
-private:
-  typedef std::map<ndn::Name, ndn::PublicKey> TrustAnchors;
-
-  ndn::SecRuleRelative m_invitationReplyRule;
-  ndn::Regex m_invitationInterestRule;
-  ndn::Regex m_innerKeyRegex;
-  TrustAnchors m_trustAnchors;
-};
-
-}//chronos
-
-#endif //CHRONOS_VALIDATOR_INVITATION_H
diff --git a/src/validator-invitation.hpp b/src/validator-invitation.hpp
new file mode 100644
index 0000000..c2a0e5a
--- /dev/null
+++ b/src/validator-invitation.hpp
@@ -0,0 +1,92 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_VALIDATOR_INVITATION_HPP
+#define CHRONOS_VALIDATOR_INVITATION_HPP
+
+#include "common.hpp"
+
+#include <ndn-cxx/security/validator.hpp>
+#include <ndn-cxx/security/certificate-cache.hpp>
+#include <ndn-cxx/security/sec-rule-relative.hpp>
+
+#include "endorse-certificate.hpp"
+
+namespace chronos {
+
+class ValidatorInvitation : public ndn::Validator
+{
+  typedef function<void(const std::string&)> OnValidationFailed;
+  typedef function<void()> OnValidated;
+
+public:
+  class Error : public ndn::Validator::Error
+  {
+  public:
+    Error(const std::string& what)
+      : ndn::Validator::Error(what)
+    {
+    }
+  };
+
+  static const shared_ptr<ndn::CertificateCache> DefaultCertificateCache;
+
+  ValidatorInvitation();
+
+  virtual
+  ~ValidatorInvitation()
+  {
+  }
+
+  void
+  addTrustAnchor(const Name& keyName, const ndn::PublicKey& key);
+
+  void
+  removeTrustAnchor(const Name& keyName);
+
+  void
+  cleanTrustAnchor();
+
+protected:
+  void
+  checkPolicy(const Data& data,
+              int stepCount,
+              const ndn::OnDataValidated& onValidated,
+              const ndn::OnDataValidationFailed& onValidationFailed,
+              std::vector<shared_ptr<ndn::ValidationRequest> >& nextSteps);
+
+  void
+  checkPolicy(const Interest& interest,
+              int stepCount,
+              const ndn::OnInterestValidated& onValidated,
+              const ndn::OnInterestValidationFailed& onValidationFailed,
+              std::vector<shared_ptr<ndn::ValidationRequest> >& nextSteps);
+
+private:
+  void
+  internalCheck(const uint8_t* buf, size_t size,
+                const Signature& sig,
+                const Name& keyLocatorName,
+                const Data& innerData,
+                const OnValidated& onValidated,
+                const OnValidationFailed& onValidationFailed);
+
+private:
+  typedef std::map<Name, ndn::PublicKey> TrustAnchors;
+
+  ndn::SecRuleRelative m_invitationReplyRule;
+  ndn::Regex m_invitationInterestRule;
+  ndn::Regex m_innerKeyRegex;
+  TrustAnchors m_trustAnchors;
+};
+
+} // namespace chronos
+
+#endif //CHRONOS_VALIDATOR_INVITATION_HPP
diff --git a/src/validator-panel.cpp b/src/validator-panel.cpp
index 9caba64..2cb71f8 100644
--- a/src/validator-panel.cpp
+++ b/src/validator-panel.cpp
@@ -8,23 +8,26 @@
  * Author: Yingdi Yu <yingdi@cs.ucla.edu>
  */
 
-#include "validator-panel.h"
+#include "validator-panel.hpp"
 
 #include "logging.h"
 
-using namespace std;
-using namespace ndn;
+namespace chronos {
 
-INIT_LOGGER("ValidatorPanel");
+using std::vector;
 
-namespace chronos{
+using ndn::CertificateCache;
+using ndn::SecRuleRelative;
+using ndn::OnDataValidated;
+using ndn::OnDataValidationFailed;
+using ndn::ValidationRequest;
+using ndn::IdentityCertificate;
 
-using ndn::shared_ptr;
+const shared_ptr<CertificateCache> ValidatorPanel::DEFAULT_CERT_CACHE =
+  shared_ptr<CertificateCache>();
 
-const shared_ptr<CertificateCache> ValidatorPanel::DEFAULT_CERT_CACHE = shared_ptr<CertificateCache>();
-
-ValidatorPanel::ValidatorPanel(int stepLimit /* = 10 */,
-                               const shared_ptr<CertificateCache> certificateCache/* = DEFAULT_CERT_CACHE */)
+ValidatorPanel::ValidatorPanel(int stepLimit,
+                               const shared_ptr<CertificateCache> certificateCache)
   : m_stepLimit(stepLimit)
   , m_certificateCache(certificateCache)
 {
@@ -33,52 +36,54 @@
                                                 "==", "\\1", "\\1\\2", true);
 }
 
+void
+ValidatorPanel::addTrustAnchor(const EndorseCertificate& cert)
+{
+  m_trustAnchors[cert.getPublicKeyName()] = cert.getPublicKeyInfo();
+}
 
+void
+ValidatorPanel::removeTrustAnchor(const Name& keyName)
+{
+  m_trustAnchors.erase(keyName);
+}
 
 void
 ValidatorPanel::checkPolicy (const Data& data,
                              int stepCount,
                              const OnDataValidated& onValidated,
                              const OnDataValidationFailed& onValidationFailed,
-                             std::vector<shared_ptr<ValidationRequest> >& nextSteps)
+                             vector<shared_ptr<ValidationRequest> >& nextSteps)
 {
-  if(m_stepLimit == stepCount)
-    {
-      _LOG_ERROR("Reach the maximum steps of verification!");
+  if (m_stepLimit == stepCount) {
+    onValidationFailed(data.shared_from_this(),
+                       "Reach maximum validation steps: " + data.getName().toUri());
+    return;
+  }
+
+  const KeyLocator& keyLocator = data.getSignature().getKeyLocator();
+
+  if (keyLocator.getType() != KeyLocator::KeyLocator_Name)
+    return onValidationFailed(data.shared_from_this(),
+                              "Key Locator is not a name: " + data.getName().toUri());
+
+  const Name& keyLocatorName = keyLocator.getName();
+
+  if (m_endorseeRule->satisfy(data.getName(), keyLocatorName)) {
+    Name keyName = IdentityCertificate::certificateNameToPublicKeyName(keyLocatorName);
+
+    if (m_trustAnchors.end() != m_trustAnchors.find(keyName) &&
+        Validator::verifySignature(data, data.getSignature(), m_trustAnchors[keyName]))
+      onValidated(data.shared_from_this());
+    else
       onValidationFailed(data.shared_from_this(),
-                         "Reach maximum validation steps: " + data.getName().toUri());
-      return;
-    }
+                         "Cannot verify signature:" + data.getName().toUri());
+  }
+  else
+    onValidationFailed(data.shared_from_this(),
+                       "Does not satisfy rule: " + data.getName().toUri());
 
-  try
-    {
-      SignatureSha256WithRsa sig(data.getSignature());
-      const Name& keyLocatorName = sig.getKeyLocator().getName();
-
-      if(m_endorseeRule->satisfy(data.getName(), keyLocatorName))
-        {
-          Name keyName = IdentityCertificate::certificateNameToPublicKeyName(keyLocatorName);
-
-          if(m_trustAnchors.end() != m_trustAnchors.find(keyName) && Validator::verifySignature(data, sig, m_trustAnchors[keyName]))
-            onValidated(data.shared_from_this());
-          else
-            onValidationFailed(data.shared_from_this(), "Cannot verify signature:" + data.getName().toUri());
-        }
-      else
-        onValidationFailed(data.shared_from_this(), "Does not satisfy rule: " + data.getName().toUri());
-
-      return;
-    }
-  catch(SignatureSha256WithRsa::Error &e)
-    {
-      return onValidationFailed(data.shared_from_this(),
-                                "Not SignatureSha256WithRsa signature: " + data.getName().toUri());
-    }
-  catch(KeyLocator::Error &e)
-    {
-      return onValidationFailed(data.shared_from_this(),
-                                "Key Locator is not a name: " + data.getName().toUri());
-    }
+  return;
 }
 
-}//chronos
+} // namespace chronos
diff --git a/src/validator-panel.h b/src/validator-panel.h
deleted file mode 100644
index c786c9f..0000000
--- a/src/validator-panel.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
-/*
- * Copyright (c) 2013, Regents of the University of California
- *                     Yingdi Yu
- *
- * BSD license, See the LICENSE file for more information
- *
- * Author: Yingdi Yu <yingdi@cs.ucla.edu>
- */
-
-#ifndef CHRONOS_VALIDATOR_PANEL_H
-#define CHRONOS_VALIDATOR_PANEL_H
-
-#include <ndn-cxx/security/validator.hpp>
-#include <ndn-cxx/security/sec-rule-relative.hpp>
-#include <ndn-cxx/security/certificate-cache.hpp>
-#include <map>
-
-#include "endorse-certificate.h"
-
-namespace chronos{
-
-class ValidatorPanel : public ndn::Validator
-{
-public:
-
-  static const ndn::shared_ptr<ndn::CertificateCache> DEFAULT_CERT_CACHE;
-
-  ValidatorPanel(int stepLimit = 10,
-                 const ndn::shared_ptr<ndn::CertificateCache> certificateCache = DEFAULT_CERT_CACHE);
-
-  ~ValidatorPanel()
-  {}
-
-  inline void
-  addTrustAnchor(const EndorseCertificate& selfEndorseCertificate);
-
-  inline void
-  removeTrustAnchor(const ndn::Name& keyName);
-
-protected:
-  virtual void
-  checkPolicy (const ndn::Data& data,
-               int stepCount,
-               const ndn::OnDataValidated& onValidated,
-               const ndn::OnDataValidationFailed& onValidationFailed,
-               std::vector<ndn::shared_ptr<ndn::ValidationRequest> >& nextSteps);
-
-  virtual void
-  checkPolicy (const ndn::Interest& interest,
-               int stepCount,
-               const ndn::OnInterestValidated& onValidated,
-               const ndn::OnInterestValidationFailed& onValidationFailed,
-               std::vector<ndn::shared_ptr<ndn::ValidationRequest> >& nextSteps)
-  {
-    onValidationFailed(interest.shared_from_this(),
-                       "No rules for interest.");
-  }
-
-private:
-  int m_stepLimit;
-  ndn::shared_ptr<ndn::CertificateCache> m_certificateCache;
-  ndn::shared_ptr<ndn::SecRuleRelative> m_endorseeRule;
-  std::map<ndn::Name, ndn::PublicKey> m_trustAnchors;
-
-};
-
-inline void
-ValidatorPanel::addTrustAnchor(const EndorseCertificate& cert)
-{ m_trustAnchors[cert.getPublicKeyName()] = cert.getPublicKeyInfo(); }
-
-inline void
-ValidatorPanel::removeTrustAnchor(const ndn::Name& keyName)
-{ m_trustAnchors.erase(keyName); }
-
-}//chronos
-
-#endif
diff --git a/src/validator-panel.hpp b/src/validator-panel.hpp
new file mode 100644
index 0000000..1277ffe
--- /dev/null
+++ b/src/validator-panel.hpp
@@ -0,0 +1,71 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *                     Yingdi Yu
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef CHRONOS_VALIDATOR_PANEL_HPP
+#define CHRONOS_VALIDATOR_PANEL_HPP
+
+#include "common.hpp"
+
+#include <ndn-cxx/security/validator.hpp>
+#include <ndn-cxx/security/sec-rule-relative.hpp>
+#include <ndn-cxx/security/certificate-cache.hpp>
+
+#include "endorse-certificate.hpp"
+
+namespace chronos {
+
+class ValidatorPanel : public ndn::Validator
+{
+public:
+
+  static const shared_ptr<ndn::CertificateCache> DEFAULT_CERT_CACHE;
+
+  ValidatorPanel(int stepLimit = 10,
+                 const shared_ptr<ndn::CertificateCache> cache = DEFAULT_CERT_CACHE);
+
+  ~ValidatorPanel()
+  {
+  }
+
+  void
+  addTrustAnchor(const EndorseCertificate& selfEndorseCertificate);
+
+  void
+  removeTrustAnchor(const Name& keyName);
+
+protected:
+  virtual void
+  checkPolicy(const Data& data,
+              int stepCount,
+              const ndn::OnDataValidated& onValidated,
+              const ndn::OnDataValidationFailed& onValidationFailed,
+              std::vector<shared_ptr<ndn::ValidationRequest> >& nextSteps);
+
+  virtual void
+  checkPolicy(const Interest& interest,
+              int stepCount,
+              const ndn::OnInterestValidated& onValidated,
+              const ndn::OnInterestValidationFailed& onValidationFailed,
+              std::vector<shared_ptr<ndn::ValidationRequest> >& nextSteps)
+  {
+    onValidationFailed(interest.shared_from_this(),
+                       "No rules for interest.");
+  }
+
+private:
+  int m_stepLimit;
+  shared_ptr<ndn::CertificateCache> m_certificateCache;
+  shared_ptr<ndn::SecRuleRelative> m_endorseeRule;
+  std::map<Name, ndn::PublicKey> m_trustAnchors;
+};
+
+} // namespace chronos
+
+#endif // CHRONOS_VALIDATOR_PANEL_HPP