#include <cctype>
#include <iostream>
#include <fstream>
#include <string>
using std::string;
#include <cleansocks.h>
#include <cleanip.h>
#include <cleanbuf.h>
using namespace cleansocks;
#include "sha256.h"
// Port numbers.
const int DFLTPORT = 45100;
// Prompt and read, when you're just not capable of adult forms of
// configuration.
template <typename T>
T pandr(string prompt)
{
        std::cout << prompt << ": ";
        T ret;
        std::cin >> ret;
        return ret;
}
// Tell if the string ends with .conf
bool is_dot_conf(string s)
{
        return s.length() > 5 && s.substr(s.length() - 5) == ".conf";
}
int main(int argc, char **argv)
{
        string pgm = argv[0];
        ++argv; --argc;
        // Port numbers
        int portno = DFLTPORT+1;
        // Parms.  Lots of ways to provide
        string hn;
        int pno = DFLTPORT;
        if(argc == 1 && is_dot_conf(argv[0])) {
                // .conf file
                std::ifstream in(argv[0]);
                in >> hn >> pno;
        } else if(argc > 0) {
                // Command line.
                hn = *argv++; argc--;
                if(argc > 0 && isdigit(argv[0][0])) {
                        pno = std::atoi(*argv++); argc--;
                }
        } else {
                hn = pandr<string>("Host");
                pno = pandr<int>("Port");
        }
        // Listener uses the even port
        if(pno % 2 == 1) --pno;
        
        // Connect.
        try {
                TCPsocket sock;
                IPaddress host = lookup_host(hn);
                IPport port = pno;
                connect(sock, IPendpoint(host,port));
                buffered_socket bs(sock);
                std::cout << "Connected" << std::endl;
                char buf[1024];
                int n;
                while((n = recvln(bs, buf, sizeof buf)) > 0) {
                        std::cout << string(buf,n-2) << std::endl;
                }
        } catch(std::exception &e) {
                std::cout << "Error: " << e.what() << std::endl;
        }
}