REM file: Zsort.bas - Public Domain DOS Utility
REM Version 1.0a created 06/08/1995
REM Version 1.1a created 08/07/1995
REM Version 1.2a created 03/06/2001
REM Version 1.3a created 11/04/2005
REM Version 1.4a created 12/10/2005

' default integer variables
DEFINT A-Z
REM $DYNAMIC

' define boolean values
CONST True = -1
CONST False = NOT True
CONST TrueD = -1#
CONST FalseD = NOT TrueD
CONST NUL = ""

' define color values
CONST Black = 0
CONST Cyan = 11
CONST Green = 10
CONST Plain = 7
CONST Red = 12
CONST White = 15
CONST Yellow = 14

' declare include files
REM $INCLUDE: 'qbx.bi'

' declare functions
DECLARE FUNCTION ParseLine (S$)
DECLARE FUNCTION BreakIS()
DECLARE FUNCTION ClearBreak()
DECLARE FUNCTION KeyIS()

' declare registers
COMMON SHARED InregsX AS RegtypeX, OutregsX AS RegtypeX
COMMON SHARED InregsX2 AS RegTypeX, InregsX3 AS RegTypeX

' declare work variables
COMMON SHARED Reverse.Sort AS INTEGER, Sort.Column AS INTEGER
COMMON SHARED Lines.Counted AS INTEGER, Max.Lines AS INTEGER
COMMON SHARED Ignore.Case AS INTEGER, Continuous.Display AS INTEGER
COMMON SHARED Strip.Blanks AS INTEGER, Sort.Swaps AS SINGLE
COMMON SHARED Control.Break AS INTEGER, Last.Switch AS INTEGER
COMMON SHARED Windows.Detected AS INTEGER, Pipe.Buffer AS STRING * 1

' declare sort array
COMMON SHARED Sort.Array() AS STRING

' declare command line work variables
COMMON SHARED Command.Line AS STRING, Redirected.Input AS INTEGER

' declare external procedures
DECLARE SUB SetInt
DECLARE SUB RestInt

' backwards compatible for bc 7.1
REM $INCLUDE: 'bc7.inc'

' install new interrupt service routine
CALL SetInt

' declare standard error trap
ON ERROR GOTO Error.Routine

' redimension sort array
REDIM Sort.Array(1 TO 128) AS STRING

' reset count variables
Max.Lines = 128

' command line parser
FUNCTION ParseLine (X$)
 Imbedded = INSTR(Command.Line, LCASE$(X$))
 IF Imbedded THEN
    Command.Line = LEFT$(Command.Line, Imbedded - 1) + MID$(Command.Line, Imbedded + LEN(X$))
    Last.Switch = Imbedded - 1
    ParseLine = True
 ELSE
    Imbedded = INSTR(Command.Line, UCASE$(X$))
    IF Imbedded THEN
       Command.Line = LEFT$(Command.Line, Imbedded - 1) + MID$(Command.Line, Imbedded + LEN(X$))
       Last.Switch = Imbedded - 1
       ParseLine = True
    ELSE
       ParseLine = False
    END IF
 END IF
END FUNCTION 

' check windows
Windows.Detected = True
If Load.Windows = False Then
   InregsX.AX = &H160A
   CALL InterruptX(&H2F, InregsX, OutregsX)
   IF OutregsX.AX > 0 THEN
      InregsX.AX = &H4A33
      CALL InterruptX(&H2F, InregsX, OutregsX)
      IF OutregsX.AX = 0 THEN
         Windows.Detected = 0 ' DOS 7.00
      ELSE
         Windows.Detected = -2 ' XP
      END IF
   END IF
END IF
IF INSTR(COMMAND$, "/_") THEN
   Windows.Detected = True
END IF

' check command line
SELECT CASE COMMAND$
CASE "/?"
   GOTO Boot.Usage
END SELECT

' read command line from PSP
Command.line = NUL
InregsX.AX = &H6200
CALL InterruptX(&H21, InregsX, OutregsX)
PSPsegment = OutregsX.BX
PSPoffset = 128
DEF SEG = PSPsegment
FOR Count = 1 TO 127
   Command.Char = PEEK(PSPoffset + Count)
   SELECT CASE Command.Char
   CASE 0, 10, 13
      EXIT FOR
   CASE ELSE
      Command.line = Command.line + CHR$(Command.Char)
   END SELECT
NEXT
DEF SEG
IF Command.Line = NUL THEN
   Command.Line = ENVIRON$("ZSORT")
END IF
Command.Line = RTRIM$(Command.Line)

' check command line switches
Continuous.Display = ParseLine ("/C")
Ignore.Case = ParseLine ("/I")
Reverse.Sort = ParseLine ("/R")
Strip.Blanks = ParseLine ("/T")
Control.Break = ParseLine ("/~")
Var = ParseLine("/_")

