' My solution to https://rosettacode.org/wiki/Take_notes_on_the_command_line#uBasic.2F4tH
' Copyright J.L. Bezemer 2022

If Cmd (0) > 1 Then                    ' if there are commandline arguments
  If Set (a, Open ("notes.txt", "a")) < 0 Then
    Print "Cannot write \qnotes.txt\q" ' open the file in "append" mode
    End                                ' on error, issue message and exit
  EndIf
                                       ' write the date and time
  Write a, Show (FUNC(_DateStr (Time ())));" ";Show (FUNC(_TimeStr (Time ())))

  Write a, "\t";                       ' prepend with a tab
  For i = 2 To Cmd (0) - 1             ' now write all commandline arguments
    Write a, Show (Cmd (i)); " ";      ' with the exception of the last one
  Next

  Write a, Show (Cmd (Cmd (0)))        ' write the last argument
Else                                   ' if no commandline arguments are given
  If Set (a, Open ("notes.txt", "r")) < 0 Then
    Print "Cannot read \qnotes.txt\q"  ' open the file in "read" mode
    End                                ' on error, issue message and exit
  EndIf

  Do While Read (a)                    ' read until EOF
    Print Show (Tok (0))               ' show the entire line
  Loop                                 ' and repeat..
EndIf

Close a                                ' finally, close the file
End

_DateStr                               ' convert epoch to date string
  Param (1)
  Local (6)

  a@ = a@ / 86400                      ' just get the number of days since epoch
  b@ = 1970+(a@/365)                   ' ball parking year, will not be accurate!

  d@ = 0
  For c@ = 1972 To b@ - 1 Step 4
    If (((c@%4) = 0) * ((c@%100) # 0)) + ((c@%400) = 0) Then d@ = d@+1
  Next

  b@ = 1970+((a@ - d@)/365)            ' calculating accurate current year by (x - extra leap days)
  e@ = ((a@ - d@)%365)+1               ' if current year is leap, set indicator to 1
  f@ = (((b@%4) = 0) * ((b@%100) # 0)) + ((b@%400) = 0)

  g@ = 0                               ' calculating current month
  For c@ = 0 To 11 Until e@ < (g@+1)
    g@ = g@ + FUNC(_Monthdays (c@, f@))
  Next
                                       ' calculating current date
  g@ = g@ - FUNC(_Monthdays (c@-1, f@))
                                       ' Print a@, d@, e@, f@
Return (Join (Str(b@), FUNC(_Format (c@, Dup("-"))), FUNC(_Format (e@ - g@, Dup("-")))))

_TimeStr                               ' convert epoch to time string
  Param (1)
Return (Join(Str((a@%86400)/3600), FUNC(_Format ((a@%3600)/60, Dup(":"))), FUNC(_Format (a@%60, Dup(":")))))

_Format    Param (2) : Return (Join (Iif (a@<10, Join(b@, "0"), b@), Str (a@)))
_Monthdays Param (2) : Return (((a@ + (a@<7)) % 2) + 30 - ((2 - b@) * (a@=1)))

