#include "stdafx.h"
#include "DoubleFITSFileBuffer.h"

int IoADoubleFITSFileBuffer::Allocate( int BufferSize )
{
    if ( IsOpen( ) ) return FALSE;

    Free( );

    for ( int i = 0; i < 2; i++ )
    {
        if ( ! m_FITSFileBuffers[ i ].Allocate( BufferSize ) )
        {
            break;
        }
    }

    if ( ! IsAllocated( ) )
    {
        Free( );

        return FALSE;
    }

    return TRUE;
}

void IoADoubleFITSFileBuffer::Free( )
{
    if ( ! IsOpen( ) )
    {
        for ( int i = 0; i < 2; i++ )
        {
            m_FITSFileBuffers[ i ].Free( );
        }
    }
}

int IoADoubleFITSFileBuffer::IsAllocated( ) const
{
    for ( int i = 0; i < 2; i++ )
    {
        if ( ! m_FITSFileBuffers[ i ].IsAllocated( ) )
        {
            return FALSE;
        }
    }

    return TRUE;
}

int IoADoubleFITSFileBuffer::CreateThreads( )
{
    if ( IsOpen( ) ) return FALSE;

    DestroyThreads( );

    for ( int i = 0; i < 2; i++ )
    {
        if ( ! m_FITSFileBuffers[ i ].CreateThread( ) )
        {
            break;
        }
    }

    if ( ! AreThreadsRunning( ) )
    {
        DestroyThreads( );

        return FALSE;
    }

    return TRUE;
}

void IoADoubleFITSFileBuffer::DestroyThreads( )
{
    for ( int i = 0; i < 2; i++ )
    {
        if ( m_FITSFileBuffers[ i ].IsThreadRunning( ) )
        {
            m_FITSFileBuffers[ i ].DestroyThread( );
        }
    }
}

int IoADoubleFITSFileBuffer::AreThreadsRunning( ) const
{
    for ( int i = 0; i < 2; i++ )
    {
        if ( ! m_FITSFileBuffers[ i ].IsThreadRunning( ) )
        {
            return FALSE;
        }
    }
    
    return TRUE;
}
