#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <termios.h>
#include <pthread.h>
#include <inttypes.h>
#include <hw/pci.h>
#include <sys/neutrino.h>
				
#define PCI_VENDOR_SIEMENS_AG  0x110a
#define PCI_ID_PROTO           0x4033      /* prototype board without any rom */
#define PCI_ID_CP1616_1        0x4026      /* CP1616 */
#define PCI_ID_CP1616_2        0x4036      /* CP1616 */
#define PCI_ID_CP1604_1        0x4038      /* CP1604 */
    
#define PCI_VENDOR_ID  PCI_VENDOR_SIEMENS_AG
#define SUB_DEVICE_ID  PCI_ID_CP1616_1 

struct pci_dev_info pdev;

int  os_pci_probe(struct pci_dev_info *pdev, int CpIndex)
{
	 int pci_index = 0;
	 int board_cnt = 0;
	 int board;
    int phdl;
    void * hdl;
	 
	 printf("cp16xx_os_pci_probe: begin\n");

	 board = CpIndex;
	 phdl = pci_attach(0);
	 
	 if (phdl < 0)
	 {
		 perror("pci_attach");
		 return(-ENODEV);
	 }
  
	 for(;;)
	 {
		 if( (hdl = pci_attach_device(NULL, PCI_SHARE|PCI_INIT_ALL|PCI_MASTER_ENABLE, pci_index, pdev)) == 0 )
		 {
			 printf("cp16xx_os_pci_probe: can't find device .. end\n");
             pci_detach(phdl);
			 return( -ENODEV );
		 }
		 if(board_cnt >= board)
			 break;  // OK ... found the board
			  
		 board_cnt++;
		 pci_index ++;	     
	 }
   
return(0);

}

int cp16xx_init(struct pci_dev_info *pdev,  int board)
{
	int err = 0;
	printf("cp16xx_init: begin\n");	
    pdev->VendorId =  PCI_VENDOR_SIEMENS_AG;
    pdev->DeviceId =  PCI_ID_CP1616_1;

    if(os_pci_probe(pdev, board))
    {  
        pdev->DeviceId =  PCI_ID_CP1616_2;  // not found
        if(os_pci_probe(pdev, board))
        {    
			pdev->DeviceId =  PCI_ID_CP1604_1;
			if(os_pci_probe(pdev, board))
			{			
            	err = -ENODEV;
			}
        }
    }
	 printf("cp16xx_init: end\n");
	return(err);
}


int main(int argc, char **argv)
{
	 int board = 0;     
    ThreadCtl(_NTO_TCTL_IO, 0);
        
    // init PCI and library
    if(cp16xx_init(&pdev, board))
    {
	   perror ("CP16XX: cp16xx_init failed");
	   exit(-1);
    }
    exit (0);
}

