
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "gdecl.h"   // Global declarations
//#include "string.h"
#include "myedit.h"
#include "curses.h"
#include <ncurses.h>

/* ************************************* Edit code ***************************************** */

int eb_init(edbuf *ed, WINDOW *orig,
			int nlines, int ncols, int begin_y, int begin_x)
{
	if (sl_init(&ed->list))
		return -1;
        	
	ed->win = orig;
	if (!ed->win)
		return -1;

	if ((nlines == 0) && (ncols == 0)
		&& (begin_y == 0) && (begin_x == 0)) {
		getbegyx(ed->win, ed->s_y0, ed->s_x0);
		getmaxyx(ed->win, ed->s_height, ed->s_width);
	} else {
		ed->s_x0 = begin_x;    // Physical start x of the edit box
		ed->s_y0 = begin_y;
		ed->s_width = ncols;        // max cols,lines
		ed->s_height = nlines;
	}

	ed->sel_x0 = -1;
	ed->sel_x1 = -1;
	ed->sel_y0 = -1;
	ed->sel_y1 = -1;

        ed->col = 1;
	ed->row = 1;
	ed->x0 = ed->s_x0 + 1;
	ed->y0 = ed->s_y0 + 1;
	ed->width = ed->s_width - 2;  // max height
	ed->height = ed->s_height - 2;
	ed->linechanged = 0;
	ed->tabwidth = 5; ///////////////////////////////////******** do some generalization
   ed->startline=0;  // The first line in view
   ed->sl_startcol=0;
   ed->sl_endcol=0;
   ed->endline=0;     // The last line in view
   ed->el_startcol=0;
   ed->el_endcol=0;
	//wrefresh(ed->win);

	ed->dsimage = newpad(ed->height, EB_MAXCOLS);
	if (!ed->dsimage)
		return -1;
	keypad(ed->dsimage, TRUE); // We read and write to ds image
        wmove(ed->dsimage,0,0);

        ed->scrimage = stdscr;


        werase(ed->scrimage);
        werase(ed->dsimage);
	eb_setattrs(ed, A_NORMAL, A_STANDOUT, A_NORMAL|A_STANDOUT );

	ed->filename = NULL;
	ed->shortname = "Untitled";
	ed->modified = 0;
	
	eb_redraw(ed);
	doupdate();
	
	return 0;               // Should be return 0
}

void eb_cleanup(edbuf *ed)
{
	sl_cleanup(&ed->list);

	if (ed->dsimage)
		delwin(ed->dsimage);

         if (ed->filename)
		free(ed->filename);

}
void eb_clear(edbuf *ed)
{
	sl_flush(&ed->list);
	eb_setfilename(ed, NULL);
	werase(ed->scrimage);
   werase(ed->dsimage);
   ed->startline=0;  // The first line in view
   ed->sl_startcol=0;
   ed->sl_endcol=0;
   ed->endline=0;     // The last line in view
   ed->el_startcol=0;
   ed->el_endcol=0;
   eb_putcurs(ed,1,1);
   ed->linechanged = 0;
   ed->modified = 0;
   eb_redraw(ed);
}

