// Generated by IcedCoffeeScript 1.7.1-b
(function() {
  var C, frame_len, pack, unpack;

  pack = require('./pack').pack;

  unpack = require('./unpack').unpack;

  C = require('./const').C;

  exports.pack = function(x, opts) {
    var b1, b2;
    if (opts == null) {
      opts = {};
    }
    b2 = pack(x, opts);
    b1 = pack(b2.length);
    return Buffer.concat([b1, b2]);
  };

  exports.frame_len = frame_len = function(c) {
    if (c <= C.positive_fix_max) {
      return 1;
    } else if (c === C.uint8) {
      return 2;
    } else if (c === C.uint16) {
      return 3;
    } else if (c === C.uint32) {
      return 5;
    } else {
      return 0;
    }
  };

  exports.unpack = function(x, opts) {
    var buf, c, flen, plen, rem, ret;
    if (opts == null) {
      opts = {};
    }
    if (x.length < 1) {
      throw new Error("need a buffer > 1 bytes");
    }
    c = x.readUInt8(0);
    flen = frame_len(c);
    if (flen === 0) {
      throw new Error("no data frame found");
    }
    if (x.length < flen) {
      throw new Error("not enough bytes to read frame: " + x.length + " < " + flen);
    }
    buf = x.slice(0, flen);
    plen = unpack(buf);
    x = x.slice(flen);
    if (x.length < plen) {
      throw new Error("not enough bytes to unframe: " + x.length + " < " + plen);
    }
    rem = x.slice(plen);
    x = x.slice(0, plen);
    ret = unpack(x);
    return [ret, rem];
  };

}).call(this);
