#include <pthread.h>
#include <sched.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <glob.h>


#include "../common.src/bastypes.h"
#include "../common.src/os.h"

// -----------------------------------------------
// T H R E A D S
// -----------------------------------------------

Thread_Id_Typ OsStartThread (void(*startaddr)(void *))
{
  pthread_attr_t thread_attr;
  pthread_t thread;
  long param;
    
  pthread_attr_init(&thread_attr);
  pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_JOINABLE);
  pthread_attr_setscope(&thread_attr,PTHREAD_SCOPE_SYSTEM);
  pthread_create(&thread,&thread_attr,(void*)startaddr,&param);
  
  return (thread);
}



void OsStopThread (Thread_Id_Typ thread_id)
{
  void* thr_retval;
  pthread_join(thread_id, &thr_retval );
}

// -----------------------------------------------
// D I R E C T O R Y
// -----------------------------------------------


short OsFindFirst (FileInfoTyp *FileInfo, char *searchmask)
{
  FileInfo->cnt = 0;
  glob (searchmask,0,NULL,&FileInfo->GlobInfo);
  if (FileInfo->GlobInfo.gl_pathc == 0) return (1);

  strcpy (FileInfo->FileName,FileInfo->GlobInfo.gl_pathv[FileInfo->cnt++]);
//  FileInfo->FileSize=
  return (0);
}

short OsFindNext  (FileInfoTyp *FileInfo)
{
  if (FileInfo->cnt >= FileInfo->GlobInfo.gl_pathc) return (1);

  strcpy (FileInfo->FileName,FileInfo->GlobInfo.gl_pathv[FileInfo->cnt++]);
//  FileInfo->FileSize=
  return (0);
}

short OsFindClose (FileInfoTyp *FileInfo)
{
  globfree(&FileInfo->GlobInfo);
  return(0);
}

// -----------------------------------------------
// S E M A P H O R E N
// -----------------------------------------------

void OSCreateMutexSem( char *v1, HMTX *sem, unsigned long d2,
                       unsigned long d3 )
{
  pthread_mutex_init(sem, 0);
}

void OSCloseMutexSem( HMTX *sem )
{
  pthread_mutex_destroy(sem);
}

void OSRequestMutexSem( HMTX *sem, long d1 )
{
  pthread_mutex_lock(sem);
}

void OSReleaseMutexSem( HMTX *sem )
{
  pthread_mutex_unlock(sem);
}

// -----------------------------------------------
// M I S C  
// -----------------------------------------------

void OsSleep (unsigned long msec)
{
  if (msec == 1)
  {
    sched_yield();
    usleep(10);
  }
  else usleep(msec*1000);
}

void OsBoot(void)
{
}


void OSSetPriority (unsigned long class)
{
}

void  OSProcessAffinity (unsigned long affinity)
{
}

void  OSBeep (unsigned long frequency, unsigned long duration)
{
}


