int networkScan() {
    uint8_t index=0;
	char endofinput[]="No.Of AP Found:";
	char nfound[4]="0";
	uint8_t ch='0';
	radio.discard();
	radio.printf("\r\n");
	radio.discard();
	radio.printf("\r\nAT+WS\r\n");
	while (!radio.available()); // and some timeout.
	
	while ((index<15)){
		while (radio.available()) {
			console.putChar(ch=(char) radio.read());
			if ((ch=='\n')||(ch=='\r')) index=0;
			if (ch==endofinput[index]) index++;
		}
		
	}
	
	while (!radio.available()); // and some timeout.
	ch='\0'; index=0;
	while ((index<4)&&(ch!='\r')&&(ch!='\n')){
		while(radio.available()) {
			console.putChar(ch=(char) radio.read());
			if (isdigit(ch)) nfound[index++]=ch;
		}
	}
	radio.discard();
	console.printf("\r\n");
	nfound[index]='\0';
	return(atoi(nfound));
	
}
void handleConsoleInput() {
    uint8_t retval;
	uint8_t index=0;
	uint8_t ch='0';
    switch (console.keyValue()) {
        case _NSC_:  
			console.printf("SOD:\r\n");
			retval=networkScan();
			console.printf("EOD:\r\n");
            console.printf("\nDBG: found=%d\r\n",retval);
            break;
        case _NJN_:  
			//console.printf("SOD:\r\n");
			retval=networkJoin(console.arguments());
			//console.printf("EOD:\r\n");
            console.printf("\nDBG: joined=%s\r\n",retval?"TRUE":"FALSE");
            break;
        case _NPW_:  
			//console.printf("SOD:\r\n");
			retval=networkSetPassword(console.arguments());
			//console.printf("EOD:\r\n");
            console.printf("\nDBG: pwd set=%s\r\n",retval?"TRUE":"FALSE");
            break;
        case _NST_:  
			retval=networkStatus();
            console.printf("NST: %s\r\n",retval?"CONNECTED":"NOT CONNECTED");
            break;
            
		case _TPT_:
			toTheEthers(1, console.arguments());
			break;
        case _TX2_:
            radio.printf("%s",console.arguments());
            index=0;
            // delay(1000);
            while (radio.available()) {
                inBuffer[index++]=ch=radio.read();
				if( index>= 99 || ((ch== '\n') || ch !='\r')) {
					inBuffer[index]='\0';
					console.puts(inBuffer);
					index=0; 
					delay(100);
				}
            } 
            inBuffer[index]='\0';
            console.puts(inBuffer);
			console.puts((char *) "\r\n");
            break;
        case _PKY_:
            strncpy(pachubeKey, console.arguments(), MAX_PATCHUBE_KEY_LENGHT-1);
            stripcrlf(pachubeKey);
            break;
        default:
            console.printf("DBG: forwarding (%s) to device\r\n",console.key());
            //device.puts("\r\n");
            break;
    }
    
    
}
/*-----------------------------------------------------------------pachubeDate()
 * pull date from pachube server
 *----------------------------------------------------------------------------*/
