#include "stdafx.h"
#include <dos.h>
#include "flsrom.h"
#include "ctl3d.h"
#include "flsdlg.h" 
#include "abireg51.h"  
#include "communic.h"
#include "flsmsg.h"  
#include "flsinfo.h"
//#include "abisub51.h"


#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif


/////////////////////////////////////////////////////////////////////////////
// CFlsromApp

// Local function prototypes.
BOOL IsContaining(UINT ,UINT*); 
BOOL CommDlg(void);    

extern STATUS AbiGetCpuId(UINT *nCpuId);

extern STATUS AbiGetFwId(UCHAR *uchMajor,  UCHAR *uchMinor);  
extern STATUS AbiIsECB2(BYTE *bResult);
extern BOOL SetCommType(int nTempCommType);
extern BOOL SetupCommunication(UINT pData);

          
int nCommType=2;
UINT nPortAddr=0x378;
UINT nPortStatus = 0x37a;
UINT nPortInp= 0x379;

//BOOL NeedCheck=TRUE; 

BEGIN_MESSAGE_MAP(CFlsromApp, CWinApp)
	//{{AFX_MSG_MAP(CFlsromApp)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFlsromApp construction

CFlsromApp::CFlsromApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CFlsromApp object

CFlsromApp NEAR theApp;

/////////////////////////////////////////////////////////////////////////////
// CFlsromApp initialization



BOOL CFlsromApp::InitInstance()
{
	if(m_hPrevInstance!=NULL)    
       {
         int returnbyte;
         HWND FirsthWnd,FirstChildhWnd;
         returnbyte=GetInstanceData(m_hPrevInstance, (BYTE*)&FirsthWnd,2);
         FirstChildhWnd = GetLastActivePopup(FirsthWnd);
//        FirsthWnd=(HWND)MAKELONG(byte[1],byte[0]); 
         BringWindowToTop(FirsthWnd);      // Bring main window to top.
         BringWindowToTop(FirstChildhWnd);      // Bring main window to top.	     
	      return FALSE;
	    }  

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

	SetDialogBkColor();        // Set dialog background color to gray
	LoadStdProfileSettings();  // Load standard INI file options (including MRU)
	EnableShellOpen();
    LoadLibrary("ctl3d.dll"); 
    Ctl3dRegister(AfxGetInstanceHandle());
    Ctl3dAutoSubclass(AfxGetInstanceHandle()); 
	
	BYTE  bResult=0;
#ifdef _ABI_ 
	while( AbiIsECB2(&bResult)) 
	{
	   AfxMessageBox(" Communication Failue!",MB_OK) ;   
	   if(FALSE==CommDlg() ) return 1;
	   SetCommType(nCommType)    ;
	   SetupCommunication(nPortAddr);
	 }  
#endif                 
	
	if(!bResult)
	{
	   AfxMessageBox("Firmware Setup is not supported by ECB-I",MB_OK) ;   
       return 0;
	 }  

  //Main frame of the application is a dialog box
UINT cpuid;
#ifdef _ABI_ 
	while( AbiGetCpuId(&cpuid) ) 
	{
	   AfxMessageBox(" Communication Failue!",MB_OK) ;   
	   if(FALSE==CommDlg() ) return 1;
	   SetCommType(nCommType)    ;
	   SetupCommunication(nPortAddr);
	 }  
#else
    cpuid=1;
#endif

	switch (SearchFW(cpuid) )
	{ 
	  case 0:return 1;
	  case 1:AfxMessageBox("Communication Failue !",MB_OK);
	         break;

	  case 2:AfxMessageBox("No Compatible file exists.\nPlease install the file in current directory",MB_OK);
             break;
	  case 3:AfxMessageBox("DownLoad Error!",MB_OK);break;  
      default:break;
      }       
    CFlsDlg* pMainWnd=new CFlsDlg;  
    m_pMainWnd = pMainWnd;
    if(-1==pMainWnd->DoModal() ) return FALSE;
   	return TRUE;
} 





/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg:public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

// Implementation
protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//{{AFX_MSG(CAboutDlg)
		// No message handlers
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

