#### RemiAudio
#### Copyright (C) 2022-2024 Remilia Scarlet <remilia@posteo.jp>
####
#### This program is free software: you can redistribute it and/or modify it
#### under the terms of the GNU Affero General Public License as published by
#### the Free Software Foundation, either version 3 of the License, or (at your
#### option) any later version.
####
#### This program is distributed in the hope that it will be useful, but WITHOUT
#### ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#### FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
#### License for more details.
####
#### You should have received a copy of the GNU Affero General Public License
#### along with this program.  If not, see <https://www.gnu.org/licenses/>.
require "./common"

module RemiAudio
  # A virtual representation of a
  # [CUE sheet](https://en.wikipedia.org/wiki/Cue_sheet_%28computing%29").
  #
  # Example that lists the files/tracks of a CUE sheet, then saves the CUE sheet
  # to a new file.
  #
  # ```
  # require "remiaudio/cue"
  #
  # cue = RemiAudio::Cue.load("/path/to/file.cue")
  # cue.files.each do |file|
  #   puts "File: #{file.filename}"
  #   file.tracks.each do |track|
  #     if title = track.title
  #       puts "  #{title}"
  #     else
  #       puts "  Unnamed track, number #{track.trackNumber}"
  #     end
  #   end
  # end
  #
  # # Write the CUE to a new file
  # File.open("/path/to/newcue.cue", "w") do |file|
  #   cue.write(file)
  # end
  # ```
  #
  # Documentation for the CUE sheet format can be found at these sources:
  #
  # * [https://web.archive.org/web/20070614044112/http://www.goldenhawk.com/download/cdrwin.pdf]()
  # * [https://wiki.hydrogenaud.io/index.php?title=Cue_sheet]()
  # * [https://github.com/libyal/libodraw/blob/main/documentation/CUE%20sheet%20format.asciidoc]()
  class Cue
    class Error < RemiAudioError
    end

    #===========================================================================

    private ARGS_REGEX = /("[^"]+")|(\S+)/

    private enum NextState
      Normal
      File
      Track
      Catalog
      CdTextFile
    end

    # :nodoc:
    private class Parser
      property line : Int64 = 1
      property column : Int64 = 0
      property io : IO
      property? strict : Bool = false
      property? foundTrack : Bool = false

      def initialize(@io : IO)
      end

      # Advances `#column` by *count*.
      @[AlwaysInline]
      def adv(count : Int32 = 1) : Nil
        @column += count
      end

      # Advances `#line` by 1, and sets `#column` to 0.
      @[AlwaysInline]
      def advLine : Nil
        @column = 0
        @line += 1
      end

      # Splits "str" in a way similar to a shell (that is, quoted items are
      # considered a single string).
      def splitArgs(str : String, dontRemoveQuotes : Bool = false) : Array(String)
        strs = str.split(ARGS_REGEX).reject(&.strip.empty?)
        if dontRemoveQuotes
          strs
        else
          strs.map! do |string|
            if string[0] == '"' && string[-1] == '"'
              string[1..-2]
            else
              string
            end
          end
        end
      end

      # Reads and discards characters until a non-whitespace character is
      # detected.
      @[AlwaysInline]
      def skipWhitespace : Nil
        c : Char? = nil
        while c = @io.peekChar
          if c.whitespace?
            @io.read_char
            adv
          else
            break
          end
        end
      end

      # Reads the next token and returns it, or returns `nil` if there are no
      # more tokens to read.
      def readToken : String?
        skipWhitespace
        return nil if @io.peekChar.nil?

        String.build do |str|
          isQuoted : Bool = @io.peekChar == '"'
          @io.read_char if isQuoted

          c : Char? = nil
          while c = @io.read_char
            case c
            when '\r'
              if @io.peekChar == '\n'
                @io.read_char
                advLine
              else
                raise ParseError.new("\\r without \\n", self)
              end

              earlyOut : String = str.to_s
              return (earlyOut.empty? ? nil : earlyOut)

            when ' ', '\n'
              if isQuoted
                if c == '\n'
                  raise ParseError.new("Quoted string does not end", self)
                else
                  str << c
                end
              else
                advLine if c == '\n'
                break
              end

            when '"'
              unless isQuoted
                raise ParseError.new("Bad quoted string (field did not start with a quote)", self)
              end

              nextC = @io.peekChar
              unless nextC.nil? || nextC == ' ' || nextC == '\n'
                raise ParseError.new("Bad quoted string: quote is not followed by a space or newline", self)
              end

              adv
              isQuoted = false

            else
              str << c
              adv
            end
          end
        end
      end

      # Reads the rest of the current line and returns it, or returns `nil` if
      # there is nothing left to read.
      def readRemainingLine(removeQuotes : Bool = false) : String?
        c : Char? = nil

        skipWhitespace
        return nil if @io.peekChar.nil?
        ret : String? = @io.gets
        unless ret.nil?
          ret = ret.strip
          if removeQuotes && ret[0] == '"' && ret[-1] == '"'
            return ret[1..-2]
          end
        end

        ret
      end

      # Reads the rest of the current line and discards it, then returns.
      def skipToEof : Nil
        unless @column == 1
          c : Char? = nil
          loop do
            c = @io.read_char
            break if c.nil?  || c == '\n'
          end
          advLine
        end
      end
    end

    #===========================================================================

    # Represents an error condition that occured while parsing a CUE sheet.
    class ParseError < Error
      # The line near where the error occurred, or `-1` if it can't be determined.
      getter line : Int64 = -1

      # The column near where the error occurred, or `-1` if it can't be determined.
      getter column : Int64 = -1

      # Creates a new `ParseError` instance, taking line and column information
      # from *parser*.
      def initialize(msg : String, parser : Parser, causedBy : Exception? = nil)
        @line = parser.line
        @column = parser.column
        @message = msg
        @cause = causedBy
      end

      def to_s(io : IO) : Nil
        ln = @line >= 0 ? @line : "??"
        col = @column >= 0 ? @column : "??"
        io << "CUE parsing error near line #{ln} column #{col}: " << message
        io << " (" << self.class << ")\n"
      end

      def inspect_with_backtrace(io : IO) : Nil
        to_s(io)
        io << " (" << self.class << ")\n"

        backtrace?.try &.each do |frame|
          io.print "  from "
          io.puts frame
        end

        if cause = @cause
          io << "Caused by: "
          cause.inspect_with_backtrace(io)
        end

        io.flush
      end
    end

    #===========================================================================

    # Represents a moment or length in time in a CUE sheet.
    class Timestamp
      # The minute value.
      getter minutes : UInt32 = 0

      # The second value.
      getter seconds : UInt32 = 0

      # The number of CD frames.
      getter frames : UInt32 = 0

      # Creates a new `Timestamp`.
      def initialize
      end

      # Creates a new `Timestamp` with the given values.
      def initialize(@minutes : UInt32, @seconds : UInt32, @frames : UInt32)
      end

      def self.fromBytePos(value : Int) : Timestamp
        raise ArgumentError.new("Value cannot be negative") if value < 0
        return Timestamp.new if value == 0

        smp = value / 4
        total = smp / 44100
        frames = (total - total.to_i32!) * 75
        seconds = total.to_i32!
        minutes = seconds.tdiv(60)
        seconds = seconds - (minutes * 60)
        Timestamp.new(minutes.to_u32!, seconds.to_u32!, frames.to_u32!)
      end

      def minutes=(value : UInt32) : Nil
        raise ::ArgumentError.new("Invalid minutes value, must be between 0 and 99, inclusive.") if value > 99
        @minutes = value
      end

      def seconds=(value : UInt32) : Nil
        raise ::ArgumentError.new("Invalid seconds value, must be between 0 and 59, inclusive.") if value > 59
        @seconds = value
      end

      def frames=(value : UInt32) : Nil
        raise ::ArgumentError.new("Invalid frames value, must be between 0 and 74, inclusive.") if value > 74
        @frames = value
      end

      # :nodoc:
      def self.parse(parser : Parser)
        startingAt : Int64 = parser.column
        token : String? = parser.readToken

        raise ParseError.new("Could not read timestamp", parser) if token.nil?
        raise ParseError.new("Timestamp is malformed", parser) unless token.size >= 8
        raise ParseError.new("Malformed timestamp", parser) unless token[2] == ':' && token[5] == ':'

        mm = token[0...2].to_u32? || raise ParseError.new("Bad minute value in timestamp", parser)
        ss = token[3...5].to_u32? || raise ParseError.new("Bad second value in timestamp", parser)
        ff = token[6..].to_u32? || raise ParseError.new("Bad frame value in timestamp", parser)
        unless ff < 75
          raise ParseError.new("Bad timestamp: frame value must be between 0 and 74, inclusive", parser)
        end
        Timestamp.new(mm, ss, ff)
      end

      def to_s(io : IO) : Nil
        io << sprintf("%02d:%02d:%02d", @minutes, @seconds, @frames)
      end

      # Convert this timestamp to a sample number.  This always assumes CD audio
      # (44100 Hz 16-bit, 2 channels).
      def toSampleNum : Int32
        (((self.minutes.to_u64 * 60) + self.seconds + (self.frames / 75)) * 44100).to_i32
      end

      # Convert this timestamp to a byte position.  This always assumes CD audio
      # (44100 Hz 16-bit, 2 channels).
      def toBytePos : Int32
        toSampleNum * 4
      end

      def nanoseconds : Int64
        totalNs : Int64 = (self.minutes.to_i64! * 60) + self.seconds
        totalNs *= 1000000000_i64
        totalNs + ((self.frames / 75) * 1e+9).to_i64
      end

      def -(other : Timestamp) : Time::Span
        Time::Span.new(nanoseconds: self.nanoseconds - other.nanoseconds)
      end
    end

    #===========================================================================

    # A virtual representation of the data for a `TRACK` command within a CUE
    # sheet.  This is a single track for a CD.
    class Track
      # The type of `Track`.
      enum Type
        # Audio track
        Audio

        # CD+G track
        Cdg

        # Cooked CD-ROM Mode 1 data (sector size: 2048)
        Mode1_2048

        # Raw CD-ROM Mode 1 data (sector size: 2352)
        Mode1_2352

        # CD-ROM Mode 2 XA form-1 data (sector size: 2048)
        Mode2_2048

        # CD-ROM Mode 2 XA form-2 data (sector size: 2324)
        Mode2_2324

        # CD-ROM Mode 2 data (sector size: 2336)
        Mode2_2336

        # CD-ROM Mode 2 data (sector size: 2352)
        Mode2_2352

        # CDI Mode 2 data (sector size: 2336)
        Cdi_2336

        # CDI Mode 2 data (sector size: 2352)
        Cdi_2352

        # Similar to `::Enum.parse?`, except that this expects the strings to
        # match those in a CUE file (e.g. `"MODE1/2048"`), and is case
        # insensitive.
        def self.parse?(string : String) : self?
          case string.upcase
          when "AUDIO" then Type::Audio
          when "CDG" then Type::Cdg
          when "MODE1/2048" then Type::Mode1_2048
          when "MODE1/2352" then Type::Mode1_2352
          when "MODE2/2048" then Type::Mode2_2048
          when "MODE2/2324" then Type::Mode2_2324
          when "MODE2/2336" then Type::Mode2_2336
          when "MODE2/2352" then Type::Mode2_2352
          when "CDI/2336" then Type::Cdi_2336
          when "CDI/2352" then Type::Cdi_2352
          else nil
          end
        end

        # Similar to `::Enum#to_s`, except that the returned values are usable in
        # a CUE file.
        def to_s : String
          case self
          in .audio? then "AUDIO"
          in .cdg? then "CDG"
          in .mode1_2048? then "MODE1/2048"
          in .mode1_2352? then "MODE1/2352"
          in .mode2_2048? then "MODE2/2048"
          in .mode2_2324? then "MODE2/2324"
          in .mode2_2336? then "MODE2/2336"
          in .mode2_2352? then "MODE2/2352"
          in .cdi_2336? then "CDI/2336"
          in .cdi_2352? then "CDI/2352"
          end
        end

        # Similar to `::Enum.names`, except that the returned values match those
        # generated with `#to_s`.
        def self.names : Array(String)
          [
            "AUDIO",
            "CDG",
            "MODE1/2048",
            "MODE1/2352",
            "MODE2/2048",
            "MODE2/2324",
            "MODE2/2336",
            "MODE2/2352",
            "CDI/2336",
            "CDI/2352"
          ]
        end
      end

      # A set of `FLAGS` for a `Track` instance.
      @[Flags]
      enum Flags
        # Digital copy permitted
        DigitalCopyPermitted

        # 4-channel audio
        FourChannel

        # Pre-emphasis enabled (for audio tracks only)
        PreEmphasis

        # Serial copy management system
        Scms

        # Similar to `::Enum.parse?`, except that this expects the strings to
        # match those in a CUE file (e.g. `"DCP"`, `"4CH"`, etc.), and is case
        # insensitive.
        def self.parse?(string : String) : self?
          case string.upcase
          when "DCP" then Flags::DigitalCopyPermitted
          when "4CH" then Flags::FourChannel
          when "PRE" then Flags::PreEmphasis
          when "SCMS" then Flags::Scms
          else nil
          end
        end

        # Similar to `::Enum#to_s`, except that the returned values are usable in
        # a CUE file.
        def to_s : String
          case self
          in .digital_copy_permitted? then "DCP"
          in .four_channel? then "4CH"
          in .pre_emphasis? then "PRE"
          in .scms? then "SCMS"
          end
        end

        # Similar to `::Enum.names`, except that the returned values match those
        # generated with `#to_s`.
        def self.names : Array(String)
          [
            "DCP",
            "4CH",
            "PRE",
            "SCMS"
          ]
        end
      end

      # The expected length of the
      # [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)
      # field, in bytes.
      ISRC_LEN = 12

      # The maximum length of the TITLE field, in bytes.
      MAX_TITLE_LEN = 80

      # The minimum length of the TITLE field, in bytes.
      MIN_TITLE_LEN = 1

      # The maximum length of the PERFORMER field, in bytes.
      MAX_PERFORMER_LEN = 80

      # The minimum length of the PERFORMER field, in bytes.
      MIN_PERFORMER_LEN = 1

      # The maximum length of the SONGWRITER field, in bytes.
      MAX_SONGWRITER_LEN = 80

      # The minimum length of the SONGWRITER field, in bytes.
      MIN_SONGWRITER_LEN = 1

      # The track number for this track.
      getter trackNumber : UInt32 = 1

      # The `Type` of this track.
      property type : Type = Type::Audio

      # The `Flags` for this track.
      property flags : Flags = Flags::None

      # The [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)
      # for this track.
      #
      # For format information, see
      # [here](https://github.com/libyal/libodraw/blob/main/documentation/CUE%20sheet%20format.asciidoc#57-isrc).
      getter isrc : String?

      # The length of the gap before this track, if any.
      property pregap : Timestamp?

      # The length of the gap after this track, if any.
      property postgap : Timestamp?

      # The title of this track.
      getter title : String?

      # The name of the performer of this track.
      getter performer : String?

      # The name of the songwriter of this track.
      getter songwriter : String?

      # The INDEX fields.
      @indices : Hash(UInt32, Timestamp) = {} of UInt32 => Timestamp

      # Creates a new `Track` instance.
      def initialize
      end

      # :nodoc:
      def self.parse(parser : Parser) : Tuple(Track, NextState)
        ret = Track.new

        if tn = parser.readToken
          trackNum = tn.to_u32? || raise ParseError.new("Bad track number", parser)
          if trackNum == 0 || trackNum > 99
            raise ParseError.new("Invalid track number, must be between 1 and 99, inclusive", parser)
          end
          ret.trackNumber = trackNum
        else
          raise ParseError.new("Bad TRACK command", parser)
        end

        if newType = parser.readToken
          ret.type = Type.parse?(newType) || raise ParseError.new("Bad TRACK type", parser)
        else
          raise ParseError.new("TRACK command is missing its type", parser)
        end

        token : String? = nil
        line : String? = nil
        afterTrack : Bool = false
        afterIndex : Bool = false
        lastIndex : Int64 = -1

        while token = parser.readToken
          case token
          when "REM" then parser.skipToEof
          when "CATALOG" then return {ret, NextState::Catalog}
          when "CDTEXTFILE" then return {ret, NextState::CdTextFile}
          when "FILE" then return {ret, NextState::File}
          when "TRACK" then return {ret, NextState::Track}

          when "PREGAP"
            if afterIndex
              raise ParseError.new("PREGAP command must come after a TRACK command and before INDEX commands",
                                   parser)
            end
            ret.pregap = Timestamp.parse(parser)

          when "POSTGAP"
            if afterIndex
              raise ParseError.new("POSTGAP command must come after a TRACK command and before INDEX commands",
                                   parser)
            end
            ret.postgap = Timestamp.parse(parser)

          when "FLAGS"
            if afterIndex
              raise ParseError.new("FLAGS command must come after a TRACK command and before INDEX commands",
                                   parser)
            end

            line = parser.readRemainingLine
            if line
              flagLine : String = line.strip.upcase
              flags = flagLine.split(' ', remove_empty: true)
              if flags.empty?
                raise ParseError.new("FLAGS is missing its flags", parser)
              else
                flags.each do |flag|
                  if flg = Flags.parse?(flag)
                    ret.flags |= flg
                  elsif parser.strict?
                    raise ParseError.new("Unrecognized FLAG: #{flag}", parser)
                  end
                end
              end
            else
              raise ParseError.new("FLAGS line is blank", parser)
            end

          when "ISRC"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize == ISRC_LEN
                if line[0..5].chars.all?(&.ascii_alphanumeric?) && line[6..].chars.all?(&.ascii_number?)
                  ret.isrc = line
                else
                  raise ParseError.new("ISRC is malformed", parser)
                end
              else
                raise ParseError.new("ISRC is not #{ISRC_LEN} bytes long", parser)
              end
            else
              raise ParseError.new("ISRC line is blank", parser)
            end

          when "INDEX"
            token = parser.readToken || raise ParseError.new("Malformed INDEX line", parser)
            num : UInt32 = token.to_u32? || raise ParseError.new("Bad INDEX number", parser)
            timestamp = Timestamp.parse(parser)

            # Check the value.
            if num > 99
              raise ParseError.new("Bad INDEX number, must be between 0 and 99, inclusive", parser)
            elsif ret.index?(num)
              raise ParseError.new("Duplicate INDEX number: #{num}", parser)
            elsif num <= lastIndex
              if num == 0 && lastIndex == -1
                lastIndex = 0
              elsif num == 1 && lastIndex == -1
                lastIndex = 1
              elsif num != lastIndex + 1
                raise ParseError.new("INDEX numbers must be sequential", parser)
              end
            end

            # Store
            ret.setIndex(num, timestamp)
            afterIndex = true
            lastIndex = num.to_i64!

          when "TITLE"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize >= MIN_TITLE_LEN && line.bytesize <= MAX_TITLE_LEN
                ret.title = line
              else
                raise Error.new("TITLE field must be between #{MIN_TITLE_LEN} and " \
                                "#{MAX_TITLE_LEN} bytes, inclusive")
              end
            else
              raise ParseError.new("TITLE line is blank", parser)
            end

          when "PERFORMER"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize >= MIN_PERFORMER_LEN && line.bytesize <= MAX_PERFORMER_LEN
                ret.performer = line
              else
                raise Error.new("PERFORMER field must be between #{MIN_PERFORMER_LEN} and " \
                                "#{MAX_PERFORMER_LEN} bytes, inclusive")
              end
            else
              raise ParseError.new("PERFORMER line is blank", parser)
            end

          when "SONGWRITER"
            line = parser.readRemainingLine
            if line
              line = line.strip
              if line.bytesize >= MIN_SONGWRITER_LEN && line.bytesize <= MAX_SONGWRITER_LEN
                ret.songwriter = line
              else
                raise Error.new("SONGWRITER field must be between #{MIN_SONGWRITER_LEN} and " \
                                "#{MAX_SONGWRITER_LEN} bytes, inclusive")
              end
            else
              raise ParseError.new("SONGWRITER line is blank", parser)
            end

          else
            if parser.strict?
              raise ParseError.new("Unknown CUE sheet command in TRACK section: #{token}", parser)
            else
              parser.skipToEof
            end
          end
        end

        {ret, NextState::Normal}
      end

      # Gets the `Timestamp` for the `INDEX` *num*.
      #
      # If *num* is not within 0 and 99 (inclusive), this will raise an
      # `::ArgumentError`.  If the index has not been set yet, this will raise a
      # `KeyError`.
      def index(num : Int) : Timestamp
        if num < 0 || num > 99
          raise ::ArgumentError.new("Invalid number value for an INDEX (must be between 0 and 99, inclusive)")
        end
        @indices[num.to_u32!]
      end

      # Gets the `Timestamp` for the `INDEX` *num*.
      #
      # If *num* is not within 0 and 99 (inclusive), this will raise an
      # `::ArgumentError`.  If the index has not been set yet, this returns
      # `nil`.
      def index?(num : Int) : Timestamp?
        if num < 0 || num > 99
          raise ::ArgumentError.new("Invalid number value for an INDEX (must be between 0 and 99, inclusive)")
        end
        @indices[num.to_u32!]?
      end

      # Sets the `Timestamp` for the `INDEX` *num*.  Any existing `Timestamp`
      # for that index will be overwritten.
      #
      # If *num* is not within 0 and 99 (inclusive), this will raise an
      # `::ArgumentError`.
      def setIndex(num : Int, ts : Timestamp) : self
        if num < 0 || num > 99
          raise ::ArgumentError.new("Invalid number value for an INDEX (must be between 0 and 99, inclusive)")
        end
        @indices[num.to_u32!] = ts
        self
      end

      def trackNumber=(value : Int) : Nil
        if value == 0 || value > 99
          raise ::ArgumentError.new("Invalid track number, must be between 1 and 99, inclusive")
        end
        @trackNumber = value.to_u32!
      end

      # Sets the
      # [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)
      # value.  The value must be exactly `ISRC_LEN` _bytes_ long.
      def isrc=(value : String?) : Nil
        if value && value.bytesize != ISRC_LEN
          raise Error.new("ISRC field must be exactly #{ISRC_LEN} bytes")
        end
        @isrc = value
      end

      # Sets the name of the title for this track.  The value must be
      # between `MIN_TITLE_LEN` and `MAX_TITLE_LEN` _bytes_ long.
      def title=(value : String?) : Nil
        if value
          bsize : Int32 = value.bytesize
          if bsize < 1 || bsize > 80
            raise Error.new("TITLE field must be between #{MIN_TITLE_LEN} and " \
                            "#{MAX_TITLE_LEN} bytes, inclusive")
          end
        end
        @title = value
      end

      # Sets the name of the performer for this track.  The value must be
      # between `MIN_PERFORMER_LEN` and `MAX_PERFORMER_LEN` _bytes_ long.
      def performer=(value : String?) : Nil
        if value
          bsize : Int32 = value.bytesize
          if bsize < 1 || bsize > 80
            raise Error.new("PERFORMER field must be between #{MIN_PERFORMER_LEN} and " \
                            "#{MAX_PERFORMER_LEN} bytes, inclusive")
          end
        end
        @performer = value
      end

      # Sets the name of the songwriter for this track.  The value must be
      # between `MIN_SONGWRITER_LEN` and `MAX_SONGWRITER_LEN` _bytes_ long.
      def songwriter=(value : String?) : Nil
        if value
          bsize : Int32 = value.bytesize
          if bsize < 1 || bsize > 80
            raise Error.new("SONGWRITER field must be between #{MIN_SONGWRITER_LEN} and " \
                            "#{MAX_SONGWRITER_LEN} bytes, inclusive")
          end
        end
        @songwriter = value
      end

      def to_s(io : IO) : Nil
        io << sprintf("TRACK %02d %s", @trackNumber, @type)
      end

      # Similar to `#to_s`, except this is properly indented for a CUE sheet and
      # includes all relevant lines.
      def write(io : IO) : Nil
        io << "  " << self << '\n'
        unless flags.none?
          Flags.values.each do |flg|
            if flags.includes?(flg)
              io << "    FLAGS " << flg << '\n'
            end
          end
        end

        if str = @isrc
          io << "    ISRC " << str << '\n'
        end

        if str = @title
          io << "    TITLE \"" << str << "\"\n"
        end

        if str = @performer
          io << "    PERFORMER \"" << str << "\"\n"
        end

        if str = @songwriter
          io << "    SONGWRITER \"" << str << "\"\n"
        end

        if gap = @pregap
          io << "    PREGAP " << gap << '\n'
        end

        if gap = @postgap
          io << "    PREGAP " << gap << '\n'
        end

        @indices.each do |key, val|
          io << sprintf("    INDEX %02d ", key) << val << '\n'
        end
      end
    end

    #===========================================================================

    # A virtual representation of the data for a `FILE` command within a CUE
    # sheet.  Note that in a CUE sheet, a single file can be used for multiple
    # tracks.
    class File
      # The type of this file.
      enum Type
        # Raw little-endian data.
        Binary

        # Raw big-endian data.
        Motorola

        # 16-bit 44.1 KHz AIFF PCM data.
        Aiff

        # 16-bit 44.1 KHz WAVE PCM data.
        Wave

        # 16-bit stereo 44.1 KHz MP3 data.
        Mp3

        # 16-bit stereo 44.1 KHz FLAC data.
        Flac

        # Similar to `::Enum.parse?`, except that this expects the strings to
        # match those in a CUE file (e.g. `"BINARY"`, `"MOTOROLA"`, etc.), and
        # is case insensitive.
        def self.parse?(string : String) : self?
          case string.upcase
          when "BINARY" then Type::Binary
          when "MOTOROLA" then Type::Binary
          when "AIFF" then Type::Binary
          when "WAVE" then Type::Binary
          when "MP3" then Type::Binary
          when "FLAC" then Type::Binary
          else nil
          end
        end

        # Similar to `::Enum#to_s`, except that the returned values are usable in
        # a CUE file.
        def to_s : String
          case self
          in .binary? then "BINARY"
          in .motorola? then "MOTOROLA"
          in .aiff? then "AIFF"
          in .wave? then "WAVE"
          in .mp3? then "MP3"
          in .flac? then "FLAC"
          end
        end

        # Similar to `::Enum.names`, except that the returned values match those
        # generated with `#to_s`.
        def self.names : Array(String)
          [
            "BINARY",
            "MOTOROLA",
            "AIFF",
            "WAVE",
            "MP3",
            "FLAC"
          ]
        end
      end

      # The associated filename.
      property filename : String = ""

      # The type of file.
      property type : Type = Type::Wave

      # The tracks that this file is used for to define.
      property tracks : Array(Track) = [] of Track

      # Creates a new `RemiAudio::Cue::File` instance.
      def initialize
      end

      # :nodoc:
      def self.parse(parser : Parser) : Tuple(RemiAudio::Cue::File, NextState)
        ret : RemiAudio::Cue::File = RemiAudio::Cue::File.new
        nxtState : NextState = NextState::Normal
        token : String? = nil
        lastTrackNum : Int64 = 0

        fileLine : String? = parser.readRemainingLine || raise ParseError.new("Incomplete FILE line", parser)
        args = parser.splitArgs(fileLine)
        unless args.size == 2
          raise ParseError.new("Bad FILE command, found #{args.size} arg#{args.size == 1 ? "" : "s"}, expected 2", parser)
        end

        ret.filename = args[0]
        ret.type = Type.parse?(args[1]) || raise ParseError.new("Invalid type for FILE command", parser)

        loop do
          token = case nxtState
                  in .normal? then parser.readToken
                  in .file? then "FILE"
                  in .track? then "TRACK"
                  in .catalog?, .cd_text_file? then return {ret, nxtState}
                  end
          break if token.nil?
          nxtState = NextState::Normal

          case token
          when "REM" then parser.skipToEof
          when "FILE" then return {ret, NextState::File}
          when "CATALOG" then return {ret, NextState::Catalog}
          when "CDTEXTFILE" then return {ret, NextState::CdTextFile}

          when "TRACK"
            newTrack, nxtState = Track.parse(parser)
            ret.tracks << newTrack
            lastTrackNum = newTrack.trackNumber.to_i64!
            parser.foundTrack = true

          else
            if parser.strict?
              raise ParseError.new("Unknown CUE sheet command in FILE section: #{token}", parser)
            else
              parser.skipToEof
            end
          end
        end

        {ret, NextState::Normal}
      end

      def to_s(io : IO) : Nil
        io << "FILE \"" << @filename << "\" " << @type
      end

      # Similar to `#to_s`, except this is properly indented for a CUE sheet and
      # includes all relevant lines.
      def write(io : IO) : Nil
        io << self << '\n'
        @tracks.each(&.write(io))
      end

      # Creates a new `Track` and yields it to the block.  When the block exits,
      # the new track is added to this `RemiAudio::Cue::File`.  The new track is returned.
      def addTrack(&) : Track
        trk = Track.new
        yield trk
        @tracks << trk
        trk
      end
    end

    #===========================================================================

    # The "Media Catalog Number" for this CUE sheet.  This is generally a UPC or
    # EAN code.
    getter catalog : String?

    # The path to an external file that contains CD-TEXT information for this
    # CUE sheet.
    property cdTextFile : String?

    # The title of this CUE sheet.
    getter title : String?

    # The performer of this CUE sheet.
    getter performer : String?

    # The songwriter of this CUE sheet.
    getter songwriter : String?

    # The `RemiAudio::Cue::File`s for this CUE sheet.
    property files : Array(RemiAudio::Cue::File) = [] of RemiAudio::Cue::File

    # The expected length of the CATALOG field, in bytes.
    CATALOG_LEN = 13

    # The maximum length of the TITLE field, in bytes.
    MAX_TITLE_LEN = 80

    # The minimum length of the TITLE field, in bytes.
    MIN_TITLE_LEN = 1

    # The maximum length of the PERFORMER field, in bytes.
    MAX_PERFORMER_LEN = 80

    # The minimum length of the PERFORMER field, in bytes.
    MIN_PERFORMER_LEN = 1

    # The maximum length of the SONGWRITER field, in bytes.
    MAX_SONGWRITER_LEN = 80

    # The minimum length of the SONGWRITER field, in bytes.
    MIN_SONGWRITER_LEN = 1

    # Creates a new, blank `Cue` instance.
    def initialize
    end

    # Creates a new `Cue` instance by parsing data from *io*.  If *strict* is
    # `true`, then certain restrictions are in place for the following cases:
    #
    # * Unrecognized commands in the `FILE` section will not be accepted.
    # * Unrecognized commands in the `TRACK` section will not be accepted.
    # * Unrecognized `FLAGS` on a FLAG line within a `TRACK` will not be accepted.
    #
    # When *strict* is `false`, then these cases are silently ignored.
    def self.parse(io : IO, *, strict : Bool = false) : Cue
      ret = Cue.new
      parser = Parser.new(io)
      token : String? = nil
      nxtState : NextState = NextState::Normal

      parser.strict = strict
      loop do
        token = case nxtState
                in .normal? then parser.readToken
                in .file? then "FILE"
                in .track? then "TRACK"
                in .catalog? then "CATALOG"
                in .cd_text_file?  then "CDTEXTFILE"
                end
        break if token.nil?
        nxtState = NextState::Normal

        case token
        when "REM" then parser.skipToEof

        when "FILE"
          # Parse new FILE command
          newFile, nxtState = RemiAudio::Cue::File.parse(parser)
          ret.files << newFile

        when "CATALOG"
          token = parser.readToken
          if token
            unless token.size == CATALOG_LEN
              raise ParseError.new("CATALOG field must be exactly #{CATALOG_LEN} bytes", parser)
            end

            unless token.chars.all?(&.ascii_number?)
              raise ParseError.new("CATALOG field must be all numbers", parser)
            end

            if ret.catalog.nil?
              ret.catalog = token
            else
              raise ParseError.new("CATALOG field can only appear once", parser)
            end
          else
            raise ParseError.new("CATALOG field is blank", parser)
          end

        when "TITLE"
          token = parser.readRemainingLine
          if token
            token = token.strip
            if token.bytesize >= MIN_TITLE_LEN && token.bytesize <= MAX_TITLE_LEN

              ret.title = token
            else
              raise Error.new("TITLE field must be between #{MIN_TITLE_LEN} and " \
                              "#{MAX_TITLE_LEN} bytes, inclusive")
            end
          else
            raise ParseError.new("TITLE line is blank", parser)
          end

        when "PERFORMER"
          token = parser.readRemainingLine
          if token
            token = token.strip
            if token.bytesize >= MIN_PERFORMER_LEN && token.bytesize <= MAX_PERFORMER_LEN

              ret.performer = token
            else
              raise Error.new("PERFORMER field must be between #{MIN_PERFORMER_LEN} and " \
                              "#{MAX_PERFORMER_LEN} bytes, inclusive")
            end
          else
            raise ParseError.new("PERFORMER line is blank", parser)
          end

        when "SONGWRITER"
          token = parser.readRemainingLine
          if token
            token = token.strip
            if token.bytesize >= MIN_SONGWRITER_LEN && token.bytesize <= MAX_SONGWRITER_LEN
              ret.songwriter = token
            else
              raise Error.new("SONGWRITER field must be between #{MIN_SONGWRITER_LEN} and " \
                              "#{MAX_SONGWRITER_LEN} bytes, inclusive")
            end
          else
            raise ParseError.new("SONGWRITER line is blank", parser)
          end

        when "CDTEXTFILE"
          token = parser.readRemainingLine(true) || raise ParseError.new("CDTEXTFILE line is incomplete", parser)
          ret.cdTextFile = token

        else
          raise ParseError.new("Unknown toplevel CUE sheet command: #{token}", parser)
        end
      end

      # There must be at least one track in the CUE sheet.
      unless parser.foundTrack?
        raise ParseError.new("No TRACKs found in the CUE sheet", parser)
      end

      unless ret.sortAndCheckTracks
        raise ParseError.new("Tracks are not sequential or duplicate track numbers found.", parser)
      end

      ret
    end

    # Creates a new `Cue` instance by parsing data from the given string.
    #
    # See `.parse(io : IO, *, strict : Bool = false)` for information about the
    # *strict* parameter.
    def self.parse(string : String, *, strict : Bool = false) : Cue
      io = IO::Memory.new(string, strict: strict)
      parse(io)
    end

    # Creates a new `Cue` instance by loading and parsing the specified file.
    #
    # See `.parse(io : IO, *, strict : Bool = false)` for information about the
    # *strict* parameter.
    def self.load(filename : Path|String, *, strict : Bool = false) : Cue
      ::File.open(filename, "r") { |file| parse(file, strict: strict) }
    end

    # Sets the "Media Catalog Number" for this CUE sheet.  This is generally a
    # UPC or EAN code.  This must be exactly `CATALOG_LEN` _bytes_ in length.
    def catalog=(value : String) : Nil
      unless value.bytesize == CATALOG_LEN
        raise Error.new("CATALOG field must be exactly #{CATALOG_LEN} bytes")
      end
      @catalog = value
    end

    # Sets the name of the title for this track.  The value must be between
    # `MIN_TITLE_LEN` and `MAX_TITLE_LEN` _bytes_ long.
    def title=(value : String?) : Nil
      if value
        bsize : Int32 = value.bytesize
        if bsize < 1 || bsize > 80
          raise Error.new("TITLE field must be between 1 and 80 bytes, inclusive")
        end
      end
      @title = value
    end

    # Sets the name of the performer for this track.  The value must be between
    # `MIN_PERFORMER_LEN` and `MAX_PERFORMER_LEN` _bytes_ long.
    def performer=(value : String?) : Nil
      if value
        bsize : Int32 = value.bytesize
        if bsize < 1 || bsize > 80
          raise Error.new("PERFORMER field must be between 1 and 80 bytes, inclusive")
        end
      end
      @performer = value
    end

    # Sets the name of the songwriter for this track.  The value must be between
    # `MIN_SONGWRITER_LEN` and `MAX_SONGWRITER_LEN` _bytes_ long.
    def songwriter=(value : String?) : Nil
      if value
        bsize : Int32 = value.bytesize
        if bsize < 1 || bsize > 80
          raise Error.new("SONGWRITER field must be between 1 and 80 bytes, inclusive")
        end
      end
      @songwriter = value
    end

    # Writes this CUE sheet to *io*.  This will automatically call
    # `sortAndCheckTracks` before writing any data.
    def write(io : IO) : Nil
      raise Error.new("CUE sheet has no files") if @files.empty?
      unless sortAndCheckTracks
        raise Error.new("Tracks are not sequential or duplicate track numbers found.")
      end

      if str = @catalog
        io << "CATALOG #{str}\n"
      end

      if str = @title
        io << "TITLE \"" << str << "\"\n"
      end

      if str = @performer
        io << "PERFORMER \"" << str << "\"\n"
      end

      if str = @songwriter
        io << "SONGWRITER \"" << str << "\"\n"
      end

      @files.each(&.write(io))
    end

    # Writes this CUE sheet to a string and returns it.  This will automatically
    # call `sortAndCheckTracks` before writing any data.
    def write : String
      String.build { |str| write(str) }
    end

    # Sorts all `RemiAudio::Cue::File#tracks` in all `#files`, then attempts to
    # sort `#files` according to their tracks, then ensures that that all of the
    # tracks are in sequential order.  If the tracks are not sequential after
    # sorting, or there are duplicates, this returns `false`.  Otherwise it
    # returns `true`.
    def sortAndCheckTracks : Bool
      # Sort all tracks in all @files.  We do this separately so that
      # @files.sort! doesn't continuously try to re-sort already sorted arrays
      # of tracks.
      @files.each do |file|
        file.tracks.sort! { |trk1, trk2| trk1.trackNumber <=> trk2.trackNumber }
      end

      # Sort @files according to the tracks for each file.
      @files.sort! do |file1, file2|
        max1 = file1.tracks.max_by(&.trackNumber).trackNumber
        max2 = file2.tracks.max_by(&.trackNumber).trackNumber
        max1 <=> max2
      end

      # Check that all tracks are sequential.
      lastIndex : UInt32 = @files[0].tracks[0].trackNumber - 1
      @files.each do |file|
        file.tracks.each do |trk|
          return false if trk.trackNumber != lastIndex + 1
          lastIndex = trk.trackNumber
        end
      end
      true
    end

    # Creates a new `RemiAudio::Cue::File` and yields it to the block.  When the
    # block exits, the new file is added to this `Cue`.  The new file is
    # returned.
    def addFile(&) : File
      file = File.new
      yield file
      @files << file
      file
      end
  end
end