int pachubeDate() {
    uint8_t n,index=0;
	int retval=0;
	char databuffer[36];
	char cid[4]="0";
    bool gotResponse=false;
    enum {CONNECT, ERROR, DISASSOCIATED} status=ERROR;//statii;
	uint8_t ch='0';
    
    if (!hasWifiModule) return retval;
    
	radio.discard();
	radio.printf("\r\n");
	radio.discard();
	radio.printf("\r\nAT+NCTCP=216.52.233.122,80\r\n");
	while (!radio.available()); // and some timeout.
    
	// ERROR
    // CONNECT <CID>
    // DISASSOCIATED
 	digitalWrite(ORN_LED,LOW);
    
	while (!gotResponse){ // this needs to catch errors.
		while (radio.available()) {
            databuffer[index]=ch=(char) radio.read();
            if (index<36) index++;
			//console.putChar(ch);
			if ((ch=='\n')||(ch=='\r')) {
                databuffer[index]='\0';
                if (strncmp("CONNECT", databuffer,6)==0) {
                    if (index>7) {
                        for (index=0, n=8; index<3 && databuffer[n];) {
                            cid[index++]=databuffer[n++]; // if isdigit????
                        }
                        cid[index]='\0';
                    }
                    status=CONNECT;
                    gotResponse=true;
                    console.debug("Connect CID=%s\r\n",cid);
                } else if (strncmp("ERROR", databuffer,5)==0) {
                    gotResponse=true;
                    status=ERROR;
                    
                } else if (strncmp("DISASSOCIATED",databuffer,index)==0) {
                    gotResponse=true;
                    status=DISASSOCIATED;
                }
                index=0;
            }
 		}
		
	}
	digitalWrite(ORN_LED,HIGH);
    
    
    if (status!=CONNECT) {
        console.debug("toPachube NOT CONNECTED! (%d) Exiting\r\n", status);
        radio.discard();
        return(0);
    }
	//snprintf(databuffer, 36, "%d,%s",key,value);
	radio.printf("\033S%dHEAD / HTTP/1.1\r\n",atoi(cid),pachubeFeed);
	radio.printf("User-Agent: SuspectDevices/Baco-matic5000 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.15\r\n");
	radio.printf("Host: api.pachube.com\r\nAccept: */*\r\nConnection: close\r\n");
	radio.printf("X-PachubeApiKey: %s\r\n",pachubeKey);
	radio.printf("Content-Length: 0\r\n\r\n\r\n\033E",strlen(databuffer),databuffer);
	//console.debug("Sending Head / request\r\n");
    
    //
    // sent data then wait for an OK
    //
	while (!radio.gotLine()); 
	while (!(retval=isErrorOrOK(radio.line()))){
		//console.debug("%s\r\n",radio.line());
		while (!radio.gotLine()) {
			;	
		}		
	}
    
	if (retval<1) {
        console.debug("NOT OK! %s\r\n",radio.line());
        radio.discard();
        return(0);
    }
    //
    // should get an escaped stream followed by a disconnect
    //
	index=0;
    gotResponse=false;
	digitalWrite(ORN_LED,LOW);
    
    while (!radio.gotLine());
    sprintf(databuffer,"%c%c%c%c%cS%dHTTP",0x1b,0x4f,0x1b,0x4f,0x1b,atoi(cid));
    if(!strncmp(databuffer, radio.line(),strlen(databuffer)) ) {
        databuffer[0]=radio.line()[16];
        databuffer[1]=radio.line()[17];
        databuffer[2]=radio.line()[18];
        databuffer[3]='\0';
        console.debug("[%d] %s\r\n",retval=atoi(databuffer),radio.line()+7);
    }
    
    while (!radio.gotLine()); 
    if(!strncmp("Date:",radio.line(),5)) {
        //Date: Sun, 03 Jun 2012 01:22:34 GMT
        //AT+SETTIME=<dd/mm/yyyy>,<HH:MM:SS>
        parseDate(radio.line(),databuffer); 
        retval=setRadioDate(databuffer);
    }
    digitalWrite(ORN_LED,HIGH);
    
    return(retval);
}
void handleConsoleInput() {
    uint8_t retval;
	uint8_t index=0;
	uint8_t ch='0';
	SdFile finger;
    
    switch (console.keyValue()) {
        case _DIR_:
			console.printf("SOD:\r\n");
            root.ls(LS_DATE | LS_SIZE);
 			console.printf("EOD:\r\n");
			break;
        case _LSV_:
			console.printf("LSV:" BOM_VERSION "\r\n");
			break;
        case _TYP_:  
            typeFile(console.arguments());
            break;
        case _NSC_:  
			console.printf("SOD:\r\n");
			retval=networkScan();
			console.printf("EOD:\r\n");
            console.printf("\nDBG: found=%d\r\n",retval);
            break;
        case _NJN_:  
			//console.printf("SOD:\r\n");
			retval=networkJoin(console.arguments());
			//console.printf("EOD:\r\n");
            console.printf("\nDBG: joined=%s\r\n",retval?"TRUE":"FALSE");
            break;
        case _NPW_:  
			//console.printf("SOD:\r\n");
			retval=networkSetPassword(console.arguments());
			//console.printf("EOD:\r\n");
            console.printf("\nDBG: pwd set=%s\r\n",retval?"TRUE":"FALSE");
            break;
        case _NST_:  
			retval=networkStatus();
            console.printf("NST: %s\r\n",retval?"CONNECTED":"NOT CONNECTED");
            break;
		case _FMT_: // there really should be some REALLY do you mean this here but.....
			root.openRoot(&volume);
			if (finger.open(&root, ".", O_WRITE|O_READ)) {
				console.printf("\nDBG: Opened / \r\n");
				finger.rmRfStar();
			} else {
				console.printf("\nDBG: FAIL \r\n");
			}	
			break;
            
		case _TPT_:
			toPachube(1, console.arguments());
			break;
        case _TX2_:
            radio.printf("%s",console.arguments());
            index=0;
            // delay(1000);
            while (radio.available()) {
                inBuffer[index++]=ch=radio.read();
				if( index>= 99 || ((ch== '\n') || ch !='\r')) {
					inBuffer[index]='\0';
					console.puts(inBuffer);
					index=0; 
					delay(100);
				}
            } 
            inBuffer[index]='\0';
            console.puts(inBuffer);
			console.puts((char *) "\r\n");
            break;
// set to one to test output for.
#if 1
        case _TS1_: toPachube(0, console.arguments()); break;
        case _TS2_: toPachube(1, console.arguments()); break;
        case _TS3_: toPachube(2, console.arguments()); break;
        case _TS4_: toPachube(3, console.arguments()); break;
        case _TS5_: toPachube(4, console.arguments()); break;
        case _FAN_: toPachube(5, console.arguments()); break;
        case _CHL_: toPachube(6, console.arguments()); break;
        case _STC_: toPachube(7, console.arguments()); break;
#endif			

        case _PKY_:
            strncpy(pachubeKey, console.arguments(), MAX_PATCHUBE_KEY_LENGHT-1);
            stripcrlf(pachubeKey);
            break;
        case _PFD_:
            strncpy(pachubeFeed, console.arguments(), MAX_PATCHUBE_FEED_LENGHT-1);
            stripcrlf(pachubeFeed);
            break;
        case _SGT_ :
            readSettings();
            break;
        case _SSV_ :
            writeSettings();
            break;
            
        default:
            console.printf("DBG: forwarding (%s) to device\r\n",console.key());
            device.puts(console.line());
            //device.puts("\r\n");
            break;
    }
    
    
}
int toTheEthers(int key, char * value) {
    uint8_t n,index=0;
	int retval=0;
	char databuffer[36];
	char cid[4]="0";
    bool gotResponse=false;
    enum {CONNECT, ERROR, DISASSOCIATED} status=ERROR;//statii;
	uint8_t ch='0';

    if (!hasWifiModule) return retval;

	radio.discard();
	radio.printf("\r\n");
	radio.discard();
	radio.printf("\r\nAT+NCTCP=198.202.31.182,80\r\n");
	while (!radio.available()); // and some timeout.
    
	// ERROR
    // CONNECT <CID>
    // DISASSOCIATED
 	digitalWrite(ORN_LED,LOW);
    
	while (!gotResponse){ // this needs to catch errors.
		while (radio.available()) {
            databuffer[index]=ch=(char) radio.read();
            if (index<36) index++;
			//console.putChar(ch);
			if ((ch=='\n')||(ch=='\r')) {
                databuffer[index]='\0';
                if (strncmp("CONNECT", databuffer,6)==0) {
                    if (index>7) {
                        for (index=0, n=8; index<3 && databuffer[n];) {
                            cid[index++]=databuffer[n++]; // if isdigit????
                        }
                        cid[index]='\0';
                    }
                    status=CONNECT;
                    gotResponse=true;
                    //console.printf("DBG: Connect CID=%s\r\n",cid);
                } else if (strncmp("ERROR", databuffer,5)==0) {
                    gotResponse=true;
                    status=ERROR;
                    
                } else if (strncmp("NOT ASSOCIATED",databuffer,13)==0) {
                    gotResponse=true;
                    status=DISASSOCIATED;
                } else if (strncmp("DISASSOCIATED",databuffer,13)==0) {
                        gotResponse=true;
                        status=DISASSOCIATED;
                }
                index=0;
            }
 		}
		
	}
	digitalWrite(ORN_LED,HIGH);
    
    if (status!=CONNECT) {
        console.printf("DBG: toPachube() NOT CONNECTED! (%d) Exiting\r\n", status);
        radio.discard();
       return(0);
     }
	//snprintf(databuffer, 36, "%d,%s",key,value);
	
    radio.printf("\033S%dGET /art2013/swls/&state=%s HTTP/1.1\r\n",atoi(cid),value?"ON" : "OFF");
	//radio.printf("\033S%dPUT /art2013/swls/%s.csv HTTP/1.1\r\n",atoi(cid));
	radio.printf("User-Agent: SuspectDevices/Baco-matic5000 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.15\r\n");
	radio.printf("Host: suspectdevices.com\r\nAccept: */*\r\nConnection: close\r\n");
	radio.printf("X-PachubeApiKey: %s\r\n\r\n",pachubeKey);
	//radio.printf("Content-Length: %d\r\n\r\n%s\r\n\033E",strlen(databuffer),databuffer);
	//console.printf("DBG: Sending to feed %s: (%d)%s \r\n",pachubeFeed,strlen(databuffer),databuffer);
    
    //
    // sent data, wait for an OK
    //
	while (!radio.gotLine()); 
	while (!(retval=isErrorOrOK(radio.line()))){
		//console.printf("DBG: %s\r\n",radio.line());
		while (!radio.gotLine()) {
			;	
		}		
	}
    
	if (retval<1) {
        console.printf("DBG: NOT OK! %s\r\n",radio.line());
        radio.discard();
        return(0);
    }
    //
    // should get an escaped stream followed by a disconnect
    //
	index=0;
    gotResponse=false;
	digitalWrite(ORN_LED,LOW);
    
    while (!radio.gotLine());
    sprintf(databuffer,"%c%c%c%c%cS%dHTTP",0x1b,0x4f,0x1b,0x4f,0x1b,atoi(cid)); // the double escapeing I dont get.
    if(!strncmp(databuffer, radio.line(),strlen(databuffer)) ) {
        databuffer[0]=radio.line()[16];
        databuffer[1]=radio.line()[17];
        databuffer[2]=radio.line()[18];
        databuffer[3]='\0';
        //console.printf("DBG:[%d] %s\r\n",retval=atoi(databuffer),radio.line()+7);
    }
    while (!radio.gotLine()); 
    radio.discard();
    delay(500); // this is not so good.
	digitalWrite(ORN_LED,HIGH);
    return(retval);
}