// For BurnIn ONLY -> No Downsize code (no SECBICODE)
// 0001, STD, SBT, M, T133P, 6, 10000, STSRT60.808, BI_0DS.STR, FFLASH(WQxxC.DN), HTBICODE(WQxxC.DN5)
// 2Sector Mass Header (20080417)
// New Grading(10단계) (20080702)
// 20090727 F2EGSD08.ETR (       ) Maker : JJJ
//          F2EG & 1PE 통합 script, FT Dfree rev 05, SC re-Test rev.01
// 20090729 : F2EGSD13.ETR (Original:F2EGSD08.ETR) Maker:PJS
//	      Change Re S/C & Cont BI & FT fuction.
// 20090813 : F2EGSD16.ETR (Original:F2EGSD13.ETR) Maker:PJS
//	      1st BI fail D/S.
// 20090909 : F2EGSD20.ETR (Original:F2EGSD16.ETR) Maker:PJS
//	      FT PTR for Even Read / ECC & Retry change
// 20090930 : F2EGSD22.ETR (Original:F2EGSD20.ETR) Maker:ds.seo
//            COMBO 불량 표시(N/R(COMBO))
// 20091014 : F2EGSD26.ETR (Original:F2EGSD22.ETR) Maker:JJJ
//            FOD clipping 10 DAC 적용, ATW MD target 90k -> 120k 
// 20091027 : F2EGSD33.ETR (Original:F2EGSD26.ETR) Maker:JJJ
//            Remove FT step check function
// 20091104 : F2EGPR01.ETR (Original:F2EGSD33.ETR) Maker:JJJ
//            Rollback Cliiping 15 DAC



#include "strfiles.inc"

// 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 POSTFIX_MAIN		77	//'M'

#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 SECTOR_SIZE_BINNING	1024

#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 RTY_DW_SCRBIN54		7
#define SECTOR_SIZE_BINNING	1024

// MASS Option set //
#define MASS_Set		1          // 1 run MASS, 0 don't use MASS.
//BINNIG DEFINES
#define PARAM_TYPE_LOW		1
#define PARAM_TYPE_MID		2
#define PARAM_TYPE_UPP		3
//TYPE
#define PT_DRV_SET		1
#define PT_DRV_SET_ZONE		2
#define PT_DRV_SET_STEP		3
#define PT_HD			4
#define PT_HD_RANGE		5
#define PT_HD_STEP		6
#define PT_HD_ZONE		7

//BINNING PARAM (F1,(TRINITY))
//====== BER ======
#define	BER_10S_MIN		1
#define	BER_10S_AVG		2
#define	TPI_OPT			3
//====== GAIN ======
#define	DATA_GAIN_AVG	  	4
#define	SERVO_GAIN_AVG	  	5
//====== FOD ======
#define	FLY_HEIGHT		6
#define	FOD_R	  		7
#define	FOD_W	  		8
#define	RWGAP	  		9
//====== WC ======
#define	OD_WC	  		10
#define	MD_WC	  		11
#define	ID_WC	  		12
//====== Servo/Mecha ======
#define	PES			13
#define	RRO			14
#define Latch_Force		15
//====== Defect ======
#define	DATA_DEFECT_ZN		16
#define	DEF_SURFACE		17
#define	SERVO_DEF_SURFACE	18
#define	TRK_DEF_SURFACE		19
#define	TA_SURFACE		20
#define	DS_Flag			21

// GLOBAL VARIABLES //
int BAUD_RATE;
int INVALID_LED;
int led;
int DOWNLOAD_BISPT;
int DOWNLOAD_DWNBI;
int RTY_DOWNLOAD;
int RTY_RESET;
int RTY_CODETYPE;
int RTY_BAUDCHANGE;
int RTY_ID;
int LED_ERROR;
int DISFLAG;
int SCCKIP;
int MAINNORESET;
int PCBAMAINCODE;
int SC1PASS;
int i;
int flag_5400RPM;
int reworkflag; 
int nSC_loop;
int flag_CONT; //
//Error count var
int nEc;
int nEc1;
int estep; 
int estep1; 
//void Errorcnt(int step);
void Dfree();
//void Dfree(int estep);

char rdbuf[1024];
char ledstatus[10];
char buffers[512];
char DWCODE[32];

// FUNCTION PROTOTYPE //
void exe_SC(int minute,int pass);
void exeBI_AZL(int minute);
void exe_FT();
void Write_SerialNumber();

void ChangeBaudRate(int baudrate,int option);
void Clean_MC(void);
void Clean_MC2(void);
void Reset_Retry();
void retryreset();
void Check_Download(int codetype);
void retrydownload();
void TurnOff();
void ChangeBaudRateOLD();
void restorehddbaud();
void Id_Retry();
void TempCheck();
void retryid();
void DW_RTY();
//void promptcheck();
//void promptchange();
void Mass();
void DNR_Test();
int  Reset_NoFail();
void dummyerror();
void Check_LedSC();

//BINNING GRADE PORTION
float	BF_DRVGRADE_HIGH;
float	BF_DRVGRADE_LOW;
int	BF_MAXPOINT;
//BINNIG VARIABLES
int 	BV_TYPE;
float	BV_BASIS;
float	BV_LCL2;
float	BV_LCL1;
float	BV_UCL1;
float	BV_UCL2;
int 	BV_WEIGHT;
int	BV_FORCED_C;
int	BV_PARAGRADE_A;
int	BV_PARAGRADE_B;
int	BV_PARAGRADE_C;
//PARAM BUFFER
int	BV_BUFFER_LOCATION;	//from 1 to max mass data
char    BV_BUFFER[SECTOR_SIZE_BINNING];

//NEW BV BUFFERS
//MASS DATA SECTOR SIZE
#define MASS_MAX_SECTOR_SIZE	64
char	BVR_FLAG[MASS_MAX_SECTOR_SIZE];
char	BV_NEW_BUFFER[0x8000];

//MASS HEADER VARIABLES
char	MH_MASS_PN[21];
char	MH_MASS_SERIES[11];
int	MH_NUMOF_HEAD;
int	MH_START_OFFSET_DRV;
int	MH_OFFSET_DRV_SET;
int	MH_OFFSET_DRV_SET_ZONE;
int	MH_OFFSET_DRV_SET_STEP;
int	MH_OFFSET_HD0;
int	MH_OFFSET_HD0_RANGE;
int	MH_OFFSET_HD0_STEP;
int	MH_OFFSET_HD0_ZONE;
int	MH_OFFSET_HD1;
int	MH_OFFSET_HD1_RANGE;
int	MH_OFFSET_HD1_STEP;
int	MH_OFFSET_HD1_ZONE;
int	MH_OFFSET_HD2;
int	MH_OFFSET_HD2_RANGE;
int	MH_OFFSET_HD2_STEP;
int	MH_OFFSET_HD2_ZONE;
int	MH_OFFSET_HD3;
int	MH_OFFSET_HD3_RANGE;
int	MH_OFFSET_HD3_STEP;
int	MH_OFFSET_HD3_ZONE;
int	MH_OFFSET_HD4;
int	MH_OFFSET_HD4_RANGE;
int	MH_OFFSET_HD4_STEP;
int	MH_OFFSET_HD4_ZONE;
int	MH_OFFSET_HD5;
int	MH_OFFSET_HD5_RANGE;
int	MH_OFFSET_HD5_STEP;
int	MH_OFFSET_HD5_ZONE;
int	MH_OFFSET_HD6;
int	MH_OFFSET_HD6_RANGE;
int	MH_OFFSET_HD6_STEP;
int	MH_OFFSET_HD6_ZONE;
int	MH_OFFSET_HD7;
int	MH_OFFSET_HD7_RANGE;
int	MH_OFFSET_HD7_STEP;
int	MH_OFFSET_HD7_ZONE;
//FORCED C GRADE
int	FORCED_C_GRADE;
// Add Command
int CLEAN_MC;
int RTY_IDFY;
void retrycleanmc();
//LOG OPTION
int	DEBUG_ON;
//PARAM RETURN VALUE
float   PARAM_RET_VALUE;

//BINNING FILES
char	BIN_FILENAME[20];

//BINNING RESULT
char	BIN_RESULT;

//BINNING FUNCTION
void	DriveBinning();
void    DriveGrading_new();
int	GetBinningVariables(int param);
int 	GetParamValue(int param, int head);//if head value exists
int 	GetParamGrade(int param);//if head value exists
int 	GetMassHeader();
void 	logivalue(int ivalue);
void 	logfvalue(float fvalue);
//int	GetMassBuffer(int ioffset, int iseccnt);

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

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

void SendMESData(int type);

// MAIN ENTRY //
void main()
{
	char biheader[6];
	char postfix;
	int reworkflag; 
        int disflag, LED;	
//        int step;

	BAUD_RATE       = 57600;
	//BAUD_RATE     = 115200;
	INVALID_LED     = 0x00;
	DOWNLOAD_BISPT  = 1;
	DOWNLOAD_DWNBI  = 1;
	RTY_DOWNLOAD    = 0;
	RTY_RESET       = 0;
	RTY_CODETYPE    = 0;
	RTY_BAUDCHANGE	= 0;
	RTY_ID		= 0;
	DISFLAG		= 0;
	SCCKIP		= 0;
	MAINNORESET	= 0;
	PCBAMAINCODE	= 0;
	SC1PASS		= 0;
    	CLEAN_MC        = 0;
	//SCCKIP	= 1;
	memset(BIN_FILENAME, 0, 0, 20);
        str_setdumpsectorsize(1710);            //for gigacube
	siolog(1);

	// setcom33v();
	setcom25v();
	DNR_Test();

	TurnOff();
	delays(5);

	//>>>>>>>>>>>>>>>>>>>>>>>>>>
	SendMESData(SEND_DATA_INIT);
	//<<<<<<<<<<<<<<<<<<<<<<<<<<

	// Get S/C Skip option
	str_getscskip(SCCKIP);

	// S/C to B/I
	if (SCCKIP == 0)
	{

		poststatus("S/C~");
		delays(5);
		exe_SC(7800,1);

		// power on default 57k baud rate
		poststatus("Turn On SC-P");
		power(1);
		delays(120);
		str_getinvalidled(INVALID_LED);
		if(INVALID_LED != 0x00) 
		{
			showled(INVALID_LED);
			stoptest();
		}
		//str_checkprompt("ENG>");
		poststatus("Reset");
		reset();
		poststatus("IDFY");
		Id_Retry();

		TurnOff();
		delays(5);

	//////////////////////////////////////////////////
	//	poststatus("SC 3Pass OK");
	//	stoptest();
	//////////////////////////////////////////////////

		poststatus("B/I~");
		delays(5);
		exeBI_AZL(15000);
	}
	else	// Only B/I
	{
		
		poststatus("Turn On");
		power(1);
		delays(50);
		Reset_Retry();
		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();
		}
		
		poststatus("B/I~");
		delays(5);
		exeBI_AZL(15000);
	}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

	poststatus("Turn On");
	power(1);
	delays(120);
	Reset_Retry();
	str_sendserialcmd("LF",2);
	delays(5);
	poststatus("IDFY");
	Id_Retry();

	//Binning Test
	poststatus("Binnig Test");
	DEBUG_ON = 1;

	poststatus("Binnig start");	
	userfilelog("+++++++++++++++ Binnig start +++++++++++++++");
