#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "frame-lock.h"

FrameLock::FrameLock()
{
  if ( pthread_mutex_init( &frame_mutex, NULL ) ) {
    perror( "pthread_mutex_init" );
    exit( 1 );
  }

  if ( pthread_cond_init( &frame_condition, NULL ) ) {
    perror( "pthread_cond_init" );
    exit( 1 );
  }

  going = 0;
}

void FrameLock::go( void )
{
  pthread_mutex_lock( &frame_mutex );
  going = 1;
  pthread_cond_broadcast( &frame_condition );
  pthread_mutex_unlock( &frame_mutex );
}

void FrameLock::went( void )
{
  pthread_mutex_lock( &frame_mutex );
  going = 0;
  pthread_cond_broadcast( &frame_condition );
  pthread_mutex_unlock( &frame_mutex );
}

void FrameLock::wait_for_go( void )
{
  pthread_mutex_lock( &frame_mutex );
  
  while ( !going ) {
    pthread_cond_wait( &frame_condition, &frame_mutex );
  }

  pthread_mutex_unlock( &frame_mutex );
}

void FrameLock::wait_for_went( void )
{
  pthread_mutex_lock( &frame_mutex );
  
  while ( going ) {
    pthread_cond_wait( &frame_condition, &frame_mutex );
  }

  pthread_mutex_unlock( &frame_mutex );
}
