#import "TWS.h"
#import <stdio.h>
#import <appkit/Matrix.h>
#import <appkit/TextField.h>

static TWS *sf;
@implementation TWS
- incField:(int)fnum
{
  int i,max=201;
  id target;

  target=[fields findCellWithTag:fnum];
  
  for(i=0;i<max;i++){
    // debugging code-- this slows things down ALOT
    //    mutex_lock(printM);
    //    fprintf(stderr, "incing %d\n", fnum);
    //    mutex_unlock(printM);

    if(!(i%10)){
      mutex_lock(lockM);
      [target setIntValue:i];
      mutex_unlock(lockM);
    }

    cthread_yield(); 
  }

  mutex_lock(doneM);
  threadCount--;
  condition_signal(doneC);
  mutex_unlock(doneM);
  mutex_lock(printM);
  fprintf(stderr, "Thread %d FINISHED...\n",fnum);
  mutex_unlock(printM);
  return self;
}

void dofield(int fnum)
{
  [sf incField:fnum];
}

- init
{
  fprintf(stderr, "Initializing TWS...\n");
  lockM=mutex_alloc();
  printM=mutex_alloc();
  doneM=mutex_alloc();
  doneC=condition_alloc();
  sf=self;
  return self;
}

- doIt:sender
{
  int i=0;
  int count=10;

  threadCount=0;
  for(i=0;i<count;i++){
    mutex_lock(printM);
    fprintf(stderr, "Starting thread %d....\n",i);
    mutex_unlock(printM);
    mutex_lock(lockM);
    cthread_detach(cthread_fork((cthread_fn_t)dofield, (any_t)i));
    mutex_lock(doneM);
    threadCount++;
    mutex_unlock(doneM);
    mutex_unlock(lockM);
  }

  mutex_lock(doneM);
  while(threadCount != 0)
    condition_wait(doneC,doneM);
  mutex_unlock(doneM);
    
  return self;
}
@end
