#include "buffedit.h"





void buffEdInit( buffEdProc_t * this ) {
 
  this->buff    = strdup("");
  this->cursor  = 0;
  this->maxlen  = 1024;
    
}



void buffEdFini(buffEdProc_t * this ) { 
  free(this->buff);
  this->buff = NULL;
}




void buffEdTakeStroke( buffEdProc_t * this , buffEdEvent_t cmd,  char c) {

  switch (cmd) {
    
    case EV_CRS_FWD:                                                                                     // move cursor forward
      if (this->cursor < strlen(this->buff) ) this->cursor++;
    break;
    
    case EV_CRS_BCK:                                                                                     // move cursor back 
      if (this->cursor != 0) this->cursor--;
    break;
    
    case EV_CRS_START:                                                                                   // move cursor to start of buffer           
       this->cursor = 0;
    break;  
    
    case EV_CRS_END:                                                                                     // move cursor to end of buffer
       this->cursor = strlen(this->buff);
    break; 
    
    case EV_OVERWR:                                                                                      // overwrite character at cursor and move right
      this->buff[this->cursor] = c;
      if (this->cursor < strlen(this->buff)) this->cursor++;
    break;
    
    case EV_INSERT:                                                                                       // insert character to left of cursor
      //memmove(&(this->buff[(this->cursor)+1]), &(this->buff[this->cursor]), this->buffLen - this->cursor -1);    
      //this->buff[this->cursor] = c;
      if (strlen(this->buff) > this->maxlen) return; // nope.
      astrinsc  ( &this->buff,  c,  this->cursor);
      if (this->cursor < strlen(this->buff)) this->cursor++;
    break;
    
    case EV_DELETE:                                                                                        // remove on the cursor, and move contents left
      if (this->cursor == strlen(this->buff)) return;
      memmove( &(this->buff[this->cursor]), &(this->buff[this->cursor+1]), strlen(this->buff) - this->cursor );
    break;
    
    case EV_BACKSP:                                                                                        // remove left of the cursor, and move contents left
      if (this->cursor == 0) return;
      memmove( &(this->buff[this->cursor-1]), &(this->buff[this->cursor]), strlen(this->buff) - this->cursor+1 );
      if (this->cursor != 0) this->cursor--;
    break;
      
  }

}