// App command to run the dialog
void CFlsromApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// CFlsromApp commands



          
UINT CFlsromApp::SearchFW(UINT uCPUType)
{
		
	char szFileName[64]="FW*.hex";  
	char szFirstFile[64];     //name of the first found file
	unsigned int FirstFileNameLen;
	struct _find_t fileinfo; 
    BOOL goon=TRUE;
    int ndos_return;
    if(_dos_findfirst( szFileName,_A_ARCH, &fileinfo ) ) return 2;
    memset(szFileName,0,64);

   	CDownload *pDownload;
	pDownload=new CDownload;  

	unsigned char uchMajor, uchMinor; //the version of the FW on EPROM

#ifdef _ABI_ 
                                     
	while( AbiGetFwId(&uchMajor, &uchMinor) ) 
	{
	   AfxMessageBox(" Communication Failue!",MB_OK) ;   
	   if(FALSE==CommDlg() ) return 1;
	   SetCommType(nCommType)    ;
	   SetupCommunication(nPortAddr);
	 }  
#else
    uchMajor=0x12;
	uchMinor=0xff;
#endif
   	    strcpy(szFirstFile,fileinfo.name);
   	    FirstFileNameLen=strlen(szFirstFile);     
    do{
   	    strcpy(szFileName,fileinfo.name);
		CFileException e;    
		if( !pDownload->m_file.Open( szFileName, CFile::modeRead, &e ) )
		{
			#ifdef _DEBUG
				afxDump << "File could not be opened " << e.m_cause << "\n";
			#endif
		}
		else
		{  
			BeginWaitCursor();                 
//    		int nResult; 
    		if( pDownload->check_ver() )   //check whether this file is compatible
    								   //and return the its supported cpu id list	
     		{
	     	  if(IsContaining(uCPUType,pDownload->m_puCPUId) )
	     	  {
	     	  	if(uchMajor==pDownload->m_uchMajor)
	     	  	    if(uchMinor>=pDownload->m_uchMinor)
	     	  	       {
	     	  	          CFlsMsg *pVerDlg;
	     	  	          pVerDlg=new CFlsMsg;  
	     	  	          if(uchMinor>pDownload->m_uchMinor)
	     	  	             pVerDlg->m_strText="The version of firmware on EPROM is high than the version of found hex file.\nDo you want to write.";
	     	  	          else 
	     	  	             pVerDlg->m_strText="The version of firmware on EPROM is the same as the version of found hex file.\nDo you want to write.";
	     	  	          if(IDCANCEL==pVerDlg->DoModal() ) goon=FALSE;
//	     	  	          Invalidate(); UpdateWindow();   
	     	  	        }
	     	  	if(goon)
	     	  	{          
	     	  	  if(!pDownload->CheckLegal() )    //checksum
	     	  	  {
//	     	  	     ShowWindow(SW_HIDE); 
	     	  	     if(IDCANCEL==AfxMessageBox("File Check is OK,\nDo You Want to Erase!",MB_OKCANCEL))  
	     	  	        return 0;

	     	  	     if(!pDownload->Download() )
    	 		     {
					    EndWaitCursor();      	
    	 			    return 3;
        	 	      }
     			     else
	     		     {  //display the downloaded file information
     	  	            CInfoDlg *pInfoDlg;
     	  	            pInfoDlg=new CInfoDlg;  
     	  	            pInfoDlg->m_szFileName=szFileName;
					    pInfoDlg->m_uRecordNum=pDownload->recordnum;
					    pInfoDlg->m_uchMajor=pDownload->m_uchMajor;     	  	           
					    pInfoDlg->m_uchMinor=pDownload->m_uchMinor;
					    pInfoDlg->m_lFileSize=fileinfo.size;
					    pInfoDlg->m_uData=fileinfo.wr_date;
     	  	            pInfoDlg->DoModal();       
	     		        EndWaitCursor(); 	
	     		        return 0;
	     		      }
	     		   }   
	     	     }
	     	    } 
	     	  }
	     }	               
	     ndos_return=_dos_findnext( &fileinfo );	//search the next file
	     if(!strncmp(szFirstFile,fileinfo.name,FirstFileNameLen) )
	        break;      
	     goon=TRUE;   
	   }while(!ndos_return);
	   
       return 2;
}
     
     


BOOL IsContaining(UINT uID, UINT* uGroup)
{
	UINT i;
	for(i=1;i<=uGroup[0];i++)
		if(uGroup[i]==uID)  return TRUE;
	return FALSE;	
}  



BOOL CommDlg(void)
{
    AfxGetApp()->DoWaitCursor(-1);
    CCommunicationDialog dlg;
    int nRet = dlg.DoModal() == IDOK;
    AfxGetApp()->DoWaitCursor(1);
    return nRet;
}     
     
