//----------------------------------------------------------------
// Example E1: consider how each error should be handled
//----------------------------------------------------------------

void sendMessage(const char *hostname,
    const char *portNum, const char *message) {
    struct hostent *hp;
    struct sockaddr_in servaddr;
    int fd;
    int port = atoi(portNum);
    struct addrinfo hints, *p, *res=0;

    if (strlen(message) >= MAX_UDP_PACKET_SIZE) {
        cerr << "Message too long for UDP\n";
        return;                         
    }  

    /* 
     * We need to lock because we are using the depricated gethostbyname 
     * function
     */
    lock_guard<mutex> gethostlock(gethostMutex);
    hp = gethostbyname(hostname);
    if (!hp) {
        cerr << "could not obtain address of " << hostname << endl;
        return;
    }

    memset((char*)&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);

    memcpy((void *)&servaddr.sin_addr, hp->h_addr_list[0], hp->h_length);

    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        cerr << "Cannot get socket\n";
        return;
    }

    if (sendto(fd, message, strlen(message), 0, (struct sockaddr *)&servaddr, 
        sizeof(servaddr)) < 0) {
        cerr << "Hostname: " << hostname << " Port: " << portNum << endl;
        cerr << "Sendto error: " << errno << "\n";
        return;
    }
}

//----------------------------------------------------------------
// Example E2: not enough information in log message
//----------------------------------------------------------------

std::ifstream config_file(CONFIG_FILE);
if (!config_file.good()) {
    std::cout << "Config file can not be found." << std::endl;
    exit(-1);
}

std::cout << "Invalid message received" << std::endl;

//----------------------------------------------------------------
// Example O1: closure obscures code
//----------------------------------------------------------------

// Closure results in opaque code:

requestCv.wait(l, [this]() {
    return (stepDown || (numSuccesses > (1 + managers.size())/2));
});

// Eliminating the closure makes things more obvious:

while (!stepDown && (numSuccesses <= managers.size()/2)) {
   requestCv.wait();
}

//----------------------------------------------------------------
// Example O2: closure hides thread main method
//----------------------------------------------------------------

void Peer::RegisterReceiveListener() {
    LOG(DEBUG) << "creating a new inbound listening thread";
    in_listener = std::thread([this] () {
        while(running) {
            AcceptConnection(dest_ip_addr.c_str(), my_port);
            LOG(DEBUG) << "receive socket: " << receive_socket;
            ListenOnSocket(receive_socket);
            if (receive_socket != -1) {
                ErrorCheckSysCall(close(receive_socket),"close receive_socket");
                receive_socket = -1;
            }
            stream_parser->ResetIncomingMessage();
            //dump anything we haven't used from this previous connection
        }
    });
}

//----------------------------------------------------------------
// Example O3: closure convenient to invoke method
//----------------------------------------------------------------

std::thread electionTimeoutThread(
    [this]() { this->electionTimeoutMonitor(); });
}

//----------------------------------------------------------------
// Example O4: iterator fields are opaque
// (copy it->second into a named local variable)
//----------------------------------------------------------------

std::unordered_map<int, ConnectionManager::Connection>::iterator
ConnectionManager::FindConnectionBySockAddr(const sockaddr_storage& addr) {
    sockaddr_in *a, *b;
    sockaddr_in6 *c, *d;
    for (auto it = connections_.begin(); it != connections_.end(); it++) {
	if (it->second.addr.ss_family != addr.ss_family)
	    continue;

	// We must to cast our storage struct into an IPv4 or IPv6 struct
	// before comparing.
	switch(addr.ss_family) {
	    case AF_INET:
		a = (sockaddr_in *)&it->second.addr;
		b = (sockaddr_in *)&it->second.addr;
		if (memcmp(&a->sin_addr, &b->sin_addr, sizeof(in_addr)) == 0)
		    return it;
		break;

	    case AF_INET6:
		c = (sockaddr_in6 *)&it->second.addr;
		d = (sockaddr_in6 *)&it->second.addr;
		if (memcmp(&c->sin6_addr, &d->sin6_addr, sizeof(in6_addr)) == 0)
		    return it;
		break;
	}
    }
    return connections_.end();
}

