; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "BSD 2-clause" license."          |
;|_______________________________________________________________________________________|
;
;  Description: SimpleDebug library.
;
;  Target OS: Win32
;
;  Dependencies: Not dependent on other libraries.
;
;  Notes:
;_________________________________________________________________________________________

DBG_CHAR_NEWLINE equ $0d, $0a

uglobal
  if used debug_con_handle
    debug_con_handle dd ?
  end if
endg


iglobal
  if used cConsoleTitle
    cConsoleTitle du 'Fresh simple debug console.', 0
  end if
endg


if (defined options.DebugMode & options.DebugMode) | used Output
initialize InitDebugConsole
begin
        invoke  AllocConsole
        invoke  GetStdHandle, STD_ERROR_HANDLE
        mov     [debug_con_handle], eax
        invoke  SetConsoleTitleW, cConsoleTitle
        return
endp
end if


if (defined options.DebugMode & options.DebugMode)

finalize FinishDebugConsole
.string rb 10
begin
        invoke  WriteFile, [STDERR], ___CloseMsg, ___CloseMsg.length, 0, 0
        lea     eax, [.string]
        invoke  ReadFile, [STDIN], eax, 1, 0, 0
        return
endp

___CloseMsg text "Press ENTER to close."

end if


maxConsoleWrite = 1024

proc Output, .ptrStr
.dummy dd ?
begin
        pushad

        stdcall __simpStrLength, [.ptrStr]
        mov     ebx, ecx

.loop:
        mov     ecx, ebx
        cmp     ecx, maxConsoleWrite
        jb      @f
        mov     ecx, maxConsoleWrite
@@:
        sub     ebx, ecx

        push    ecx
        lea     eax, [.dummy]
        invoke  WriteConsoleA, [debug_con_handle], [.ptrStr], ecx, eax, 0
        pop     ecx
        add     [.ptrStr], ecx

        test    ebx, ebx
        jnz     .loop

.finish:
        popad
        return
endp



proc GetTimestamp
begin
        pushad
        invoke  GetTickCount
        mov     [esp+4*regEAX], eax
        popad
        return
endp

uglobal
if used GetFineTimestamp
  __FPerfCnt dd ?
end if
endg

if used GetFineTimestamp
initialize InitPerformanceCounter
.freq rd 2
begin
        pushad
        lea     eax, [.freq]
        invoke  QueryPerformanceFrequency, eax
        mov     eax, [.freq]
        mov     [__FPerfCnt], eax
        popad
        return
endp
end if


; returns dword timestamp in uS

proc GetFineTimestamp
.time dq ?
begin
        push    ecx edx

        lea     eax, [.time]
        invoke  QueryPerformanceCounter, eax

        mov     eax, dword [.time]
        xor     edx, edx
        mov     ecx, 1000000
        mul     ecx
        div     dword [__FPerfCnt]

        pop     edx ecx
        return
endp