int eb_keypress(edbuf *ed, chtype ch)
{
	int x, y;
   	char buf[512];
   	
	switch(ch)
	 {

	case KEY_UP:
		eb_movecurs(ed, -1, 0);
		break;
	case KEY_DOWN:
		eb_movecurs(ed, 1, 0);
		break;
	case KEY_LEFT:
		eb_movecurs(ed, 0, -1);
		break;
	case KEY_RIGHT:
		eb_movecurs(ed, 0, 1);
		break;
	case KEY_HOME:
		eb_getcurs(ed, &y, &x);
		eb_putcurs(ed, y, 0);
		break;
	case KEY_END:{
		eb_getcurs(ed, &y, &x);
		
			if((ed->list.st_len[ed->list_y]-(ed->list_x))> RIGHT-LEFT+1)
			      		eb_putcurs(ed,y,RIGHT-LEFT+1);
			else
			    eb_putcurs(ed,y,(ed->list.st_len[ed->list_y] +1 ));
		}	
		break;
	case KEY_NPAGE: {                  // Page down

                         ed->startline=ed->endline;
                         ed->sl_startcol=ed->el_startcol;
                         update_dsimage(ed);
                         map_dsto_scrimage(ed);
                         eb_putcurs(ed,1,1);
                         }
                        break;                    ////////// Prefresh here????????????

	case KEY_PPAGE:
	         	{
		        int i=1; 		
		        // eb_getcurs(ed, &y, &x);
	
	                while(i<BOTTOM-TOP+2 && ed->startline != 0)
	                 {
	                   eb_movecurs(ed,-1,0);
	                   i++;
	                 }
	
		        }
		        break;
	
	
	case KEY_DC:
	             if( ( ed->list_y==ed->list.count-1) && (ed->list_x==ed->list.st_len[ed->list_y]) )
	                   break;       // Trying to delete the last char +1 of the last line.
	             eb_movecurs(ed,0,1);
	
	                      // No break here... continue to back space.
	
	case KEY_BACKSPACE:
             {

              if((ed->list_x==0) && (ed->list_y==0) ) // Start of file
                            break;
             else
               {
                 if(ed->list_x==0)  // Trying to back space on the first char of the line
                   {
                     eb_movecurs(ed,0,-1);
                     sl_strappend(&ed->list,ed->list_y,(ed->list.items[ed->list_y+1]) );
                    //sl_strappend(&ed->list,ed->list_y,ed->list.items[(ed->list_y)+1]);
                   //Ok. Since list_x was 0, the eb_move will decrease
                  //list_y by one. This is done so that startline, startcol
                 //the ed row ,col  is taken care of by the eb_move
                //and now list_y+1 is the one to be concatenated with list_y
               //(before, the target was: "concatenate list_y TO list_y-1;")

                    sl_delete(&ed->list,(ed->list_y+1));
                    update_dsimage(ed);  // update really really necessary
                   }
                 else
                   {    update_dsimage(ed);
                        eb_movecurs(ed,0,-1);

                        wmove(ed->dsimage,ed->list_y-ed->startline,ed->list_x);
                                     // list_y-startline because range of dsimage pad is 0 to LINES-2 max

                        wdelch(ed->dsimage);

                        eb_update(ed,KEY_BACKSPACE);
                    }
                 ed->linechanged = 1;
		 ed->modified = 1;
                }                                      // end else list_x ==0

            eb_update(ed,KEY_BACKSPACE);
            map_dsto_scrimage(ed);

            wnoutrefresh(ed->scrimage);

            ed->linechanged = 0;
	    ed->modified = 1;
	    }
       	break;

	case '\n': {
                int i;
		char buff[EB_MAXCOLS + 1];
                char buff2[EB_MAXCOLS + 1];




                wmove(ed->dsimage,ed->list_y-ed->startline,ed->list_x);
		if ((winstr(ed->dsimage, buff) == ERR))
			return -1;
                		
		werase(ed->dsimage);
		wrefresh(ed->dsimage);
		
		ed->linechanged = 1;
	        if ((ed->list_y + 1) < ed->list.count)
			sl_insert(&ed->list, ed->list_y + 1, "");
		else
		        sl_add(&ed->list, "");
		
			                         // Removing buf's trailing white space
		buff[(ed->list.st_len[ed->list_y])-(ed->list_x)]='\0';
		
                for(i=0;  i<( (ed->list.st_len[ed->list_y]) - strlen(buff) ); i++)
		                   buff2[i]=ed->list.items[ed->list_y][i];
		
		buff2[i]='\0';
		
		sl_strassign(&ed->list, (ed->list_y), buff2);	
		sl_strassign(&ed->list, (ed->list_y+1), buff);	
		update_dsimage(ed);
	                       	
		eb_movecurs(ed,1,0);
		update_dsimage(ed);
		
		map_dsto_scrimage(ed);
		ed->modified = 1;
                ed->linechanged=1;

	}
	break;
	case KEY_F(8):

      	// for now, complete refresh:
      			{
			      update_dsimage(ed);
			      map_dsto_scrimage(ed);
			      wnoutrefresh(ed->scrimage);
			      wnoutrefresh(stdscr);
      			      doupdate();
       			}
     			 break;

	case '\t':
			{       	
				int i;
		
				if(ed->list.count==0)
		  		sl_add(&ed->list,"");
				for (i = 0; i < ed->tabwidth; i++)
					winsch(ed->dsimage, ' ');
		
				eb_movecurs(ed, 0, ed->tabwidth);
				ed->linechanged = 1;
				ed->modified = 1;
				map_dsto_scrimage(ed);
				wnoutrefresh(stdscr);
			}
			break;

	default:
		if (isprint(ch) )
		 {
		        char *buf[2];
		        buf[0]=ch;
		        buf[1]='\0';
		        if(ed->list.count==0)
		                      sl_add(&ed->list,"");
		
		        mvwinsch(ed->dsimage,(ed->list_y-ed->startline),ed->list_x,ch);
			ed->linechanged = 1;
			eb_update(ed,ch);
			eb_movecurs(ed, 0,1);
			ed->modified = 1;
		}
		break;
    }// End switch

	return 0;
}

