/*
 *      memorywin.cpp
 *
 *      Copyright 2009 salvi <salvi@asus>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
#include "memorywin.h"

#define LINELEN   8
#define LINMASK   0xfff8
void memoryWin::refresh () {
  int i,j;
  int firstOp = dbg->getFirstOp();
  int secondOp = dbg->getSecondOp();

  if (firstOp >= 0 && firstOp < start) {
    start = firstOp;
    if (secondOp >= 0 && secondOp < start && secondOp >= firstOp - LINELEN * h) {
      start = secondOp;
    }
  } else {
    if (firstOp >= 0 && firstOp >= start + LINELEN * h) {
      start = firstOp - LINELEN * (h - 1);
      if (secondOp >= 0 && secondOp > firstOp && secondOp < firstOp + LINELEN * (h - 1)) {
        start = secondOp - LINELEN * (h - 1);
      }
    }
  }

  start &= LINMASK;  // Allinea l'inizio della memoria
  for (i = 0; i < h; i++) {
    mvwprintw (win, i, 0, "%04X ", start + LINELEN*i);
    for (j = 0; j<LINELEN; j++) {
      if (firstOp == (start + LINELEN*i + j) || secondOp  == (start + LINELEN*i + j)) {
        wcolor_set(win, COLOR_RED, NULL);
      }
      wprintw (win, "%02X ", dbg->getMem(start + LINELEN*i + j));
      if (firstOp == (start + LINELEN*i + j) || secondOp  == (start + LINELEN*i + j)) {
        wcolor_set(win, COLOR_NORMAL, NULL);
      }
    }
    wprintw (win, " ");
    for (j = 0; j<LINELEN; j++) {
      unsigned char c = dbg->getMem(start + LINELEN*i + j);
      if (firstOp == (start + LINELEN*i + j) || secondOp  == (start + LINELEN*i + j)) {
        wcolor_set(win, COLOR_RED, NULL);
      }
      wprintw (win, (c >= ' ' && c < 0x7f) ? "%c" : ".", c);
      if (firstOp == (start + LINELEN*i + j) || secondOp  == (start + LINELEN*i + j)) {
        wcolor_set(win, COLOR_NORMAL, NULL);
      }
    }
  }

  wrefresh (win);
}
