//0000, STD, E01, M, F2_4D, 8, 65535, STSALL25.808, F2_BI_p40.ETR, HTBICODE(SHOS.dn), OVERLAY(overlay.bin), DSGEOSPT(geo_down.bin), GEOSPT(geo.bin), BISPT(biscript.bin), SDATAMEM(sdatamem.txt)

// This Script is for No Model Change of 5400RPM D/S

//   20091106 : F3S2PS00.ETR (Original:) Maker:ds.seo
//              Sol 2P MP Script
//   20091110 : F32P1S00.ETR (Original:F3S2PS00) Maker:ds.seo
//              1D SBT Test Script
//   20091110 : F32P1S01.ETR (Original:F3S2PS00) Maker:ds.seo
//              1D SB1 Test Script
//   20091114 : F32P1S02.ETR (Original:F3S2PS00) Maker:ds.seo
//              Grade Spec change 
//   20091127 : F32P1S08.ETR (Original:F32P1S02) Maker:ds.seo
//              SC Start Cmd Delete
//   20091216 : F32P1S11.ETR (Original:F32P1S02) Maker:ds.seo
//              고온 FT 전 모델 적용
//   20100108 : F32P1S12.ETR (Original:F32P1S11) 
//              TCC2 Patch(7200RPM Only), FT Script modify
//   20100113 : F32P1S14.ETR (Original:F32P1S12) 
////DriveGrading 주석 삭제(//DriveGrading --> DriveGrading)
//   20100113 : F32P1S16.ETR (Original:F32P1S14) 
//              AList Disable at FT
//   20100128 : F32P1S28.ETR (Original:F32P1S21) Maker:ds.seo
//              L28xx(2801,2809,2819) Inline D/S(5400RPM)
//              BER Gap : 1.5 --> 2.0
//   20100227 : F32P1S54.ETR (Original:F32P1S28) Maker:ds.seo
//              Delete TCC2 patch, because that TCC2 ID 3 DAC Push applied at r37c BI code  
//              10Grade 적용 + ATW 수정
//   20100323 : F32P1S64.ETR (Original:F32P1S55) Maker: ds.seo
//              SC N/R 개선(SN_clear 후 power off 추가)
//   20100402 : F32P1S72.ETR (Original:F32P1S64) Maker: ds.seo
//              FUJI Killing,DD/S 공법 전환 설정
//   20100416 : F32P1S82.ETR (Original:F32P1S72) Maker: GY.LEE
//              FUJI Killing,DD/S 공법 추가(W6329,W6330)
//   20100430 : F32P1S94.ETR (Original:F32P1S82) Maker: JJH
//              FOD patch @ MOD개선, FT단축 // 1D
//   20100511 : F32P1SA4.ETR (Original:F32P1S94) Maker: ds.seo
//              MES CODE 추가
//   20100623  : F32P1SB5.ETR (Original:F32P1SA4) Maket: JJH
//               Add ATW Retry 
//   20100623  : F32P1SB5.ETR (Original:F32P1SA4) Maket: JJH
//               Add Screen FODR/W Gap at Zn13 
//   20100711 : F32P1SC8.ETR (Original:F32P1SB5) Maker: ds.seo
//              single BOM 공법 추가
//   20100729 : F32P1SD3.ETR (Original:F32P1SC8) Maker: ds.seo
//              ASSC와 Even/Odd 구분 
//   20100824 : F32P1SE3.ETR (Original:F32P1SD3.ETR) Maker: ds.seo
//              Model Check 추가(SMT CODE 체크)
//   20100830 : F32P1SF4.ETR (Original:F32P1SE3.ETR) Maker: ds.seo
//              Add  FT Mapping 
//   20101007 : F32P1SF8.ETR (Original:F32P1SF4.ETR) Maker: ds.seo
//              Add  FOD Patch
//   20101202 : F32P1SG2.ETR (Original:F32P1SF8.ETR) Maker: ds.seo
//              Add DNR Process
//   20110104 : F32P1SGA.ETR (Original:F32P1SG2.ETR) Maker: JJH
//              FODW Redution
//   20110106 : F32P1SGB.ETR (Original:F32P1SGA.ETR) Maker: JJH
//              Add InlineKilling
//   20110106 : F32P1SGC.ETR (Original:F32P1SGB.ETR) Maker: JJH
//              FODReduction삭제(G2 Base_Inline Killing만 추가)
//   20110124 : F32P2SGC.ETR (Original: F32P2SG2.ETR ) Maker: ds.seo    
//              D/S Test 시 Delay로 표시
//   20110206 : F32P1SGD.ETR (Original:F32P1SGC.ETR) Maker: JJH
//              Reduction(1SGB) + 258G 이하 KLilling(1SGD) (w/ DS delay)

//=================================================================================================
// GRADE C Value : C,1_fored c / C,2_Mapping / C,3_5400RPM 2801 Fail / C_4/5/6_ATW Retry(OD/MD/ID)
//==================================================================================================
// SHDS Disk //

#include "strfiles.inc"
// Define Alphabet //
#define CHAR_0			        48	    //'0'
#define CHAR_1			        49	    //'1'
#define CHAR_2			        50	    //'2'
#define CHAR_3			        51	    //'3'
#define CHAR_4			        52	    //'4'
#define CHAR_5			        53	    //'5'
#define CHAR_6			        54	    //'6'
#define CHAR_7			        55	    //'7'
#define CHAR_8			        56	    //'8'
#define CHAR_9			        57	    //'9'

// Define Alphabet //
#define CHAR_A                  65      //'A'
#define CHAR_B                  66      //'B'
#define CHAR_C                  67      //'C'
#define CHAR_D                  68      //'D'
#define CHAR_E                  69      //'E'
#define CHAR_F                  70      //'F'
#define CHAR_G                  71      //'G'
#define CHAR_H                  72      //'H'
#define CHAR_I                  73      //'I'
#define CHAR_J                  74      //'J'
#define CHAR_K                  75      //'K'
#define CHAR_L                  76      //'L'
#define CHAR_M                  77      //'M'
#define CHAR_N                  78      //'N'
#define CHAR_O                  79      //'O'
#define CHAR_P                  80      //'P'
#define CHAR_Q                  81      //'Q'
#define CHAR_R                  82      //'R'
#define CHAR_S                  83      //'S'
#define CHAR_T                  84      //'T'
#define CHAR_U                  85      //'U'
#define CHAR_V                  86      //'V'
#define CHAR_W                  87      //'W'
#define CHAR_X                  88      //'X'
#define CHAR_Y                  89      //'Y'
#define CHAR_Z                  90      //'Z'

// Define //
#define POSTFIX_SC              83      //'S'
#define POSTFIX_HT              70      //'F'
#define POSTFIX_BI              66      //'B'
#define POSTFIX_COMBINE         67      //'C'
#define POSTFIX_SMT             80      //'P'

#define LED_R                   82      //'R'
#define LED_G                   71      //'G'
#define LED_Y                   89      //'Y'
#define LED_X                   88      //'X'
#define SECTOR_SIZE		        512

#define RTY_DW_SCCODE		    1
#define RTY_DW_HTCODE		    2
#define RTY_DW_BBIN		        3
#define RTY_DW_FFLASH		    4
#define RTY_DW_HTBICODE		    5
#define RTY_DW_SCRBIN		    6
#define SECTOR_SIZE_BINNING		1024

// Global variables //
int BAUD_RATE;
int INVALID_LED;
int RTY_RESET;
int RTY_DOWNLOAD;
int RTY_CODETYPE;
int flag_5400RPM;
int flag_InlineKill;
int SPIRAL_ERASE;
int MAGNET_ERASE;
int ASSC_SC;
int SCCKIP;
int nSC_loop;
int flag_OEM;
int flag;
int tled,disflag,ftled;
int flag_DDS;
int flag_KIL;
int flag_SC_KILL; //james test

char DWCODE[32];
char buf[32];

// FUNCTION PROTOTYPE //
void exe_SC(int minute);
void exe_BI(int minute);
void exe_BI1(int minute);
void exeDELAY();
void TurnOff();
void Clean_MC(void);
void ChangeBaudRate(int baudrate,int option);
void chk_ENG_wRetry();
void retryprmt();
void chk_ENG_wRetry1();
void retryprmt1();
void retryreset();
void retryreset1();
char serialno[16];
void PN_Write();
void Mass_MP();
void Mass_RND();
void GRADE_RND();
void GRADE_RND2();
void DriveGrading();
void retryreset();
void Id_Retry();
void DNR_Id_Retry();
void retryid();
void dnr_retryid();
void TurnOff();
void Check_LedSC();
void Check_LedSC1();
void Check_LedBI();
void cmd_CB();
void cmd_IN();
void cmd_LF();
void Reset_Retry();
void HighTempexeSCR();
void DW_RTY();
void dummyerror();
void SN_clear();
void DS_Fail();
void Grade_Fail();
void GO54001RPM();
void Clean_MC();
void Clean_MC2();
void retrycleanmc();
void DNR_Test();
void errmesreset();
void errmesidfy();

//SEND MES DATA
#define SEND_DATA_INIT	0
#define SEND_SC_START	1
#define SEND_SC_PASS	2
#define SEND_BI_START	3
#define SEND_BI_PASS	4
#define SEND_BI_MODEL   5

char FG_SC_START;
char FG_SC_PASS;
char FG_BI_START;
char FG_BI_PASS;
char FG_BI_MODEL;

void SendMESData(int type);

// Global variables //
int  DISFLAG;
char model[16];
char dispbuf[16];
char grade[512];
char rdbuf[1024];

//PN Write option
int port;
char snfile[32];
int fhandle;
char pn[16];
char buffer[10080];
char serialno[16];
char strled[16];  
char RDBUF[512];
int  df_grade;
int  config1;
int  MH_NUMOF_HEAD;
char BV_BUFFER[SECTOR_SIZE];
int  g_tpi,g_ber,g_ow,g_disktype;
//MGET
int MGET(int mcid, int offset); //F1 MCFS
int MGET1(int mcid, int offset); //F1 MCFS
int nOffs;
int ver0;
int ver1;
int ver2;
int ver3;
int ver4;
int code1;
int code2;
int code3;
int code4;

//MASS DATA SECTOR SIZE
#define MASS_MAX_SECTOR_SIZE	64
char	BVR_FLAG[MASS_MAX_SECTOR_SIZE];
char	BV_NEW_BUFFER[0x8000];
    
//BINNING FUNCTION
char	BIN_FILENAME[20];
int	GetMassBuffer(int ioffset, int iseccnt);
char grade[512];
char temp[128];
int  RetryCont;
int  LED_ERROR;
int CLEAN_MC;
int  main_code;
//MC Read
void dummyerror();
//FT Mapping
//Error count var
int nEc,nEc1,nEc2,step,error_cnt1,error_cnt2;

int estep; 
int estep1,Screen_ft; 
void Errorcnt(int step);
void Dfree(int estep); 
//ATW Screen
void ATW_SCR(); // JJH_100622
void ATW_Grade();
int CHECK_HEAD;
int ATW_Screen;
int ATW_step,i; 
int  Reset_NoFail();
int Kill_H;
int flag_BIfail;


//FOD Scree
void FOD_screen();
//FODW Reduction Patch - 20100909
void FODW_Patch();
//Inline Killing - 20110105
void Inline_Kill();
int flag_delay,flag_FODWRduction;
int delay_test;
//void Patch_code();  //0211_JJH
int flag_readycheck;
void Reset_Retry_Kill();
int Step_FODW;
int No_MASS;