void eb_getcurs(edbuf *ed, int *y, int *x)
{
    *y=ed->row;
    *x=ed->col;
	
}

int eb_putcurs(edbuf *ed, int ly, int lx)     // Logical x,y
 {
   int ty=ly,tx=lx;
   int phy=physical_y(ly);   // These are requested so,
   int phx=physical_x(lx);   // we check if they equal to limits
   int nlines;
   chtype junk;


  if((phy <= BOTTOM) && (phy >=TOP)  )
    {
       syncmove(ed,ly,lx);
    }     /// End first if
   else
     {
       if(phy < TOP)
        {                       // Requested is above the view
                                // swap in a certain no. of files
           nlines=TOP-phy;     // Usually nlines =1 .
           bringfromtop(ed,nlines);  // also set the cursor positions there
           eb_putcurs(ed,ed->row,ed->col);

         }

       else if(phy > BOTTOM)
         {
            nlines = phy-BOTTOM;

            bringfromdown(ed,nlines);

            eb_putcurs(ed,ed->row,1);

         }
     }


   return 0;
}           // End put_cursor


int eb_movecurs(edbuf *ed, int dy,int dx)
  {
    int x,y;
    y= ed->row;   // The present logical coordinates
    x= ed->col;


    x=x+dx;
    y=y+dy;

   // Now x,y are the required (target) logical coordinates

                                   // Now if LEFT key is pressed when we are on col 1
                              // x is 0. So we need to translate x  to a proper position in y--
    if(  physical_x(x)< LEFT ) // The first if means if ed->list_x is beyond the right margin,
    {                       // if it is, it implies that the line on
        y--;

        if( (   ( ((ed->list_x+1) % (RIGHT-LEFT+1)) >= 1 ) ) && ed->list_x!=0)
                   x=(RIGHT-LEFT+1);
        else
         if(ed->list_y-1>=0)
                   x=(ed->list.st_len[ed->list_y-1]) % (RIGHT-LEFT+1)+1;

     }
   if( ((physical_y(y)>=BOTTOM)  &&    (physical_x(x)  > RIGHT ) )  || (physical_x(x) > RIGHT))
     {
       y++;          // The cursor is requesting beyond the last char .
       x=1;          // Next logical co ordinate are calced here.
    }               //  el_endcol is kept track when endline is written.

    eb_putcurs(ed,y,x);

    return (1);
  }

int eb_redraw(edbuf *ed)
{
	/* draw the bounding box */
	wattrset(ed->win, ed->attr);
	curs_box(ed->win, ed->s_y0, ed->s_x0, ed->s_height, ed->s_width);

	/* draw the title */
	wattrset(ed->win, ed->attr_title );
	wmove(ed->win, ed->s_y0, ed->s_x0 + ed->width / 2
		  - (strlen(ed->shortname) + 2) / 2);
	wprintw(ed->win, " %s ", ed->shortname);
        wattrset(ed->win, ed->attr);
	 mvwaddch(ed->win,TOP,0,ACS_DIAMOND);
        // Top margin

        mvwaddch(ed->win,BOTTOM,0,ACS_DIAMOND);
        // BOTTOM

        mvwaddch(ed->win,LINES-2,LEFT,ACS_DIAMOND);
        mvwaddch(ed->win,LINES-2,RIGHT,ACS_DIAMOND);
        	
	return (eb_refresh(ed));
}


int eb_refresh(edbuf *ed)
{
	
	wnoutrefresh(ed->win);

	move(physical_y(ed->row),physical_x(ed->col));
	return wnoutrefresh(ed->scrimage);
}

