/*
Copyright 2003/2004, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
 
- Neither the name of Freie Universitaet Berlin (FUB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

This software is provided by FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

This implementation was developed by the CST group at the FUB.
Contributors: Bjoern Lichtblau

For documentation and questions please use the web site
http://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2003/2004/2005
*/

#include "ScatterWeb.System.h"

UINT8* bufwriter_dest;

static const UINT8 decimal_table[16][3] = { 
    "00", "06", "13", "19", "25", "31", "38", "44", 
    "50", "56", "63", "69", "75", "81", "88", "94" };
    
void writeString(fp_char_t writer, const UINT8* str){
    UINT16 i = 0;
    while(str[i]!='\0') writer(str[i++]);
}

void bufwriter(UINT8 c){
  *bufwriter_dest =  c;
  bufwriter_dest++;    
}

int String_writeUInt(fp_char_t writer, UINT16 number, UINT16 length){
  const UINT8 pots = 5;
  const UINT16 pot[] = { 1, 10, 100, 1000, 10000 };
  UINT8 pos = 0; // position in output out[pos]
  UINT8 t;       // temporary to hold the digit
  UINT8 j;       // loop counter
  if(number==0){
    if(length==0) length++;
    for(j=0; j<length; j++) writer('0');
    return 1;
  }
  for(j=pots; j>0; j--){
    t = 0x30;
    while(number >= pot[j-1]){ number -= pot[j-1]; t++; }   
    if( (t>0x30) || (pos>0) || (j<=length) ){ writer(t); pos++; }   
  }
  return pos;     
}

int String_writeULongInt(fp_char_t writer, UINT32 number, UINT16 length){
  const UINT8 pots = 10;
  const UINT32 pot[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 
                                    10000000, 100000000, 1000000000 };
  UINT8 pos = 0; // position in output out[pos]
  UINT8 t;       // temporary to hold the digit
  UINT8 j;       // loop counter
  if(number==0){
    if(length==0) length=1;
    for(j=0; j<length; j++) writer('0');
    return 1;
  }
  for(j=pots; j>0; j--){
    t = 0x30;
    while(number >= pot[j-1]){ number -= pot[j-1]; t++; }   
    if( (t>0x30) || (pos>0) || (j<=length) ) { writer(t); pos++; }   
  }
  return pos;     
}

bool String_writeTemperature(fp_char_t writer, temp_t temp){
  if(temp.u & 0x8000){ writer('-'); temp.u = (temp.u ^ 0xFFFF) + 1; }
  else                 writer('+');
  String_writeUInt(writer, (temp.u & 0x7F80) >> 7, 0 );
  writer('.');
  writeString(writer, decimal_table[ (temp.u & 0x0078) >> 3] );
  return True;
}

UINT16 String_parseInt(const UINT8* c, UINT8** ptr){
  UINT16 i = 0;
  while((*c >= 0x30) && (*c <= 0x39)){
    i = i * 10;
    i = i + (*c - 0x30);
    c++;
  }
  if(ptr!=NULL) *(ptr) = (UINT8*) c;
  return i;  
}   	    
	    
UINT32 String_parseLongInt(const UINT8* c, UINT8** ptr){
  UINT32 i = 0;
  while((*c >= 0x30) && (*c <= 0x39)){
    i = i * 10;
    i = i + (*c - 0x30);
    c++;
  }
  if(ptr!=NULL) *(ptr) = (UINT8*) c;
  return i;  
}   	    

bool String_fromByteToHex(UINT8 b, UINT8* cs){
  cs[0] = "0123456789ABCDEF" [ (( b & 0xF0) >> 4) ];    
  cs[1] = "0123456789ABCDEF" [ ( b & 0x0F) ];     
  return True;
}

UINT8 String_fromHexToByte(const UINT8* cs){
  UINT8 b = 0;
  if((cs[0] >= '0') && (cs[0] <= '9')){
      b = (cs[0] - '0') << 4;
  } else { // expects cs[0] to be A-F
      b = (cs[0] - 'A' + 10) << 4;      
  }
  if((cs[1] >= '0') && (cs[1] <= '9')){
      b += (cs[1] - '0');
  } else { // expects cs[1] to be A-F
      b += (cs[1] - 'A' + 10);      
  }
  return b; 
}

