#include<iostream>
#include<cstdlib>
#include <string>
#include <process.h>
#include <windows.h>
#include <fstream>
using namespace std;
HANDLE hMutex;
void startserver(void *lol){
    WaitForSingleObject( hMutex, INFINITE );
    string b="\"F:\\Program Files (x86)\\namecoind\\namecoind\" ";
    const char * d = b.c_str();
    system(d);
    ReleaseMutex( hMutex );
}
void cbracket() {}
string icomma()
{



}
void genconf(){
    system("md %APPDATA%\\Roaming\\Namecoin");
    fstream config;
    config.open("%APPDATA%\\Namecoin\\bitcoin.conf",ios::out);
    config<<"rpcuser=username\nrpcpassword=l0l0l0l0l0l\nrpcport=8336\ndaemon=1";
    config.close();
}
int main()
{
    hMutex = CreateMutex( NULL, FALSE, NULL );
    string a;
    string b="\"F:\\Program Files (x86)\\namecoind\\namecoind\" ";
    string c;
    const char * d = b.c_str();
    _beginthread(startserver,0,NULL);
    cout<<"namecoind instance starting...";
    if (WaitForSingleObject( hMutex, 15000 )!=WAIT_TIMEOUT){
        cout<<"\nconfig missing. Generating config...";
        genconf();
        cout<<"ok, \npress any key to quit. restart the program after this"<<endl;
        cin.ignore();
    }
    else {
    cout<<"started"<<endl;
    cout<<"Type in help and press enter to check."<<endl;
    cout<<"if it says error: cannot connect to server, that means it is still starting. Try some more till it list out the commands."<<endl;
    cout<<"QUIT ONLY BY TYPING quit IN LOWER CASE AND PRESS ENTER"<<endl;
    //cout<<"if you are getting the error of no config file, type in \"genconf\" in lower case and press enter, then start the application again."<<endl;
    while(true)
    {
        cout<<">";
        getline(cin,a);
        if (a=="quit")
        {
            system("\"F:\\Program Files (x86)\\namecoind\\namecoind\" stop");
            break;
        }
        //else if(a=="genconf")genconf();
        else
        {
            c=b+a;
            d = c.c_str();
            system(d);
        }
    }
    _endthread();
    }
}