int eb_update(edbuf *ed,chtype ch)
{
	if (ed->linechanged)
	{ 	
	  if ((ed->el_endcol==EB_MAXCOLS) ) 	
		  beep();

	  eb_dsimagetods(ed, (ed->list_y-ed->startline),1,ch);
                            // list_y-startline because range of dsimage pad is 0 to LINES-2 max
	   ed->linechanged = 0;
        	
	}
	return 0;
}
int eb_dsimagetods(edbuf *ed, int imageline0,int linecount,chtype ch)
{
	static char buf[EB_MAXCOLS + 1];
	int i, j;

	for (i = 0; i < linecount; i++)
           {    		
	        wmove(ed->dsimage, imageline0 + i, 0);
             	if (winstr(ed->dsimage, buf) == ERR)
			return -1;

		/* strip the trailing whitespace */

		for (j = EB_MAXCOLS - 1; j >= 0; j--)
		    {
			if ((buf[j] != ' ') && (buf[j] != '\t'))
			 {
				if(ch==' ')
                		    buf[j + 2] = '\0';  //If the last char is space, spare it.
				else
				    buf[j+1]= '\0';
				break;
	         	}
	            }
		if (j < 0)
			buf[0] = '\0';

	sl_strassign(&ed->list, (ed->startline+(imageline0 + i)), buf);
   }

return 0;
}

int str_assign(char **pstr, char *text)
{
	char *p;
	
	if (!text)
	{
		free(*pstr);
		*pstr = NULL;
		return 0;
	}

	p = realloc(*pstr, strlen(text) + 1);
	if (!p)
		return -1;
	*pstr = p;
	strcpy(p, text);
	return 0;
}


int eb_setfilename(edbuf *ed, char *filename)
{
	char *c;

	str_assign(&(ed->filename), filename);

	if (filename==NULL)
	{
		  ed->shortname="Untitled";
		  return 0;
	}
        c = strrchr(filename, '/');
        ed->shortname = (char **) malloc(sizeof(char) * (strlen(filename) +1) );
	if (c)
	   strcpy(ed->shortname, ++c);
	else
	   strcpy(ed->shortname, filename);
	return 0;
}

void eb_setattrs(edbuf *ed,chtype attr, chtype attr_sel, chtype attr_title)
{
	ed->attr = attr;
	wbkgd(ed->win, ' ' | attr);
	wbkgd(ed->scrimage, ' ' | attr);
        wbkgd(ed->dsimage, ' ' | attr);
	wattrset(ed->dsimage, attr);
        wattrset(ed->scrimage, attr);

	ed->attr_sel = attr_sel;

	ed->attr_title |= attr_title;
}

/*
 * Returns 1 if the character at buffer coords
 * by, bx is selected, 0 otherwise.
 */

int eb_issel(edbuf *ed, int by, int bx)
{
	int res = 0;

	if(ed->sel_x0 == -1)
	  return 0 ;
	
	if ((by > ed->sel_y0) && (by < ed->sel_y1))
		return 1;
	if( (by==ed->sel_y0) && (bx >= ed->sel_x0) && (bx<=ed->sel_x1))
	        return 1;
	else
	  return 0;
	   /*       	
	
	if ((by < ed->sel_y0) || (by > ed->sel_y1))
		return 0;

	if ((by > ed->sel_y0) && (by < ed->sel_y1))
		return 1;

	if ((by == ed->sel_y0) && (bx >= ed->sel_x0))
		res = 1;

	if ((by == ed->sel_y1) && (bx <= ed->sel_x1))
		return res;
                  */
	return 0;
}

/* as sl_fromstream, but replaces tabs with spaces */
int eb_fromstream(edbuf *ed, FILE *f)
{
	char buf[BUFSIZ], c;
	int pos = 0;

	sl_flush(&ed->list);

	while (fread(&c, 1, 1, f) == 1)
	{
		if (pos >= EB_MAXCOLS)
			return -1;

		switch(c)
		{
		
		case '\r':     // For now, no handling of '\r'
		
		              break;
		
		case '\n': /* eol, add line to list */
			buf[pos] = '\0';
			if (sl_add(&ed->list, buf))
				return -1;
			pos = 0;
			buf[pos] = '\0';
			break;

		case '\t': /* tabstop, replace with spaces */
			/* check for buffer overflow */
			if ((pos + ed->tabwidth) > EB_MAXCOLS)
				return -1;

			memset(buf + pos, ' ', ed->tabwidth);
			pos += ed->tabwidth;
			buf[pos] = '\0';
			break;

		case '\0': /* null byte, binary file, error */
			return 13;

		default: /* default, add char to buffer */
			buf[pos++] = c;
			break;
		}
	}
	if (pos > 0)
	{
		buf[pos] = '\0';
		sl_add(&ed->list, buf);
	}

   ed->modified = 0;
   update_dsimage(ed);
   map_dsto_scrimage(ed);
   eb_putcurs(ed, 1,1);

	return 0;
}

inline int eb_textwidth(edbuf *ed, char *text)
{
	return strlen(text);
}

