//-------------------------------------------------
//          TestSuite: Range
//-------------------------------------------------

/*
  XXX NOTE XXX

  The garbage collection must WORK for this test to run correctly!
  The run will hang, if you have a bug in the process termination.
*/

#include "lcd.h"
#include "util.h"
#include "os_input.h"
#include "os_core.h"
#include "os_scheduler.h"
#include "os_memory.h"

#include <avr/interrupt.h>

#define DELAY 100

#define DRIVER intHeap
#define DSIZE (os_getUseSize(DRIVER)/4)

uint16_t size = 1;
volatile uint16_t check_i=0;
PROGRAM(1, AUTOSTART) {
  ProgramID cont = 1;
  lcd_clear();
  lcd_writeProgString(PSTR("[Testing range]"));
  if (size <= DSIZE) {
    lcd_line2();
    lcd_writeProgString(PSTR("Mass alloc: "));
    lcd_writeDec(size);
    uint16_t i;
    for (i = 0; i < DSIZE/size; i++) {
      if (!os_malloc(DRIVER,size)) {
        lcd_clear();
        lcd_writeProgString(PSTR("Could not alloc!"));
        os_waitForInput();
        size = DSIZE;
      }

      lcd_drawBar((uint16_t)((100ul*i)/(DSIZE/size)));
      lcd_line2();
      lcd_writeProgString(PSTR("Mass alloc: "));
      lcd_writeDec(size);
	  check_i=i;
      
    }
    size++;
  } else {
    cont = 2;
  }
  lcd_line2();
  lcd_writeProgString(PSTR("okay, next..."));
  os_enterCriticalSection();
  os_exec(cont,DEFAULT_PRIORITY);
}

PROGRAM(2, DONTSTART) {
  lcd_clear();
  lcd_writeProgString(PSTR("[Testing range]"));
  for (size = 1; size <= DSIZE; size++) {
    lcd_line2();
    lcd_writeProgString(PSTR("Random free: "));
    lcd_writeDec(size);
    uint16_t i;
    for (i = 0; i < size; i++) {
      os_free(DRIVER,os_malloc(DRIVER,size)+i);
      lcd_drawBar((100*i)/size);
      lcd_line2();
      lcd_writeProgString(PSTR("Random free: "));
      lcd_writeDec(size);
      
    }
  }
  lcd_line2();
  lcd_writeProgString(PSTR("TEST COMPLETE   "));
}