void main()
{
	char biheader[6];
	char postfix;
	int reworkflag; 
	int disflag;	
	int SCCKIP;
    int ret;

	BAUD_RATE       = 57600;
	INVALID_LED     = 0x00;
    RTY_RESET       = 0;
	SCCKIP		    = 0;
    main_code       = 0;
    CLEAN_MC    	= 0;
    flag_DDS        = 0;
    flag_KIL        = 0;    
    flag_SC_KILL    = 0; //james test        
    delay_test      = 0;   //0124-JJH
    flag_delay      = 0;   //0124-JJH 
    flag_readycheck = 0;   //0228-JJH
    flag_5400RPM    = 0;
	str_setdumpsectorsize(1710);            //for gigacube
    
	setcom25v();
	siolog(1);
    
    DNR_Test();

	TurnOff();
	delays(5);
    
    
	//>>>>>>>>>>>>>>>>>>>>>>>>>>
	SendMESData(SEND_DATA_INIT);
	//<<<<<<<<<<<<<<<<<<<<<<<<<<	

    //SN_clear();
	
	// Get S/C Skip option
	str_getscskip(SCCKIP);
    str_getdelayproc(ret);
    
    if(ret != 0)
    {
        flag_delay = 1;
        exeDELAY();
    }
    else
    {
    
        // S/C to B/I
        if (SCCKIP == 0)
        {
            SN_clear();
            poststatus("S/C~");
            delays(5);
            exe_SC(15000);
        
            poststatus("Turn On");
            power(1);
            delays(120);
            Reset_Retry();
            chk_ENG_wRetry();
            	   
            cmd_CB();		//Cancel Resume BI
        
            cmd_LF();
            poststatus("IDFY");
            Id_Retry();
          
          //=====================james test==========================
          
            str_getidfydata(0, 511, rdbuf); 
            if(rdbuf[215] == 0x53 || rdbuf[215] == 0x73)   // SC code check
            {
                str_usercmd("DI 64",5,1000,22,0,buf,32);
                atoi(buf,18,16,flag);
                printf("%x",flag);

                if(flag == 0xff00)
                {
                    flag_SC_KILL = 0;  
                }  
                else
                {
                    flag_SC_KILL = 1;
                }
            }
            //=====================james test==========================
            TurnOff();
            delays(10);
        
            poststatus("B/I~");
            delays(5);
            exe_BI(25000);
         if ( delay_test == 1)
            {
                goto GO5400RPM;
            }
        }
        else
        {
            poststatus("Turn On");
            power(1);
            delays(120);
            //Check_LedBI();
            Reset_Retry_Kill();
            chk_ENG_wRetry();
            
            cmd_IN();    
            cmd_CB();
        
            cmd_LF();
            poststatus("IDFY");
            Id_Retry();
            str_getidfydata(0, 511, rdbuf);

            // Code Check(_"P",_"S" Check)
            if (rdbuf[215] == 0x53 || rdbuf[215] == 0x50 || rdbuf[215] == 0x73 || rdbuf[215] == 0x70)
            {
                poststatus("Re S/C");
                stoptest();
            }
            
            exe_BI(25000);
        if ( delay_test == 1)
            {
                goto GO5400RPM;
            }
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////
    
	/*
    poststatus("Turn On");
	power(1);
	delays(120);
	Check_LedBI();
	chk_ENG_wRetry();
    
	cmd_IN();    

	Reset_Retry();
	poststatus("IDFY");
	Id_Retry();
    */
    
    if( main_code == 0)
    {
        poststatus("MASS");
        Mass_MP();
        //Mass_RND();
        str_mesdownsize(0); //Inline DS Model Enable
        poststatus("GRADE");
////DriveGrading(); //10Grade
        //GRADE_RND();
    }   

    //Killing Model Change
    str_getidfydata(0, 511, rdbuf); 
	if( rdbuf[64] == 0x31 && rdbuf[65] == 0x36) // "16" 1ch 160G 강제 불량 처리
	{
        str_stoptestfail(3, 0x0160);
    }
	if( rdbuf[64] == 0x32 && rdbuf[65] == 0x35)
	{
        if( rdbuf[68] == 0x4A)	// 4A : "J" 7200rpm
        {
            str_usercmd("DI 64",5,1000,22,0,buf,32);
            atoi(buf,18,16,flag);
            printf("%x",flag);

            if(flag == 0xff00)
            {
                poststatus("Non Killing");
                flag_DDS = 1;
            }  
            else
            {
                poststatus("Killing");
                flag_KIL = 1;
            }
        }
        else if( rdbuf[68] == 0x49)	// 49 : "I" 5400rpm
        {
            str_stoptestfail(3, 0x0160);
        }
        else
        {
            poststatus("Check Model");
            stoptest();
        }
    }

    if( main_code == 0) // "0" : BI CODE, "1" : Main(FT) code
    {

        //===Send Grade Data to MES=========
        //>>>>>>>>>>>>>>>>>>>>>>>>
        //B/I PASS
        SendMESData(SEND_BI_START);
        delays(10);  
        
        SendMESData(SEND_BI_MODEL);
        delays(10);  
        
        SendMESData(SEND_BI_PASS);
        //<<<<<<<<<<<<<<<<<<<<<<<<<
        //===BI END=========================
    }
    
	poststatus("Final Test");
	HighTempexeSCR();

   
//=====OEM& DIS Check =============

	poststatus("GO BF1");  // OEM -> need to BF1

	power(0);
	delays(15);

GO5400RPM:                 // 5400rpm -> need to HB1 with 5400rpm

}

void exe_SC(int minute)
{
	ASSC_SC=0;     //0 = Odd/Even, 1= ASSC

	//>>>>>>>>>>>>>>>>>>>>>>>>>>
	// S/C START
	SendMESData(SEND_SC_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<<		

	poststatus("Turn On");
	power(1);
	delays(120);
	Check_LedSC();		//Check Not Ready Failure ex. 1102, 1702 etc		
    Reset_Retry();
	chk_ENG_wRetry();	//check prmpt
	
	cmd_IN();    		//CPU interrupt Disable, CA for Abnormal log
                        //This cmd must be after Power On Step
	Id_Retry();
	str_getidfydata(0, 511, rdbuf);
	
	// Code Check
	if (rdbuf[215] == 0x42 || rdbuf[215] == 0x62)
	{
		poststatus("LABEL_BICODE");
		delays(1);
        CLEAN_MC= 1;
		goto LABEL_BICODE;
	}
	if (rdbuf[215] == 0x4D || rdbuf[215] == 0x6D)
	{
		poststatus("LABEL_MAINCODE");
		delays(1);
        CLEAN_MC= 1;
		goto LABEL_MAINCODE;
	}
    
    
//download SC code
    poststatus("SCCODE2 D/L");
    strcpy(DWCODE,SCCODE2);DW_RTY();
    poststatus("CHK BOOT SCCODE2");
    delays(10);
    
    TurnOff();
	delays(10);
    
    poststatus("Turn On");
    power(1);
    delays(120);
    Check_LedSC();
    chk_ENG_wRetry();
    
    cmd_IN();    
    
    Reset_Retry();        
	poststatus("IDFY");
	Id_Retry();
    str_getidfydata(0, 511, rdbuf);
    
    if( rdbuf[186] == 0x53 && rdbuf[187] == 0x41)   //0x53 = S, 0x41 = A (SA=ASSC)
    {
        ASSC_SC=1;   
    }
    
    if(ASSC_SC == 0)  // Odd/Even
    {
        //download SC code for Prime Drive
        poststatus("SCCODE1 D/L");
        strcpy(DWCODE,SCCODE1);DW_RTY();
        poststatus("CHK BOOT SCCODE1");
        delays(10);

        TurnOff();
        delays(10);
                
        poststatus("Turn On");
        power(1);
        delays(120);
        Check_LedSC();		//Check Not Ready Failure ex. 1102, 1702 etc		
        chk_ENG_wRetry();	//check prmpt
    
        cmd_IN();    		//CPU interrupt Disable, CA for Abnormal log
                            //This cmd must be after Power On Step
        Reset_Retry();
        poststatus("IDFY");
        Id_Retry();
    }
    //>>>>>>>>>>>>>>>>>>>>>>>>>>
	// S/C START
	SendMESData(SEND_SC_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<<

    //download SC Overlay code
    if(ASSC_SC == 0)    // Odd/Even
    {
        poststatus("SCOVERLAY D/L");
        str_userdownload("DO",SCOVERLAY,0x4C);
        poststatus("CHK ENG SCOVERLAY");
    }
    else     // ASSC
    {
        poststatus("SCOVERLAY_1P D/L");
        str_userdownload("DO",SCOVERLAY_1P,0x4C);
        poststatus("CHK ENG SCOVERLAY_1P");
    }
	delays(10);
	str_checkprompt("ENG>");


	// download SC Script         
    if(ASSC_SC == 0)     // Odd/Even
    {   
        poststatus("SCSPT D/L");
        str_downloadbiscript(SCSPT);
        poststatus("CHK ENG SCSPT");
    }
    else   // ASSC
    {
        poststatus("SCSPT_1P D/L");
        str_downloadbiscript(SCSPT_1P);
        poststatus("CHK ENG SCSPT_1P");
    }
	delays(10);
	str_checkprompt("ENG>");
    
    // run SC Test
    str_starttest();
    str_monitorsc(minute);

    LABEL_BICODE:
    LABEL_MAINCODE:
    
    delays(10);
    TurnOff();
	delays(10);
	

	//>>>>>>>>>>>>>>>>>>>>>>>>
	//S/C PASS
	SendMESData(SEND_SC_PASS);
	//<<<<<<<<<<<<<<<<<<<<<<<<

}

void exe_BI(int minute)
{
    int invled;
	int tled, disflag;
	
	//>>>>>>>>>>>>>>>>>>>>>>>>>
	//B/I START
	SendMESData(SEND_BI_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<	

    flag_5400RPM    = 0;	//0 = 7200RPM, 1 = 5400RPM
    flag_InlineKill = 0;

LABEL_5400RPM:	
	


//======Change Model 7200RPM to 5400RPM for D/S End==============

    // burnin code download
    poststatus("HTBI D/L");
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
    {
       	strcpy(DWCODE,HTBICODE);DW_RTY();
	    poststatus("CHK BOOT HTBICODE");
    }
    else
    {
	    strcpy(DWCODE,HTBI54);DW_RTY();
	    poststatus("CHK BOOT HTBI54");
    }
    delays(10);
	
	poststatus("Turnoff");
    power(0);
    delays(15);
	
    poststatus("Turn On");
    power(1);
    if ( flag_InlineKill == 1)
    {
      delays(300);   
    }
    
    delays(120);
    Reset_Retry_Kill();
    chk_ENG_wRetry();
    cmd_IN();
    cmd_CB();
	
    if (CLEAN_MC == 1 || SCCKIP == 1) 
	{           
        Clean_MC();  // check "ENG"
	}

	else
	{
        Clean_MC2();  // Don't Check "ENG"
	}       
	
	TurnOff();
	delays(10);

   	poststatus("Turn On");
   	power(1);
    if ( flag_InlineKill == 1)
    {
      delays(300);   
    }
   	delays(120);
    Reset_Retry();
    chk_ENG_wRetry();
    cmd_IN();
    cmd_CB();
    cmd_LF();
    Id_Retry();
	
	//>>>>>>>>>>>>>>>>>>>>>>>>>
	//B/I START
	SendMESData(SEND_BI_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<

   	poststatus("OVLY D/L");
   	
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
   	{
   		str_userdownload("DO",OVERLAY,0x4C);      
   	}
   	else
    {
       	str_userdownload("DO",OVERLAY_54,0x4C);
    }

    delays(30);
    str_checkprompt("ENG>");

   	// NEW AZL
   	// download geometry file         
    poststatus("GEO D/L");
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
    {
    	str_downloadgeo(GEOSPT);
    }
    else
    {
       	str_downloadgeo(GEOSPT54);
    }

    delays(30);
    str_checkprompt("ENG>");

    // download biscript         
    poststatus("BISPT D/L");
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
   	{
       	str_downloadbiscript(BISPT);
    }
    else
    {
       	str_downloadbiscript(BISPT54);
    }
    delays(30);
    str_checkprompt("ENG>");

    // run burnin
    str_starttest();
	ONTESTERROR(Mass_MP);  //set mass hadler when B/I fail
    //if (flag_InlineKill == 0 )
    if ( flag_5400RPM ==0 )      
    {
       	str_monitoring("B/I", minute, tled, disflag);
    }
    else
    {
        str_nopoweroff(1);
        str_mesoff();
        delay_test = 1;
        poststatus("GO Delay");
        return;
    }
	
	if (tled == 0)
	{
		//go through
	}
	//else if (flag_5400RPM == 0 && flag_InlineKill == 0 && (tled == 0x1C08 || tled == 0x2801 || tled == 0x2809 || tled == 0x2819 || tled == 0x1A03 ))
	else if (flag_5400RPM == 0 && flag_InlineKill == 0 &&  tled != 0 )
	
    {
		//5400RPM D/S
		flag_5400RPM = 1;
		power(0);
		delays(15);
        poststatus("Turn On");
        power(1);
        delays(120);
        Check_LedSC();		//Check Not Ready Failure ex. 1102, 1702 etc		
        chk_ENG_wRetry();	//check prmpt

        cmd_IN();    		//CPU interrupt Disable, CA for Abnormal log
                            //This cmd must be after Power On Step
        Reset_Retry();
		goto LABEL_5400RPM;
	}
    
//	else if (flag_5400RPM == 1 && flag_InlineKill == 0 && (tled == 0x1C08 || tled == 0x2801 || tled == 0x2809 || tled == 0x2819 || tled == 0x1A03 ))
	else if (flag_5400RPM == 1 && flag_InlineKill == 0 && tled != 0)
	{
		//Inline Killing
		power(0);
		delays(15);
       	power(1);
        delays(120);
        Check_LedBI();
        Reset_Retry();
        chk_ENG_wRetry();
        cmd_IN();
        
        flag_InlineKill = 1;
        flag_5400RPM = 0 ;       
        Inline_Kill();
         
        power(0);
		delays(15);
         
        poststatus("Turn On");
        power(1);
        delays(300);
        Check_LedSC();		//Check Not Ready Failure ex. 1102, 1702 etc		
        chk_ENG_wRetry();	//check prmpt
        cmd_IN();    		//CPU interrupt Disable, CA for Abnormal log
                            //This cmd must be after Power On Step
        Reset_Retry();
		goto LABEL_5400RPM;
	}
    
	else
	{
		str_stoptestfail(3, tled);
	}

    ONTESTERRORCLEAR(); //clear mass handler
  
	TurnOff();
	delays(10);
    power(1);
    delays(30);
    Check_LedBI();
    Reset_Retry();
    chk_ENG_wRetry();
    cmd_IN();
    Reset_Retry();
    cmd_LF();
    poststatus("IDFY");
	Id_Retry();

    str_getidfydata(0, 511, rdbuf); 
	if( rdbuf[64] == 0x32 && rdbuf[65] == 0x35) 
    {
        if( rdbuf[68] == 0x49)	   // 49 : "I" 5400rpm 250G 5400RPM
        {
            flag_InlineKill = 1;
            flag_5400RPM = 0;
            Inline_Kill();
            goto LABEL_5400RPM;
        }
    }
  
}


void HighTempexeSCR()
{
    poststatus("SCRBIN D/L");
    if (flag_5400RPM == 0)
    {
       	strcpy(DWCODE,SCRBIN);DW_RTY();
       	poststatus("CHK BOOT SCRBIN");
   	}
   	else
    {
    	strcpy(DWCODE,SCRBIN54);DW_RTY();
    	poststatus("CHK BOOT SCRBIN54");
    }
	delays(10);

	power(0);
	delays(15);
    
    poststatus("Turn On");
	power(1);
    delays(30);
    str_checkprompt("ENG>");

   	cmd_IN();
   
   	Reset_Retry();
   	poststatus("IDFY");
	Id_Retry();
   
	str_mesftstart();
   
   	Reset_Retry();
	str_sendserialcmd("EP 0",4);
	delays(30);
 
   	str_sendserialcmd("IC 1 0",6);
   	delays(120);    
    
/*  
    str_sendserialcmd("TC",2);  // Disable TCC3, v37c 
   	delays(30);  
*/
    power(0);
	delays(15);
    
    poststatus("Turn On");
	power(1);
    delays(30);
    str_checkprompt("ENG>"); 	


	// FT Alist improve ====================
    str_sendserialcmd("AT 9A C1 0 320A FF A0",21);   // wuid(0x320A, 0xff)
    delays(60);
    str_sendserialcmd("AT 9A C1 0 320B FF A0",21);    // wuid(0x320B, 0xff)
    delays(60);  
    poststatus("Turn Off ");
    power(0);
    delays(15);

    poststatus("Turn On FT");
	power(1);
    delays(60);
    str_checkprompt("ENG>"); 	
    
    cmd_IN();
    
 	Reset_Retry();
   	poststatus("IDFY");
	Id_Retry();
 
    
 //==================================================================================
  //  FOD_screen();
 //==================================================================================
    
// =============================  Add FT @ 4/22 (FT단축)=========================================== 
 
    if( main_code == 1)
    {
        //Full Track Write ...(7hr)
        poststatus("FTW");
        str_sendserialcmd("TU 10002 0 1426 40 7FFFFFFF",27);  // ecc 20, retry 38
        delays(5);
        str_monitorscrstep(1200,"FTW","FT","SW00"); 
        delays(1);
        Reset_Retry(); 
    }     

    //Ran. R/W/R x 50K         ...60min
   	poststatus("RDW");
    str_sendserialcmd("TU 1020121 C350 141E 100 7FFFFFFF",33);   // C350 --> 50k,,,  14 -> ECC 20,   1E--> retry 30  
   	delays(10);
   	str_monitorscrstep(200,"RDW","FT", "RW01");
   	delays(1);   
   	Reset_Retry();        
   	delays(10);   
    
    //ATW Test (10K WRITE)..80min
   	poststatus("ATW");
	str_sendserialcmd("TU 2040000 0 13881460 5 000002",30);  // 1388 --> 5k, 20 --> ECC 20,  3C --> retry 100, 0212, OD/MD
   	delays(10);
   	str_monitorscrstep(150,"ATW","FT","AW02");
   	delays(1);  
   	Reset_Retry();         
    ATW_step = 0; 
    ATW_Grade();           

    if (ATW_Screen == 0)
    {
        //ATW Test ("ATW")..80min
        poststatus("ATW");
        str_sendserialcmd("TU 2040000 0 13881460 5 002000",30);  // 1388 ->5k, 20 --> ECC 20,  3C --> retry 100 / MD
        delays(10);
        str_monitorscrstep(150,"ATW","FT","AW03");
        delays(1);  
        Reset_Retry(); 
        ATW_step = 1; 
        ATW_Grade(); 
    } 

    if (ATW_Screen == 0)  
    {
        //ATW Test ("ATW")..80min
        poststatus("ATW");
        str_sendserialcmd("TU 2040000 0 13881460 5 200000",30);  // 1388 ->5k, 20 --> ECC 20,  3C --> retry 100 / ID
        delays(10);
        str_monitorscrstep(150,"ATW","FT","AW04");
        delays(1);  
        Reset_Retry();
        ATW_step = 2; 
        ATW_Grade();
    }
    
    if (ATW_Screen == 1 || ATW_Screen == 2 || ATW_Screen == 3 )
    {
        
        //FODW_Patch();
        
        //ATW Test ("ATW")..80min
        poststatus("ATW");
        str_sendserialcmd("TU 40000 0 FA01460 5 2",22);  // 1388 ->5k, 20 --> ECC 20,  3C --> retry 100 / MD
        delays(10);
        str_monitorscrstep(150,"ATW","FT","AW05");
        delays(1);  
        Reset_Retry(); 
        
        //ATW Test ("ATW")..80min
        poststatus("ATW");
        str_sendserialcmd("TU 40000 0 FA01460 5 2000",25);  // 1388 ->5k, 20 --> ECC 20,  3C --> retry 100 / MD
        delays(10);
        str_monitorscrstep(150,"ATW","FT","AW06");
        delays(1);  
        Reset_Retry(); 
        
        //ATW Test ("ATW")..80min
        poststatus("ATW");
        str_sendserialcmd("TU 40000 0 FA01460 5 200000",27);  // 1388 ->5k, 20 --> ECC 20,  3C --> retry 100 / MD
        delays(10);
        str_monitorscrstep(150,"ATW","FT","AW07");
        delays(1);  
        Reset_Retry(); 
    } 

    //MD full Track Write(CHS)
    poststatus("Full Write");
    str_sendserialcmd("TU 10002 0 141E 15F90 249F0",27);            // MIN ~ MAX Cyl. Interval 2.
    str_monitorscrstep(600,"MD Write","FT","SW08");
    delays(10);
    Reset_Retry(); 
    
    //MD Full Track Read    
   	poststatus("FTR");
    str_sendserialcmd("TU 10001 0 1016 15F90 249F0",27);   // ecc 16, retry 22
   	delays(10);   
    str_monitoring("F/T", 600, ftled, disflag); 
    if (ftled == 0)
    {
        //str_monitorscrstep(300,"BER","FT","BE15");    
        delays(1);  
        Reset_Retry();
    }
    else
    {
        //FODW_Patch();
     
        //MD full Track Write(CHS)
        poststatus("Full Write");
        str_sendserialcmd("TU 10002 0 141E 15F90 249F0",27);            // MIN ~ MAX Cyl. Interval 2.
        str_monitorscrstep(600,"MD Write","FT","SR09");
        delays(10);
        Reset_Retry(); 
        
        //MD Full Track Read    
        poststatus("FTR");
        str_sendserialcmd("TU 10001 0 1016 15F90 249F0",27);   // ecc 16, retry 22
        delays(10);
        str_monitorscrstep(600,"MD Read","FT","SW10");
        delays(1);  
        Reset_Retry();     
        
    }     
    
   //Full Track Read  ...150min
   	poststatus("FTR");
    str_sendserialcmd("TU 1010001 0 0E14 40 7FFFFFFF",29);   // ecc 14, retry 20
   	delays(10);
   	str_monitorscrstep(600,"FTR","FT","SR11");
   	delays(1);  
   	Reset_Retry(); 
    delays(10);

    //Full Track Write ...150min
   	poststatus("FTW");
   	str_sendserialcmd("TU 1010002 0 1426 40 7FFFFFFF",29);  // ecc 20, retry 38
   	delays(5);
   	str_monitorscrstep(600,"FTW","FT","SW12"); 
   	delays(1);
   	Reset_Retry();  
    delays(10);    
	

    // 2nd FT Mapping
   	step=2; 
    Errorcnt(step);
	Dfree(estep);
    
   
   if(nEc > 0)
	{     
        // Rand W/R
        poststatus("Randw");
        str_sendserialcmd("TU 20012 186A0 1426 40 7FFFFFFF",31);   // 249F0 --> 150k,,,  14 -> ECC 20,  26--> retry 0x26
        delays(10);
        str_monitorscrstep(400,"RDW","FT", "RW13");
        delays(1);   
        Reset_Retry(); 	
        delays(10);     
    }      
    
    //Full Track Read  ...150min
   	poststatus("FTR");
    str_sendserialcmd("TU 1010001 0 1016 40 7FFFFFFF",29);   // ecc 16, retry 22
   	delays(10);
   	str_monitorscrstep(600,"FTR","FT","SR14");
   	delays(1);  
   	Reset_Retry();  

    // 2nd FT Mapping
   	step=3; 
    Errorcnt(step);
	Dfree(estep);   	

    // FT Alist improve ====================
    str_sendserialcmd("AT 9A C1 0 320A 10 A0",21);    // wuid(0x320A, 0x10)
    delays(60);
    str_sendserialcmd("AT 9A C1 0 320B 10 A0",21);    // wuid(0x320B, 0x10)
    delays(60); 


	//FT Result
	poststatus("FT END"); 
	str_sendserialcmd("TU 0 3",6);
	delays(10);
	Reset_Retry();

    str_mesftend();  
   
}

void Inline_Kill()
{
    int Dlist_0,Dlist_1,Vlist_0,Vlist_1,Capa_0,Capa_1;
    int Kill,Kill1,Kill2,Kill3;
    No_MASS = 0;
    // Dlist Total

    str_sendserialcmd("PP",2);
    delays(300); 
    chk_ENG_wRetry1();
    if (No_MASS == 1)
    {
        poststatus("Turnoff");
        power(0)	;
        delays(15);
        poststatus("Turn On");
        power(1);
        delays(120);
        str_sendserialcmd("AT 8F 3C 0 0 1",14);
        delays(30);
        goto SKIP_KILL;
    }
 
    if( MGET1(168,0x000) != 0 )
    {
        poststatus("Re B/I");
        delays (10);
        stoptest();
    }
    CHECK_HEAD = RDBUF[36];  

    if( CHECK_HEAD == 2)
    {
      
        if( MGET1(168,0x1400) != 0 )
        {
            poststatus("Re B/I"); delays (10); stoptest();
        }
        Dlist_0 = ( RDBUF[97] << 32 | RDBUF[96] << 16 | RDBUF[99] << 8 | RDBUF[98] );
        

        if( MGET1(168,0x2600) != 0 )
        {
            poststatus("Re B/I"); delays (10); stoptest();
        }
        Dlist_1 =  ( RDBUF[97] << 32 | RDBUF[96] << 16 | RDBUF[99] << 8 | RDBUF[98] );


        // Vlist-OD
        if( MGET1(168,0xC00) != 0 )
        {
            poststatus("Re B/I"); delays (10); stoptest();
        }
        Vlist_0 = ( RDBUF[53] << 32 | RDBUF[52] << 16 | RDBUF[55] << 8 | RDBUF[54] );
        

        if( MGET1(168,0x1E00) != 0 )
        {
            poststatus("Re B/I"); delays (10); stoptest();
        }
        Vlist_1  = ( RDBUF[53] << 32 | RDBUF[52] << 16 | RDBUF[55] << 8 | RDBUF[54] );
        
        
           // Capa
        if( MGET1(168,0xA00) != 0 )
        {
            poststatus("Re B/I"); delays (10); stoptest();
        }
        Capa_0 = ( RDBUF[227] << 8 | RDBUF[226] );
        
        
      
        if( MGET1(168,0x1C00) != 0 )
        {
            poststatus("Re B/I"); delays (10); stoptest();
        }
        Capa_1 = ( RDBUF[227] << 8 | RDBUF[226] );
      
       
        if( Capa_0 > 258 || Capa_1 > 258 )
        {
           if (Capa_0 >= Capa_1)
            {
                Kill_H = 1;   // Head 1 Killing 
            }   
            else
            {
                Kill_H = 0;   // Head 0 Killing   
            }    
        }    
       
        else 
        {
              
            if ( Dlist_0 >= Dlist_1)
            {
              Kill = 0;
            }   
            else 
            {
              Kill = 1;
            }    
            
            
            if ( Vlist_0 >= Vlist_1)
            {
              Kill1 = 0;
            }   
            else 
            {
              Kill1 = 1;
            }    
            
            
            if ( Capa_0 < Capa_1)
            {
              Kill2 = 0;
            }   
            else 
            {
              Kill2 = 1;
            }    
            
            Kill3 = Kill + Kill1 + Kill2 ;
            
            if ( Kill3 < 2)
            {
              Kill_H =0; 
            } 
            else
            {
              Kill_H =1; 
            }
        }     
        
        if (Kill_H ==0)  // Head_0 Killing
        {
            str_sendserialcmd("AT 8F 3C 0 0 1",14);
            delays(30);
        }   
            
            
        if (Kill_H ==1)  // Head_1 Killing
        {
            str_sendserialcmd("AT 8F 3C 0 0 2",14);
            delays(30);
        } 
    }
    SKIP_KILL :
}



void FODW_Patch()
{

    poststatus("SCRBIN D/L");
    if (flag_5400RPM == 0)
    {
       	//strcpy(DWCODE,FM1CODE);DW_RTY();
       	poststatus("CHK BOOT SCRBIN");
    }   
    else
    {
        goto SKIP_FOWPATCH ;
        //strcpy(DWCODE,SCRBIN54);DW_RTY();
      	//poststatus("CHK BOOT SCRBIN54");
    }
	delays(10);

	poststatus("Turn Off");
    power(0);
	delays(15);
    
    poststatus("Turn On");
	power(1);
    delays(30);
    str_checkprompt("ENG>");
   	cmd_IN();    
    str_sendserialcmd("AT 8F 94",8);          //MCFS Init
	delays(10);           
    
    poststatus("FODW patch");
    str_sendserialcmd("AT 8F F2 9 0 0 0",16); // Channel TBL FODW 원복 + FODW patch
    delays(120);
    chk_ENG_wRetry();
 
    poststatus("FODW patch");
    str_sendserialcmd("AT 8F F2 8 0 0 0",16); // FODW patch for Z-Grade
    delays(10);
    //str_monitorscr(100,"FODW patch","BI");
    str_monitoring("B/I", 30, tled, disflag);
	if (tled == 0)
	{
		//go through
	}
	 else
	{
		str_stoptestfail(3, tled);
	}
    
	poststatus("Turnoff");
	power(0);
	delays(15);

	poststatus("Turn On");
	power(1);
   
	power(1);
	delays(60);
	Check_LedBI();
	Reset_Retry();
	chk_ENG_wRetry();
 
 
    poststatus("MOD Improve");
    str_sendserialcmd("AT 8F F2 9 0 2",14); // MOD개선 patch
    delays(180);
    chk_ENG_wRetry();
    
    poststatus("OSA patch");
    str_sendserialcmd("AT 8F F5 2 2 3F8 3",18); // OSA patch
    delays(120);
    chk_ENG_wRetry();  
      
    poststatus("FODW Reduction");
    str_sendserialcmd("AT 8F F2 C 0 0",14); // FODW reduction
    delays(1800);
    chk_ENG_wRetry();

     
// =============Main code D/L =============================
    poststatus("SCRBIN D/L");
    if (flag_5400RPM == 0)
    {
       	strcpy(DWCODE,SCRBIN);DW_RTY();
       	poststatus("CHK BOOT SCRBIN");
   	}
   	else
    {
    	strcpy(DWCODE,SCRBIN54);DW_RTY();
    	poststatus("CHK BOOT SCRBIN54");
    }
	delays(10);

	power(0);
	delays(15);
    
    poststatus("Turn On");
	power(1);
    delays(60);
    str_checkprompt("ENG>");

   	cmd_IN();
   
   	Reset_Retry();
   	poststatus("IDFY");
	Id_Retry();   
    
    
    SKIP_FOWPATCH:
}

void DW_RTY()
{
	char bootbuf[32];
	char cmd[16];
	int  ret, rtycnt, dbgmode;
	int  MAX_DL_RTY;
	
	MAX_DL_RTY = 3;
	
	cmd[0]=0x0d;cmd[1]=0x0d;cmd[2]=0;//CRCR
	
	//check current prompt in "DBG>"
	memset(bootbuf,0,0,32);
	ONERROR(dummyerror);
	str_usercmd(cmd,2,1000,30,0,bootbuf,30); bootbuf[31]=0;
	ONERRORCLEAR();
	strstr(bootbuf,"DBG>",dbgmode);
    
	for(rtycnt = MAX_DL_RTY ; rtycnt > 0; rtycnt--)
	{
		//if not debug mod, change baudrate
		if(dbgmode == 0)
		{
			if(rtycnt == MAX_DL_RTY) //1st try @ 230400bps
			{
				str_sendserialcmd("SB 900",6); //230400 bps drive
				setbaud(230400); //machine
                
				//check prompt
				memset(bootbuf,0,0,32);
				ONERROR(dummyerror);
				str_usercmd(cmd,2,1000,30,0,bootbuf,30); bootbuf[31]=0;
				ONERRORCLEAR();
				strstr(bootbuf,"ENG>",ret);
				if(ret == 0)
				{
					setbaud(57600); //restore baudrate 
					//retry DL 
					TurnOff();
					delays(5);
					
					power(1);
					poststatus("DL retry");
					delays(120);
					Reset_Retry();                  
					
					continue;
				}
			}
			if(rtycnt == MAX_DL_RTY-1) //2nd try @ 115200bps
			{
				ONERROR(dummyerror);
				str_changehddbaud(115200);
				ONERRORCLEAR();
			}
		}
		//download code & wait flash write
		dw(DWCODE);
		delays(20);
		
		//send CR(enter)
		memset(bootbuf,0,0,32);
		ONERROR(dummyerror);
		str_usercmd(cmd,2,1000,30,0,bootbuf,30); bootbuf[31]=0;
		ONERRORCLEAR();
		
		//check prompt
		strstr(bootbuf,"BOOT>",ret);
		//Check D/L ok?
		if(ret == 0)
		{
			if(rtycnt == 1) //last retry
			{
				str_checkprompt("BOOT>"); //make d/l fail
			}
			else
			{
				//power cycle for retry
				power(0); delays(3); power(1);
				//wait ready & reset
				delays(60);
				if(dbgmode == 1)
				{
					str_debugmode();
				}
				else
				{
					reset();
				}
			}
		}
		else
		{
			memset(DWCODE,0,0,32);
			return; // D/L Ok
		}
	}
	memset(DWCODE,0,0,32);
}

 
void FOD_screen()
{
    char FODR[16];
    char FODW[16];
    char FOD_GAP[16]; 
    int h;
     
    // FODW Gap (1.8 ~ 2.2)  
    if( MGET(119,0x600) != 0 )  // MGET 119 - FOD Result
    {
        poststatus("Re B/I");
        delays (10);
        stoptest();
    }
    /*
    FODW0_z13 = RDBUF[127];
    FODW1_z13 = RDBUF[127+50]; 
    FODW2_z13 = RDBUF[127+100];
    FODW3_z13 = RDBUF[127+150)];      
    */
    
    for(h=0; h<4 ;h=h+1)
    {
     FODW[h] = RDBUF[127+(50*h)] ;
    }
    
   if( MGET(119,0x400) != 0 )  // MGET 119 - FOD Result
    {
        poststatus("Re B/I");
        delays (10);
        stoptest();
    }  
    
    /*
    FODR0_z13 = RDBUF[239];
    FODR1_z13 = RDBUF[239+50]; 
    FODR2_z13 = RDBUF[239+100];
    FODR3_z13 = RDBUF[239+150)];  
    */
    
    for(h=0; h<4 ;h=h+1)
    {
     FODR[h] = RDBUF[239+(50*h)];
    }
    
        
    for(h=0; h<4 ;h=h+1)
    {
        FOD_GAP[h]= FODR[h] - FODW[h];
        if ( FOD_GAP[h] > 30 )
        {
            str_stoptestfail(4, 0xB706);   // B706 : FH Delta Screen
        }
    }   
    
}


void ATW_SCR()
{
    
    int FOD_gap,Tpi_grade,Check_pf,h;  
    
    // check ATW count
    if( MGET(9,0x000) != 0 )
    {
        poststatus("Re B/I");
        delays (10);
        stoptest();
    }
    Tpi_grade = RDBUF[319] ;


// TPI Grade Screen (0x16 Screen)
    if ( Tpi_grade == 0x16)
    {
        str_stoptestfail(4, 0xAB04);
    }  
    
// Zn1 & TPI Grade (1.8 ~ 2.2)    
    if ( (Tpi_grade == 0x12 || Tpi_grade == 0x14 || Tpi_grade == 0x16) && ATW_Screen == 1)   // ATW Scree=1 is  fail of zn1
    {
        str_stoptestfail(4, 0xAB04);   
    }

 // FODW Gap (1.8 ~ 2.2)  
    if( MGET(119,0x600) != 0 )  // MGET 119 - FOD Result
    {
        poststatus("Re B/I");
        delays (10);
        stoptest();
    }
    
    for(h=0; h<4 ;h=h+1)
    {
        FOD_gap = RDBUF[127+(50*h)] - RDBUF[115+(50*h)] ;
        if ( FOD_gap > 7 )
        {
            str_stoptestfail(4, 0xAB04);  
        }
    }        
}
 
 
void ATW_Grade()
{
    int Count_h0,Count_h1,Count_h2,Count_h3;
    int Re_h0,Re_h1,Re_h2,Re_h3,Result,Check_pf;
    
  /*  
    if( ATW_step == 0)
    {   
        if( MGET(168,0x000) != 0 )
        {
        poststatus("script Err");
        delays (10);
        stoptest();
        }
        
        CHECK_HEAD = RDBUF[36];
    }
  */  
    // check ATW count
    if( MGET(11,0xE00) != 0 )
    {
        poststatus("Re B/I");
        delays (10);
        stoptest();
    }
  
    Count_h0 = RDBUF[245] ;
    Count_h1 = RDBUF[249] ;
	Count_h2 = RDBUF[253] ;
	Count_h3 = RDBUF[257] ;
    
    Re_h0 = RDBUF[247] ;
    Re_h1 = RDBUF[251] ;
	Re_h2 = RDBUF[255] ;
	Re_h3 = RDBUF[259] ;
    
    Result = Re_h0 + Re_h1 + Re_h2 + Re_h3 ; 
 
 /*
    if( Result > 0)
    { 
        if  (CHECK_HEAD == 4)  // 2D
        {
            if  ((Count_h0 <= 3) || (Count_h1 <= 3) || (Count_h2 <= 3) || (Count_h3 <= 3))  
            {
            str_stoptestfail(4, 0xAB04);
            }
        }   
        else if (CHECK_HEAD == 3)  // 2D
        {
            if  ((Count_h0 <= 3) || (Count_h1 <= 3) || (Count_h2 <= 3))  
            {
            str_stoptestfail(4, 0xAB04);
            }
        }
        
        else if (CHECK_HEAD == 2)  // 2D
        {
            if  ((Count_h0 <= 3) || (Count_h1 <= 3))  
            {
            str_stoptestfail(4, 0xAB04);
            }
        }
        
        else if (CHECK_HEAD == 1)  // 2D
        {
            if  (Count_h0 <= 3) 
            {
            str_stoptestfail(4, 0xAB04);
            }       
        }
        else
        {
            
        }
        
    }
 */  
    
    if (Result > 0)   // Errror 
    {
        if( ATW_step == 0)
		{
		str_setdrvgrade(CHAR_C, 4);
        ATW_Screen = 1;
		}
		else if( ATW_step == 1)
		{
		str_setdrvgrade(CHAR_C, 5);
        ATW_Screen = 2;
		}
		else if( ATW_step == 2)
		{
		str_setdrvgrade(CHAR_C, 6);
        ATW_Screen = 3;
		}
    }
    else 
    {
        ATW_Screen = 0;
    }    
   
}  


int MGET1(int mcid, int offset) //F1 MCFS
{
    char cmd[32];
    char addr[16];
    int  cmdlen,i,naddr,nOffSn;
    
    
   // nOffSn = offset/512;
    nOffSn = 0;
    sprintf(cmd,"TF %x 0 0 1 %x",mcid, nOffSn);
    strlen(cmd,cmdlen);
    
    ONERROR(dummyerror);
    str_usercmd(cmd,cmdlen,5000,512,0,RDBUF,512);
    ONERRORCLEAR();
    
    strstr(RDBUF,"OK",i);
    if(i == 0)
    return 1;

    strfind(RDBUF,"ddr",cmdlen);
    cmdlen = cmdlen+6;  //space
    
    for(i = 0; i < 8; i++)
    addr[i]=RDBUF[cmdlen+i];
    
    atoi(addr,0,16,naddr); 
    if(addr == 0)
    return 1;
        
	//str_setbyteswap(0);
    sputd(cmd,"DS %x 100",naddr+(offset));
    //sputd(cmd,"DS %x 100",naddr+(offset%512));
    //sputd(cmd,"DS 140F2400 100",naddr+(offset%512));
    strlen(cmd,cmdlen);
    str_usercmd(cmd,cmdlen,2000,1716,1,RDBUF,512);
	//str_setbyteswap(1);
    return 0;
}

int MGET(int mcid, int offset) //F1 MCFS
{
    char cmd[32];
    char addr[16];
    int  cmdlen,i,naddr,nOffSn;
    
    TurnOff();
	delays(15);
	poststatus("pwr on");
	power(1);
	delays(30);
    
   // nOffSn = offset/512;
    nOffSn = 0;
    sprintf(cmd,"TF %x 0 0 1 %x",mcid, nOffSn);
    strlen(cmd,cmdlen);
    
    ONERROR(dummyerror);
    str_usercmd(cmd,cmdlen,5000,512,0,RDBUF,512);
    ONERRORCLEAR();
    
    strstr(RDBUF,"OK",i);
    if(i == 0)
    return 1;

    strfind(RDBUF,"ddr",cmdlen);
    cmdlen = cmdlen+6;  //space
    
    for(i = 0; i < 8; i++)
    addr[i]=RDBUF[cmdlen+i];
    
    atoi(addr,0,16,naddr); 
    if(addr == 0)
    return 1;
    
	//str_setbyteswap(0);
    sputd(cmd,"DS %x 100",naddr+(offset));
    //sputd(cmd,"DS %x 100",naddr+(offset%512));
    //sputd(cmd,"DS 140F2400 100",naddr+(offset%512));
    strlen(cmd,cmdlen);
    str_usercmd(cmd,cmdlen,2000,1716,1,RDBUF,512);
	//str_setbyteswap(1);
    return 0;
}
void dummyerror()
{
	poststatus("DummyErr");
	return;
}

void Errorcnt(int step)
{

    Id_Retry();
   	str_getidfydata(0, 511, rdbuf);
    
	nEc= ((rdbuf[232]<<8) | rdbuf[233]);
    estep = 0;
    
    if (step == 1 || step ==2 )
    {   
         nEc1 = nEc;
    }

    if(step == 3)
    {
        nEc2 = nEc1 - nEc;
        estep = nEc2;        
    }    
    
    power(0);
	delays(15);
    
    poststatus("Turn On");
	power(1);
    delays(30);
    str_checkprompt("ENG>"); 	
    

}//End Error Log count check


void Dfree(int estep)
{
    int tled;
    
	if(nEc == 0 )
	{
       	poststatus("No Error"); 
	}
  
	else
	{
 
		str_setdrvgrade(CHAR_C, 2);  //fored C Grade 
		delays(2);
        str_checkprompt("ENG>");
    	
	//BI code D/L		
		if (flag_5400RPM == 0 )
		{	
            poststatus("D/F HTBI D/L");
            strcpy(DWCODE,HTBICODE);DW_RTY();
		}
		else
		{	
            poststatus("D/F HTBI54 D/L"); 
            strcpy(DWCODE,HTBI54);DW_RTY();
		}
	    poststatus("CHK BOOT HTBICODE");
		delays(30);
		poststatus("poweroff BICode");
		power(0);
		delays(15);
		poststatus("Turn On");
		power(1);
		delays(60);
		Reset_Retry();	

   	    poststatus("OVLY D/L");
		if (flag_5400RPM == 0 )
        {
            str_userdownload("DO",OVERLAY,0x4C);      
        }
        else
        {
            str_userdownload("DO",OVERLAY_54,0x4C);
        }
        delays(10);
        str_checkprompt("ENG>");
    
		//Defect Free
		poststatus("Inline DF1");
 		str_sendserialcmd("DD",2);
        delays(1500);
        
       
		// Main code D/L
		poststatus("SCRBIN D/L");
		if (flag_5400RPM == 0)
		{	
            delays(15);
            poststatus("SCRBIN D/L");
    		strcpy(DWCODE,SCRBIN);DW_RTY();
		}
		else
		{	
            delays(15);
            poststatus("SCRBIN54 D/L");
            strcpy(DWCODE,SCRBIN54);DW_RTY();
		}
		poststatus("CHK BOOT SCRBIN");
		delays(30);
		str_checkprompt("BOOT>");
		delays(3);
		poststatus("poweroff SCRBIN");
		power(0);
		delays(15);
		poststatus("Turn On");
		power(1);
		delays(20);
		Reset_Retry();	
 	}
    
    if (step == 3 && nEc2 > 0)
    {
        str_setdrvgrade(CHAR_D, estep);  //fored C Grade 
    }
    		
       
    if( nEc > 150 )
    {
       str_stoptestfail(4, 0x3104); 
    }

}


//New MES
void SendMESData(int step)
{
    char pn[16];
    int  pnlen;
    char debug[20];
    int ret;
    int  proc;
    char mcode[16];
    char dsmcode[16];
    char ddsmcode[16];
    char klmcode[16];
    char dklmcode[16];
    char kldmcode[16];
    char basicmodel[16];
    char filepath[50];
    char appname[20];
    char keyname[20];
    char keyvalue[50];
    int  mdlmatch;
    

    if (step == SEND_DATA_INIT)
    {
        FG_SC_START = 0;
        FG_SC_PASS  = 0;
        FG_BI_START = 0;
        FG_BI_PASS  = 0;
        FG_BI_MODEL = 0;
        return;
   	}

    //check S/N
    getsn(pn);
    strlen(pn, pnlen);

    if (pnlen != 0x0E)
    {
        //sputd(debug, "PN %d", pnlen);
        //poststatus(debug);
        return;
    }
    
    strncpy(mcode, pn, 4);
	mcode[4] = 0;
    
    //str_checkmodel();
    delays(2);
    
    if (step == SEND_SC_START && FG_SC_START == 0)
    {
        poststatus("SEND_SC_START");
        str_messcstart();
        FG_SC_START = 1;
    }

    if (step == SEND_SC_PASS && FG_SC_PASS == 0)
    {
        if (FG_SC_START == 0)
        {
            str_messcstart();
            FG_SC_START = 1;
            delays(2);
        }
    
        poststatus("SEND_SC_PASS");
        str_messcend();
        FG_SC_PASS = 1;
    }

    if (step == SEND_BI_START && FG_BI_START == 0)
    {
        str_getscskip(SCCKIP);
        str_getdelayproc(ret);
        if(ret != 0)
        {
            
        }
        else
        {
            if (SCCKIP == 0)
            {
                if (FG_SC_START == 0)
                {
                    str_messcstart();
                    FG_SC_START = 1;
                    delays(2);
                }
                if (FG_SC_PASS == 0)
                {
                    str_messcend();
                    FG_SC_PASS = 1;
                    delays(2);
                }
            }
        }
        
        poststatus("SEND_BI_START");
        str_mesbistart();
        //str_messcript();
        str_messespecscript();      
        FG_BI_START = 1;
    }

    if (step == SEND_BI_MODEL && FG_BI_MODEL == 0)
    {
        str_getbasicmodel(basicmodel);
        basicmodel[7] = 0;
        
     	//we have to do only inline d/s, we don't have inline killing
        
        strcpy(filepath, "emodel.txt");
        
        //basic model
        getkeystring(filepath, "BASIC_MODEL", mcode, keyvalue);
        keyvalue[7] = 0;
        
        strcmp(basicmodel, keyvalue, 7, mdlmatch);
        if (mdlmatch == 0)
        {
            str_changemesmodel(mcode);
        }
        
        //inline D/S
        strcpy(dsmcode, mcode);
        if (mcode[2] == CHAR_0)
        {
            dsmcode[2] = CHAR_J; 
        }
        else
        {
            dsmcode[2] = mcode[2]+0x10; 
        }
        
        getkeystring(filepath, "BASIC_MODEL", dsmcode, keyvalue);
        keyvalue[7] = 0;
    
        strcmp(basicmodel, keyvalue, 7, mdlmatch);
        if (mdlmatch == 0)
        {
            str_changemesmodel(dsmcode);
        }
        
        if (flag_DDS == 1)
        {
            //inline D/S
           strcpy(ddsmcode, mcode);
            if (mcode[2] == CHAR_0)
            {	
                ddsmcode[2] = CHAR_T; 
            }
            else
            {	
                ddsmcode[2] = mcode[2]+0x1A; 
            }
            getkeystring(filepath, "BASIC_MODEL", ddsmcode, keyvalue);
            keyvalue[7] = 0;
            
            strcmp(basicmodel, keyvalue, 7, mdlmatch);
            if (mdlmatch == 0)
            {
                str_changemesmodel(ddsmcode);
            }
        }
        
        if (flag_KIL == 1)
        {
            //inline Killing
            strcpy(klmcode, mcode);
            if (mcode[3] == CHAR_0)
            {	
                klmcode[3] = CHAR_J; 
            }
            else
            {	
                klmcode[3] = mcode[3]+0x10; 
            }
            getkeystring(filepath, "BASIC_MODEL", klmcode, keyvalue);
            keyvalue[7] = 0;
                
            strcmp(basicmodel, keyvalue, 7, mdlmatch);
            if (mdlmatch == 0)
            {
                str_changemesmodel(klmcode);
            }
  		}
        
        FG_BI_MODEL = 1;
    }

    if (step == SEND_BI_PASS && FG_BI_PASS == 0)
    {
        if (FG_BI_START == 0)
        {
            str_mesbistart();
            //str_messcript();
            str_messespecscript();      
            FG_BI_START = 1;
            delays(2);
        }
    
       	poststatus("SEND_BI_PASS");
        //str_mesdownsize(0);
        str_mesbiend();
        FG_BI_PASS = 1;
    }
    return;
}

void cmd_CB()
{
    poststatus("Cmd CB");
    str_sendserialcmd("CB",2);
    delays(20);
    chk_ENG_wRetry();
}

void cmd_IN()
{
    str_sendserialcmd("IN 1",4);
    delays(20);
    chk_ENG_wRetry();
}

void cmd_LF()
{
    str_sendserialcmd("LF",2);
    delays(5);
    chk_ENG_wRetry();
}
void Check_LedBI()
{
    str_getinvalidled(INVALID_LED);
    if (INVALID_LED != 0x00 )
    {
       	delays(300);  
       	str_stoptestfail(3, INVALID_LED);
    }
}

void Check_LedSC()
{
    str_getinvalidled(INVALID_LED);
    if(INVALID_LED != 0x00 )
    {
        delays(300);  
      	str_stoptestfail(1, INVALID_LED);
      
    }
}

void Check_LedSC1()
{
    if (SCCKIP == 0)
    {
        str_getinvalidled(INVALID_LED);
        if(INVALID_LED != 0x00 )
        {
            str_debugmode();
            str_checkprompt("DBG>");

            //download SC code
            poststatus("SCCODE2 D/L");
            strcpy(DWCODE,SCCODE2);DW_RTY();
            poststatus("CHK BOOT SCCODE2");
            delays(10);
            
            TurnOff();
            delays(10);
            
            poststatus("Turn On");
            power(1);
            delays(120);
            Check_LedSC();
            chk_ENG_wRetry();
        }        
    }
    else
    {
        Reset_Retry();
        str_getinvalidled(INVALID_LED);
        if(INVALID_LED != 0x00 )
        {
            delays(300);  
            str_stoptestfail(1, INVALID_LED);
          
        }
    }

}
void Id_Retry()
{
	ONERROR(retryid);
	poststatus("IDFY");
	cmdtimeout(10000);     // 10 sec
	id(0);
	cmdtimeout(0);
	ONERRORCLEAR();
}

void retryid()
{
	ONERRORCLEAR();
	TurnOff();
	delays(15);
	poststatus("ID_Re");
	power(1);
	delays(120);
	reset();
    cmd_IN();
	cmdtimeout(200000);     // 200 sec
	id(0);
	cmdtimeout(0);

}

void DNR_Id_Retry()
{
    ONERROR(dnr_retryid);
    poststatus("IDFY");
    cmdtimeout(30000);     // 30 sec
    id(0);
    cmdtimeout(0);
    ONERRORCLEAR();
}

void dnr_retryid()
{
    ONERROR(errmesreset);
    TurnOff();
    delays(60);
    poststatus("ID_Re");
    power(1);
    delays(120);
    reset();
    ONERROR(errmesidfy);
    cmdtimeout(200000);     // 200 sec
    id(0);
    cmdtimeout(0);
}

void errmesreset()
{
    ONERRORCLEAR();
    str_messcstart();
    reset();
}

void errmesidfy()
{
    ONERRORCLEAR();
    str_messcstart();
    id(0);
}
void SN_clear()
{
    poststatus("Turn On");
	power(1);
	delays(120);
    //Check_LedSC1();		//Check Not Ready Failure ex. 1102, 1702 etc
	Reset_Retry_Kill();
    cmd_IN();
    cmd_LF();
    poststatus("IDFY");
	Id_Retry();
	str_getidfydata(0, 511, rdbuf);
	// Code Check(_"P",Check)
	if (rdbuf[215] == 0x50)
	{
		poststatus("smt");
		str_sendserialcmd("EU",2); 
        delays(5);
        if ((rdbuf[218] == 0x32)   ||  (rdbuf[218] == 0x37))  // check SMT code P/F: 2x & 7x => F3
        {     
            delays(5);
        }
        else 
        {
            poststatus("Check Model");
            stoptest();
        }
    }

    poststatus("Turn Off");
    power(0);
    delays(15);
    
}


void TurnOff()
{
	power(0);
	delays(15);
	BAUD_RATE= 57600;
}

void PN_Write()
{
    int i;
    int nopn;
    nopn = 0;
    cmdtimeout(120000);     // 1 min
    id(0);
    cmdtimeout(0);
    str_getidfydata(20, 14, pn);
    //Check PN
    for(i = 0 ; i < 14 ; i++)
    {
        if((pn[i]<0x30 || pn[i]>0x39) && (pn[i]<0x41 || pn[i]>0x5A))
        {
            nopn = 1;   
        }   
    }        
        if(nopn==1)
        {
      
            portnum(port);          
            delays(port);
            sputd(snfile,"C:\STR-2\PN.TXT", port);
            fopen(fhandle,snfile,"r");
            if(fhandle != -1)
            {
                char strport[6];
                int offset;

                memset(pn,0,0,16);
                fread(fhandle,buffer,10080);
                fclose(fhandle);

                sputd(strport,"P%03d",port);
                strfind(buffer,strport,offset);
                if(offset !=0 )
                {
                    memnmov(pn,buffer,0,offset+5,14,0);
                    poststatus(pn);
                }
                poststatus("SN Write START");    
                str_sendserialcmd("LI 7",4);
                delays(10);
                poststatus("PN");
                str_sendserialcmd(pn,14);
                delays(10);
                poststatus("WS");
                str_sendserialcmd("WS",2);
                delays(120);
                str_checkprompt("ENG>"); 
                poststatus("WO");
                str_sendserialcmd("WO",2);
                delays(120);
                str_checkprompt("ENG>");    
                poststatus("SN DONE");
            }
         	power(0);
        	delays(15);
        
        	power(1);
        	delays(60);
            chk_ENG_wRetry();
            cmd_IN();
        }
}

void GRADE_RND()
{
    int i, k, b[8], cause;
    
  	//check invalid led
	str_getinvalidled(INVALID_LED);
	if (INVALID_LED != 0x00 )
	{
        delays(300);  
		str_stoptestfail(3, INVALID_LED);
	}
    
    str_checkprompt("ENG>");
    
	reset();
    str_getidfydata(452, 2, grade);

    // FUJI Grade Cause
    k=256;
    for(i=0;i<8;i++)
    {
        k=k/2;
        b[i] = grade[0]/k;
        cause = grade[0]%k;
        grade[0] = cause;
    } 

    if((grade[1] == 0x01) && ((b[0]==1)||(b[1]==1)||(b[6]==1)))
    {
        str_setdrvgrade(CHAR_C,1);
        flag_OEM = 1;
    }    

    if((b[3]==1)&&(b[4]==1)&&(b[6]==1))
    {
        str_setdrvgrade(CHAR_S,1);
        flag_OEM = 2; 
    }
}

void GRADE_RND2()
{

  	//check invalid led
	str_getinvalidled(INVALID_LED);
	if (INVALID_LED != 0x00 )
	{
        delays(300);  
		str_stoptestfail(3, INVALID_LED);
	}
    
    str_checkprompt("ENG>");
    
	reset();
    str_getidfydata(452, 2, grade);

    if( grade[1] == 0x00)  
    {
    	//str_setdrvgrade(CHAR_A,10);
        flag_OEM = 1;
    }
    else
    {
    	//str_setdrvgrade(CHAR_C,1);
        flag_OEM = 0;
    }   

}

//******** DNR test function **********//

void DNR_Test()
{
	int postfix;
	int dnrenabled;
	int resetOK;
	int pnmismatch;
	int invled;
	char mc_pn[21];
	char scan_pn[21];
	int mc_pn_len;
	int scan_pn_len;
	int maincodetest;

	resetOK			= 0;
	dnrenabled		= 0;
	pnmismatch		= 0;
	invled			= 0;
	mc_pn_len		= 0;
	scan_pn_len		= 0;
	maincodetest		= 0;
	
/*	str_getmcodeoption(maincodetest);
	if (maincodetest != 0)
	{
		// power recycle
		power(0);
		delays(10);
		poststatus("DNR TEST");
		power(1);
		delays(180);
		str_debugmode();
		userfilelog("D/L flash in maincode option");
		
		// D/L flash code
		dw(HTBICODE);
		//dw(FFLASH);
		//dw(HTCODE);
		delays(30);
		poststatus("CHK BOOT");
		str_checkprompt("BOOT>");
		poststatus("Turnoff");
		power(0);
		delays(10);		
	}	
*/   
	str_getdnroption(dnrenabled);
	if (dnrenabled != 0)
	{
		// check debug prompt for port fail
		//Diagnose_PortStatus();
		
		// power recycle
		power(0);
		delays(10);
		poststatus("DNR TEST");
		power(1);
		delays(180);
		
		// get invalid led
		invled = 0;
		str_getinvalidled(invled);

		// set scanned pn
		pnmismatch = 0;
		str_getscannedpn(scan_pn);
		strlen(scan_pn, pnmismatch);
		if (pnmismatch == 0x0E)
		{
			str_setscannedpn(scan_pn);
			userfilelog("set scanned pn");
			userfilelog(scan_pn);
		}
		
		// reset
		resetOK = Reset_NoFail();
		
		if (resetOK == 0)	// reset ok
		{
			poststatus("resetOK");
            DNR_Id_Retry();
			str_getpostfix(postfix);
						
			//compare scanned pn with identified pn
			if (postfix != POSTFIX_SMT)
			{
				poststatus("Check PN");
				getsn(mc_pn);
				str_getscannedpn(scan_pn);
				
				strlen(scan_pn, scan_pn_len);
				strlen(mc_pn, mc_pn_len);
				if (scan_pn_len == 0x0E && mc_pn_len == 0x0E)		
				{
					pnmismatch = 0;
					strcmp(mc_pn, scan_pn, 14, pnmismatch);
					
					if (pnmismatch != 0)
					{
						poststatus("PN MISMATCH");
						userfilelog("PN MISMATCH");
						stoptest();
					}
					poststatus("PN GOOD");
				}
			}

			if (postfix != POSTFIX_SMT && invled != 0x00)
			{
				//if (invled == 0x13 || invled == 0x14)
				if (invled == 0x1411 || invled == 0x1102)
				{
					if (postfix == POSTFIX_SC)
					{
						str_mesbistart();
						//str_messcript();
                        			str_messespecscript();      
						delays(5);

						userfilelog("D/L flash");
						
						// D/L flash code
						dw(HTBICODE);
						//dw(FFLASH);
						//dw(HTCODE);
						delays(30);
						poststatus("CHK BOOT");
						str_checkprompt("BOOT>");
						poststatus("Turnoff");
						power(0);
						delays(10);	
													
					}
					else
					{
						//str_mesbistart();
						str_messcstart();
						//str_messcript();
                       		 		str_messespecscript();      
						delays(5);						
						
						userfilelog("D/L s/c");
						
						// D/L S/C
						dw(SCCODE1);
						delays(30);
						poststatus("CHK BOOT");
						str_checkprompt("BOOT>");
						poststatus("Turnoff");
						power(0);
						delays(10);								
					}
				}
				else
				{
					poststatus("LED FAIL");
					
					//str_mesbistart();
					//str_messcript();
					delays(5);
					
					delays(5);
					if (postfix == POSTFIX_SC)	// S/C error
					{
						str_messcstart();
						//str_messcript();
                        			str_messespecscript();      
						userfilelog("S/C led fail");
						str_stoptestfail(1, invled);
					}
					else	// B/I error
					{
						str_mesbistart();
						//str_messcript();
                        			str_messespecscript();      
						userfilelog("B/I led fail");
						str_stoptestfail(3, invled);
					}
				}
			}
			else	// LED == 0x00 or SMT CODE
			{
				// NOP
				userfilelog("NOP");
				if (invled != 0x00)
				{
					str_mesbistart();
					//str_messcript();
                    			str_messespecscript();      
					delays(5);
					
					userfilelog("B/I led fail(NOP)");
					str_stoptestfail(3, invled);
				}
			
			}
		}
		else if (resetOK == 1)	// main code
		{
			poststatus("MaybeMaincode");
			
			str_mesbistart();
			//str_messcript();
            		str_messespecscript();      
			delays(5);		
			
			userfilelog("D/L fflash");
			
			// D/L flash code
			dw(HTBICODE);
			//dw(FFLASH);
			//dw(HTCODE);
			delays(30);
			poststatus("CHK BOOT");
			str_checkprompt("BOOT>");
			poststatus("Turnoff");
			power(0);
			delays(10);			
		}
		else	// reset fail
		{
			pnmismatch = 0;
			str_getscannedpn(scan_pn);
			strlen(scan_pn, pnmismatch);
			if (pnmismatch == 0x0E)
			{
				userfilelog("reset failed(in DNR)");
				
				str_setscannedpn(scan_pn);
				poststatus("NotReady");
				str_messcstart();
				//str_messcript();
                		str_messespecscript();      
				delays(5);
				str_stoptestfail(5, 8);		// 8 is Not Ready error code
			}
			else
			{
				userfilelog("PN BROKEN");
				
				poststatus("PN BROKEN");
				stoptest();
			}
		}
	}	
	
	return;
}


int Reset_NoFail()
{
	char CMD[16];
	char RCV[512];
	int ret_reset;

	CMD[0]= 0x12;
  	CMD[1]= 0x00;
  	
  	//********** for normal case ***************//
  	memset(RCV,0,0,512);
  	
  	ONERROR(dummyerror);
  	str_usercmd(CMD, 2, 1000, 30, 0, RCV, 512);
  	ONERRORCLEAR();
  	
  	// main code "Inv"
  	ret_reset = 0;
  	strstr(RCV, "Inv", ret_reset);
  	if (ret_reset != 0)
  	{
  		poststatus("-M-");
  		return 1;
  	}
  	
  	// reset ok
  	ret_reset = 0;
  	strstr(RCV, "ENG>", ret_reset);
  	if (ret_reset != 0)
  	{
  		poststatus("-GOOD-");
  		return 0;
  	}

	//********** for loopback ********************//
	// reset fail
	ONERROR(dummyerror);
	str_debugmode();
	ONERRORCLEAR();

  	memset(RCV,0,0,512);
  	ONERROR(dummyerror);
  	str_usercmd(CMD, 2, 1000, 30, 0, RCV, 512);
	ONERRORCLEAR();
	
  	// main code "Inv"
  	ret_reset = 0;
  	strstr(RCV, "Inv", ret_reset);
  	if (ret_reset != 0)
  	{
  		return 1;
  	}
  	
  	// reset ok
  	ret_reset = 0;
  	strstr(RCV, "DBG>", ret_reset);
  	if (ret_reset != 0)
  	{
  		return 0;
  	}
	
	return 2;
}

void Mass_MP()
{
    int MASS_ITEM_HD_LEN;
    int MASS_MAX_SUBITEM;
    int MASS_MAX_SECTOR_ITEM;
    int MASS_ITEM_LENGTH;

    char masshead[SECTOR_SIZE];
    char massdata[SECTOR_SIZE];
    char data[32];
    
    char dplfile[32];
    char CRLF[2];
    int  handle;

    char datetime[16];
    char racknumber[6];
    char portnumber[4];
    char reworkflag[16];
	//   char sbr[16];
    char passfail;

    char pn[20];
    int  numberofhead;
    char series[10];
    int  startoffset;

    char itemhead[4];//'BDRV'or'BHD#'
    int  tablenumber;
    int  item_group;
    int  item_subgroup;
    int  item_count;
    int  item_offset;

    int  ivalue;
    int  itemp;
    char codename[16];
    //char bisptrev[16];
    int  sectorloop,itemremain;
    int  i,j,k;

  	//initialize variables 
  	MASS_ITEM_HD_LEN = 32;
  	MASS_MAX_SUBITEM = 7;
  	MASS_MAX_SECTOR_ITEM= 128;
  	MASS_ITEM_LENGTH = 4;
  
  	CRLF[0]=0x0D;
  	CRLF[1]=0x0A;

  	reset();
    getracknumber(racknumber);                  //get rack number
    portnum(ivalue);                        //get port number
    sputd(portnumber, "%d", ivalue);
  	sputd(dplfile,"C:\STR-2\MASSDATA\P%03d.DPL", ivalue);  //portnumber.DPL
 	datetimestamp(datetime);                           //get date time
  	getled(ivalue);                                    //get pass fail
  	if(ivalue == 0x00 )
    	passfail = CHAR_P;
   	else
  	{
   		passfail = CHAR_F;
 
		TurnOff();
		delays(10);
		power(1);
		delays(60);
		cmd_IN();   
   	}
 
  	//get MASS header 
  	str_sendserialcmd("PP",2);
  	delays(300);
  	//str_getmasssize(ivalue);                           //init pmp & read pmp size

  	ivalue = GetMassBuffer(0, 1);
  	if (ivalue == 0)
  	{
		memnmov(masshead, BV_NEW_BUFFER, 0, 0, SECTOR_SIZE, 0);
  	}
  	else
  	{
    	if( passfail == CHAR_F )
    		stoptest();
    	return;  	  	
  	}
  
  	memnmov(pn,    masshead,0,0x10,20,0);//get pn
  	memnmov(series,masshead,0,0x26,10,0);//get series
  	getreworkflag(reworkflag);          //get reworkflag
  	peek(masshead,0x24,2,numberofhead);  //get numer of head
  	peek(masshead,0x60,4,startoffset);   //get start offset of DRV header
  	if(pn[0] == 0x00)
  	{
    	if( passfail == CHAR_F )
    		stoptest();
    	return;
  	}
    
  	//////////////////////////////////////////////////////////////////////////////
  	//parse PMP data
 	 //////////////////////////////////////////////////////////////////////////////
  	fopen(handle,dplfile,"ab");
  	if(handle == -1)
  	{
    	if( passfail == CHAR_F )
    		stoptest();
    	return;
  	}
  
  	item_group    = 0;  
  	item_subgroup = 0;
  	tablenumber   = 1;  
 	while(item_group < 9)//drv(1)+head(8) 
  	{
    	itemp = startoffset+MASS_ITEM_HD_LEN*item_group+item_subgroup*MASS_ITEM_LENGTH+4;
    	peek(masshead,itemp,2,item_offset);
    	itemp = startoffset+MASS_ITEM_HD_LEN*item_group+item_subgroup*MASS_ITEM_LENGTH+6;
    	peek(masshead,itemp,2,item_count);
    	item_subgroup++;
    	//end of paramter
    	if( item_offset == 0 || item_count == 0 ) 
    	{
    		if( item_subgroup >= MASS_MAX_SUBITEM  )
    		{
    			item_group++;     //increase item group	
    			item_subgroup = 0;//Item Sub group
    				tablenumber   = 1;//initialize tablenumber         
            }
   			else
    		{
    			tablenumber++;
    		}
      
    		continue;
    	}
    
    	//Fixed protocol head
    	sputs(data, "%s", pn);         
    	fwrite(handle,data,15);         //report pn
    	sputs(data, ",%s", datetime);
    	fwrite(handle,data,15);         //report datetime
    	sputs(data, ",%s", racknumber);
    	fwrite(handle,data,5);          //report racknumber
    	sputs(data, ",%s", portnumber);
    	strlen(data,ivalue);
   		fwrite(handle,data,ivalue);     //report portnumber
       	sputs(data, ",%s", series);
       	strlen(data,ivalue);
       	fwrite(handle,data,ivalue);     //report series
       	    
       	itemp = startoffset + MASS_ITEM_HD_LEN*item_group;
       	memset(itemhead,0,0,4);
       	memnmov(itemhead,masshead,0,itemp,3,0);
       	sputs(data, ",%s", itemhead);
       	fwrite(handle,data,4);          //report 'BDR' or 'BHD'
    	sputd(data, ",%d", tablenumber);
   		fwrite(handle,data,2);          //report tableno
   
    	//itemp_group == 0 is DRV info
   		if( item_group == 0 )
    	{
    		sputd(data, ",%d",0);
    	}
   		else
    	{
    		itemp = startoffset+MASS_ITEM_HD_LEN*item_group+3;
    		peek(masshead,itemp,1,ivalue);
    		sputd(data, ",%c",ivalue);
    	}
    	fwrite(handle,data,2);          //report head number
    	sputd(data, ",%c", passfail);
    	fwrite(handle,data,2);          //report passfail
    
    	sputd(data, ",%c", reworkflag);
    	fwrite(handle,data,2);          //report reworkflag
    
    	if( tablenumber == 1 && item_group == 0)
    	{
    		memset(codename,0,0,16);
    		memnmov(codename,masshead,0,0x30,16,0);//get sccode
           	for(i=0; i<16 ; i++)
           	{
           		if(((codename[i]<0x2D || codename[i]>0x39) && (codename[i]<0x41 || codename[i]>0x5A) && (codename[i]<0x61 || codename[i]>0x7A))) { codename[i]=0; break; }
           	}
    		strlen(codename,ivalue);
    		if(ivalue == 0)
    		{
      			sputd(data, ",%d", 0);
    		}
    		else
    		{
      			sputs(data, ",%s", codename);
    		}
    		strlen(data,ivalue);
    		fwrite(handle,data,ivalue);           //report sccode
      
    		memset(codename,0,0,16);
    		memnmov(codename,masshead,0,0x40,16,0);//get htcode
         	for(i=0; i<16 ; i++)
         	{
         		if(((codename[i]<0x2D || codename[i]>0x39) && (codename[i]<0x41 || codename[i]>0x5A) && (codename[i]<0x61 || codename[i]>0x7A))) { codename[i]=0; break; }
           	}
            strlen(codename,ivalue);
      		if(ivalue == 0)
      		{
        		sputd(data, ",%d", 0);
      		}
      		else
      		{
        		sputs(data, ",%s", codename);
      		}
      		strlen(data,ivalue);
      		fwrite(handle,data,ivalue);           //report htcode
      
      		memset(codename,0,0,16);
      		memnmov(codename,masshead,0,0x50,16,0);//get bicode
            for(i=0; i<16 ; i++)
            {
            	if(((codename[i]<0x2D || codename[i]>0x39) && (codename[i]<0x41 || codename[i]>0x5A) && (codename[i]<0x61 || codename[i]>0x7A))) { codename[i]=0; break; }
            }
      		strlen(codename,ivalue);
      		if(ivalue == 0)
      		{
        		sputd(data, ",%d", 0);
      		}
      		else
      		{
        		sputs(data, ",%s", codename);
      		}
      		strlen(data,ivalue);
      		fwrite(handle,data,ivalue);           //report bicode
    	}
    
    	sectorloop = item_count/MASS_MAX_SECTOR_ITEM+1;	//calculate data sector count
    	itemremain = item_count;
    	for(k = 0 ; k < sectorloop ; k++)
    	{
    		itemp = item_offset + k;

			cmdtimeout(1500);     
			ivalue = GetMassBuffer(itemp, 1);
			cmdtimeout(0);     
			if (ivalue == 0)
			{
				memnmov(massdata, BV_NEW_BUFFER, 0, itemp*SECTOR_SIZE, SECTOR_SIZE, 0);
			}	
			else
			{
	    		fwrite(handle,CRLF,2);
	      		fclose(handle);
	      		if( passfail == CHAR_F )
	        		stoptest();
	      		return;
			}	    

	    
	    	i = 0;  
	    	j = 0;
	    
	    	if(itemremain > MASS_MAX_SECTOR_ITEM)	//calculate sector data count
	    		itemp = MASS_MAX_SECTOR_ITEM;
	    	else
	    		itemp = itemremain;
	    
	    	for(i=0;i<itemp;i++)
	    	{
	      		j = i*MASS_ITEM_LENGTH;
	      		peek(massdata,j,4,ivalue);
	      		sputd(data, ",%d", ivalue);
	      		strlen(data,ivalue);
	      		fwrite(handle,data,ivalue);
	      		itemremain--;
    		}  
    	}
    
    	fwrite(handle,CRLF,2);
    	tablenumber++;//increase tableno
  	}
  	fclose(handle);
    
  	//if test is fail, stop the test
  	if( passfail == CHAR_F )
    	stoptest();
}

// 10 Grading 진행
void DriveGrading()
{
    char massbuf[1024];
    char basicmdl[24];
    char filename[24];
    char keyname[24];
    char prmfilename[32];
    char pn_mcode[24];
    char filepath[48];
    char appname[24];
    char keyvalue[48];
    
    int   MAX_GRADE_PARAM; //MAX PARAMETER COUNT
    int   paramno;
    float fparamvalue;
    
    //MASS MC data
    int   grade_offset, grade_sectorno;
    
    //.prm file parameter
    float prm_basis, prm_lcl4, prm_lcl3, prm_lcl2, prm_lcl1, prm_ucl4, prm_ucl3, prm_ucl2, prm_ucl1;
    float prm_g0, prm_g1, prm_g2, prm_g3, prm_g4, prm_g5, prm_g6, prm_g7, prm_g8;
    int   prm_drivegrade_high, prm_drivegrade_low;
    int   prm_type, prm_weight, prm_forced_c, prm_paragrade_a, prm_paragrade_b, prm_paragrade_c, prm_paragrade_d, prm_paragrade_e;

    //temporary variable
    int   ivalue1, ivalue2;
    float fvalue1, fvalue2, fvalue3;
    char  temp[128];
    
    //grade value 
    int   paramgrade, paramflag, forced, GX;
    int   totalsum, valuesum, percent;
    float fpercent;
    
    //for mass
    char  mass_int[2048];
    char  mass_ext[512];
    char  mass_header[256];
    char  datetime[16];
    char  series[16];
    char  dplfile[32];
    char  CRLF[2];
    char  gradeformass;
    char  rackno[6];
    int   portno, handle;
    
    CRLF[0]=0x0D; CRLF[1]=0x0A;
    MAX_GRADE_PARAM = 300; // MC:256, EXTERNAL:4
    
    poststatus("Grading");
    
    //MAKE MASS DATA
    str_sendserialcmd("PP",2);
    delays(300);
    
    //FIND PRM FILE NAME
    str_getdrvparamname(prmfilename);	// get prime prmfile
    memset(pn_mcode, 0, 0, 20);
    getsn(pn_mcode); pn_mcode[4] = 0;
    strlen(pn_mcode,ivalue1);
    if(ivalue1 == 0) return;            // No P/N 
    strcpy(filepath, "emodel.txt");
    getkeystring(filepath, "BASIC_MODEL", pn_mcode, keyvalue);
    strlen(keyvalue, ivalue1);
    if (ivalue1 >= 7)
    {
        memset(basicmdl, 0, 0, 20);
        str_getbasicmodel(basicmdl);
        strcmp(basicmdl, keyvalue, 7, ivalue1);
        if (ivalue1 != 0)
        {
            str_getdsdrvparamname(prmfilename);
            strlen(prmfilename, ivalue1);
            if (ivalue1 < 11)
            {
                str_getdrvparamname(prmfilename);// get prime prmfile
            }
        }			
    }
    strlen(prmfilename, ivalue1);
	if (ivalue1 < 11)
	{
		poststatus("No Binnig Info");
		stoptest();
	}
    userfilelog(prmfilename);
    
    //MAKE PRM FILE PATH
    strcpy(filepath, "script/");
	strcat(filepath, prmfilename);
    
    //GET GRADE DATA FROM MASS
    getkeystring(filepath, "DRIVE_GRADE", "OFFSETLOC", keyvalue);
    atoi(keyvalue,0,16,grade_offset);
    if (grade_offset == 0)
	{
		poststatus("Get Grade Offs");
		stoptest();
	}
    str_getmassdata(massbuf,0,2,ivalue1);
    if(ivalue1 != 1024)
    {
        poststatus("Get Grade Hdr");
        stoptest();
    }
    peek(massbuf,grade_offset,2,grade_sectorno);//get sector number
    memnmov(series,massbuf,0,0x26,10,0);        //get series
    str_getmassdata(massbuf,grade_sectorno,2,ivalue1);
    if(ivalue1 != 1024)
    {
        poststatus("Get Grade Dat");
        stoptest();
    }

    //get grade A,B,C criteria
    getkeystring(filepath, "DRIVE_GRADE", "DRVGRADE_HIGH", keyvalue); atoi(keyvalue,0,10,prm_drivegrade_high);
    getkeystring(filepath, "DRIVE_GRADE", "DRVGRADE_LOW" , keyvalue); atoi(keyvalue,0,10,prm_drivegrade_low);
    
    //get G0 - G8 criteria
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G0", keyvalue); atof(keyvalue,prm_g0);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G1", keyvalue); atof(keyvalue,prm_g1);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G2", keyvalue); atof(keyvalue,prm_g2);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G3", keyvalue); atof(keyvalue,prm_g3);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G4", keyvalue); atof(keyvalue,prm_g4);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G5", keyvalue); atof(keyvalue,prm_g5);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G6", keyvalue); atof(keyvalue,prm_g6);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G7", keyvalue); atof(keyvalue,prm_g7);
    getkeystring(filepath, "DRIVE_GRADE", "GRADE_G8", keyvalue); atof(keyvalue,prm_g8);

    for(paramno = 1 ; paramno <= MAX_GRADE_PARAM ; paramno++)
    {
        //
        //GET PARAMTER FROM .PRM
        //
        //get type from .prm
        sputd(appname,"PARAM_%03d",paramno);
        getkeystring(filepath, appname, "TYPE", keyvalue);
        strlen(keyvalue,ivalue1);
        delays(1);
        if(ivalue1 == 0)
            continue;
        
        //get param type
        strstr(keyvalue,"Upper Best Type",ivalue1);  if(ivalue1 != 0)  prm_type = 0;
        strstr(keyvalue,"Lower Best Type",ivalue1);  if(ivalue1 != 0)  prm_type = 1;
        strstr(keyvalue,"Mid Best Type",ivalue1);    if(ivalue1 != 0)  prm_type = 2;
        
        //get basis from .prm
        getkeystring(filepath, appname, "BASIS", keyvalue);atof(keyvalue,prm_basis);
        
        //get LCL4 - LCL1, UCL4 - UCL1 from .prm
        getkeystring(filepath, appname, "LCL4", keyvalue); atof(keyvalue,prm_lcl4);
        getkeystring(filepath, appname, "LCL3", keyvalue); atof(keyvalue,prm_lcl3);
        getkeystring(filepath, appname, "LCL2", keyvalue); atof(keyvalue,prm_lcl2);
        getkeystring(filepath, appname, "LCL1", keyvalue); atof(keyvalue,prm_lcl1);        
        getkeystring(filepath, appname, "UCL4", keyvalue); atof(keyvalue,prm_ucl4);
        getkeystring(filepath, appname, "UCL3", keyvalue); atof(keyvalue,prm_ucl3);
        getkeystring(filepath, appname, "UCL2", keyvalue); atof(keyvalue,prm_ucl2);
        getkeystring(filepath, appname, "UCL1", keyvalue); atof(keyvalue,prm_ucl1);        
        
        //get Weight from .prm
        getkeystring(filepath, appname, "Weight", keyvalue);  atoi(keyvalue,0,10,prm_weight);
        
        //get FORCED_C from .prm
        getkeystring(filepath, appname, "FORCED_C", keyvalue); atoi(keyvalue,0,10,prm_forced_c);
        
        //get PARAMGRADE_A - PARAMGRADE_E from .prm
        getkeystring(filepath, appname, "PARAGRADE_A", keyvalue); atoi(keyvalue,0,10,prm_paragrade_a);
        getkeystring(filepath, appname, "PARAGRADE_B", keyvalue); atoi(keyvalue,0,10,prm_paragrade_b);
        getkeystring(filepath, appname, "PARAGRADE_C", keyvalue); atoi(keyvalue,0,10,prm_paragrade_c);
        getkeystring(filepath, appname, "PARAGRADE_D", keyvalue); atoi(keyvalue,0,10,prm_paragrade_d);
        getkeystring(filepath, appname, "PARAGRADE_E", keyvalue); atoi(keyvalue,0,10,prm_paragrade_e);
        
        //totalsum
        totalsum = totalsum + prm_paragrade_a*prm_weight;
        
        //
        //GET PARAM VALUE FROM MASS or MES
        //
        if(paramno <= 256)
        {
            int  i1,i2,i3;
            ivalue1 = (paramno-1)*4;
            peek(massbuf,ivalue1,4,ivalue2);
            fparamvalue = ivalue2;
            
            switch (paramno)
            {
                case 1:
                case 2:
                    // -log(value*512*8/100)
                    log10(ivalue2,fvalue1);
                    log10(4096,fvalue2);
                    fparamvalue = fvalue1 + fvalue2 - 3;//2 -> log10(1000)
                    //sputf(temp,"-%f",fparamvalue);
                    //atof(temp,fparamvalue);
                    break;
                case 3:
                    // -log(value/100)
                    if(ivalue2 < 1000 )
                    {
                    	fparamvalue = 0;
                    }
                    else
                    {	
                        log10(ivalue2,fparamvalue);
                        fparamvalue = fparamvalue - 3;
                    }
                    //sputf(temp,"-%f",fparamvalue);
                    //atof(temp,fparamvalue);
                    break;
                case 12:
                case 13:
                case 14:
                case 49:    
		case 63:
		case 64:
                    fparamvalue = fparamvalue/100;
                    break;
                case 15:
                    fvalue1 = fparamvalue/10;
                    sqrt(fvalue1,fparamvalue);
                    break;
                case 16:
                    //abs(16-15)
                    peek(massbuf,14*4,4,i1); 
                    ivalue1 = i1/10;
                    fvalue1 = ivalue1;
                    sqrt(fvalue1,fvalue2);
                    
                    ivalue1 = ivalue2/10;
                    fvalue1 = ivalue1;
                    sqrt(fvalue1,fvalue3);
                    
                    if(fvalue2 > fvalue3)
                        fparamvalue = fvalue2 - fvalue3;
                    else
                        fparamvalue = fvalue3 - fvalue2;
                    break; 

		case 70:
                case 71:
                   if(ivalue2 < 10 )
                    {
                    	fparamvalue = 0;
                    }
                    else
                    {	
                        log10(ivalue2,fparamvalue);
                  	fparamvalue = fparamvalue * 10 ;
                    }
                    break; 

                default:
                    break; 
            }
        }
        else
        {
            //wait for value(2 Hour)
            int cnt;
            char flag;
            cnt = 240;
            
            if(prm_weight != 0)
            {
	            while(cnt != 0)
	            {
	            	poststatus("Wait Grade Ext");
	                getreworkflag(flag);
	                if(flag != 0x53) break;
	                delays(30);
	                cnt--;
	                if(cnt == 0) 
	                {
	                    poststatus("MES Bin I/F");
	                    stoptest();
	                }
	            }
            }
            //Leakage
            if(paramno == 257)
            {
                fparamvalue = 1000000; //default
                str_getleakage(fparamvalue);
            }
            //Imbalance
            else if(paramno == 258)
            {
                str_getimbalance(fvalue1,fparamvalue);//spec,measured
                if(fvalue1==0 && fparamvalue==0)    //value not exist
                    fparamvalue = 1000000;
            }
            //DMR
            else if(paramno == 259)
            {
                str_getdmrflag(flag);
                if(flag == 0x4E) //'N'
                    fparamvalue = 0;
                else
                    fparamvalue = 1000000;
            }
            //ReSTW/REWORK
            else if(paramno == 260)
            {
                str_getreprocessflag(flag);
                if(flag == 0x4E) //'N'
                    fparamvalue = 0;
                else
                    fparamvalue = 1000000;
            }
            //PCBA USED COUNT
            else if(paramno == 261)
            {
                str_getpcbausedcnt(ivalue1);
                fparamvalue = ivalue1;
            }
        }
        
        //
        //DECISION GRADE
        //
        //Upper Best Type
        if(prm_type == 0)
        {
            if(fparamvalue > prm_ucl1)                                     paramgrade = prm_paragrade_a;
            else if((fparamvalue > prm_ucl2) && (fparamvalue <= prm_ucl1)) paramgrade = prm_paragrade_b;
            else if((fparamvalue > prm_ucl3) && (fparamvalue <= prm_ucl2)) paramgrade = prm_paragrade_c;
            else if((fparamvalue > prm_ucl4) && (fparamvalue <= prm_ucl3)) paramgrade = prm_paragrade_d;
            else                                                           paramgrade = prm_paragrade_e; 
        }
        //Lower Best Type
        else if(prm_type == 1)
        {
            if(fparamvalue < prm_lcl1)                                      paramgrade = prm_paragrade_a;
            else if((fparamvalue < prm_lcl2) && (fparamvalue >= prm_lcl1))  paramgrade = prm_paragrade_b;
            else if((fparamvalue < prm_lcl3) && (fparamvalue >= prm_lcl2))  paramgrade = prm_paragrade_c;
            else if((fparamvalue < prm_lcl4) && (fparamvalue >= prm_lcl3))  paramgrade = prm_paragrade_d;
            else                                                            paramgrade = prm_paragrade_e; 
        }
        //Mid Best Type
        else if(prm_type == 2)
        {
            if((fparamvalue > prm_lcl1) && (fparamvalue <= prm_ucl1))       paramgrade = prm_paragrade_a;
            else if((fparamvalue > prm_lcl2) && (fparamvalue <= prm_lcl1))  paramgrade = prm_paragrade_b;
            else if((fparamvalue > prm_lcl3) && (fparamvalue <= prm_lcl2))  paramgrade = prm_paragrade_c;
            else if((fparamvalue > prm_lcl4) && (fparamvalue <= prm_lcl3))  paramgrade = prm_paragrade_d;
            else if((fparamvalue > prm_ucl1) && (fparamvalue <= prm_ucl2))  paramgrade = prm_paragrade_b;
            else if((fparamvalue > prm_ucl2) && (fparamvalue <= prm_ucl3))  paramgrade = prm_paragrade_c;
            else if((fparamvalue > prm_ucl3) && (fparamvalue <= prm_ucl4))  paramgrade = prm_paragrade_d;                
            else                                                            paramgrade = prm_paragrade_e; 
        }

    	if(prm_weight != 0)
    	{
        	if(paramgrade == prm_paragrade_c || paramgrade == prm_paragrade_d) 
        	{
            	paramflag = 1;
        	}
        	else if(paramgrade == prm_paragrade_e)
	        {
	            paramflag = 1;
            	if(forced < prm_forced_c)
                    forced = prm_forced_c;
        	}
    	}
        valuesum = valuesum + paramgrade*prm_weight;//gradevalue sum
        
        //each parameter store for mass 
        if(paramgrade == prm_paragrade_a)       sprintf(temp,"%3.2f,P0,%d,%d,",fparamvalue,prm_weight,prm_forced_c);
        else if(paramgrade == prm_paragrade_b)  sprintf(temp,"%3.2f,P1,%d,%d,",fparamvalue,prm_weight,prm_forced_c);
        else if(paramgrade == prm_paragrade_c)  sprintf(temp,"%3.2f,P2,%d,%d,",fparamvalue,prm_weight,prm_forced_c);
        else if(paramgrade == prm_paragrade_d)  sprintf(temp,"%3.2f,P3,%d,%d,",fparamvalue,prm_weight,prm_forced_c);
        else                                    sprintf(temp,"%3.2f,P4,%d,%d,",fparamvalue,prm_weight,prm_forced_c);
        if(paramno <= 256)
            strcat(mass_int,temp);
        else
            strcat(mass_ext,temp);
        
        //DEBUGLOG
        sprintf(temp,"PARNO_%d, hddval:%8.2f, grade:%d", paramno, fparamvalue, paramgrade);
        userfilelog(temp);
    }
	fvalue1 = valuesum*100;
    fvalue2 = totalsum;
    fpercent = fvalue1/fvalue2;
    percent  = (valuesum*100)/totalsum;
    //DEBUGLOG
    sprintf(temp,"valuesum:%d, totalsum:%d, PERCENT: %3.2f",valuesum, totalsum, fpercent);
    userfilelog(temp);
    
    //compare value and get A,B,C and set grade for mes
    if(forced == 0)
    {
        //P0 - P1
        if(paramflag == 0)
        {
            if(fpercent >= prm_g0)      GX = 0;
            else                        GX = 1; 
        }
        //P2 - P3
        else
        {
            if(fpercent >= prm_g2)      GX = 2;
            else if(fpercent >= prm_g3) GX = 3; 
            else if(fpercent >= prm_g4) GX = 4;    
            else if(fpercent >= prm_g5) GX = 5;    
            else                        GX = 6;
        }
    }
    else//P4
    {
        if(forced == 1)                 GX = 7;
        else if(forced == 2)            GX = 8;
	else                            GX = 9;
    }
	 if(GX < prm_drivegrade_high)
    {
        str_setdrvgrade(CHAR_A, percent);
        gradeformass = CHAR_A;
    }
    else if(GX < prm_drivegrade_low)
    {
        str_setdrvgrade(CHAR_B, percent);
        gradeformass = CHAR_B;
    }
    else
    {
        str_setdrvgrade(CHAR_C, percent);
        gradeformass = CHAR_C;
    }
  
    
    //make mass parameter data 
    getsn(pn_mcode);
    strlen(pn_mcode,ivalue1); if(ivalue1 == 0) return;
    getracknumber(rackno);
    datetimestamp(datetime);
    portnum(portno);
    sputd(dplfile,"C:\STR-2\MASSDATA\P%03d.DPL", portno);
    
    fopen(handle,dplfile,"a");
    if(handle == -1)
        return;
    
    //PN	DATETIME	설비번호	PORTNO	계열군코드	DRIVE/HEAD구분	TABLE구분	HEAD구분	양품/불량구분	REWORK구분	SET GRADE A	SET GRADE B	SET 총점	파라미터1 VALUE	파라미터1 등급
    //기본정보와 동일					BDR	7	기본정보와 동일			G0~G9	A~C			P0~P4
    memset(mass_header,0,0,256);
    sputs(temp,"%s ,",pn_mcode);         strcat(mass_header,temp);
    sputs(temp,"%s,",datetime);         strcat(mass_header,temp);
    sputs(temp,"%s,",rackno);           strcat(mass_header,temp);
    sputd(temp,"%d,",portno);           strcat(mass_header,temp);
    sputs(temp,"%s,",series);           strcat(mass_header,temp);
    sputd(temp,"BDR,6,0,P,P,G%d,",GX);  strcat(mass_header,temp);//TABLE 6
    sputd(temp,"%c,",gradeformass);     strcat(mass_header,temp);
    sputf(temp,"%3.2f,",fpercent);      strcat(mass_header,temp);
    strlen(mass_header,ivalue1);
    fwrite(handle,mass_header,ivalue1);
    strlen(mass_int,ivalue1);
    fwrite(handle,mass_int,ivalue1-1);//eliminate ','
    fwrite(handle,CRLF,2);
    
    strlen(mass_ext,ivalue1);
    if(ivalue1 == 0)
    {
        fclose(handle);
        return;
    }
    memset(mass_header,0,0,256);
    sputs(temp,"%s ,",pn_mcode);         strcat(mass_header,temp);
    sputs(temp,"%s,",datetime);         strcat(mass_header,temp);
    sputs(temp,"%s,",rackno);           strcat(mass_header,temp);
    sputd(temp,"%d,",portno);           strcat(mass_header,temp);
    sputs(temp,"%s,",series);           strcat(mass_header,temp);
    sputd(temp,"BDR,7,0,P,P,G%d,",GX);  strcat(mass_header,temp);//TABLE 7
    sputd(temp,"%c,",gradeformass);     strcat(mass_header,temp);
    sputf(temp,"%3.2f,",fpercent);      strcat(mass_header,temp);
    strlen(mass_header,ivalue1);
    fwrite(handle,mass_header,ivalue1);
    strlen(mass_ext,ivalue1);
    fwrite(handle,mass_ext,ivalue1-1);//eliminate ','
    fwrite(handle,CRLF,2);
    fclose(handle);
    
}
void Mass_RND()
{
    int MASS_ITEM_HD_LEN;
    int MASS_MAX_SUBITEM;
    int MASS_MAX_SECTOR_ITEM;
    int MASS_ITEM_LENGTH;
    int MASS_TYPE;
    char SET_GROUP[24];
    char HEAD_GROUP[24];
    char SET_TABLE[24];
    char HEAD_TABLE[24];

    char masshead[1024];
    char massdata[SECTOR_SIZE];
    char data[32];
    

    char dplfile[32];
    char CRLF[2];
    int  handle;

    char datetime[16];
    char racknumber[6];
    char portnumber[4];
    char reworkflag[16];
 //   char sbr[16];
    char passfail;

    char pn[20];
    int  numberofhead;
    char series[10];
    int  startoffset;

    char itemhead[4];//'BDRV'or'BHD#'
    int  tablenumber;
    int  item_group;
    int  item_subgroup;
    int  item_count;
    int  item_offset;

    int  ivalue;
    int  itemp;
    char codename[16];
    //char bisptrev[16];
    int  sectorloop,itemremain;
    int  i,j,k;


    /*
        str_geasssize(ivalue);                  //init MASS & read MASS size
        for( i = 0 ; i < 15 ; i++)
        {
            sputd(dplfile,"C:\data%d.DAT", i);
            fopen(handle,dplfile,"ab");
            str_getmassdata(masshead,i,1,ivalue); //read head data
            fwrite(handle,masshead,512);          //report reworkflag
            fclose(handle);
        }
        return;
    */

    strcpy(SET_GROUP,"ABCABCDEFGHABCDEFGHABCD");
    strcpy(SET_TABLE,"11122222222333333334444");
    strcpy(HEAD_GROUP,"ABCABCDABCDABCDEFGHIJKL");
    strcpy(HEAD_TABLE,"11122223333444444444444");

    CRLF[0]=0x0D; CRLF[1]=0x0A;
    MASS_MAX_SECTOR_ITEM= 128;
    MASS_ITEM_LENGTH = 4;
    MASS_ITEM_HD_LEN = 96;
    MASS_MAX_SUBITEM = 23;

    getracknumber(ivalue);                  //get rack number
    sputd(racknumber, "%d", ivalue);
    portnum(ivalue);                        //get port number
    sputd(portnumber, "%d", ivalue);
    datetimestamp(datetime);                //get date time
    getled(ivalue);                         //get pass fail
    if(ivalue == 0x00 )
        passfail = CHAR_P;
    else
        passfail = CHAR_F;

	TurnOff();
	delays(5);

    power(1);
    delays(120);
    Check_LedBI();
    chk_ENG_wRetry();
    
    cmd_IN();
    
    Reset_Retry();
    
    for(MASS_TYPE=1 ; MASS_TYPE<2 ; MASS_TYPE++)
    {
        if(MASS_TYPE == 1)
        {
            str_getsbr(reworkflag);
            strlen(reworkflag,ivalue);
            if(ivalue == 0)
            {
                if( passfail == CHAR_F )
                    stoptest();
                return;
            }

            //download MCCODE for MASS DEV
            //poststatus("DBG Mode");
            //str_debugmode();
          
            cmdtimeout(120000);     // 5min
            id(0);
            cmdtimeout(0);

        }
        
        //initialize variables 
        if(MASS_TYPE == 0)
        {
            portnum(ivalue);                                        //get port number
            sputd(dplfile,"C:\STR-2\MASSDATA\P%03d.DPL", ivalue);   //PXXX.DPL
            
            memset(reworkflag,0,0,16);
            getreworkflag(reworkflag);                              //get reworkflag for MP
            delays(10);
            str_sendserialcmd("PP",2);
            delays(300);
            str_getmassdata(masshead, 0, 2, ivalue);
            if(ivalue != SECTOR_SIZE*2)
            {
                if(passfail == CHAR_F)
                    stoptest();
                return;
            }
        }
        else
        {
            portnum(ivalue);                                        //get port number
            sputd(dplfile,"C:\STR-2\MASSDATA\P%03d.TPL", ivalue);   //PXXX.TPL
            
            str_getsbr(reworkflag);                                 //get sbr for SAMPLE
            delays(10);
            //str_sendserialcmd("TM",2); 
            //delays(10);
            //str_checkprompt("ENG>");            
            delays(10);
            str_sendserialcmd("PP",2);
            delays(180);
            str_getmassdata(masshead, 0, 2, ivalue);
            if(ivalue != SECTOR_SIZE*2)
            {
                if(passfail == CHAR_F)
                    stoptest();
                return;
            }
        }
        
        memnmov(pn,masshead,0,0x10,20,0);       //get pn
        memset(series,0,0,10);
        memnmov(series,masshead,0,0x26,10,0);   //get series
        peek(masshead,0x24,2,numberofhead);     //get numer of head
        peek(masshead,0x60,4,startoffset);      //get start offset of DRV header
        //memset(bisptrev,0,0,16);
        //memnmov(bisptrev,masshead,0,0x64,12,0); //get bisptrev
        
        //Check PN
        for(i = 0 ; i < 14 ; i++)
        {
            if((pn[i]<0x30 || pn[i]>0x39) && (pn[i]<0x41 || pn[i]>0x5A))
            {
                if( passfail == CHAR_F )
                    stoptest();
                else
                    return;
            }
        }
        
        //////////////////////////////////////////////////////////////////////////////
        //parse MASS data
        //////////////////////////////////////////////////////////////////////////////
        fopen(handle,dplfile,"ab");
        if(handle == -1)
        {
            if(passfail == CHAR_F)
                stoptest();
            return;
        }
      
        item_group    = 0;  
        item_subgroup = 0;
        tablenumber   = 1;  
        while(item_group < 9)//drv(1)+head(8) 
        {
            itemp = startoffset+MASS_ITEM_HD_LEN*item_group+item_subgroup*MASS_ITEM_LENGTH+4;
            peek(masshead,itemp,2,item_offset);
            itemp = startoffset+MASS_ITEM_HD_LEN*item_group+item_subgroup*MASS_ITEM_LENGTH+6;
            peek(masshead,itemp,2,item_count);
            item_subgroup++;
            //end of paramter
            if(item_offset == 0 || item_count == 0 || item_subgroup > MASS_MAX_SUBITEM) 
            {
                if(item_subgroup > MASS_MAX_SUBITEM)
                {
                    item_group++;           //increase item group	
                    item_subgroup = 0;      //Item Sub group
                    tablenumber   = 1;      //initialize tablenumber         
                }
                else
                {
                    tablenumber++;
                }
                continue;
            }
            
            //Fixed protocol head
            sputs(data, "%s", pn);         
            fwrite(handle,data,15);         //report pn
            sputs(data, ",%s", datetime);
            fwrite(handle,data,15);         //report datetime
            sputs(data, ",%s", racknumber);
            fwrite(handle,data,5);          //report racknumber
            sputs(data, ",%s", portnumber);
            strlen(data,ivalue);
            fwrite(handle,data,ivalue);     //report portnumber
            sputs(data, ",%s", series);
            strlen(data,ivalue);
            fwrite(handle,data,ivalue);     //report series
            
            itemp = startoffset + MASS_ITEM_HD_LEN*item_group;
            memset(itemhead,0,0,4);
            memnmov(itemhead,masshead,0,itemp,3,0);
            sputs(data, ",%s", itemhead);
            fwrite(handle,data,4);          //report 'BDR' or 'BHD'
            
            if( item_group == 0)
                sputd(data, ",%c", SET_TABLE[tablenumber-1]);
            else
                sputd(data, ",%c", HEAD_TABLE[tablenumber-1]);
            strlen(data,ivalue);
            fwrite(handle,data,ivalue);     //report tableno
            
            if(item_group == 0)             //DRV info
            {
                sputd(data, ",%d",0);
            }
            else
            {
                itemp = startoffset+MASS_ITEM_HD_LEN*item_group+3;
                peek(masshead,itemp,1,ivalue);
                sputd(data, ",%c",ivalue);
            }
            fwrite(handle,data,2);          //report head number
            
            sputd(data, ",%c", passfail);
            fwrite(handle,data,2);          //report passfail
            
            sputs(data, ",%s", reworkflag);
            strlen(data,ivalue);
            fwrite(handle,data,ivalue);     //report reworkflag(sbr)
            if(MASS_TYPE == 1)
            {
                if( item_group == 0)
                    sputd(data, ",%c", SET_GROUP[tablenumber-1]);
                else
                    sputd(data, ",%c", HEAD_GROUP[tablenumber-1]);
                strlen(data,ivalue);
                fwrite(handle,data,ivalue); //report group for dev mass
            }
            
            if(item_group == 0)
            {
                if(tablenumber == 1)
                {
                    memset(codename,0,0,16);
                    memnmov(codename,masshead,0,0x30,16,0); //get sccode
                    for(i=0; i<16 ; i++)
                    {
                        if(((codename[i]<0x2D || codename[i]>0x39) && (codename[i]<0x41 || codename[i]>0x5A) && (codename[i]<0x61 || codename[i]>0x7A))) { codename[i]=0; break; }
                    }
                    strlen(codename,ivalue);
                    if(ivalue == 0)
                    {
                        sputd(data, ",%d", 0);
                    }
                        else
                    {
                        sputs(data, ",%s", codename);
                    }
                    strlen(data,ivalue);
                    fwrite(handle,data,ivalue);             //report sccode
                    
                    memset(codename,0,0,16);
                    memnmov(codename,masshead,0,0x40,16,0); //get htcode
                    for(i=0; i<16 ; i++)
                    {
                        if(((codename[i]<0x2D || codename[i]>0x39) && (codename[i]<0x41 || codename[i]>0x5A) && (codename[i]<0x61 || codename[i]>0x7A))) { codename[i]=0; break; }
                    }
                    strlen(codename,ivalue);
                    if(ivalue == 0)
                    {
                        sputd(data, ",%d", 0);
                    }
                    else
                    {
                        sputs(data, ",%s", codename);
                    }
                    strlen(data,ivalue);
                    fwrite(handle,data,ivalue);             //report htcode
                    
                    memset(codename,0,0,16);
                    memnmov(codename,masshead,0,0x50,16,0); //get bicode
                    for(i=0; i<16 ; i++)
                    {
                        if(((codename[i]<0x2D || codename[i]>0x39) && (codename[i]<0x41 || codename[i]>0x5A) && (codename[i]<0x61 || codename[i]>0x7A))) { codename[i]=0; break; }
                    }
                    strlen(codename,ivalue);
                    if(ivalue == 0)
                    {
                        sputd(data, ",%d", 0);
                    }
                    else
                    {
                        sputs(data, ",%s", codename);
                    }
                    strlen(data,ivalue);
                    fwrite(handle,data,ivalue);             //report bicode
                }
                //if(tablenumber == 4)
                //{
                //    strlen(bisptrev,ivalue);
                //    if(ivalue == 0)
                //    {
                //        sputd(data, ",%d", 0);
                //    }
                //    else
                //    {
                //        sputs(data, ",%s", bisptrev);
                //    }
                //    strlen(bisptrev,ivalue);
                //    fwrite(handle,data,ivalue);             //report bisptrev
                //}
            }
            
            sectorloop = item_count/MASS_MAX_SECTOR_ITEM+1;	//calculate data sector count
            itemremain = item_count;
            for(k = 0 ; k<sectorloop ; k++)
            {
                itemp = item_offset + k;
                str_getmassdata(massdata,itemp,1,ivalue);   //read mass 1sector
                //MASS read fail
                if(ivalue != SECTOR_SIZE)
                {
                    fwrite(handle,CRLF,2);
                    fclose(handle);
                    if( passfail == CHAR_F )
                        stoptest();
                    return;
                }
                
                i = 0;  j = 0;
                if(itemremain > MASS_MAX_SECTOR_ITEM)	    //calculate sector data count
                    itemp = MASS_MAX_SECTOR_ITEM;
                else
                    itemp = itemremain;
                
                for(i=0 ; i<itemp ; i++)
                {
                    j = i*MASS_ITEM_LENGTH;
                    peek(massdata,j,4,ivalue);
                    sputd(data, ",%d", ivalue);
                    strlen(data,ivalue);
                    fwrite(handle,data,ivalue);
                    itemremain--;
                }  
            }
            fwrite(handle,CRLF,2);
            tablenumber++;  //increase tableno
        }
        fclose(handle);
    }
            if( passfail == CHAR_F )
    {   
        stoptest();
    }
}


void ChangeBaudRate(int baudrate,int option)
{
    poststatus("Set BaudRate");
    if (option == 1)
    {
	    BAUD_RATE = baudrate;
	    setbaud(BAUD_RATE);
    }
    else
    {
	    BAUD_RATE = baudrate;
	    str_changehddbaud(BAUD_RATE);
	    str_checkprompt("ENG>");
    }
}

void chk_ENG_wRetry()
{
	ONERROR(retryprmt);
	str_checkprompt("ENG>");
	ONERRORCLEAR();
}

void retryprmt()
{
    int i;
	    
    poststatus("retry ENG");
    i = i + 1;
    if( i > 30 )
    ONERRORCLEAR();
    delays(10);

    poststatus("retry CHK ENG");
	str_checkprompt("ENG>");
	ONERRORCLEAR();

	i = 0;
}

void chk_ENG_wRetry1()
{
	ONERROR(retryprmt1);
	str_checkprompt("ENG>");
	ONERRORCLEAR();
}

void retryprmt1()
{
    int i;
	    
    poststatus("retry ENG");
    i = i + 1;
    if( i > 3 )
    {
    TurnOff();
	delays(10);
	poststatus("retry reset");
	power(1);
	delays(150);
	reset(); 
    ONERRORCLEAR();
    delays(10);  
    }
    poststatus("retry CHK ENG");
	//str_checkprompt("ENG>");
	ONERRORCLEAR();
    No_MASS = 1;

	i = 0;
}

void Reset_Retry()
{
	ONERROR(retryreset);
	reset();
	ONERRORCLEAR();
}

void Reset_Retry_Kill()
{
	ONERROR(retryreset1);
	reset();
	ONERRORCLEAR();
}

void retryreset()
{
	// Set retry count
	RTY_RESET = RTY_RESET+1;
	if (RTY_RESET > 2)
        ONERRORCLEAR();

	if (RTY_RESET == 3)
	{
		//str_debugmode();
		//str_checkprompt("DBG>");
		//poststatus("N/R");
		//str_stoptestfail(3, tled);
        //stoptest();
        poststatus("N/R");
        delays(20);
        
        str_getinvalidled(INVALID_LED);
        if (INVALID_LED == 0x00  )
        {
            str_stoptestfail(5, 8);		// 8 is Not Ready error code
        }
        else
        {
            showled(INVALID_LED);
            stoptest();
        }
	}

	// Reset retry
	TurnOff();
	delays(10);
	poststatus("retry reset");
	power(1);
	delays(150);
	reset();
    cmd_IN();
	ONERRORCLEAR();
	RTY_RESET = 0;
}

void retryreset1()
{
	// Set retry count
	RTY_RESET = RTY_RESET+1;

	if (RTY_RESET == 3)
	{
        flag_readycheck = 1;
		str_debugmode();
		str_checkprompt("DBG>");
		poststatus("Killing");
        str_sendserialcmd("MI 64 1",7);
        delays(10);    
	}
    
    if (RTY_RESET == 4)
	{
        flag_readycheck = 1;
		str_debugmode();
		str_checkprompt("DBG>");
		poststatus("Killing");
        str_sendserialcmd("MI 64 2",7);
        delays(10);    
	}
    
     if (RTY_RESET == 5)
	{   
        str_debugmode();
        str_checkprompt("DBG>");
        
        poststatus("Killing"); 
        str_sendserialcmd("MI 64 0",7);
        
        TurnOff();
        delays(10);
        
        poststatus("Turn On");
        power(1);
        delays(10);
        str_debugmode();
        str_checkprompt("DBG>");

        //download SC code
        poststatus("SCCODE2 D/L");
        strcpy(DWCODE,SCCODE2);DW_RTY();
        poststatus("CHK BOOT SCCODE2");
        delays(10);
        
        TurnOff();
        delays(10);
        
        poststatus("Turn On");
        power(1);
        delays(120);
        Check_LedSC();
        chk_ENG_wRetry();
        exe_SC(15000);
    }    
    
    if (RTY_RESET == 6)
	{
        poststatus("N/R");
        delays(20);

        str_getinvalidled(INVALID_LED);
        if (INVALID_LED == 0x00  )
        {
            str_stoptestfail(5, 8);  // 8 is Not Ready error code
        }
        else
        {
            showled(INVALID_LED);
            stoptest();
            ONERRORCLEAR();
        }
	}
    
    if (RTY_RESET == 7)
	{
        ONERRORCLEAR();
	}

	// Reset retry
	TurnOff();
	delays(10);
	poststatus("retry reset");
	power(1);
	delays(150);

	reset();
    cmd_IN();
	ONERRORCLEAR();
    Check_LedBI();
	RTY_RESET = 0;
}

void Clean_MC(void)
{    
    if ( flag_InlineKill == 0 && flag_readycheck == 0 )
    {
        //==========================james test======================
        if(flag_SC_KILL == 0)
        {
        cmd_LF();
        poststatus("Flash clear");
        str_sendserialcmd("EU 1",4);    //command to HDD  
        delays(5);
        }
        else
        {
        //cmd_LF();
        //poststatus("Flash clear");
        //str_sendserialcmd("EU 1",4);    //command to HDD  
        //delays(5);    
        }
        //==========================james test======================   
    }     

    ONERROR(retrycleanmc);
    poststatus("Cmd ZM");
    str_sendserialcmd("ZM",2);    //command to HDD
    delays(120);
    //str_checkprompt("ENG>");
}

void Clean_MC2(void)
{
    if ( flag_InlineKill == 0 && flag_readycheck == 0 )
    {
        //==========================james test======================
        if(flag_SC_KILL == 0)
        {
        cmd_LF();
        poststatus("Flash clear");
        str_sendserialcmd("EU 1",4);    //command to HDD  
        delays(5);
        }
        else
        {
        //cmd_LF();
        //poststatus("Flash clear");
        //str_sendserialcmd("EU 1",4);    //command to HDD  
        //delays(5);    
        }
        //==========================james test======================   
    }     

	poststatus("Cmd ZM2");
    str_sendserialcmd("ZM",2);    //command to HDD
    delays(120);
    //str_checkprompt("ENG>");
}

void retrycleanmc()
{
	ONERRORCLEAR();
	TurnOff();
	delays(10);
	power(1);
	delays(120);
	reset();
	Clean_MC2();
} 


int GetMassBuffer(int ioffset, int iseccnt)
{
	int loop;
	int ivalue;
	int iexist;
	char tempbuf[1024];
	int isoff, itoff, imovsize;
	
	//Cannot exceed 2 sectors at once
	if (iseccnt > 2)
		return 1;
	//Cannot exceed MAX SECTOR SIZE
	if ( (ioffset+iseccnt) > MASS_MAX_SECTOR_SIZE )
		return 2;
	
	iexist = 1;
	for (loop = 0; loop < iseccnt; loop++)
	{
		ivalue = ioffset+loop;
		if (BVR_FLAG[ivalue] == 0)
		{	
			iexist = 0;
			break;
		}
	}
	if (iexist == 1)
		return 0;
	
	ivalue = 0;
	str_getmassdata(tempbuf, ioffset, iseccnt, ivalue);
	if (ivalue != (iseccnt*SECTOR_SIZE) && ioffset==0)
	{
		TurnOff();
		delays(10);
		power(1);
		delays(150);
		Reset_Retry();
        cmd_IN();
		str_sendserialcmd("PP",2);
	        delays(300);
	        str_getmassdata(tempbuf, ioffset, iseccnt, ivalue);
	}
	if (ivalue != (iseccnt*SECTOR_SIZE))
		return 3;
	
	
	isoff = 0;
	itoff = ioffset*SECTOR_SIZE;
	imovsize = iseccnt*SECTOR_SIZE;
	memnmov(BV_NEW_BUFFER, tempbuf, itoff, isoff, imovsize, 0);

	for (loop = 0; loop < iseccnt; loop++)
	{
		ivalue = ioffset+loop;
		BVR_FLAG[ivalue] = 1;
	}
	return 0; // OK	
}

void DS_Fail()
{
	str_stoptestfail(3, 0x0320);
}

void Grade_Fail()
{
	if (flag_5400RPM == 0)  // 7200RPM S grade
	{
		//str_stoptestfail(3, 0x0500);
	}
	else                    // 5400RPM S grade
	{
		str_stoptestfail(3, 0x0320);
	}
}
void exeDELAY()
{ 
    char biheader[6];
	char postfix;
    flag_BIfail =0;
    
    poststatus("Turn On");
	power(1);
 	delays(60);
    Reset_Retry();
 	
 	cmd_IN();       // delays _ 60s
 	cmd_CB();		//Cancel Resume BI
 	
 	str_getinvalidled(INVALID_LED);
	if (INVALID_LED == 0x00  )
	{
		poststatus("Reset");
		Reset_Retry();
	}
	else
	{
		showled(INVALID_LED);
		stoptest();
	}
	
	poststatus("IDFY");
	Id_Retry();
	
	// Get S/C Skip option
	str_getscskip(SCCKIP);
  	
  	str_getidfydata(0, 511, rdbuf); 
	if(rdbuf[68] == 0x4A)	// "J" 7200rpm
	{
        flag_5400RPM	= 0;
    }
	else if(rdbuf[68] == 0x49)	// "I" 5400rpm
	{
        flag_5400RPM	= 1;
    }  
    else
    {
    }
 
    
    if( rdbuf[64] == 0x32) // "2" 250G (Killing)
	{
        flag_InlineKill = 1; 
        if (rdbuf[68] == 0x49)  // 250G 5400RPM
        {
            poststatus("B/I CONT");
            flag_BIfail = 1;
            goto LABEL_MAINCODE1;
        }
    }
    
    if( rdbuf[64] == 0x31 && rdbuf[65] == 0x36) 
	{
        flag_InlineKill = 1; 
        poststatus("B/I CONT");
        flag_BIfail = 1;
        goto LABEL_MAINCODE1;

    }
    // Code Check
 	str_getidfydata(0, 511, rdbuf);
 	if (rdbuf[215] == 0x4D || rdbuf[215] == 0x6D)
	{
		main_code = 1;
        poststatus("LABEL_MAINCODE1");
		delays(1);
        poststatus("GRADE");
        GRADE_RND2();
		goto LABEL_MAINCODE1;
	}
	
	str_getpostfix(postfix);
	str_getbiheader(biheader);
	
//check postfix "BURN", "CONT"
	if (postfix != CHAR_B && postfix != CHAR_C)
	{
		poststatus("B/I FAIL");	// Default
		if (postfix == CHAR_P)
			poststatus("Re S/C");
		if (postfix == CHAR_S)
			poststatus("Re S/C");
		//if (postfix == CHAR_F)
		//	poststatus("B/I FAIL");
		stoptest();
	}
	// B/I Fail "FAIL"
	else if (biheader[0] == CHAR_F  || postfix == CHAR_F  )
	{
		poststatus("B/I CONT");
        flag_BIfail = 1;
        goto LABEL_MAINCODE1;
	}
	
	// B/I cont
	else if (biheader[0] == CHAR_C || biheader[0] == CHAR_B)
	{
       if( MGET1(9,0x000) != 0 )
        {
            poststatus("Re B/I");
            delays (10);
            stoptest();
        }
        
        if ( RDBUF[21] >= 40) 
        {
        poststatus("B/I CONT");
		exe_BI1(10000);   
        }   
        
        else
        {
        flag_BIfail = 1;   
        GO54001RPM();
        exe_BI1(10000);  
        flag_BIfail = 0; 
        goto LABEL_MAINCODE1;
        }   
	}
	else
	{
		if (biheader[0] != CHAR_E)
		{
			poststatus("RE B/I");
			//stoptest();
            flag_BIfail = 1;   
            GO54001RPM();
            exe_BI1(10000);
            flag_BIfail = 0;   
		}
	}
    
    LABEL_MAINCODE1:
    if (flag_BIfail == 1)
    {
        flag_5400RPM = 0;
        flag_InlineKill = 1; 
        Inline_Kill();
        power(0); delays(15);	power(1); delays(120);
		chk_ENG_wRetry();
		cmd_IN();    
		Reset_Retry();
        GO54001RPM();
        exe_BI1(10000);
    }
}



void exe_BI1(int minute)
{
    int tled, disflag;
    
    if( flag_BIfail == 0)
    {
        power(0);
        delays(10);
        
        //burn in
        poststatus("Turn On B/I");
        power(1);
        delays(120);
        
        str_sendserialcmd("IN 1",4);
        delays(60);
    }
    
LABEL_54001RPM:	
	
	//>>>>>>>>>>>>>>>>>>>>>>>>>
	//B/I START
	SendMESData(SEND_BI_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<
    ONTESTERROR(Mass_MP);  //set mass hadler when B/I fail
	str_monitoring("B/I", minute, tled, disflag);
	
	if (tled == 0)
	{
		//go through
	} 

	//else if ((tled == 0x1C08 || tled == 0x2801 || tled == 0x2809 || tled == 0x2819) && flag_5400RPM == 0)
    else if (flag_5400RPM == 0 && flag_InlineKill == 0 &&  tled != 0) 
	{
		//5400RPM D/S
		flag_5400RPM = 1;
		power(0);
		delays(15);
        
		power(1);
		delays(120);
		chk_ENG_wRetry();
		cmd_IN();    
		Reset_Retry();
		GO54001RPM();
		goto LABEL_54001RPM;
	}
    else if (flag_5400RPM == 1 && flag_InlineKill == 0 && tled != 0)
	{
  
		//Inline Killing

		power(0);
		delays(15);
       	power(1);
        delays(120);
        Check_LedBI();
        Reset_Retry();
        chk_ENG_wRetry();
        cmd_IN();
  

        
        flag_InlineKill = 1; 
        flag_5400RPM = 0;       
        Inline_Kill();
        
        power(0); delays(15); power(1); delays(300);
        
		chk_ENG_wRetry();
		cmd_IN();    
		Reset_Retry();

        
        GO54001RPM();
         
		goto LABEL_54001RPM;
	}
	else if (flag_5400RPM == 0 && flag_InlineKill == 1 && tled != 0) 
	{
		//Inline Killing
		power(0);
		delays(15);
       	power(1);
        delays(120);
        Check_LedBI();
        Reset_Retry();
        chk_ENG_wRetry();
        cmd_IN();
        
        str_usercmd("DI 64",5,1000,22,0,buf,32);
        atoi(buf,18,16,flag);
        printf("%x",flag);

        if(flag == 0xff01)
        {
            poststatus("Non Killing");
            Kill_H = 0;
        }  
        else
        {
            Kill_H = 1; 
        }
        if (Kill_H ==0)  // Head_1 Killing
        {
            str_sendserialcmd("AT 8F 3C 0 0 2",14);
            delays(30);
        }   
            
            
        if (Kill_H ==1)  // Head_0 Killing
        {
            str_sendserialcmd("AT 8F 3C 0 0 1",14);
            delays(30);
        } 
        
        flag_InlineKill = 2;
        flag_5400RPM = 0 ;
        power(0); delays(15); power(1); delays(300);
        
		chk_ENG_wRetry();
		cmd_IN();    
		Reset_Retry();
        GO54001RPM();
        
		goto LABEL_54001RPM;
	}    
    

	else
	{
		str_stoptestfail(3, tled);
	}
    
    
    ONTESTERRORCLEAR(); //clear mass handler
	str_mesdownsize(0); //Inline DS Model Enable
	delays(10);	
	TurnOff();
	delays(10);	
	power(1);
	delays(120);
	
	str_getinvalidled(INVALID_LED);
	if(INVALID_LED != 0x00) 
	{
		showled(INVALID_LED);
		stoptest();
	}
	Reset_Retry();
    poststatus("IDFY");
    Id_Retry();
        
        
    str_getidfydata(0, 511, rdbuf); 
	if((rdbuf[64] == 0x32 && rdbuf[65] == 0x35) || (rdbuf[64] == 0x31 && rdbuf[65] == 0x36))  // 250G or 160G
    {

        if ((rdbuf[68] == 0x49) || 	(rdbuf[64] == 0x31 && rdbuf[65] == 0x36))   // 49 : "I" 5400rpm 250G 5400RPM or 160G
        {
            if (flag_InlineKill == 2)
            {
                str_stoptestfail(3, 0x0160);
            }
            
            flag_InlineKill = 1;
            flag_5400RPM = 0 ;
            
            //Inline_Kill();
            GO54001RPM();
            goto LABEL_54001RPM;
        }
    }
    
    if(rdbuf[68] == 0x49)	// 5400RPM
    {
        GRADE_RND();
        if ( flag_OEM == 2)
        {
            flag_InlineKill = 1;
            flag_5400RPM = 0 ;
            Inline_Kill();
            GO54001RPM();
            goto LABEL_54001RPM;     
        }
    }

}
void GO54001RPM()
{
    poststatus("HTBI D/L");
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
    {
       	strcpy(DWCODE,HTBICODE);DW_RTY();
	    poststatus("CHK BOOT HTBICODE");
    }
    else
    {
	    strcpy(DWCODE,HTBI54);DW_RTY();
	    poststatus("CHK BOOT HTBI54");
    }
	delays(30);
	poststatus("poweroff BICode");
	power(0);
	delays(10);
	//power on
	poststatus("Turn On");
	power(1);
	delays(150);
	Reset_Retry_Kill();
    
	str_checkprompt("ENG>");
	Clean_MC2();
	poststatus("Turn Off");
	power(0);
	delays(5);
	//>>>>>>>>>>>>>>>>>>>>>>>>>
	//B/I START
	SendMESData(SEND_BI_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<
	// BISPT download
	poststatus("Turn On BISPT");
	power(1);
	delays(120);
	
	Reset_Retry_Kill();
    poststatus("IDFY");
    Id_Retry();
    delays(10);

    poststatus("OVLY D/L");
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
   	{
   		str_userdownload("DO",OVERLAY,0x4C);      
   	}
   	else
    {
       	str_userdownload("DO",OVERLAY_54,0x4C);
    }

    delays(30);
    str_checkprompt("ENG>");

   	// NEW AZL
   	// download geometry file         
    poststatus("GEO D/L");
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
    {
    	str_downloadgeo(GEOSPT);
    }
    else
    {
       	str_downloadgeo(GEOSPT54);
    }

    delays(30);
    str_checkprompt("ENG>");

    // download biscript         
    poststatus("BISPT D/L");
    if (flag_5400RPM == 0 || flag_InlineKill == 1)
   	{
       	str_downloadbiscript(BISPT);
    }
    else
    {
       	str_downloadbiscript(BISPT54);
    }
    delays(30);
	str_checkprompt("ENG>");              
    
	// run burnin
	if(INVALID_LED != 0x00) 
	{
		showled(INVALID_LED);
		stoptest();
	}
	str_checkprompt("ENG>");
	poststatus("BIStart OK");
	str_starttest();
	poststatus("5400-B/I");
	
}