int bringfromtop(edbuf *ed, int nlines)
 {
   int target=0;

   while(target != nlines)
    {
      if((ed->startline ==0) && ( (ed->sl_startcol)<=(RIGHT-LEFT) )  )
        {     break;   beep(); } // At the top of file so nothing more to display

      else
        {
          if(ed->sl_startcol < (RIGHT-LEFT+1)  )   // if equal then startcol is in next logical line
           {
               ed->startline--;
               if(ed->list.st_len[ed->startline] > (RIGHT-LEFT+1))
                ed->sl_startcol =
                ( ed->list.st_len[ed->startline]-((ed->list.st_len[ed->startline])%(RIGHT-LEFT+1)));
                   // ie bring into view last part of above line
               else
                  ed->sl_startcol =  0; //(ed->list.st_len[ed->startline]-1);
                            // ie the new stline is less than viewable chars
                           // new start col is 0;
            }  //endif

      else        // means ed->sl_startcol >= RIGHT-LEFT +1
          ed->sl_startcol= ed->sl_startcol-(RIGHT-LEFT+1);

       } // end first if .. else

     target++;
   }   // end while;

   update_dsimage(ed);
     // Put into data structure buffer pad, list lines from startline
     // until they fit into (BOTTOM-TOP+1) or runs out of file.

   map_dsto_scrimage(ed);
     // Put startline,sl_startcol at physical_y(1),physical_x(1) and so on
     //until BOTTOM is reached then keep track of endline, el_startcol & el_endcol
     // till  endline<list.count  , sl_endcol;

   syncmove(ed,(ed->row),(ed->col));
  return 0;
 }


int bringfromdown(edbuf *ed,int nlines)
{
  int target=0;

  while(target != nlines)
   {
    if(ed->endline < ed->list.count)
      {
          //if(ed->el_endcol <= ed->list.st_len[ed->endline])  //////// why is this condition?????? think.
            {
               if((ed->startline ==ed->list.count-1) && (ed->sl_startcol<=(RIGHT-LEFT)) )
                 {
                   beep();  // At the end of file so nothing more to display
                   break;      // Error. could give seg faults
                  }
               else
                {

                   if( ( ( ed->sl_endcol+1)>=(ed->list.st_len[ed->startline]-1) ) ||
                     (ed->list.st_len[ed->startline]==0) )   //1 if(( ed->sl_endcol)<= (RIGHT-LEFT)  )
                            					//2 no of chars
                     {                                      // 3 zero length ie blankline \n
                          ed->startline++;
                          ed->sl_startcol=0;
                      }

                  else
                    ed->sl_startcol =ed->sl_endcol+1;
                          // ie the new stline is more than viewable chars
                                     // new start col is end+1;
                 } //end else
            }  //endif

        // target++;
        }
     target++;
   }   // end while;

    update_dsimage(ed);
    map_dsto_scrimage(ed) ;

  return 0;
  }

int syncmove(edbuf *ed,int ly,int lx)     // Logical x and logical y
 {
                             // The requested location is definitely within( This has to be ensured )
      ed->row=1;              // The current view, so we try to
      ed->col=1;              // Synchronously reach logical_y,x from start view

      ed->list_y =ed->startline;
      ed->list_x =ed->sl_startcol;  // Start line start col


      while( ((ed->row < ly) ||  (ed->col < lx) )  && (ed->list.count!=0) )
       {
           if((ed->row==ly+1 && ed->col==1))
             break;
           if (ed->row == 1)
              ed->sl_endcol=ed->list_x;

           if(  ((ed->list_x+1) == ed->list.st_len[ed->list_y]) &&
               (((ed->row) == ly) && (ed->col+1)== lx) && ((physical_x(ed->col+1))<=RIGHT))
                {
                  ed->col++;
                  ed->list_x++;
                  break;            // Request is the end of the "LINE"
                }

           if((ed->list_x+1) <= (ed->list.st_len[ed->list_y])  ) // <= may be in error
               {
                   ed->list_x++;                // less than coz, listx starts from 0
                   if((physical_x(ed->col+1)<=RIGHT)  && ((ed->col+1)<=(RIGHT-LEFT+1)) )
                     ed->col++;
                   else
                      {

                         ed->row++;
                         ed->col=1;
                         if(physical_y(ed->row)>BOTTOM)
                          {
                           ed->row--;
                            break;
                          }
                       }
                }
             else
               {
                  if(((ed->list_y)+1) != ed->list.count)  // Means next listy is not eof
              	     {
                        	ed->list_y=ed->list_y+1; // list.count is the total no . of lines.
                 		ed->list_x=0;
                 		ed->row++;
                 		ed->col=1;

               		if(physical_y(ed->row)>BOTTOM)
                         {
                           ed->row--;
                           break;
                         }
                  }
                  else
                    break;       // End of file so stop;

               }

         }            // End while

         map_dsto_scrimage(ed);
         wnoutrefresh(ed->scrimage);
         wattrset(stdscr,ed->attr);

         wmove(stdscr,physical_y(ed->row),physical_x(ed->col));
         wmove(ed->dsimage,(ed->list_y-ed->startline),(ed->list_x));
             // list_y-startline, because, startline is the line no. of the
          // file where as  location corresponding to list_y
          // ranges from 0==start line to BOTTOM-TOP+1;

         wnoutrefresh(ed->scrimage);

     return 0;
}

