#include "fmt_defs.h"
#include <stdint.h>

/* ip must be int32_t aligned */
unsigned int fmt_utmp_ip(char *buf, const char ip[16]) /*EXTRACT_INCL*/{
  unsigned int temp, k, pos0=0, len0=0, pos1=0, compr=0;
  int32_t *u = (void *)ip;
  char *s = buf;

  if (u[1]==0 && u[2]==0 && u[3]==0) {
    if (u[0]) {
      for (k=0; k<4; k++) {
	s += fmt_ulong(s, (unsigned char)ip[k]);
	if (k<3) *s++ = '.';
      }
    }
  } else {
    for (k=0; k<16; k+=2) {
      if (ip[k]==0 && ip[k+1]==0) {
	if (!compr) {
	  compr=1;
	  pos1=k;
	}
	if (k==14) { k=16; goto last; }
      } else if (compr) {
      last:
	if ((temp=k-pos1) > len0) {
	  len0=temp;
	  pos0=pos1;
	}
	compr=0;
      }
    }

    for (k=0; k<16; k+=2) {
      if (pos0==k && len0) {
	if (k==0) *s++ = ':';
	*s++ = ':';
	k += len0-2;
	continue;
      }
      temp = ((unsigned long) (unsigned char) ip[k] << 8) +
	(unsigned long) (unsigned char) ip[k+1];
      s += fmt_xlong(s, temp);
      if (k<14) *s++ = ':';
    }
  }
  *s = 0;
  return s-buf;
}