' get sort column
Sort.Column = 1
Imbedded = INSTR(UCASE$(Command.Line), "/N")
IF Imbedded THEN
   Last.Switch = Imbedded - 1
   Imbedded2 = Imbedded + 2
   DO
      Switch$ = MID$(Command.Line, Imbedded2, 1)
      IF Switch$ >= "0" AND Switch$ <= "9" THEN
         Column$ = Column$ + Switch$
      ELSE
         EXIT DO
      END IF
      Imbedded2 = Imbedded2 + 1
   LOOP
   IF Column$ = Nul THEN
      GOTO Boot.Error
   END IF
   Sort.Column = INT(VAL(Column$))
   IF Sort.Column = False THEN
      GOTO Boot.Error
   END IF
   Command.Line = LEFT$(Command.Line, Imbedded - 1) + MID$(Command.Line, Imbedded2)
END IF
Command.Line = RTRIM$(Command.Line)

' recheck command line
IF INSTR(Command.Line, "/") THEN
   GOTO Boot.Error
END IF
Command.Line = RTRIM$(Command.Line)
IF Last.Switch THEN
   IF LEN(Command.Line) > Last.Switch THEN
      GOTO Boot.Error
   END IF
END IF

' check break flag override
IF Control.Break THEN
   Var = ClearBreak
END IF

' search through all redirected input
Lines.Counted = False
Redirected.Input = False

' check pipe length
InregsX.AX = &H4202 ' eof
InregsX.BX = 0 ' stdin
InregsX.CX = 0
InregsX.DX = 0
Call InterruptX(&H21, InregsX, OutregsX)
If OutregsX.AX = 0 Then
   DEF SEG = &H40
   X = PEEK(&H71)
   DEF SEG
   IF X = 64 THEN
      DEF SEG = &H40
      POKE &H71, 0
      DEF SEG
   END IF
Endif
If OutregsX.AX > 0 Then
   InregsX.AX = &H4200
   InregsX.BX = 0 ' stdin
   InregsX.CX = 0
   InregsX.DX = 0
   Call InterruptX(&H21, InregsX, OutregsX)
   DO
      ' check control break
      IF BreakIS THEN
         EXIT DO
      END IF

      ' read from device
      InregsX.AX = &H3F00
      InregsX.BX = 0 ' stdin
      InregsX.CX = 1 ' char
      InregsX.DS = VARSEG(Pipe.Buffer)
      InregsX.DX = VARPTR(Pipe.Buffer)
      Call InterruptX(&H21, InregsX, OutregsX)
      If (OutregsX.Flags AND &H1) = &H1 Then
         Exit Do
      Endif
      If (OutregsX.Flags AND &H1) = &H0 Then
         If OutregsX.AX = 0 Then
            Exit Do
         Endif

         ' store input flag
         Redirected.Input = True

         ' store character
         Char$ = Pipe.Buffer

         ' check character
         SELECT CASE ASC(Char$)
         CASE 13
         CASE 10
            Flag = True
            IF Strip.Blanks THEN
               IF Line1$ = NUL THEN
                  Flag = False
               END IF
            END IF
            IF Flag THEN
               Lines.Counted = Lines.Counted + 1
               IF Lines.Counted > Max.Lines THEN
                  Max.Lines = Max.Lines + 16
                  REDIM PRESERVE Sort.Array(1 TO Max.Lines) AS STRING
               END IF
               Sort.Array(Lines.Counted) = Line1$
            END IF
            Line1$ = NUL
         CASE ELSE
            Line1$ = Line1$ + Char$
         END SELECT
      END IF
   LOOP
END IF

' check control break
IF BreakIS THEN
   GOTO End.Zsort
END IF

' check filename
IF Redirected.Input = False THEN
   CALL RestInt ' restore Control-Break
   X$ = Inkey$ ' quits here
   CALL SetInt ' reset Control-Break
   IF X$ = CHR$(0) + CHR$(0) THEN
      GOTO End.Zsort
   END IF
END IF

' shell sort
Sort.Swaps = False
Num = Lines.Counted
Span = INT(Num / 2)
DO WHILE Span > False
   IF BreakIS THEN
      EXIT DO
   END IF
   FOR Start = Span TO Num - 1
      FOR Element = (Start - Span + 1) TO 1 STEP -Span
         Sort.Column1$ = MID$(Sort.Array(Element), Sort.Column)
         Sort.Column2$ = MID$(Sort.Array(Element + Span), Sort.Column)
	 IF Ignore.Case THEN
	    Sort.Column1$ = UCASE$(Sort.Column1$)
	    Sort.Column2$ = UCASE$(Sort.Column2$)
	 END IF
	 IF Reverse.Sort THEN
	    IF Sort.Column2$ <= Sort.Column1$ THEN
	       EXIT FOR
	    END IF
	 ELSE
	    IF Sort.Column1$ <= Sort.Column2$ THEN
	       EXIT FOR
	    END IF
	 END IF
         SWAP Sort.Array(Element), Sort.Array(Element + Span)
	 Sort.Swaps = Sort.Swaps + 1
      NEXT
   NEXT
   Span = INT(Span / 2)