//----------------------------------------------------------------
// Example O5: C++ I/O is awkward
//----------------------------------------------------------------

std::cout << "recv: " << strerror(errno) << "(" << errno << ")";

vs.
	
printf("recv: %s (%d)\n", strerror(errno), errno);

//----------------------------------------------------------------
// Example D1: documentation duplicates code
//----------------------------------------------------------------

// deal with mail pile
while (!mail_pile.empty()) {

bool receivedValidHeartbeat;        // did i receive a heartbeat?

/**
 * @brief Returns the size of the message buffer in bytes
 *
 * @return uint32_t
 */
uint32_t getSize();

// Vector of next commit indices, with the index within the vector
// corresponding to other server ids
std::vector<size_t> next_commit_idx;

//----------------------------------------------------------------
// Example D2: interface comment describes implementation
//----------------------------------------------------------------

/**
 * Function: writeout_persistent_data
 *
 * @param curr_term: Current term of the server.
 * @param voted_for: Server ID which the server voted for.
 *
 * Writes the current term of the server and who the server voted for
 * to the file "<server_id>_storage". The format of the lines in the file
 * is curr_term,voted_for. It first writes out to a temp file, flushes
 * the file to disk, then renames the temp file to the real filename
 * to maintain robustness, so if writing out to a file crashes, the application
 * can use the previous values stored.
 */
void writeout_persistent_data(size_t curr_term, int voted_for);

/**
 * @brief Constructs a NetworkingHandler object, which attempts to open
 * connections with other NetworkingHandlers in the cluster. The object
 * listens for new connections on a newly-spawned thread and after accepting
 * connections, begins listening for messages from the peer
 * NetworkingHandler on a newly-spawned thread. When connections are closed,
 * the object automatically and continually makes attempts to reestablish
 * the connection.
 */
NetworkingHandler();

/*
 * Converts a Message into its string representation
 *
 * The format of a message is as follows:
 * type:[message type],term:[term],addr:[server address], .. other fields\n
 *
 * @param message the Message to deparse
 * @return the string representation of the Message
 */
static std::string deparse_message(const Message &message);

//----------------------------------------------------------------
// Example D3: comments not at the right level
//----------------------------------------------------------------

/* Server creation parameter. */
const int CONN_BACKLOG = 32;

/**
 * Convenience structure, used to store entries read in from the config
 * file.
 */
struct ConfigData {
    uint32_t id;
    std::string hostname;
    std::string ip_address;
    uint16_t port;
};

//----------------------------------------------------------------
// Example D4: comment describes how variable is used, not what it is
//----------------------------------------------------------------


// File path opened repeatedly by FileStorage during committing/recovering
std::string filePath;

/*
 * This enum represents the three states a Raft server can be in: when the
 * server is a Follower, it receives heartbeat messages from the leader;
 * when the server has not received a heartbeat message for a certain
 * amount of time, it tries to become leader, and is a candidate; when the
 * server has won an election, it becomes leader until it receives
 * heartbeats from a server with a greater term, at which point it becomes
 * a follower again
 */
enum State {
    Follower,
    Candidate,
    Leader
};

/*
 * The current state of the server. Should be updated when messages are
 * received or when timeouts occur
 */
enum State _state;

//----------------------------------------------------------------
// Example V1: variable names too generic
//----------------------------------------------------------------

string id;      // The port number of the sender.
bool response;

//----------------------------------------------------------------
// Example V2: argument name doesn't reflect true meaning
//----------------------------------------------------------------

/**
 * Function: initialize_server_socket
 *
 * Params:
 * port: The port number top start server socket on.
 * num_servers: Total number of servers.
 *
 * Initializes server socket for this machine. Returns the file descriptor
 * of the newly created socket.
 */
int initialize_server_socket(int port, int num_servers) {
    ...
    if (listen(server_fd, num_servers) < 0) {