bool String_abstractWrite(fp_char_t writer, const char *fmt, va_list argp){
  const char *p;
  // variables for va_arg parsing
  UINT16 i;
  UINT32 l;
  UINT8 c;
  UINT8* str;
  // temp buffer
  UINT8 tmpstr[4];
  UINT16 tmpi;
  for(p = fmt; *p != '\0'; p++){
    if(*p != '%'){ writer(*p); continue; }
    switch(*++p){
    	case 'c': c = va_arg(argp, UINT16); writer(c); break; 
    	case 'i': i = va_arg(argp, UINT16);  String_writeUInt(writer, i, 0); break;
    	case 'l': l = va_arg(argp, UINT32);  String_writeULongInt(writer, l, 0); break;
    	case 'b': c = va_arg(argp, UINT16);
                String_fromByteToHex(c, tmpstr); 
                writer(tmpstr[0]);
                writer(tmpstr[1]); 
                break;
    	case 'x': i = va_arg(argp, UINT16); 
                String_fromByteToHex(i>>8, tmpstr);
                String_fromByteToHex(i, tmpstr+2);
                writer(tmpstr[0]);
                writer(tmpstr[1]); 
                writer(tmpstr[2]);
                writer(tmpstr[3]); 
                break;
    	case 's': str = va_arg(argp, UINT8*); 
                tmpi=0;
                while(str[tmpi]!='\0') writer(str[tmpi++]);
                break;
      case 't': Time_writeTime(writer, va_arg(argp, btime_t*));
                break;
      case 'T': String_writeTemperature(writer, va_arg(argp, temp_t));
                break;
      case 'z': { btime_t btime;
                  time_t* time = va_arg(argp, time_t*);
                  Time_convertSystemTime(time, &btime);
                  Time_writeTime(writer, &btime);
                  break;
                }
      case 'e': { sdata_t* data = va_arg(argp, sdata_t*);
                  btime_t btime;
                  Time_convertSystemTime(&(data->timeStamp), &btime);
                  String_writeUInt(writer, data->id, 0);
                  writer(' ');
                  writer('['); Time_writeTime(writer, &btime); writer(']'); writer(' ');
                  switch(data->sensor){
                    case SENSOR_VIBRATION:    if(data->value) writeString(writer, "VIB DETECT");
                                              else            writeString(writer, "VIB SILENT");
                                              break;
                    case SENSOR_MOVEMENT:     if(data->value) writeString(writer, "PIR DETECT");
                                              else            writeString(writer, "PIR SILENT");
                                              break;
                    case SENSOR_BUTTON:       if(data->value) writeString(writer, "BUTTON PRESSED");
                                              else              writeString(writer, "BUTTON RELEASED");
                                              break;
                    case SENSOR_MICROPHONE:   if(data->value) writeString(writer, "MIC LOUD");
                                              else            writeString(writer, "MIC SILENT");
                                              break;
                    case SENSOR_VOLTAGE:      writeString(writer, "[Bat:");
                                              String_writeUInt(writer, data->value, 0);
                                              writeString(writer, "]");
                                              break;
                    case SENSOR_TEMPERATURE:    writeString(writer, "[Tmp:");
                                                String_writeTemperature(writer, *((temp_t*)&data->value) );
                                                writeString(writer, "]");
                                                break;
                    case SENSOR_RC5:    writeString(writer, "[RC5: C(");
                                        String_writeUInt(writer, data->value & 0x003F, 0);
                                        writeString(writer, ")A(");
                                        String_writeUInt(writer, (data->value & 0x07C0) >> 6, 0);
                                        writeString(writer, ")]");
                                        break;
                    default: writeString(writer, "???"); break;
                  }
                }
                break;
    	case '%': writer('%'); break;
    	default: writer('?');
    	}
  }
  return True;
}

bool String_write(UINT8* dest, const char *fmt, ...){
  va_list argp;
  va_start(argp, fmt);
  bufwriter_dest = dest;
  String_abstractWrite(bufwriter, fmt, argp);  
  va_end(argp);
  *bufwriter_dest = '\0';
  return True;  
}
