001package jmri.jmrix.loconet.sdf;
002
003import java.util.ArrayList;
004
005/**
006 * Implement the CHANNEL_START macro from the Digitrax sound definition language
007 *
008 * @author Bob Jacobsen Copyright (C) 2007
009 */
010public class ChannelStart extends SdfMacro {
011
012    public ChannelStart(int number) {
013        this.number = number;
014    }
015
016    @Override
017    public String name() {
018        return "CHANNEL_START"; // NOI18N
019    }
020
021    int number;
022
023    @Override
024    public int length() {
025        return 2;
026    }
027
028    static public SdfMacro match(SdfBuffer buff) {
029        if ((buff.getAtIndex() & 0xFF) != 0x81) {
030            return null;
031        }
032        buff.getAtIndexAndInc(); // drop opcode
033        ChannelStart result = new ChannelStart(buff.getAtIndexAndInc());
034
035        // gather leaves underneath
036        SdfMacro next;
037        while (buff.moreData()) {
038            // look ahead at next instruction
039            int peek = buff.getAtIndex() & 0xFF;
040
041            // if SKEME_START or CHANNEL_START, done
042            if (peek == 0xF1
043                    || peek == 0x81) {
044                break;
045            }
046
047            // next is leaf, keep it
048            next = decodeInstruction(buff);
049            if (result.children == null) {
050                result.children = new ArrayList<SdfMacro>(); // make sure it's initialized
051            }
052            result.children.add(next);
053        }
054        return result;
055    }
056
057    /**
058     * Store into a buffer.
059     */
060    @Override
061    public void loadByteArray(SdfBuffer buffer) {
062        // data
063        buffer.setAtIndexAndInc(0x81);
064        buffer.setAtIndexAndInc(number);
065
066        // store children
067        super.loadByteArray(buffer);
068    }
069
070    @Override
071    public String toString() {
072        return "Channel " + number + '\n'; // NOI18N
073    }
074
075    @Override
076    public String oneInstructionString() {
077        return name() + ' ' + number + '\n'; // NOI18N
078    }
079
080    @Override
081    public String allInstructionString(String indent) {
082        StringBuilder output = new StringBuilder(indent);
083        output.append(oneInstructionString());
084        if (children == null) {
085            return output.toString();
086        }
087        for (int i = 0; i < children.size(); i++) {
088            output.append(children.get(i).allInstructionString(indent + "  "));
089        }
090        return output.toString();
091    }
092}