// [2008-04-11]
// This utility is written by Chen Jun(chenjun@mail.nlscan) in order that some files
// on PT-850 can be copied up to PC in case uService fails to work(e.g. when uService
// fails to list the files on PT-850).

#include <windows.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <RAPI.h> // !End user: change this to <RAPI.h> please.

int main(int argc, char *argv[])
{

	if(argc!=4)
	{
		printf("Usage:   NLScopyfile <COM> <baudrate> <filename-on-device>\n");
		printf("Example: NLScopyfile 1 115200 SysConf.ini\n");
		return 1;
	}

	int ComPort = atoi(argv[1]);
	int Baudrate = atoi(argv[2]);

	printf("NLS_RapiInit(%d,%d)...\n", ComPort, Baudrate);
	int isSuccess = NLS_RapiInit(ComPort, Baudrate, false);
	if(!isSuccess)
	{
		printf("Fail!\n");
		return 2;
	}

/*
 
BOOL NLS_CopyFileEx (     
	LPCSTR  lpExistingFileName,      
	LPCSTR  lpNewFileName,      
	LPTHREAD_START_ROUTINE  lpProgressRoutine,      
	LPVOID  lpData,      
	LPBOOL  pbCancel,      
	DWORD  dwCopyFlags  );
*/
	char *filename = argv[3];
	char szfnNls[255];
	sprintf(szfnNls, "NLS:\\%s", filename);
	
	printf("Copying %s from device to PC...\n", filename);
	int pct = 0;
	BOOL isCancel = 0;
	BOOL b = NLS_CopyFileEx(szfnNls, filename, NULL, (void*)&pct, &isCancel, 0);
		// This returns immediately.

	// Now check `pct' to know whether the copy progress is done.

	for(;pct<100;)
	{
		printf("\rDone %d%%", pct);
		Sleep(500);
	}

	if(pct==100)
	{
		printf("\nSuccess.\n");
		return 0;
	}

	if(pct>100)
	{
		printf("\nNLS_CopyFileEx fail, errcode=%d\n", pct);
		return 3;
	}

	return 0;
}
