// Copyright (c) 2004 Rowley Associates Limited.
//
// This file may be distributed under the terms of the License Agreement
// provided with this software.
//
// THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// test1 
// A CTL application that creates two tasks that wait on an semaphore whilst the main task loops.
// This application illustrates the use of a semaphore to share access to a resource.

#include <ctl_api.h>
#include <string.h>
#include "test.h"

CTL_TASK_t mainTask,other1Task,other2Task;
int othercount;

#define CALLSTACKSIZE 16 // this is only required for AVR builds
#define STACKSIZE 64
unsigned other1Stack[1+STACKSIZE+1], other2Stack[1+STACKSIZE+1]; // allocate 1 word before and after to aid debugging stack space problems
CTL_SEMAPHORE_t s1=1; // initialised to 1 so that one of the tasks will succesfully wait

void 
other(void *p)
{
  unsigned v=0;
  while (1)
    {
      v++;
      ctl_semaphore_wait(&s1, 0, 0);
      ctl_timeout_wait(ctl_get_current_time()+1000);
      ctl_semaphore_signal(&s1);   
    }  
}

void
ctl_handle_error(CTL_ERROR_CODE_t e)
{
  while (1);
}

int
main(void)
{
  int i;
  BoardInit();
  ctl_task_init(&mainTask, 0, "main"); 
  SetTimerISR(ctl_increment_tick_from_isr);
  memset(other1Stack, 0xcd, sizeof(other1Stack));
  memset(other2Stack, 0xcd, sizeof(other2Stack));
  other1Stack[0]=other1Stack[1+STACKSIZE]=other2Stack[0]=other2Stack[1+STACKSIZE]=0xfacefeed;
  ctl_task_run(&other1Task, 1, other, 0, "other1", STACKSIZE, other1Stack+1, CALLSTACKSIZE);
  ctl_task_run(&other2Task, 1, other, 0, "other2", STACKSIZE, other2Stack+1, CALLSTACKSIZE);
  while (1)
    Idle();
}
