/*
 * Emunation Plugin for MD-API 
 *
 * This code is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
 */
 
#include "patparser.h"
#include "dvbsectiondata.h"
#include "..\\main.h"
#define WRITE(x){m_DLLInstance.x;}

#ifdef PAT_PARSER
cPATParser::cPATParser()
:cDataParser()
{
}

cPATParser::cPATParser(unsigned char* buffer, int length)
:cDataParser(buffer,length)
{
}

cPATParser::~cPATParser()
{
}

bool cPATParser::Parse()
{
    WRITE(Log("Parsing PAT!"));
    if(m_buf)
    {
        WRITE(Log("Deleting m_data:%p ",m_data));
        if(m_data) delete m_data;
        WRITE(Log("m_data deleted!%s\n","!"));

        if(m_buf[0]!=0x00) return false;

        cPAT* patdata = new cPAT();
        patdata->table_id = m_buf[0];
        patdata->section_syntax_indicator = GetBits (0, 8, 1);
        patdata->reserved_1 = GetBits (0, 10, 2);
        patdata->section_length = GetBits (0, 12, 12);
        patdata->transport_stream_id = GetBits (0, 24, 16);
        patdata->reserved_2 = GetBits (0, 40, 2);
        patdata->version_number = GetBits (0, 42, 5);
        patdata->current_next_indicator = GetBits (0, 47, 1);
        patdata->section_number = GetBits (0, 48, 8);
        patdata->last_section_number = GetBits (0, 56, 8);       

        int n = patdata->section_length - 5 - 4;
        m_buf = m_buf + 8;
        for (; n>=4; n=n-4) 
        {
            patdata->Add(new cPAT_PMTList(GetBits (0, 0, 16),//Program number
                                        GetBits (0, 16, 3),//Reserved
                                        GetBits (0, 19, 13)//PMT pid
                        ));
        	m_buf += 4;
        }
        m_data=patdata; 
        return true;
    }
    return false;
}
#endif