LOOP

' check break
IF BreakIS THEN
   GOTO End.Zsort
END IF

' output array
COLOR Yellow, Black
FOR Array.Line = 1 TO Lines.Counted
   PRINT Sort.Array(Array.Line)
NEXT

End.Zsort:

' display counters
IF Continuous.Display = False THEN
   COLOR Yellow, Black
   PRINT "Lines counted"; Lines.Counted
   PRINT "Sort swaps made"; Sort.Swaps
   Prompt$ = "Press <enter> to exit to DOS:"
   CALL MorePrompt(Prompt$, CHR$(13), Outpt$)
END IF

' restore key trapping
CALL RestInt
COLOR Plain, Black
END

Boot.Usage:
 ' restore key trapping
 CALL RestInt
 Var$=Inkey$
 ' make header
 COLOR White, Black
 PRINT "Zsort v1.4a: Pipe sort utility; "
 COLOR Yellow, Black
 PRINT "Usage:"
 PRINT "   Zsort [/cinrt]"
 PRINT "Where:"
 PRINT "   /c  continuous list"
 PRINT "   /i  ignore case"
 PRINT "   /n###  sort at column"
 PRINT "   /r  reverse order"
 PRINT "   /t  strip blank lines"
 COLOR Plain, Black
 END

Boot.Error:
 CALL RestInt
 Var$=Inkey$
 COLOR White, Black
 PRINT "Command line error. Type Zsort /? for help."
 COLOR Plain, Black
 END

' critical error trap
Error.Routine:
 Data.Error = ERR
 SELECT CASE Data.Error
 CASE 9
    PRINT "Subscript out of range."
    END
 CASE 14
    PRINT "Out of string space."
    END
 CASE 53
    Temp.Outpt$ = "File not found."
 CASE 61
    Temp.Outpt$ = "Disk full."
 CASE 70
    Temp.Outpt$ = "Permission denied."
 CASE 71
    Temp.Outpt$ = "Disk not ready."
 CASE ELSE
    Temp.Outpt$ = "Untrapped error" + STR$(Data.Error) + "."
 END SELECT
 COLOR White, Black
 PRINT Temp.Outpt$
 Prompt$ = "Press R to retry, Q to quit, C to continue:"
 CALL MorePrompt(Prompt$, "rqc", Outpt$)
 IF BreakIS THEN
    Outpt$ = "q"
 END IF
 SELECT CASE Outpt$
 CASE "r"
    RESUME
 CASE "q"
    Error.Level = True
    RESUME End.Zsort
 CASE "c"
    OutregsX.Flags = &H1
    RESUME NEXT
 END SELECT
 COLOR Plain, Black
 ' restore key trapping
 CALL RestInt
 END 0

SUB MorePrompt (Input.String$, Input.Mask$, Output.String$)
 COLOR White, Black
 PRINT Input.String$ + " ";
 Input.Char$ = NUL
 DO
    LOCATE , , 1
    InregsX2 = InregsX
    DO
       IF BreakIS THEN
          EXIT DO
       END IF
       IF KeyIS THEN
          IF OutregsX.AX <> 0 THEN
             InregsX.AX = &H0000
             CALL InterruptX(&H16, InregsX, OutregsX)
             Input.Char$=CHR$(OutregsX.AX AND &HFF)
             EXIT DO
          END IF
       END IF
    LOOP
    InregsX = InregsX2
    IF BreakIS THEN
       EXIT DO
    END IF
    IF LEN(Input.Char$) THEN
       Input.Char$ = LCASE$(Input.Char$)
       IF INSTR(Input.Mask$, Input.Char$) THEN
	  PRINT Input.Char$
	  Output.String$ = Input.Char$
	  EXIT DO
       END IF
    END IF
 LOOP
END SUB

' clears Control-Break flag
FUNCTION ClearBreak
 DEF SEG = &H40
 POKE &H71, &H0
 DEF SEG
 ClearBreak = True
END FUNCTION

' checks Control-Break
FUNCTION BreakIS
 STATIC Var AS INTEGER
 IF Redirected.Input THEN
    DEF SEG = &H40
    X = PEEK(&H71)
    DEF SEG
    IF X = 64 THEN
       Var = True
    END IF
 END IF
 IF KeyIS THEN
    IF OutregsX.AX = 0 THEN
       Var = True
       DEF SEG = &H40
       POKE &H71, 64
       DEF SEG
    END IF
 END IF
 IF Var THEN
    Continuous.Display = True
 END IF
 BreakIS = Var
END FUNCTION

' checks keyboard buffer
FUNCTION KeyIS
 InregsX3 = InregsX
 InregsX.AX = &H0100
 CALL InterruptX(&H16, InregsX, OutregsX)
 InregsX = InregsX3
 IF (OutregsX.Flags AND &H40) = &H40 THEN
    KeyIS = False
 ELSE
    KeyIS = True
 END IF
END FUNCTION
