re-writing to fix several problems with variable length and so on