////DriveGrading_new();
	poststatus("Binnig Done"); 
	userfilelog("+++++++++++++++ Binnig Done  +++++++++++++++");
	
	//>>>>>>>>>>>>>>>>>>>>>>>>
	//B/I PASS
	SendMESData(SEND_BI_START);
	SendMESData(SEND_BI_PASS);
	//<<<<<<<<<<<<<<<<<<<<<<<<<

	exe_FT();
	
	poststatus("Poweroff BI-P");
	//power(0);
	//led pass and str_showmodel
	str_showmodel();
}

void exe_FT()
{
	int step;
	
	step = 0;
	
// ========= STR FT Script start========== //
	ChangeBaudRateOLD();
	if (SC1PASS == 1)
	{	
	 str_sendserialcmd("SD",2);  // 'SD' Command <- spin down before code D/L
	 delays(15);
	 poststatus("SCRBIN54 D/L");
    	 //dw(SCRBIN54);   
    	 strcpy(DWCODE,SCRBIN54);DW_RTY();
	}
	else if (flag_5400RPM == 0)
	{	
	 str_sendserialcmd("SD",2);  // 'SD' Command <- spin down before code D/L
	 delays(15);
	 poststatus("SCRBIN D/L");
	 //dw(SCRBIN);
	 strcpy(DWCODE,SCRBIN);DW_RTY();
	}
	else
	{	
	 str_sendserialcmd("SD",2);  // 'SD' Command <- spin down before code D/L
	 delays(15);
	 poststatus("SCRBIN54 D/L");
    	 //dw(SCRBIN54);   
    	 strcpy(DWCODE,SCRBIN54);DW_RTY();
	}
	 poststatus("CHK BOOT SCRBIN");
	 delays(30);
	 poststatus("poweroff SCRBIN");
     poststatus("Turn Off");
	 power(0);
	 delays(10);

    	poststatus("Turn On");
	power(1);
	delays(600);

	//str_sendserialcmd("CE", 2);	// Insitu ON
    	str_sendserialcmd("IC 1 0",6);  //insitu on
    	delays(60);    
    
    	str_sendserialcmd("TC",2);  // TCC3 update
    	delays(60);  
    	
    	// Add str script in j8b7
    	str_sendserialcmd("CF F",4);  ////clipping fod value Setting 15 DAC
    	delays(60);     	    	
      	
      	str_sendserialcmd("FX",2);  // FOW patch
    	delays(60);    
    
    
    poststatus("Turn Off");
    	TurnOff();
	delays(30);  

	//power on
	poststatus("Turn On");
	power(1);
	delays(120);
	Reset_Retry();

// ========= STR Reject Script start========== //
if(0)
{
   	str_sendserialcmd("RU 2506 A",9);   // Serail Number clear
    	str_sendserialcmd("WU 2271",7);     // Serail Number clear
   
    	//power off
    	poststatus("Turn Off");
    	power(0);
	delays(10);
	//power on
	poststatus("Turn On");
	power(1);
	delays(20);
    	Reset_Retry();
}	
// ========= STR FT Script start========== //

	poststatus("IDFY_3");
    	Id_Retry();
    	str_mesftstart();

	str_sendserialcmd("DH",2);        // ATWH Disable
    	nEc=0;
	nEc1=0;
	estep=0;
	estep1=0;
	delays(10);
// START TEST
	str_sendserialcmd("WU B002",7);     // Option 2 _ FT Result log
	str_sendserialcmd("FTST",4);        // Write FT Start  
	delays(10);
	str_checkprompt("ENG>");
	delays(20);


//=========================================
//  Power on/off cycle(Loop 5)
//=========================================

	for ( i = 0; i < 5; i ++)
		{
            	poststatus("H/PWR_5");
		power(0);
		delays(15);
		power(1);
		delays(20);
		Reset_Retry();
		//1.Random  W/R Screen (Min ~ MAX_LBA)
		poststatus("Rand W/R TEST");
            	str_sendserialcmd("TU 1020012 3E8 141E 0 7FFFFFFF",30); //loop_1K
		str_monitorscrstep(800,"Rand W/R","FT","WR01");
		delays(10);
		Reset_Retry();
		//str_checkprompt("ENG>");
		delays(20);
		}                  
//=========================================

//ERROR Count
    //   	step=1; //Power on/off cycle
    //          Errorcnt(step); 	

//2.OD Track Read
	poststatus("OD Read");
	str_sendserialcmd("TU 1010001 0 141E 40 4E20",25); // Read 64 ~ 20000
	str_monitorscrstep(900,"OD Read","FT","OR02");
	delays(10);
	Reset_Retry();

//ERROR Count
//      step=2; //OD Track Read
//      Errorcnt(step);
	
//3.OD Track Write
	//Full Track Write 
	poststatus("OD Write");
	str_sendserialcmd("TU 1010002 0 141E 40 4E20",25); // Wrtie 64 ~ 20000
	str_monitorscrstep(900,"OD Write","FT","OW03");
	delays(10);
	Reset_Retry();	

//ERROR Count
//      step=3; //OD Track Write
//      Errorcnt(step);
	
//4.OD Track Read
	poststatus("OD Read");
	str_sendserialcmd("TU 1010001 0 141E 40 4E20",25); // Read 0 ~ 20000
	str_monitorscrstep(900,"OD Read","FT","OR04");
	delays(10);
	Reset_Retry();	

//ERROR Count
//      step=4; //OD Track Read (After OD Write)
//      Errorcnt(step);
	
//5.DST Shrot Test loop x 5
        poststatus("DST Shrot");
        str_sendserialcmd("SI",2); //Init
        delays(5);
        str_sendserialcmd("SE",2); // SMART Enable
        delays(5);
        power(0);
        delays(15);			
        power(1);
        delays(20);
        Reset_Retry();
        str_checkprompt("ENG>");
            for ( i = 0; i < 5; i ++)
            {
             str_sendserialcmd("TU 80000 0 0 0 0",16); 
             str_monitorscrstep(100,"DST","FT","DS05");
             delays(10);
             Reset_Retry();
            } 
        str_sendserialcmd("SI",2); //Init
        delays(5);	
        str_sendserialcmd("SD",2); // Disable
        delays(5); 	
    poststatus("Turn Off");
        power(0);
        delays(15);			
    poststatus("Turn On");
        power(1);
        delays(20);	
        Reset_Retry();
	
//6.CSS Test 100
	poststatus("CSS TEST");
	str_sendserialcmd("TU 1050012 1E 141E 1 1388",25); // Loop 30 (CSS 1 + Ran W/R 5K )
	str_monitorscrstep(900,"CSS","FT","CS06");
	delays(10);		
	Reset_Retry();


//ERROR Count
//      step=6; //CSS Test
//      Errorcnt(step);

//7.Random  W/R Screen (Min ~ MAX_LBA)
	poststatus("Rand W/R TEST");
    	str_sendserialcmd("TU 1020012 9C40 141E 0 7FFFFFFF",31); //loop_40K
    	str_monitorscrstep(900,"Rand W/R","FT","WR07");
	delays(10);
	Reset_Retry(); 	

//ERROR Count
//      step=7; //Random W/R
//      Errorcnt(step);

//8.ATW Test
	poststatus("ATW TEST");
	str_sendserialcmd("TU 40001 0 7DD141E 2710",23); // 10K
	str_monitorscrstep(800,"ATW0","FT","AW08");
	delays(10);
	Reset_Retry();
//9.ATW1 Test
	str_sendserialcmd("TU 40001 0 7DD141E 1D4C0",24); //120K
	str_monitorscrstep(800,"ATW1","FT","AW09");
	delays(10);
	Reset_Retry();
//10.ATW3 Test
	str_sendserialcmd("TU 140001 0 7DD141E 3E8",23);  // Max cyl - 1K
	str_monitorscrstep(800,"ATW3","FT","AW10");
	delays(10);
	Reset_Retry();

//11.Most OD BER Screen
	poststatus("Most OD");
	str_sendserialcmd("TU 60000 A 0A0D 40 7FFFFFFF",27); // Criteria 10, ECC 10, Retry 13(BI code 07rG)
	//str_monitorscr(100,"Most OD","FT");
	str_monitorscrstep(800,"Most","FT","MO11");
	delays(10);
	Reset_Retry();	
	
//12.seq full Track Read(CHS)
	poststatus("Full Read");
    	str_sendserialcmd("TU 1810001 0 0E19 40 7FFFFFFF",29); //ECC 14, Retry 25, Even Track read
	str_monitorscrstep(900,"Full Read","FT","SR12");
	Reset_Retry();				
	
//ERROR Count
//      step=8; //Full read (Err
//      Errorcnt(step);

//13.seq full Track Write(CHS)
        poststatus("Full Write");
	str_sendserialcmd("TU 1010002 0 141E 40 7FFFFFFF",29);    // CHS Mode
        str_monitorscrstep(900,"Full Write","FT","SW13");
        delays(10);
        Reset_Retry(); 	

//14.MC Read(CHS)
	poststatus("Full Read");
	str_sendserialcmd("TU 10001 0 141E 0 40",20);//ECC 20, Retry 30
	str_monitorscrstep(60,"Full Read","FT","SR99");
	Reset_Retry();	

//14.seq full Track Read(CHS)
	poststatus("Full Read");
	str_sendserialcmd("TU 1010001 0 0D19 40 7FFFFFFF",29);//ECC 13, Retry 25
	str_monitorscrstep(900,"Full Read","FT","SR14");
	Reset_Retry();	

//ERROR Count
//      step=9; //Full read (Err
//      Errorcnt(step);
//      estep=estep+estep1;

	Dfree();
	
	if(nEc)
	{
	//14.seq full Track Write(CHS)
	        poststatus("Full Write");
		str_sendserialcmd("TU 10002 0 141E 40 7FFFFFFF",27);    // CHS Mode
	        str_monitorscrstep(900,"Full Write","FT","SW15");
	        delays(10);
	        Reset_Retry(); 	
	
	//16.seq full Track Read(CHS)
		poststatus("Full Read");
		str_sendserialcmd("TU 10001 0 141E 0 7FFFFFFF",26);//ECC 20, Retry 30
		str_monitorscrstep(900,"Full Read","FT","SR16");
		Reset_Retry();	
	}
	
	str_sendserialcmd("EH",2);        // ATWH Enable
	delays(10);	
	str_sendserialcmd("AH",2);        // ATWH Initial
	delays(10);		

//Write test Result at mc(Mget 11)	
	str_sendserialcmd("WU B002",7);
	str_sendserialcmd("FT01",4); // Wirte Reject test result 
	// Wirte Reject test result 
	delays(20);
	str_sendserialcmd("TU 10001 1 0D1E 40 50",21);
	str_monitorscr(5,"RESULT","FT");

	str_mesftend();	

// ========= STR FT Script End========== //

}


