#if !defined( _IOAFITSFILEHANDLER_H )
#define _IOAFITSFILEHANDLER_H

#include "FITSFileBuffer.h"
#include "FrameBuffer.h"

class IoAFITSFileHandler
{
public:
    IoAFITSFileHandler( )
    {
        m_RootFolder  [ 0 ] = '\0';
        m_SequenceName[ 0 ] = '\0';

        m_FramesPerFile = -1;
    }

    ~IoAFITSFileHandler( )
    {
        delete [ ] m_FITSFileBuffers;
    }

    int Allocate( int BufferSize )
    {
        Free( );

        if ( BufferSize <= 0 ) return FALSE;

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

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

            return FALSE;
        }

        return TRUE;
    }

    void Free( )
    {
        for ( int i = 0; i < 2; i++ )
        {
            m_FITSFileBuffers[ i ].Free( );
        }
    }

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

        return TRUE;
    }

    int Open( const char *RootFolder, const char *SequenceName, int FramesPerFile = 1 )
    {
        Close( );

        if ( RootFolder == NULL || SequenceName == NULL || FramesPerFile < 1 ) return FALSE;

        if ( ! IsAllocated( ) ) return FALSE;

        int m = ::strlen( RootFolder );

        if ( m == 0 || m >= sizeof( m_RootFolder ) ) return FALSE;

        ::strcpy( m_RootFolder, RootFolder );

        int n = ::strlen( SequenceName );

        if ( n == 0 || n >= sizeof( m_SequenceName ) ) return FALSE;

        ::strcpy( m_SequenceName, SequenceName );

        m_FramesPerFile = FramesPerFile;

        m_BufferIndex = 0;

        return TRUE;
    }

    void Close( )
    {
        if ( IsOpen( ) )
        {
            Flush( );  // wait till file buffer I/O finished


        }

        m_BufferIndex = -1;
    }

    int IsOpen( ) const { return m_BufferIndex >= 0; }

    int AddFrame( const IoAFrameBuffer& FrameBuffer )
    {
        return TRUE;
    }

private:
    IoAFITSFileBuffer m_FITSFileBuffers[ 2 ];  // double-buffered I/O

    char m_RootFolder[ 300 ];
    char m_SequenceName[ 80 ];

    int m_FramesPerFile;
    int m_BufferIndex;
}

#endif
