#include <kern.h>
#include <stdio.h>
#include <trap.h>
#include <bsp.h>
#include <malloc.h>


#ifndef TEST_MALLOC

#define STACKSIZE 1024

extern tcb_t *cur_task;


void beep_task() ;

#endif

sem_t test_sem ;

void wait1(){
  while(1){
    printf( "wait1: trying test_sem\n" ) ;
    sem_p(&test_sem);
    printf( "wait1: got it\n" ) ;
    sleep( 1000 ) ;
  }
}
void wait2(){
  while(1){
    printf( "wait2: trying test_sem\n" ) ;
    sem_p(&test_sem);
    printf( "wait2: got it\n" ) ;
    sleep( 1000 ) ;
  }
}

void test_task(){
  
  int i;
  
  char * pmem = 0 ;
  int * pmem2 = 0 ;
  
  
#ifndef TEST_MALLOC

#define NUMER_TEST_TASKS 20

  char stacks [2][STACKSIZE] ;  
  char names[2][9]={
    "wait1\0" ,
    "wait2\0" } ;


  tcb_t * tasks[2] ;
  delay(60) ;
  sem_init(&test_sem);
  tasks [0] = spawn( names[0]
		     , stacks[0]
		     , wait1
		     , STACKSIZE
		     , 1000-3
		     , 0) ;
  tasks [1] = spawn( names[0]
		     , stacks[0]
		     , wait2
		     , STACKSIZE
		     , 1000-4
		     , 0) ;
  if( tasks[0] == NULL ){
    printf("Spawn of %s Failed\n" , names[0]);
  }else{
    printf("Spawn of %s: Succeess\n" , names[0]);
    exec(tasks[0]);
  }
  if( tasks[1] == NULL ){
    printf("Spawn of %s Failed\n" , names[1]);
  }else{
    printf("Spawn of %s: Succeess\n" , names[1]);
    exec(tasks[1]);
  }
  while(1){
    printf("test_task: sem_v( &test_sem ) ;\n" ) ;
    sem_v(&test_sem);
    sleep(1100) ;
  }


#else
  
  printf("allocing 64Byte\n");
  pmem = malloc( 64*sizeof(char) ) ;
  printf("pmem:%p\n",pmem);
  pmem2 = malloc( 64*sizeof(char) ) ;
  printf("pmem2:%p\n",pmem2);
  printf("Dump of pmem:\n" ) ;
  dump( pmem , 64) ;
  printf("Dump of pmem2:\n" ) ;
  dump( pmem2 , 64) ;
  memcpy( pmem , pmem2 , 64 ) ;
  printf("Dump of pmem:\n" ) ;
  dump( pmem , 64) ;
  printf("Dump of pmem2:\n" ) ;
  dump( pmem2 , 64) ;
  free( pmem2 ) ;
  free( pmem ) ;

#endif

}

#ifndef TEST_MALLOC

void beep_task(){
  int i = 0 ;
  for(i=0;i<10;i++){
    lprintf("%s\n" , cur_task->tcb_name ) ;
    beep(400,6);
    sleep( 300 ) ;
  }
}

#endif