void exe_SC(int minute,int pass)
{
	int tled, disflag;
	
	// power on default 57k baud rate
	poststatus("Turn On SCCode");
	power(1);
	delays(120);
    Check_LedSC();		//Check Not Ready Failure ex. 1701 etc	    
	str_checkprompt("ENG>");  // BI 07n8...
	poststatus("Reset");
	Reset_Retry();      
	poststatus("IDFY");
	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;
		PCBAMAINCODE	= 1;
		goto LABEL_MAINCODE;
	}

	//>>>>>>>>>>>>>>>>>>>>>>>>>>
	// S/C START
	SendMESData(SEND_SC_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<<
	nSC_loop = 0; // 1st SC start
		
	ChangeBaudRate(115200,0);
	// SC code download
	if (pass==1) 
	{
		poststatus("SC1 D/L");
		//dw(SCCODE1);
		strcpy(DWCODE,SCCODE1);DW_RTY();
		
	}
	else
	{
        	if (pass==2)
        	{
			poststatus("SC2 D/L");
			//dw(SCCODE2);
        	}
		else
		{
			if (pass==3) 
			{
				poststatus("SC3 D/L");
				//dw(SCCODE3);
			}
		}
	}
	poststatus("CHK BOOT SCCode D/L OK");
	delays(30);
	str_checkprompt("BOOT>");
	delays(5);
	poststatus("Turnoff SCCode");
	TurnOff();
	delays(10);
	
	SECOND_SC:  //2nd SC start
	
	// power on default 57k baud rate
	poststatus("Turn On SC");
	power(1);
	delays(120);
    Check_LedSC();		//Check Not Ready Failure ex. 1701 etc	
	str_getinvalidled(INVALID_LED);
	if(INVALID_LED != 0x00) 
	{
		showled(INVALID_LED);
		stoptest();
	}

	//ChangeBaudRate(115200,0);
	str_checkprompt("ENG>");
	poststatus("IDFY");
	//id(0);
	Id_Retry();
	str_getidfydata(0, 511, rdbuf);

//==================== 1Pass Check Start ====================
	if (rdbuf[215] == 0x53 || rdbuf[215] == 0x73)
	{
		poststatus("SCCode_Old");
		delays(1);
		if (rdbuf[192] == 0x42 && rdbuf[193] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
	if (rdbuf[215] == 0x53 || rdbuf[215] == 0x73)
	{
		poststatus("SCCode");
		delays(1);
		if (rdbuf[188] == 0x42 && rdbuf[189] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
	if (rdbuf[215] == 0x42 || rdbuf[215] == 0x62)
	{
		poststatus("BICode");
		delays(1);
		if (rdbuf[188] == 0x42 && rdbuf[189] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
	if (rdbuf[215] == 0x4D || rdbuf[215] == 0x6D)
	{
		poststatus("MainCode");
		delays(1);
		if (rdbuf[188] == 0x42 && rdbuf[189] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
//==================== 1Pass Check END ====================

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

	if (SC1PASS == 1)
	{
	 // download SC Script         
	 poststatus("SCSPT_1P D/L");
	 str_downloadbiscript(SCSPT_1P);
	 delays(10);
	 str_checkprompt("ENG>");
	}
	else
	{
	 // download SC Script         
	 poststatus("SCSPT D/L");
	 str_downloadbiscript(SCSPT);
	 delays(10);
	 str_checkprompt("ENG>");
	}

	// run SC
	//poststatus("SCStart OK");
	str_starttest();
//	str_monitorsc(minute);

// SC1419 & 1429 Reporcess
	str_monitoring("S/C", minute, tled, disflag);
	if (tled == 0)
	{
		//go through
	}
	else if ((tled & 0xFF00)== 0x1400 && nSC_loop == 0) //
	{
		//Do 2nd S/C
		nSC_loop = 1;
		power(0);
		delays(10);
		goto SECOND_SC;
	}
	else
	{
		str_stoptestfail(1, tled); // Proc 0: REF, 1:SC, 2:PT , 3:BI + LED Fail
                                           // Proc 4~ + Interal Fail Code
	}

	LABEL_BICODE:
	LABEL_MAINCODE:

	delays(5);
	poststatus("Turnoff SC");
	TurnOff();
	delays(10);

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

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

	flag_5400RPM = 0;
	flag_CONT = 0; //
	
LABEL_5400RPM:	

	// burnin code download
	poststatus("Turn On BICode");
	power(1);
	delays(120);
	Reset_Retry();
	
	str_getmcodeoption(MAINNORESET);	//Main Code jump command "reset"

	if (MAINNORESET == 0)
	{
		if (PCBAMAINCODE == 0)
		{
			str_getinvalidled(INVALID_LED);
			if(INVALID_LED != 0x00) 
			{

				str_checkprompt("ENG>");  // BI 07n8...
			}
			poststatus("reset");
            		Reset_Retry();
			delays(3);
		}
		if (PCBAMAINCODE == 1)
		{
			poststatus("Main Code");
			delays(3);
		}
	}
	else
	{
		poststatus("Main Code");
		delays(3);
	}
	
		poststatus("IDFY");
		Id_Retry();
	
		str_getidfydata(0, 511, rdbuf);
	
//==================== 1Pass Check Start ('BE' check for Magnet Erase) ====================
	if (rdbuf[215] == 0x53 || rdbuf[215] == 0x73)
	{
		poststatus("SCCode_Old");
		delays(1);
		if (rdbuf[192] == 0x42 && rdbuf[193] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
	if (rdbuf[215] == 0x53 || rdbuf[215] == 0x73)
	{
		poststatus("SCCode");
		delays(1);
		if (rdbuf[188] == 0x42 && rdbuf[189] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
	if (rdbuf[215] == 0x42 || rdbuf[215] == 0x62)
	{
		poststatus("BICode");
		delays(1);
		if (rdbuf[188] == 0x42 && rdbuf[189] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
	if (rdbuf[215] == 0x4D || rdbuf[215] == 0x6D)
	{
		poststatus("MainCode");
		delays(1);
		if (rdbuf[188] == 0x42 && rdbuf[189] == 0x45)
		{
			SC1PASS	= 1;
		}
	}
//==================== 1Pass Check END ====================

	// Code Check
	if (rdbuf[215] == 0x50 || rdbuf[215] == 0x70)
	{
		poststatus("LABEL_SMTCODE");
		delays(1);
		poststatus("ReS/C Test SMTCODE");
		stoptest();
	}

	ChangeBaudRateOLD();
	poststatus("HTBI D/L");
	if (SC1PASS == 1)
	{	
		//dw(HTBI54);
		strcpy(DWCODE,HTBI54);DW_RTY();
	}
	else if (flag_5400RPM == 0)
	{	
		//dw(HTBICODE);
		strcpy(DWCODE,HTBICODE);DW_RTY();
	}
	else
	{	
		//dw(HTBI54);   
		strcpy(DWCODE,HTBI54);DW_RTY();
	}
	poststatus("CHK BOOT HTBICODE");
	delays(30);
	poststatus("poweroff BICode");
	power(0);
	delays(10);

	//power on
	poststatus("Turn On");
	power(1);
	delays(120);
 	Reset_Retry();
	str_getinvalidled(INVALID_LED);
	if(INVALID_LED != 0x00) 
	{
		showled(INVALID_LED);
		stoptest();
	}
	str_checkprompt("ENG>");
	poststatus("IDFY");

	if (CLEAN_MC == 1 || SCCKIP == 1) 
	{           
         Clean_MC();  // check "ENG"
	}

	else
	{
	 Clean_MC2();  // Don't Check "ENG"
	}
	poststatus("Turn Off");
	power(0);
	delays(15);

	//>>>>>>>>>>>>>>>>>>>>>>>>>
	//B/I START
	SendMESData(SEND_BI_START);
	//<<<<<<<<<<<<<<<<<<<<<<<<<

	// BISPT download
	poststatus("Turn On BISPT");
	power(1);
	delays(120);
	str_sendserialcmd("LF",2);
	delays(5);
	Reset_Retry();
	Id_Retry();
	
	str_getinvalidled(INVALID_LED);
	if(INVALID_LED != 0x00) 
	{
		showled(INVALID_LED);
		stoptest();
	}

	//ChangeBaudRateOLD();
	poststatus("BISPT D/L");
	if (SC1PASS == 1)
	{
		str_downloadbiscript(BISPT54);
	}
	else if (flag_5400RPM == 0)
	{	
		str_downloadbiscript(BISPT);
	}
	else
	{	
		str_downloadbiscript(BISPT54);
	}
	
	poststatus("CHK ENG BISPT");
	delays(10);
	str_checkprompt("ENG>");

	// download geometry AZL file
	poststatus("GEO SPT");
	if (SC1PASS == 1)
	{
		str_downloadgeo(GEOSPT54);
	}	
	else if (flag_5400RPM == 0)
	{	
		str_downloadgeo(GEOSPT);
	}
	else
	{	
		str_downloadgeo(GEOSPT54);
	}
	poststatus("CHK ENG GEOSPT");
	delays(10);
	str_checkprompt("ENG>");

	// run burnin
	if(INVALID_LED != 0x00) 
	//if( invled != 0 )
	{
		showled(INVALID_LED);
		//showled(invled);
		stoptest();
	}
	str_checkprompt("ENG>");
	poststatus("BIStart OK");
	str_starttest();
	poststatus("B/I");
BI_CONT: //
	delays(3600);	
	if(MASS_Set==1){ONTESTERROR(Mass);} //set mass handler when B/I fail	
	
	str_monitoring("B/I", minute, tled, disflag);
	if (tled == 0)
	{
		//go through
	}
	else if (tled == 0x2308)
	{
		if(flag_CONT)
		{
			//5400 D/S
			flag_5400RPM = 1;
			flag_CONT = 0;
			power(0);
			delays(10);
			goto LABEL_5400RPM;
		}
		else
		{
			flag_CONT = 1;
			power(0);
			delays(10);
			power(1);
			delays(10);
			goto BI_CONT;
		}	
	}
//	else if ((tled == 0x2354 || tled == 0x1C04 || (tled & 0x1600) == 0x1600 || (tled & 0x1A00) == 0x1A00 || (tled & 0x2800) == 0x2800 || tled == 0x2408 || tled == 0x2C0C ) && flag_5400RPM == 0)
	else if (flag_5400RPM == 0)
	{
		//5400 D/S
		flag_5400RPM = 1;
		flag_CONT = 0;
		power(0);
		delays(10);
		goto LABEL_5400RPM;
	}	
	else
	{
		str_stoptestfail(3, tled);
	}
	
	//str_monitorbi(minute);

	delays(10);	
	TurnOff();
	delays(10);	
	power(1);
	delays(120);
	
	str_getinvalidled(INVALID_LED);
	if(INVALID_LED != 0x00) 
	{
		showled(INVALID_LED);
		stoptest();
	}

	Reset_Retry();

        str_mesdownsize(0);
	if(MASS_Set==1)
	{
		ONTESTERRORCLEAR();				 //clear mass handler
		poststatus("MASS");
		Mass();
	}
	delays(1);	
	TurnOff();
	delays(10);	
}

void Write_SerialNumber()
{
	// Write Serial Number

	str_debugmode();
	delays(5);
	str_checkprompt("DBG>");

	str_sendsn();
	delays(5);
	str_checkprompt("DBG>");
	poststatus("WrSN DONE");
	delays(1);
}

//New MES
void SendMESData(int step)
{
    char pn[16];
    int  pnlen;
    char debug[20];

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

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

    if (pnlen != 0x0E)
    {
        //sputd(debug, "PN %d", pnlen);
        //poststatus(debug);
        return;
    }

    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);
        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_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 ChangeBaudRate(int baudrate,int option)
{
	poststatus("Change Baud Rate");
	if (option == 1)
	{
		BAUD_RATE = baudrate;
		setbaud(BAUD_RATE);
	}
	else
	{
		if(BAUD_RATE != 115200)
		{
			//invalid ready does not support 115200
			if(INVALID_LED != 0x0000) 
			{
				BAUD_RATE = 57600;
			}
			else
			{
				BAUD_RATE = 115200;
			}
		}
	str_changehddbaud(BAUD_RATE);
	BAUD_RATE = 115200;
	}
}

void Clean_MC(void)
{
        str_sendserialcmd("LF",2);
	delays(5);
    poststatus("Cmd EI");
    str_sendserialcmd("EI",2);  //Erase Flash of PCBA
    delays(5);
	ONERROR(retrycleanmc);
    poststatus("Cmd ZM");
    str_sendserialcmd("ZM",2);    //command to HDD
    delays(300);
    str_checkprompt("ENG>");
	ONERRORCLEAR();
}
void Clean_MC2(void)
{
        str_sendserialcmd("LF",2);
	delays(5);
    poststatus("Cmd EI");
    str_sendserialcmd("EI",2);  //Erase Flash of PCBA
    delays(5);

	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();
}  	

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

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

	if (RTY_RESET == 3)
	{
		str_debugmode();
		str_checkprompt("DBG>");
		poststatus("Main code");
		stoptest();
	}

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

void Check_Download(int codetype)
{
	ONERROR(retrydownload);
	RTY_CODETYPE = codetype;
	str_checkprompt("BOOT>");
	ONERRORCLEAR();
}

void retrydownload()
{
	poststatus("retry D/L");
	
	// Set retry count
	RTY_DOWNLOAD = RTY_DOWNLOAD+1;
	if (RTY_DOWNLOAD > 2)
		ONERRORCLEAR();
		
	delays(10);
	TurnOff();
	delays(10);

	power(1);
	delays(120);
	reset();

/*	if (RTY_CODETYPE == RTY_DW_SCCODE)
	{
	//	dw(SCCODE1);
	}
	//else if (RTY_CODETYPE == RTY_DW_HTCODE)
	//{
	//	dw(HTCODE);
	//}
	//else if (RTY_CODETYPE == RTY_DW_BBIN)
	//{
	//	dw(BBIN);
	//}
	else if (RTY_CODETYPE == RTY_DW_FFLASH)
	{
	//	dw(FFLASH);
	}
	else if (RTY_CODETYPE == RTY_DW_HTBICODE)
	{
	//	dw(HTBICODE);
	}
	//else if (RTY_CODETYPE == RTY_DW_SCRBIN)
	//{
	//	dw(SCRBIN);
	//}
	else
	{
		poststatus("D/L RETRY FAIL");
		stoptest();
	}	
*/	
	delays(50);
	poststatus("retry CHK BOOT");
	str_checkprompt("BOOT>");
	ONERRORCLEAR();

	RTY_DOWNLOAD = 0;
	RTY_CODETYPE = 0;
}

void DW_RTY()
{
    char bootbuf[32];
    char cmd[4];
    int  ret;
    
    cmd[0]=0x0d;cmd[1]=0x0d;cmd[2]=0;//CRCR
    
    //download code & wait flash write
    dw(DWCODE); delays(20);
    
    //send CR(enter)
    ONERROR(dummyerror);
    str_usercmd(cmd,2,1000,32,0,bootbuf,32); bootbuf[31]=0;
    ONERRORCLEAR();
    
    //check prompt
    strstr(bootbuf,"BOOT>",ret);
    if(ret == 0)
    {
        //power cycle for retry
        power(0); delays(3); power(1);
        
        //wait ready & reset
        delays(60); reset();
        
        //download code & wait flash write
        dw(DWCODE); delays(20);
        str_checkprompt("BOOT>");
    } 
    
    memset(DWCODE,0,0,32);
}

void TempCheck()

{
  char sn[20];
  char tmstamp[32];
  char dplfile[32];
  int itemp;
  int offset;
  int  ivalue;
  int  handle;
  char CRLF[2];
  
  CRLF[0]=0x0D;
  CRLF[1]=0x0A;

    portnum(ivalue);                             //get port number
    sputd(dplfile,"C:\tmstamp%d.DAT", ivalue);
    fopen(handle,dplfile,"ab");
    timestamp(ivalue);
    memset(tmstamp,0,0,32);
    sputd(tmstamp,"tmstamp: %d",ivalue);
    strlen(tmstamp,ivalue);
    fwrite(handle,tmstamp,ivalue);          //report reworkflag
    fwrite(handle,CRLF,2);
    fclose(handle);
}

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

void ChangeBaudRateOLD()
{
	if(BAUD_RATE != 115200)
	{
		//invalid ready does not support 115200
		if(INVALID_LED != 0x00) 
		{
	  		BAUD_RATE = 57600;
		}
		else
		{
			BAUD_RATE = 115200;
		}
	}
	
	ONERROR(restorehddbaud);
	str_changehddbaud(BAUD_RATE);
	ONERRORCLEAR();
	BAUD_RATE = 115200;
}

void restorehddbaud()
{
	// Set retry count
	RTY_BAUDCHANGE = RTY_BAUDCHANGE+1;
	if (RTY_BAUDCHANGE > 3)
		ONERRORCLEAR();

	poststatus("fixbaud");
	TurnOff();
	delays(10);
	power(1);
	delays(120);
	reset();
	ONERRORCLEAR();
	RTY_BAUDCHANGE = 0;
}

void Id_Retry()
{
    RTY_IDFY = 0;
    ONERROR(retryid);
    poststatus("IDFY");
    cmdtimeout(40000);     // 40 sec
    id(0);
    cmdtimeout(0);
    ONERRORCLEAR();
}

/*
void retryid()
{
	ONERRORCLEAR();
	TurnOff();
	delays(15);
	poststatus("ID_Re");
	power(1);
	delays(80);
	reset();
	cmdtimeout(180000);	//180sec
	id(0);
	cmdtimeout(0);
	//str_debugmode();
}
*/
void retryid()
{
	//ONERRORCLEAR();
	RTY_IDFY = RTY_IDFY + 1;
	if( RTY_IDFY == 2)
	{
		ONERRORCLEAR(); 
		TurnOff();
		delays(15);
		poststatus("ID_Re2");
		power(1);
		delays(120);
		reset();
		cmdtimeout(300000);	//5min
		id(0);
		cmdtimeout(0);
		goto ID_PASS;
	}	
	TurnOff();
	delays(15);
	poststatus("ID_Re1");
	power(1);
	delays(120);
	reset();
	poststatus("ID_Re1");
        //str_sendserialcmd("RC",2);  //Erase Flash of PCBA
        //delays(480);
	cmdtimeout(180000);	//180sec
	id(0);
	cmdtimeout(0);
	ONERRORCLEAR();
ID_PASS:
	RTY_IDFY = 0;
	//str_debugmode();
}

void Mass()
{
    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_getmasssize(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;

   // reset();
	TurnOff();
	delays(10);
	power(1);
	delays(200);
	Reset_Retry();
	//reset();

    for(MASS_TYPE=0 ; MASS_TYPE<2 ; MASS_TYPE++)
    {
        if(MASS_TYPE == 1)
        {
            str_getsbr(reworkflag);
            strlen(reworkflag,ivalue);
            if(ivalue == 0)
            {
                if( passfail == CHAR_F )
                    stoptest();
                return;
            }
            //must uncomment out when download MCCODE for MASS DEV
            //dw(MCCODE);
            delays(40);
            str_checkprompt("BOOT>");
            TurnOff();
            delays(10);
            power(1);
            delays(240);
            Reset_Retry();
            //reset();
          
           Id_Retry();
        }
        
        //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
            str_sendserialcmd("TM",2); 
            delays(10);
            str_sendserialcmd("PP",2);
            delays(300);
            str_getmassdata(masshead, 0, 2, ivalue);
            delays(20);
            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) 
            {
                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 test is fail, stop the test
    if( passfail == CHAR_F )
    {   
        if (flag_5400RPM == 0)
        {	
            dw(HTBICODE);
        }
        else
        {	
		dw(HTBI54);   
        }
        delays(30);
        str_checkprompt("BOOT>");
        TurnOff();
        delays(10);
        power(1);
        delays(240);
        reset();
        stoptest();
    }
} 

 // Drive Binning for F1(Trinity)
void DriveBinning()
{
	int 	ret;
	int 	totalgrade;
	char 	grade;
	int 	gradevalue;
	int 	gradeweight;
	float 	percentage;
	float   maxpoint;
	float   gradepoint;
	int		cmpflaga;
	int		cmpflagb;
	float   remainder;
	float   quotient;
	float   quotienttemp;
	int     gradereport;
	
	BF_MAXPOINT 	= 0;
	FORCED_C_GRADE 	= 0;
	
	BV_BUFFER_LOCATION = 0;
	memset(BV_BUFFER,0,0,SECTOR_SIZE_BINNING);
	gradevalue = 0;
	 str_setdumpsectorsize(1710);                       //for gigacube

	ret = GetMassHeader();
	if (ret != 0)
	{
		poststatus("GetMassHeader fail");
		userfilelog("GetMassHeader fail"); logivalue(ret);
	}
	
    	gradevalue = gradevalue + GetParamGrade(BER_10S_MIN);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(BER_10S_AVG);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(TPI_OPT);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);

    	gradevalue = gradevalue + GetParamGrade(DATA_GAIN_AVG);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(SERVO_GAIN_AVG);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);

   		gradevalue = gradevalue + GetParamGrade(FLY_HEIGHT);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(FOD_R);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(FOD_W);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(RWGAP);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);

    	gradevalue = gradevalue + GetParamGrade(OD_WC);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(MD_WC);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(ID_WC);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);

    	gradevalue = gradevalue + GetParamGrade(PES);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(RRO);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
		gradevalue = gradevalue + GetParamGrade(Latch_Force);
			userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);

    	gradevalue = gradevalue + GetParamGrade(DATA_DEFECT_ZN);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(DEF_SURFACE);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(SERVO_DEF_SURFACE);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);
    	gradevalue = gradevalue + GetParamGrade(TRK_DEF_SURFACE);
    		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue); 		
	gradevalue = gradevalue + GetParamGrade(TA_SURFACE);
		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);

	gradevalue = gradevalue + GetParamGrade(DS_Flag);
		userfilelog("SUM OF GRADE VALUE = "); logivalue(gradevalue);

	userfilelog("TOTAL GRADE VALUE = "); logivalue(gradevalue);
	userfilelog("MAX   GRADE VALUE = "); logivalue(BF_MAXPOINT);	
	if (FORCED_C_GRADE != 0)
	{
		BIN_RESULT = CHAR_C;
		
		grade = CHAR_C;
		gradevalue = 1;
		str_setdrvgrade(grade, gradevalue);
		userfilelog("<GRADE>");
		userfilelog("- FORCED C -");
	}
	else
	{
		//BF_MAXPOINT;
		gradepoint = gradevalue;
		maxpoint   = BF_MAXPOINT;

		quotient   = gradepoint*10000;
		percentage = quotient/maxpoint;
		
		BF_DRVGRADE_LOW = BF_DRVGRADE_LOW*100;
		BF_DRVGRADE_HIGH = BF_DRVGRADE_HIGH*100;
		
		
		gradereport = percentage/100;
		
		cmparefloat(percentage, BF_DRVGRADE_LOW, cmpflaga);
		cmparefloat(percentage, BF_DRVGRADE_HIGH, cmpflagb);
		
		if (cmpflagb >= 0)
		{
			BIN_RESULT = CHAR_A;
			
			str_setdrvgrade(CHAR_A, gradereport);
			userfilelog("<GRADE>");
			userfilelog("- A -"); logivalue(gradereport);
		}
		else if (cmpflaga >= 0 && cmpflagb < 0)
		{
			BIN_RESULT = CHAR_B;
			
			str_setdrvgrade(CHAR_B, gradereport);
			userfilelog("<GRADE>");
			userfilelog("- B -"); logivalue(gradereport);			
		}
		else
		{
			BIN_RESULT = CHAR_C;
			
			str_setdrvgrade(CHAR_C, gradereport);
			userfilelog("<GRADE>");
			userfilelog("- C -"); logivalue(gradereport);			
		}
	}
}

// New Grading 10단계 
void DriveGrading_new()
{
    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;
    int   rackno, 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 - 2;//2 -> log10(100)
                    //sputf(temp,"-%f",fparamvalue);
                    //atof(temp,fparamvalue);
                    break;
                case 3:
                    // -log(value/100)
                    if(ivalue2 < 100 )
                    {
                    	fparamvalue = 0;
                    }
                    else
                    {	
                        log10(ivalue2,fparamvalue);
                        fparamvalue = fparamvalue - 2;
                    }
                    //sputf(temp,"-%f",fparamvalue);
                    //atof(temp,fparamvalue);
                    break;
                case 12:
                case 13:
                case 14:
                case 49:    
                    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; 
                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;

        }

    }

/*        
        if((paramgrade == prm_paragrade_c || paramgrade == prm_paragrade_d) && prm_weight != 0)
        {
            paramflag = 1;
        } 
        else if(paramgrade == prm_paragrade_e)
        {
            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)
    {
	BIN_RESULT = CHAR_A;
        str_setdrvgrade(CHAR_A, percent);
        gradeformass = CHAR_A;
    }
    else if(GX < prm_drivegrade_low)
    {
	BIN_RESULT = CHAR_B;
        str_setdrvgrade(CHAR_B, percent);
        gradeformass = CHAR_B;
    }
    else
    {
	BIN_RESULT = CHAR_C;
        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);
    sputd(temp,"%d,",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);
    sputd(temp,"%d,",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);
}
int GetParamGrade(int item)
{
	int  	ret;
	int  	gradevalue;
	int  	grade;
	int	gradeb;
	float	paramvalue;
	float	paramvalueb;
	int     iparamvlue_ok;
	int	loopcnt;
	int	cmpflaga;
	int	cmpflagb;
	int	cmpflagc;
	int	cmpflagd;
	int	loopcntb;
	
	char    buf[128];
	
	gradevalue = 0;
	paramvalue = 0;
	
	if (DEBUG_ON != 0)
	{
		userfilelog("-------------GET PARAM GRADE-----------------------------");
		userfilelog("PARAM NO"); logivalue(item);
	}
	
	// get variables
	ret = GetBinningVariables(item);
	if (ret != 0)
	{
		poststatus("fail bin var");
		return 0;
	}
	// get param value
	iparamvlue_ok = 0;

	if( item == Latch_Force )
	{
		loopcntb = 1;
	}
	else
	{
		loopcntb = MH_NUMOF_HEAD;
	}

	grade = 30000;
	for (loopcnt = 0; loopcnt < loopcntb;)
	{
		iparamvlue_ok = GetParamValue(item, loopcnt);
		if (iparamvlue_ok == 0)
		{
			poststatus("fail GetParamValue");
			return 0;
		}

		paramvalue = PARAM_RET_VALUE;	

		cmparefloat(paramvalue, BV_LCL1, cmpflaga);
		cmparefloat(paramvalue, BV_LCL2, cmpflagb);
		cmparefloat(paramvalue, BV_UCL1, cmpflagc);
		cmparefloat(paramvalue, BV_UCL2, cmpflagd);
	
		// judging grade
		if (BV_TYPE == PARAM_TYPE_LOW)
		{
			if (cmpflaga < 0)
			{	gradeb = BV_PARAGRADE_A;	}
			else if (cmpflaga >= 0 && cmpflagb < 0)
			{	gradeb = BV_PARAGRADE_B;	}
			else
			{	gradeb = BV_PARAGRADE_C;	}		
		}
		else if (BV_TYPE == PARAM_TYPE_MID)
		{
			if (cmpflaga > 0 && cmpflagc <= 0)
			{	gradeb = BV_PARAGRADE_A;	}
			else if (cmpflagb > 0 && cmpflaga <= 0)
			{	gradeb = BV_PARAGRADE_B; }
			else if (cmpflagd < 0 && cmpflagc >= 0)
			{	gradeb = BV_PARAGRADE_B; }
				else
			{	gradeb = BV_PARAGRADE_C; }
		}
		else if (BV_TYPE == PARAM_TYPE_UPP)
		{
			if (cmpflagc > 0)
			{	gradeb = BV_PARAGRADE_A;	}
			else if (cmpflagd > 0 && cmpflagc <= 0)
			{	gradeb = BV_PARAGRADE_B;	}
			else
			{	gradeb = BV_PARAGRADE_C;	}		
		}
		else
		{
			poststatus("No Type");
			stoptest();
		}
		if( grade > gradeb )
		{
			grade = gradeb;
		}	
	
		loopcnt = loopcnt + 1;
	}	
	//check forced c
	if (grade == BV_PARAGRADE_C && BV_FORCED_C != 0)
		FORCED_C_GRADE = 1;

	// grade x weight
	gradevalue = grade*BV_WEIGHT;
	
	if (DEBUG_ON != 0)
	{
		userfilelog("--------------GetParamGrade-----------------------");
		userfilelog("FORCED_C_GRADE"); logivalue(FORCED_C_GRADE);
		userfilelog("grade"); logivalue(grade);
		userfilelog("BV_WEIGHT"); logivalue(BV_WEIGHT);
		userfilelog("paramvalue"); { sputf(buf, "%f", paramvalue); userfilelog(buf); }
		userfilelog("gradevalue"); logivalue(gradevalue);
		userfilelog("-------------END PARAM GRADE-----------------------------");
	}	

	return gradevalue;
}

int GetParamValue(int item, int headnum)
{
	float 	retvalue;
	float   fvaltemp;
	float   fvaltempb;
	//float   retvaluesum;
	float   fber;
	int	location_of_sector;
	int	location_of_head_zero;
	int     offset_zero;
	int	offset;
	int     offsetb;
	int	pt_type;
	int	num_of_zone;
	int	hd_sector_gap;
	int	ber_rd_cnt;
	int	ivalue;
	int	ivaluea;	
	int	ivalueb;
	//int	loopcnt;
	int	loopcntb;
	int	cmpflaga;
	int	cmpflagb;
	char    buf[128];
	char	bufa[128];
	char	bufb[128];
	
	PARAM_RET_VALUE = 0;
	
	if (DEBUG_ON != 0)
	{
		userfilelog("-------------GET PARAM VALUE-----------------------------");
		userfilelog("PARAM NO"); logivalue(item);
	}

	num_of_zone = 24;
	hd_sector_gap = MH_OFFSET_HD1 - MH_OFFSET_HD0;

	//set location
	if (item == BER_10S_MIN)
	{
		location_of_sector 	= MH_OFFSET_HD0_ZONE;
		offset 				= 0x68;
		pt_type 			= PT_HD_ZONE;
	}
	if (item == BER_10S_AVG)
	{
		location_of_sector 	= MH_OFFSET_HD0_ZONE;
		offset 				= 0xC8;
		pt_type 			= PT_HD_ZONE;
	}
	if (item == TPI_OPT)
	{
		location_of_sector 	= MH_OFFSET_HD0;
		offset 				= 0x18;
		pt_type 			= PT_HD;
	}
	if (item == DATA_GAIN_AVG)
	{
		location_of_sector 	= MH_OFFSET_HD0_RANGE;
		offset 				= 0x0;
		pt_type 			= PT_HD_RANGE;
	}
	if (item == SERVO_GAIN_AVG)
	{
		location_of_sector 	= MH_OFFSET_HD0_RANGE;
		offset 				= 0x10;
		pt_type 			= PT_HD_RANGE;
	}
	if (item == FLY_HEIGHT)
	{
		location_of_sector 	= MH_OFFSET_HD0_STEP;
		offset 				= 0x214;
		pt_type 			= PT_HD_STEP;
	}
	if (item == FOD_R)
	{
		location_of_sector 	= MH_OFFSET_HD0_STEP;
		offset 				= 0x1EC;
		pt_type 			= PT_HD_STEP;
	}
	if (item == FOD_W)
	{
		location_of_sector 	= MH_OFFSET_HD0_STEP;
		offset 				= 0x200;
		pt_type 			= PT_HD_STEP;
	}
	if (item == RWGAP)
	{
		location_of_sector 	= MH_OFFSET_HD0_STEP;
		offset 				= 0x1EC;
		pt_type 			= PT_HD_STEP;
	}
	if (item == OD_WC)
	{
		location_of_sector 	= MH_OFFSET_HD0_RANGE;
		offset 				= 0x64;
		pt_type 			= PT_HD_RANGE;
	}
	if (item == MD_WC)
	{
		location_of_sector 	= MH_OFFSET_HD0_RANGE;
		offset 				= 0x68;
		pt_type 			= PT_HD_RANGE;
	}
	if (item == ID_WC)
	{
		location_of_sector 	= MH_OFFSET_HD0_RANGE;
		offset 				= 0x6C;
		pt_type 			= PT_HD_RANGE;
	}
	if (item == PES)
	{
		location_of_sector 	= MH_OFFSET_HD0;
		offset 				= 0x10;
		pt_type 			= PT_HD;
	}
	if (item == RRO)
	{
		location_of_sector 	= MH_OFFSET_HD0;
		offset 				= 0x0C;
		pt_type 			= PT_HD;
	}
	if (item == Latch_Force)
	{
		location_of_sector 	= MH_OFFSET_DRV_SET;
		offset 				= 0x4C;
		pt_type 			= PT_DRV_SET;
	}
	if (item == DATA_DEFECT_ZN)
	{
		location_of_sector 	= MH_OFFSET_HD0_ZONE;
		offset 				= 0x0;
		pt_type 			= PT_HD_ZONE;
	}
	if (item == DEF_SURFACE)
	{
		location_of_sector 	= MH_OFFSET_HD0_ZONE;
		offset 				= 0x60;
		pt_type 			= PT_HD_ZONE;
	}
	
	if (item == SERVO_DEF_SURFACE)
	{
		location_of_sector 	= MH_OFFSET_HD0_RANGE;
		offset 				= 0x30;
		pt_type 			= PT_HD_RANGE;
	}
	if (item == TRK_DEF_SURFACE)
	{
		location_of_sector 	= MH_OFFSET_HD0_RANGE;
		offset 				= 0x40;
		pt_type 			= PT_HD_RANGE;
	}
	if (item == TA_SURFACE)
	{
		location_of_sector 	= MH_OFFSET_HD0_ZONE;
		offset 				= 0x0;
		pt_type 			= PT_HD_ZONE;
	}
	if (item == DS_Flag)
	{
		location_of_sector 	= MH_OFFSET_DRV_SET;
		offset 				= 0x58;
		pt_type 			= PT_DRV_SET;
	}
	// peek value
	if (pt_type == PT_DRV_SET || pt_type == PT_DRV_SET_ZONE || pt_type == PT_DRV_SET_STEP )
	{
		//get mass data
		if (BV_BUFFER_LOCATION != location_of_sector)
		{
			str_getmassdata(BV_BUFFER, location_of_sector, 2, ivalue);
			if (ivalue != SECTOR_SIZE_BINNING)
			{
				poststatus("PT_DRV_SET fail");
				stoptest();
			}
			else
			{
				BV_BUFFER_LOCATION = location_of_sector;
			}
		}

	
		if (item == Latch_Force)
		{
			peek(BV_BUFFER, offset, 4, ivalue);
							
			if (DEBUG_ON != 0)
			{
				userfilelog("~~~~~~~~~~~");
				sputf(buf, "Latch_Force=%d",ivalue );
				userfilelog(buf);					
				userfilelog("~~~~~~~~~~~");								
			}	
			
			retvalue = ivalue;
			sputf(buf, "%f", retvalue); userfilelog(buf);
	 	}
		else if (item == DS_Flag)
		{
			peek(BV_BUFFER, offset, 4, ivalue);
							
			if (DEBUG_ON != 0)
			{
				userfilelog("~~~~~~~~~~~");
				sputf(buf, "Downsizing Flag=%d",ivalue );
				userfilelog(buf);					
				userfilelog("~~~~~~~~~~~");								
			}	
			if( ( ivalue == 0x1001 ) || ( ivalue == 0x2001 ) || ( ivalue == 0x4001 ) )
			{
				retvalue = 1;
			}
			else
			{
				retvalue = 0;
			}
			sputf(buf, "%f", retvalue); userfilelog(buf);
 		}
		else
		{		
			peek(BV_BUFFER, offset, 4, ivalue);
			retvalue = ivalue;
			
			if (DEBUG_ON != 0)
			{
				userfilelog("~~SET~~~~~~");
				sputd(buf, "RP 0x%X 1 :", location_of_sector);
				sputd(bufa, "offset 0x%X, ", offset);
				sputd(bufb,  "value  0x%X", retvalue);
				strcat(buf, bufa);
				strcat(buf, bufb);
				userfilelog(buf);
				userfilelog("~~~~~~~~~~~");
			}
		}
	}
	if (pt_type == PT_HD ||	pt_type == PT_HD_RANGE || pt_type == PT_HD_STEP || pt_type == PT_HD_ZONE)
	{
		location_of_head_zero = location_of_sector;
		offset_zero = offset;
		//retvaluesum = 0;

		//HEADSUM//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//for (loopcnt = 0; loopcnt < MH_NUMOF_HEAD; )
		//{
			retvalue = 0;
			//get mass data
			location_of_sector = location_of_head_zero + hd_sector_gap*headnum;
			//location_of_sector = location_of_head_zero + hd_sector_gap*loopcnt;
			
			if (BV_BUFFER_LOCATION != location_of_sector)
			{
				str_getmassdata(BV_BUFFER, location_of_sector, 2, ivalue);
				if (ivalue != SECTOR_SIZE_BINNING)
				{
					poststatus("PT_DRV_SET fail");
					stoptest();
				}
				else
				{
					BV_BUFFER_LOCATION = location_of_sector;
				}
			}

			peek(BV_BUFFER, offset, 4, ivalue);	//default
			
			//Default peek value log
			if (DEBUG_ON != 0)
			{
				userfilelog("~~ HEAD ~~");
				sputd(buf, "RP 0x%X 1 :", location_of_sector);
				sputd(bufa, "offset 0x%X, ", offset);
				sputd(bufb,  "value  0x%X", ivalue);
				strcat(buf, bufa);
				strcat(buf, bufb);
				userfilelog(buf);
				userfilelog("~~~~~~~~~~~");				
			}

			if (item == BER_10S_MIN)
			{
				userfilelog("in BER_10S_MIN");
				
				peek(BV_BUFFER, 0x64, 4, ber_rd_cnt);
				if (DEBUG_ON != 0)
				{ 
					userfilelog("ber_rd_cnt"); 
					logivalue(ber_rd_cnt); 
				}
				
				fber = 0;
				
				for (loopcntb = 0; loopcntb < num_of_zone; )
				{
					offset = offset_zero + 4*loopcntb;
					peek(BV_BUFFER, offset, 4, ivalue);
					if (DEBUG_ON != 0)
					{ 
						userfilelog("~~~~~~~~~~~");
						sputd(buf, "zone offset 0x%X, ", offset);
						sputd(bufa, "zone no 0x%X, ", loopcntb);
						sputd(bufb, "zone value 0x%X", ivalue);
						strcat(buf, bufa);
						strcat(buf, bufb);
						userfilelog(buf);
						//userfilelog("~~~~~~~~~~~");
					}
					
					if (ivalue == 0)
					{
						//userfilelog("~~~~~~~~~~~");
						atof("8.01", fvaltemp);
						userfilelog("zone value : 8.01 because error is 0");
						//sputf(buf, "%f", fvaltemp); userfilelog(buf);
						userfilelog("~~~~~~~~~~~");
					}
					else
					{
						ivalueb = (ber_rd_cnt*8*512/24)/ivalue;
						log10(ivalueb, fvaltemp);
						if (DEBUG_ON != 0)
						{
							//userfilelog("~~~~~~~~~~~");
							sputd(buf, "(ber_rd_cnt*8*512/24)/ivalue = 0x%X : ", ivalueb);
							sputf(bufa, "BER is log10(X) = %f", fvaltemp);
							strcat(buf, bufa);
							userfilelog(buf);
							userfilelog("~~~~~~~~~~~");
						}
					}
					
					cmparefloat(fber, 0, cmpflaga);
					if (cmpflaga == 0)
					{
						fber = fvaltemp;
					}
					else
					{
						cmparefloat(fvaltemp, fber, cmpflagb);
						if (cmpflagb < 	0)
							fber = fvaltemp;						
					}
					loopcntb = loopcntb + 1;
				}
	
				retvalue = fber;
				
				userfilelog("HD NO-"); logivalue(headnum);
				sputf(buf, "%f", retvalue); userfilelog(buf);				
			}
			else if (item == BER_10S_AVG)
			{
				userfilelog("in BER_10S_AVG");
				
				peek(BV_BUFFER, 0x64, 4, ber_rd_cnt);
				if (DEBUG_ON != 0)
				{ 
					userfilelog("ber_rd_cnt"); 
					logivalue(ber_rd_cnt); 
				}
			
				peek(BV_BUFFER, offset, 4, ivalue);
				if (DEBUG_ON != 0)
				{ 
					userfilelog("~~~~~~~~~~~");
					sputd(bufb, "Avg value 0x%X", ivalue);
					strcat(buf, bufa);
					strcat(buf, bufb);
					userfilelog(buf);
					//userfilelog("~~~~~~~~~~~");
				}
					
				if (ivalue == 0)
				{
					//userfilelog("~~~~~~~~~~~");
					atof("8.01", ivalue);
					userfilelog("zone value : 8.01 because error is 0");
					//sputf(buf, "%f", fvaltemp); userfilelog(buf);
					userfilelog("~~~~~~~~~~~");
				}
				else
				{
					ivalueb = (ber_rd_cnt*8*512/24)/ivalue;
					log10(ivalueb, fvaltemp);
					if (DEBUG_ON != 0)
					{
						//userfilelog("~~~~~~~~~~~");
						sputd(buf, "(ber_rd_cnt*8*512/24)/ivalue = 0x%X : ", ivalueb);
						sputf(bufa, "BER is log10(X) = %f", fvaltemp);
						strcat(buf, bufa);
						userfilelog(buf);
						userfilelog("~~~~~~~~~~~");
					}
				}
	
				fber = fvaltemp;
				retvalue = fber;
				
				userfilelog("HD NO-"); logivalue(headnum);
				sputf(buf, "%f", retvalue); userfilelog(buf);				
			}
			else if (item == DATA_DEFECT_ZN)
			{
				ivalueb = 0;
				for (loopcntb = 0; loopcntb < num_of_zone; )
				{
					offset = offset_zero + 4*loopcntb;
					peek(BV_BUFFER, offset, 4, ivalue);
					if (DEBUG_ON != 0)
					{ 
						userfilelog("~~~~~~~~~~~");
						sputd(buf, "zone offset 0x%X, ", offset);
						sputd(bufa, "zone no 0x%X, ", loopcntb);
						sputd(bufb, "zone value 0x%X", ivalue);
						strcat(buf, bufa);
						strcat(buf, bufb);
						userfilelog(buf);
						//userfilelog("~~~~~~~~~~~");
					}					

                   		 if (ivalue > ivalueb)
		                    {
		                        ivalueb = ivalue;   
		                    }
		                    loopcntb = loopcntb + 1;
		                }
		                retvalue = ivalueb;
            
                		userfilelog("HD NO-"); logivalue(headnum);
		                sputf(buf, "%f", retvalue); userfilelog(buf);
			}
			
			else if (item == TA_SURFACE)
			{
				ivalueb = 0;
                for(loopcntb = 9; loopcntb <16 ; )
                {
					offset = offset_zero + 4*loopcntb;
					peek(BV_BUFFER, offset, 4, ivalue);
                   			 if (DEBUG_ON != 0)
					{ 
						userfilelog("~~~~~~~~~~~");
						sputd(buf, "zone offset 0x%X, ", offset);
						sputd(bufa, "zone no 0x%X, ", loopcntb);
						sputd(bufb, "zone value 0x%X", ivalue);
						strcat(buf, bufa);
						strcat(buf, bufb);
						userfilelog(buf);
						//userfilelog("~~~~~~~~~~~");
					}
                        if (ivalue > ivalueb)
                            {
                                ivalueb = ivalue;   
                            }
                        loopcntb = loopcntb + 1;
                }
                 
                        retvalue = ivalueb;
                
                        userfilelog("HD NO-"); logivalue(headnum);
                        sputf(buf, "%f", retvalue); userfilelog(buf);
			}
			else if (item == FOD_R || item == FOD_W )
			{
				ivalueb = 0;
				ivaluea = 1024;

				for (loopcntb = 0; loopcntb < 4; )
				{
					offset = offset_zero + 4 * loopcntb;
					peek(BV_BUFFER, offset, 4, ivalue);

					
					if( ivalue > ivalueb)
					{
						ivalueb = ivalue;
					}
					if( ivalue < ivaluea)
					{
						ivaluea = ivalue;
					}
					loopcntb = loopcntb + 1;					
				}
				
				ivalue = ivalueb - ivaluea;
				
				retvalue = ivalue;
	                	userfilelog("HD NO-"); logivalue(headnum);
	                	sputf(buf, "%f", retvalue); userfilelog(buf);

			}
			else if (item == RWGAP )
			{
				ivalue = 0;
				ivaluea = 0;
				ivalueb = 0;				
				for (loopcntb = 0; loopcntb < 4; )
				{
					offset = offset_zero + 4 * loopcntb;
					peek(BV_BUFFER, offset, 4, ivalue);

					ivalueb = ivalueb + ivalue;
					
					loopcntb = loopcntb + 1;					
				}
				userfilelog("~~~~~~~~~~~");
				sputd(bufb, "FODR AVG value 0x%X", ivalueb);
				strcat(buf, bufa);
				strcat(buf, bufb);
				userfilelog(buf);
				//userfilelog("~~~~~~~~~~~");				
				ivalueb = ivalueb / 4;			

				for (loopcntb = 5; loopcntb < 9; )
				{
					offset = offset_zero + 4*loopcntb;
					peek(BV_BUFFER, offset, 4, ivalue);
					
					ivaluea = ivaluea + ivalue;
					
					loopcntb = loopcntb + 1;					
				}				
				ivaluea = ivaluea / 4;
				
				ivalue = ivalueb - ivaluea;
				
				retvalue = ivalue;
	                	userfilelog("HD NO-"); logivalue(headnum);
	                	sputf(buf, "%f", retvalue); userfilelog(buf);
			}
			else if (item == FLY_HEIGHT)
			{			
				ivalueb = 0;
				ivalue = 0;
				for (loopcntb = 0; loopcntb < 4; )
				{
					offset = offset_zero + 4 * loopcntb;
					peek(BV_BUFFER, offset, 4, ivalueb);

					ivalue = ivalue + ivalueb;
					loopcntb = loopcntb + 1;					
				}
				
				
				ivalue = ivalue / 4;	
				
				userfilelog("~~~~~~~~~~~");
				sputd(bufb, "FH Delta value 0x%X", ivalue);
				strcat(buf, bufa);
				strcat(buf, bufb);
				userfilelog(buf);
				//userfilelog("~~~~~~~~~~~");
			
				fvaltemp = ivalue;
				atof("2.54", fvaltempb);
				fvaltemp = fvaltemp * fvaltempb;
				fvaltemp = fvaltemp/10000;
				
				if (DEBUG_ON != 0)
				{
					userfilelog("~~~~~~~~~~~");
					sputf(bufa, "Fly Height is = %f", fvaltemp);
					strcat(buf, bufa);
					userfilelog(buf);
					userfilelog("~~~~~~~~~~~");
				}	
				retvalue = fvaltemp;
			}
			else if (item == PES || item == RRO)
			{
				peek(BV_BUFFER, offset, 4, ivalue);
				fvaltemp = ivalue/10;
				sqrt(fvaltemp, retvalue);
				
				if (DEBUG_ON != 0)
				{
					userfilelog("~~~~~~~~~~~");
					
					sputf(buf, "sqrt(x/10) = %f", retvalue);
					userfilelog(buf);					
					userfilelog("~~~~~~~~~~~");								
				}								
				
			}
			else if (item == TPI_OPT)
			{
				peek(BV_BUFFER, offset, 4, ivalue);
         		if (ivalue & 0x80000000)
         		{
         			// minus value
         			ivalue = ivalue ^ 0xFFFFFFFF;   //2's complement
         			ivalue = ivalue+1;      			
	    			fvaltemp = ivalue;
   					atof("-1", fvaltempb);
 					retvalue = fvaltemp*fvaltempb;         			
         			
         		}
         		else
         		{
         			fvaltemp = ivalue;
         			retvalue = fvaltemp;
         		}
				if (DEBUG_ON != 0)
				{
					userfilelog("~~~~~~~~~~~");
					sputf(buf, "SEL TPI = %f", retvalue);
					userfilelog(buf);					
					userfilelog("~~~~~~~~~~~");						
				}		
			}
			else
			{
				sputf(buf, "%f", retvalue); userfilelog(buf);
				
				retvalue = retvalue + ivalue;
				
				if (DEBUG_ON != 0)
				{
					userfilelog("~~~~~~~~~~~");
					sputd(buf, "Default is 0x%X,", ivalue);
					sputf(bufa, "Sum is %f ", retvalue);
					strcat(buf, bufa);
					userfilelog(buf);					
					userfilelog("~~~~~~~~~~~");										
				}								
			}
			
			// Sum of head's value
			//loopcnt = loopcnt+1;
			//retvaluesum = retvaluesum + retvalue;
		//}
		//divid by head
		//retvalue = retvaluesum/MH_NUMOF_HEAD;
		//HEADSUM//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	}

	//save return value
	PARAM_RET_VALUE = retvalue;

	userfilelog("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	userfilelog("return PARAM_RET_VALUE"); sputf(buf, "%f", PARAM_RET_VALUE); userfilelog(buf);
	userfilelog("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
	
	return 1;
}

int GetBinningVariables(int param)
{
	int  strlength;
	int  strcatflag;
	char filename[20];
	char filepath[50];
	char appname[20];
	char keyname[20];
	char keyvalue[50];
	char buf[128];
	char pn_mcode[20];
	char mdlmatch;
	char basicmdl[20];
	
	strcpy(appname, "");

	if (param == RRO)
		strcpy(appname, "RRO");
	if (param == BER_10S_MIN)
		strcpy(appname, "10S BER_MIN");
	if (param == FOD_R)
		strcpy(appname, "FOD_R");
	if (param == TPI_OPT)
		strcpy(appname, "OPT_TPI");
	if (param == BER_10S_AVG)
		strcpy(appname, "10S BER_AVG");
	if (param == DATA_GAIN_AVG)
		strcpy(appname, "DATA_GAIN_AVG");
	if (param == SERVO_GAIN_AVG)
		strcpy(appname, "SERVO_GAIN");
	if (param == FLY_HEIGHT)
		strcpy(appname, "FLY_HEIGHT");
	if (param == PES)
		strcpy(appname, "PES");
	if (param == Latch_Force)
		strcpy(appname, "Latch Force");
	if (param == DATA_DEFECT_ZN)
		strcpy(appname, "Data Defect");
	if (param == DEF_SURFACE)
		strcpy(appname, "DEF/SURFACE");
	if (param == SERVO_DEF_SURFACE)
		strcpy(appname, "SERVO DEFECT_TOTAL");
	if (param == TA_SURFACE)
		strcpy(appname, "TA");
	if (param == FOD_W)
		strcpy(appname, "FOD_W");
	if (param == RWGAP)
		strcpy(appname, "RWGAP");
	if (param == OD_WC)
		strcpy(appname, "OD-WC");
	if (param == MD_WC)
		strcpy(appname, "MD-WC");
	if (param == ID_WC)
		strcpy(appname, "ID-WC");
	if (param == TRK_DEF_SURFACE)
		strcpy(appname, "TLIST");
	if (param == DS_Flag)
		strcpy(appname, "DIS_Flag");  

	strlen(appname, strlength);
	if (strlength < 1)
	{
		poststatus("appname invalid");
		return 1;
	}							

	strlen(BIN_FILENAME, strlength);
	if (strlength == 0)
	{
		str_getdrvparamname(BIN_FILENAME);	// set default
		
		memset(pn_mcode, 0, 0, 20);
		getsn(pn_mcode);
		pn_mcode[4] = 0;
		
		strcpy(filepath, "emodel.txt");
		getkeystring(filepath, "BASIC_MODEL", pn_mcode, keyvalue);
		strlen(keyvalue, strlength);
		if (strlength >= 7)
		{
			memset(basicmdl, 0, 0, 20);
			str_getbasicmodel(basicmdl);
			strcmp(basicmdl, keyvalue, 7, mdlmatch);
			if (mdlmatch != 0)
			{
				str_getdsdrvparamname(BIN_FILENAME);			
				strlen(BIN_FILENAME, strlength);
				if (strlength < 11)
				{
					str_getdrvparamname(BIN_FILENAME);	// set default
				}
			}			
		}
		userfilelog(BIN_FILENAME);
	}
	strlen(BIN_FILENAME, strlength);
	if (strlength < 11)
	{
		poststatus("No Binnig Info");
		stoptest();
	}
	strcpy(filepath, "script/");
	strcat(filepath, BIN_FILENAME);

	/*
	str_getdrvparamname(filename);
	strlen(filename, strlength);
	if (strlength < 11)
	{
		poststatus("file length invalid");
		stoptest();
	}
	strcpy(filepath, "script/");
	strcat(filepath, filename);
	*/

	getkeystring(filepath, "DRIVE_GRADE", "DRVGRADE_HIGH", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find DRVGRADE_HIGH");
		return 2;
	}
	atof(keyvalue, BF_DRVGRADE_HIGH);
	
	getkeystring(filepath, "DRIVE_GRADE", "DRVGRADE_LOW", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find DRVGRADE_HIGH");
		return 2;
	}		
	atof(keyvalue, BF_DRVGRADE_LOW);

	getkeystring(filepath, appname, "TYPE", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find key");
		return 2;
	}
	strstr(keyvalue, "Upper Best Type", strcatflag);
	if (strcatflag != 0)
	{
		BV_TYPE = PARAM_TYPE_UPP;
	}
	strstr(keyvalue, "Lower Best Type", strcatflag);
	if (strcatflag != 0)
	{
		BV_TYPE = PARAM_TYPE_LOW;
	}
	strstr(keyvalue, "Mid Best Type", strcatflag);
	if (strcatflag != 0)
	{
		BV_TYPE = PARAM_TYPE_MID;
	}
	
	getkeystring(filepath, appname, "BASIS", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find key");
		return 2;
	}
	atof(keyvalue, BV_BASIS);
	
	BV_LCL2 = 0; BV_LCL1 = 0;
	BV_UCL2 = 0; BV_UCL1 = 0;
	
	getkeystring(filepath, appname, "LCL2", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength > 0)
		atof(keyvalue, BV_LCL2);

	getkeystring(filepath, appname, "LCL1", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength > 0)
		atof(keyvalue, BV_LCL1);
	
	getkeystring(filepath, appname, "UCL1", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength > 0)
		atof(keyvalue, BV_UCL1);
	
	getkeystring(filepath, appname, "UCL2", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength > 0)
		atof(keyvalue, BV_UCL2);
	
	getkeystring(filepath, appname, "Weight", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find key");
		return 2;
	}
	atoi(keyvalue, 0, 10, BV_WEIGHT);
	
	getkeystring(filepath, appname, "FORCED_C", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find key");
		return 2;
	}	
	atoi(keyvalue, 0, 10, BV_FORCED_C);
						
	getkeystring(filepath, appname, "PARAGRADE_A", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find key");
		return 2;
	}
	atoi(keyvalue, 0, 10, BV_PARAGRADE_A);
					
	getkeystring(filepath, appname, "PARAGRADE_B", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find key");
		return 2;
	}						
	atoi(keyvalue, 0, 10, BV_PARAGRADE_B);
	
	getkeystring(filepath, appname, "PARAGRADE_C", keyvalue);
	strlen(keyvalue, strlength);
	if (strlength <= 0)
	{
		poststatus("cannot find key");
		return 2;
	}										
	atoi(keyvalue, 0, 10, BV_PARAGRADE_C);
	
	//calc max point
	BF_MAXPOINT = BF_MAXPOINT + BV_PARAGRADE_A*BV_WEIGHT;
	
	if (DEBUG_ON != 0)
	{
		userfilelog("BINNING VARIABLES*****************************************");
		userfilelog(appname);
		userfilelog("**********************************************************");
		
		userfilelog("BF_DRVGRADE_HIGH"); logfvalue(BF_DRVGRADE_HIGH);
		userfilelog("BF_DRVGRADE_LOW"); logfvalue(BF_DRVGRADE_LOW);
		
		userfilelog("BV_TYPE"); logivalue(BV_TYPE);
		if (BV_TYPE == PARAM_TYPE_UPP) { userfilelog("Upper Best Type"); }
		if (BV_TYPE == PARAM_TYPE_LOW) { userfilelog("Lower Best Type"); }
		if (BV_TYPE == PARAM_TYPE_MID) { userfilelog("Mid   Best Type"); }
		
		userfilelog("BV_BASIS"); { sputf(buf, "%f", BV_BASIS); userfilelog(buf); }
		userfilelog("BV_LCL2");	{ sputf(buf, "%f", BV_LCL2); userfilelog(buf); }
		userfilelog("BV_LCL1");	{ sputf(buf, "%f", BV_LCL1); userfilelog(buf); }
		userfilelog("BV_UCL1");	{ sputf(buf, "%f", BV_UCL1); userfilelog(buf); }
		userfilelog("BV_UCL2");	{ sputf(buf, "%f", BV_UCL2); userfilelog(buf); }		
		
		userfilelog("BV_WEIGHT"); logivalue(BV_WEIGHT);
		userfilelog("BV_FORCED_C"); logivalue(BV_FORCED_C);
		userfilelog("BV_PARAGRADE_A"); logivalue(BV_PARAGRADE_A);
		userfilelog("BV_PARAGRADE_B"); logivalue(BV_PARAGRADE_B);
		userfilelog("BV_PARAGRADE_C"); logivalue(BV_PARAGRADE_C);
		
		userfilelog("BF_MAXPOINT"); logivalue(BF_MAXPOINT);
		userfilelog("***********************************************************");	
	}		

	return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Function : get mass header information
//
///////////////////////////////////////////////////////////////////////////////
int GetMassHeader()
{
	int ivalue;
	char pmphead[SECTOR_SIZE_BINNING];
	
	str_sendserialcmd("PP",2);
	delays(300);
	str_getmassdata(pmphead,0,2,ivalue);
	if(ivalue != SECTOR_SIZE_BINNING)
	{
		poststatus("Mass Header fail");
		stoptest();
		return 1;
	}

	memnmov(MH_MASS_PN,pmphead,0,0x10,20,0);		//get pn
	memnmov(MH_MASS_SERIES,pmphead,0,0x26,10,0);	//get series
	peek(pmphead,0x24,2,MH_NUMOF_HEAD);  			//get numer of head
	peek(pmphead,0x60,4,MH_START_OFFSET_DRV);   	//get start offset of DRV header
	
	peek(pmphead,0x84,2,MH_OFFSET_DRV_SET);   		
//	peek(pmphead,0x90,2,MH_OFFSET_DRV_SET_ZONE);   	
	peek(pmphead,0xB0,2,MH_OFFSET_DRV_SET_STEP);   	
	
	peek(pmphead,0xE4,2,MH_OFFSET_HD0);   			//get head 0 ~ 7
	peek(pmphead,0xF0,2,MH_OFFSET_HD0_RANGE);   	
	peek(pmphead,0x100,2,MH_OFFSET_HD0_STEP);   		
	peek(pmphead,0x110,2,MH_OFFSET_HD0_ZONE);   		

	peek(pmphead,0x144,2,MH_OFFSET_HD1);   			
	peek(pmphead,0x150,2,MH_OFFSET_HD1_RANGE);   	
	peek(pmphead,0x160,2,MH_OFFSET_HD1_STEP);   		
	peek(pmphead,0x170,2,MH_OFFSET_HD1_ZONE);   		
	
	peek(pmphead,0x1A4,2,MH_OFFSET_HD2);   			
	peek(pmphead,0x1B0,2,MH_OFFSET_HD2_RANGE);   	
	peek(pmphead,0x1C0,2,MH_OFFSET_HD2_STEP);   		
	peek(pmphead,0x1D0,2,MH_OFFSET_HD2_ZONE);   		
	
	peek(pmphead,0x204,2,MH_OFFSET_HD3);   			
	peek(pmphead,0x210,2,MH_OFFSET_HD3_RANGE);   	
	peek(pmphead,0x220,2,MH_OFFSET_HD3_STEP);   	
	peek(pmphead,0x230,2,MH_OFFSET_HD3_ZONE);   	
	
	peek(pmphead,0x264,2,MH_OFFSET_HD4);   			
	peek(pmphead,0x270,2,MH_OFFSET_HD4_RANGE);   	
	peek(pmphead,0x280,2,MH_OFFSET_HD4_STEP);   	
	peek(pmphead,0x290,2,MH_OFFSET_HD4_ZONE);   	
	
	peek(pmphead,0x2C4,2,MH_OFFSET_HD5);   			
	peek(pmphead,0x2D0,2,MH_OFFSET_HD5_RANGE);   	
	peek(pmphead,0x2E0,2,MH_OFFSET_HD5_STEP);   	
	peek(pmphead,0x2F0,2,MH_OFFSET_HD5_ZONE);   	
	
	peek(pmphead,0x324,2,MH_OFFSET_HD6);   			
	peek(pmphead,0x330,2,MH_OFFSET_HD6_RANGE);   	
	peek(pmphead,0x340,2,MH_OFFSET_HD6_STEP);   	
	peek(pmphead,0x350,2,MH_OFFSET_HD6_ZONE);   	
	
	peek(pmphead,0x384,2,MH_OFFSET_HD7);
	peek(pmphead,0x390,2,MH_OFFSET_HD7_RANGE);   	
	peek(pmphead,0x3A0,2,MH_OFFSET_HD7_STEP);   	
	peek(pmphead,0x3B0,2,MH_OFFSET_HD7_ZONE); 

	if (DEBUG_ON != 0)
	{
		userfilelog("-------------GET MASS HEADER-----------------------------");
		userfilelog(MH_MASS_PN);
		userfilelog(MH_MASS_SERIES);
		userfilelog("MH_NUMOF_HEAD");			logivalue(MH_NUMOF_HEAD);
		userfilelog("MH_START_OFFSET_DRV");		logivalue(MH_START_OFFSET_DRV);

		userfilelog("MH_OFFSET_DRV_SET");		logivalue(MH_OFFSET_DRV_SET);
		userfilelog("MH_OFFSET_DRV_SET_ZONE");	logivalue(MH_OFFSET_DRV_SET_ZONE);
		userfilelog("MH_OFFSET_DRV_SET_STEP");	logivalue(MH_OFFSET_DRV_SET_STEP);

		userfilelog("MH_OFFSET_HD0");			logivalue(MH_OFFSET_HD0);
		userfilelog("MH_OFFSET_HD0_RANGE");		logivalue(MH_OFFSET_HD0_RANGE);
		userfilelog("MH_OFFSET_HD0_STEP");		logivalue(MH_OFFSET_HD0_STEP);
		userfilelog("MH_OFFSET_HD0_ZONE");		logivalue(MH_OFFSET_HD0_ZONE);

		userfilelog("MH_OFFSET_HD1");			logivalue(MH_OFFSET_HD1);
		userfilelog("MH_OFFSET_HD1_RANGE");		logivalue(MH_OFFSET_HD1_RANGE);
		userfilelog("MH_OFFSET_HD1_STEP");		logivalue(MH_OFFSET_HD1_STEP);
		userfilelog("MH_OFFSET_HD1_ZONE");		logivalue(MH_OFFSET_HD1_ZONE);
		
		userfilelog("MH_OFFSET_HD2");			logivalue(MH_OFFSET_HD2);
		userfilelog("MH_OFFSET_HD2_RANGE");		logivalue(MH_OFFSET_HD2_RANGE);
		userfilelog("MH_OFFSET_HD2_STEP");		logivalue(MH_OFFSET_HD2_STEP);
		userfilelog("MH_OFFSET_HD2_ZONE");		logivalue(MH_OFFSET_HD2_ZONE);
		
		userfilelog("MH_OFFSET_HD3");			logivalue(MH_OFFSET_HD3);
		userfilelog("MH_OFFSET_HD3_RANGE");		logivalue(MH_OFFSET_HD3_RANGE);
		userfilelog("MH_OFFSET_HD3_STEP");		logivalue(MH_OFFSET_HD3_STEP);
		userfilelog("MH_OFFSET_HD3_ZONE");		logivalue(MH_OFFSET_HD3_ZONE);

		userfilelog("MH_OFFSET_HD4");			logivalue(MH_OFFSET_HD4);
		userfilelog("MH_OFFSET_HD4_RANGE");		logivalue(MH_OFFSET_HD4_RANGE);
		userfilelog("MH_OFFSET_HD4_STEP");		logivalue(MH_OFFSET_HD4_STEP);
		userfilelog("MH_OFFSET_HD4_ZONE");		logivalue(MH_OFFSET_HD4_ZONE);

		userfilelog("MH_OFFSET_HD5");			logivalue(MH_OFFSET_HD5);
		userfilelog("MH_OFFSET_HD5_RANGE");		logivalue(MH_OFFSET_HD5_RANGE);
		userfilelog("MH_OFFSET_HD5_STEP");		logivalue(MH_OFFSET_HD5_STEP);
		userfilelog("MH_OFFSET_HD5_ZONE");		logivalue(MH_OFFSET_HD5_ZONE);
		userfilelog("-------------END MASS HEADER-----------------------------");				
	}	
	
	return 0;  	
}
void logivalue(int ivalue)
{
	char buf[128];

	sputd(buf, "0x%X", ivalue);
	userfilelog(buf);
}
void logfvalue(float fvalue)
{
	char buf[128];

	sputf(buf, "%f", fvalue);
	userfilelog(buf);

}


//******** 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");
                        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;
}
void dummyerror()
{
	poststatus("DummyErr");
	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;
}
/*
//Error Log count check
void Errorcnt(int step)
{

    	Id_Retry();
   	str_getidfydata(0, 511, rdbuf);
   	   	
	nEc=(rdbuf[233]<<8) | rdbuf[232];
	if(nEc>nEc1)
	{
		if(nEc1==0)
		{
			estep=step*10;
		}
		nEc1=nEc;
		
		estep1=step;	
	}
	else
	{
		
	}
	delays(10);

  
  
}//End Error Log count check
*/

// Defect Free function
void Dfree()
{
    	int tled;
    	
    	Id_Retry();
   	str_getidfydata(0, 511, rdbuf);

	// Code Check 232,233
	if (rdbuf[232] == 0x00 && rdbuf[233] == 0x00  )
	{
		poststatus("No Error");
		nEc=0;
		delays(1);
		//goto FT_PASS;
	}
	else
	{
		nEc=1;
		str_setdrvgrade(CHAR_S, 1);  //fored S Grade 
		delays(2);
		
		//BI code D/L		
		if (flag_5400RPM == 0)
		{	
		poststatus("Inline D/F");
		poststatus("HTBI D/L");
	        dw(HTBICODE);
		}
		else
		{	
		poststatus("Inline D/F");
		poststatus("HTBI54 D/L");
    		dw(HTBI54);     
		}

	        poststatus("CHK BOOT HTBICODE");
		delays(30);
		str_checkprompt("BOOT>");
		delays(3);
		poststatus("poweroff BICode");
		power(0);
		delays(15);
		poststatus("Turn On");
		power(1);
		delays(80);
		Reset_Retry();	
		
		//Defect Free
		poststatus("Inline DF1");
		str_sendserialcmd("DF",2); 
                delays(800);
		str_checkprompt("ENG>");
		poststatus("Inline DF2");
		str_sendserialcmd("DF",2);
		delays(800);
		str_checkprompt("ENG>");
		
		// Main code D/L
		poststatus("SCRBIN D/L");
		if (flag_5400RPM == 0)
		{	
		 str_sendserialcmd("SD",2);  // 'SD' Command <- spin down before code D/L
		 delays(15);
		 poststatus("SCRBIN D/L");
		 dw(SCRBIN);
//		 strcpy(DWCODE,SCRBIN);DW_RTY();
		}
		else
		{	
		 str_sendserialcmd("SD",2);  // 'SD' Command <- spin down before code D/L
		 delays(15);
		 poststatus("SCRBIN54 D/L");
    		 dw(SCRBIN54);   
//    		 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();	
    }
}
void Check_LedSC()
{
    str_getinvalidled(INVALID_LED);
    if(INVALID_LED != 0x00 )
    {
        if (INVALID_LED == 0x1701 || INVALID_LED == 0x1702 || INVALID_LED == 0x1703 || INVALID_LED == 0x1102 )
        {
            delays(5);
            poststatus("N/R(COMBO)");
            stoptest();
        }
        else
        {
            delays(300);  
        	str_stoptestfail(1, INVALID_LED);
        }
    }
}    