#include "stdafx.h"
#include <dos.h>
#include "flsrom.h"
#include "ctl3d.h"
#include "flsdlg.h" 
#include "flsmsg.h"  
#include "flsinfo.h"
#include "abitype.h"

#include "abifn196.h"
#include "abiextfn.h"
#include "initapi.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 BOOL jedLoad(CString filename, BOOL);

          
//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

} 

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

/////////////////////////////////////////////////////////////////////////////
// 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;              
	
 //97.4 to support serial port com chris                         
 	//init comset dialog and relink dialog                   
	Init196DLL();
    //init abi dll
    InitABIDLL();
    //new abi class                                                  
	if(!NewABIDLL(MAKE_REAL_196_ABI)) return FALSE;
	//if(!NewABIDLL(MAKE_SIMULATOR_ABI)) return FALSE;
	
//marked by chris, 4/7/97
//check the fw version;                                    
// BYTE uchMajor,uchMinor;
// if (ICE_OK != emuGetFwId(&uchMajor,&uchMinor)) {
// 	AfxMessageBox("Fail in getting FW-ID");
// } else { 
// 	if(uchMinor>=0x20 || (uchMajor>=0x05 && uchMajor<=0x10)) { 
// 	} else {         
// 	}
// }		
	
  //Main frame of the application is a dialog box
UINT cpuid;
#ifdef _ABI_ 
//by chris: 2/21/97
 	U8 IdInfo[6];
 	
 	if( emuGetID((U8*)&IdInfo) ) 
 		cpuid=(UINT)IdInfo[0]*0x100+IdInfo[1];
//	{
//	   AfxMessageBox(" Communication Failue!",MB_OK) ;   
//	   if(FALSE==CommDlg() ) return 1;
//	   SetCommType(nPortType)    ;
//	   SetupCommunication(nPortAddr);
//	 }  
#else
    cpuid=1;
#endif
/* Modified by Gates Hua	
	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;
      }       
*/      
	BOOL bOut=FALSE;
	do
	{
	switch (SearchFW(cpuid) )
	{ 
	  case 0:AfxMessageBox("FW DownLoad Setup OK!",MB_OK);break;
	  case 1:AfxMessageBox("Communication Failue !",MB_OK);break;
	  case 2://AfxMessageBox("Not compatible file or file not exists. \nPlease check hex/jed file",MB_OK);
	  		 bOut=TRUE;
             break;
	  case 3:AfxMessageBox("DownLoad Error!",MB_OK);break;  
	  case 4:AfxMessageBox("Cancel FW Setup!",MB_OK);break;  
      default:break;
      }                           
   }while(!bOut);
/* Modified by Gates Hua	
    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
// This rountine modified by Gates Hua for Mr Dome's command at 2/14/97.

/////////////////////////////////////////////////////////////////////////////
// CMyFileDialog dialog
CMyFileDialog::CMyFileDialog( BOOL bOpenFileDialog, LPCSTR lpszDefExt, 
		LPCSTR lpszFileName, LPCSTR lpszFilter, DWORD dwFlags, CWnd* pParentWnd )
		: CFileDialog( bOpenFileDialog, lpszDefExt, 
		lpszFileName, dwFlags, lpszFilter, pParentWnd )
{
}

void CMyFileDialog::DoDataExchange(CDataExchange* pDX)
{
	CFileDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMyFileDialog)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMyFileDialog, CFileDialog)
	//{{AFX_MSG_MAP(CMyFileDialog)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()
	
BOOL CMyFileDialog::OnInitDialog() 
{
	if ( CFileDialog::OnInitDialog() != TRUE ) return FALSE;

	CenterWindow();
	SetWindowText("FW Setup");
	CWnd *pWnd = GetDlgItem(IDOK);
	if ( pWnd ) pWnd->SetWindowText("Download");
	pWnd = GetDlgItem(IDCANCEL);
	if ( pWnd ) pWnd->SetWindowText("Exit");
	return TRUE;
}

UINT CFlsromApp::SearchFW(UINT uCPUType)
{
CString strFileName;
struct _find_t fileinfo;
BOOL goon=TRUE;

	CMyFileDialog dlg(TRUE, "*.hex;*.jed", "*.hex;*.jed",
		"Hex,Jed Files  (*.hex;*.jed) | *.hex;*.jed ||");

	if ( IDOK != dlg.DoModal() ) return 2;
	strFileName = dlg.GetPathName();
    if(dlg.GetFileExt()=="JED")
    {
    	if(jedLoad(strFileName, 0))
    		return 0;
    	else
    		return 100;	//message already handled.
    }
    
   	CDownload Download;
   	CDownload* pDownload=&Download;
	//pDownload=new CDownload;  

    U8 IdInfo[6];

	if( emuGetID((U8*)&IdInfo) ) 
	   return 1;
	unsigned char uchMajor, uchMinor; //the version of the FW on EPROM
	
	uchMajor=IdInfo[2];
	uchMinor=IdInfo[3];

	CFileException e;    
	if( !pDownload->m_file.Open( strFileName, 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) )
     	  {        
				CFlsDlg VerDlg1;
				CFlsDlg* pMainWnd=&VerDlg1;
				m_pMainWnd = pMainWnd;
				if(-1==pMainWnd->DoModal() ) return 4;
     	  }*/
     	  {
     	  	if(uchMajor==pDownload->m_uchMajor)
     	  	    if(uchMinor>=pDownload->m_uchMinor)
     	  	       {
     	  	          CFlsMsg *pVerDlg, VerDlg2;
     	  	          pVerDlg=&VerDlg2;  
     	  	          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;
 	  	            char *szFileName;                
 	  	            szFileName = new char[ strFileName.GetLength()+1 ];
					if ( !szFileName ) return 0; 	  	            
					strcpy( szFileName, strFileName.GetBuffer(strFileName.GetLength()) );
 	  	            _dos_findfirst( szFileName,_A_ARCH, &fileinfo );
 	  	            
 	  	            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->m_uYear=(fileinfo.wr_date>>9)+1980;
 	  	            pInfoDlg->DoModal();       
     		        EndWaitCursor(); 	
     		        delete szFileName;
     		        delete pInfoDlg;
     		        return 0;
     		      }
     		   }   
     	     }
     	     else return 4;
     	    } 
     	  }
     }	                              
     return 3;
}

/*          
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(nPortType)    ;
	   //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;
    return TRUE;
}     
     