/* ****************************** Buffer operation code ******************* */

int update_dsimage(edbuf *ed)
 {
   int count=0,n,i=0;

   n=ed->startline;
   werase(ed->dsimage);
   wrefresh(ed->dsimage);
      while(n < ed->list.count)
    {
       if(i <= (BOTTOM-TOP+1))
        {
         wmove(ed->dsimage,i,0);
         wclrtoeol(ed->dsimage);
         mvwprintw(ed->dsimage,i,0,"%s",ed->list.items[n]);
        }
       else
         break;
       i++;
       n++;
    }
    wrefresh(ed->dsimage);
   return 1;
 }

//map_dsto_scrimage();
     // Put startline,sl_startcol at physical_y(1),physical_x(1) and so on
     //until BOTTOM is reached then keep track of endline, el_startcol & el_endcol
     // till  endline<list.count  , sl_endcol;


int map_dsto_scrimage(edbuf *ed)
 {
   int erow=1,ecol=1,k,p;             // Edit box row, col
   int i=ed->startline;
   int j=ed->sl_startcol;  // Prev j, prev i
   char c;
   int prev_el=ed->startline,prev_eecol=j;    // prev endline , end col;
   ed->el_startcol=j;
   ed->el_endcol=j;
   curs_set(0);
   werase(stdscr);
   wnoutrefresh(stdscr);
   while((physical_y(erow)<=BOTTOM)  && (i<ed->list.count) )
    {

      c=ed->list.items[i][j];

      if(j==0 )
          {
           wmove(ed->scrimage,physical_y(erow),physical_x(ecol));
           wclrtoeol(ed->scrimage);
          }

      if(c=='\0')
        {

          erow++;
          ecol=1;
          if(((j+1) < ed->list.st_len[i] ) && (physical_y(erow)<= BOTTOM))
              {                                   // -1 since null is not added to line
               ed->el_startcol=j+1;
               ed->el_endcol=j+1;
               }                    // else , j is end of line do nothing
        }
      else
        {
          if(eb_issel(ed,i,j) )
            {

            wattrset(ed->scrimage,ed->attr|A_STANDOUT);
            mvwaddch(ed->scrimage,physical_y(erow),physical_x(ecol),c);
            wattrset(ed->scrimage,ed->attr);
            }


             else
              mvwaddch(ed->scrimage,physical_y(erow),physical_x(ecol),c);
          ed->el_endcol=j;
          if((ecol+1) <= (RIGHT-LEFT+1))
           {           ecol++;

           }
          else
            {
              erow++;
              ecol=1;
              if(((j+1) < ed->list.st_len[i]) && (physical_y(erow)<= BOTTOM))
                  {
               ed->el_startcol=j+1;

               }       // else , j is end of line do nothing  actually taken care below.
            }
      ed->endline=i;
     }

  if((i==ed->startline) && ((j<= (RIGHT-LEFT)) &&  (c!='\0')))
          ed->sl_endcol=j;

  if(c=='\0')
        {
          i++;
          j=0;
          if((i<ed->list.count) && (physical_y(erow) <= BOTTOM))
              {
                ed->el_startcol=0;
                ed->el_endcol=0;
              }
        }
      else
          j++;

    }           ///  End while

  wnoutrefresh(ed->scrimage);


  curs_set(1);
  return 1;
}
 /* ************************* End of buffer operation code *************** */
/* ********************************************************************** */


/********************************** End of Edit code ********************************************** */
/* ************************************************************************************************ */
inline int physical_y(int ly)
 { return (ly+TOP-1); }

 inline int physical_x(int lx)
 { return (lx+LEFT-1); }

 /* inline int logical_y(int py)
  { return (py-LEFT+1); } */
