/*
 *  CREATEITEXT.C
 */

#include "newlook.h"

struct TextAttr Topaz80= {
  (STRPTR) "topaz.font",  /* ta_Name  */
  8,                      /* ta_YSize */
  FS_NORMAL,              /* ta_Style */
  FPF_ROMFONT,            /* ta_Flags */
};

/*
   strgen(s,t,u) copies all non-underscore characters in `s' to `t' and
   the underscore characters (if any) to `u'.  A space character will be
   written to `u' for each non-underscore character in `s'.
   The #of space characters before the first underscore in `u' will be
   returned.
*/

static int strgen(s,t,u)
register char *s,*t,*u;
{
  register char *v=u;
  register int n=0;

  do
  { if(*s!='_')
    { *t++= *s;
      n++;
    }
    else /* *s=='_' */
    { for(;n>0;--n,*u++=' ');
      *u++= *s;
      n= -1;
    }
  } while(*s++);
  *u= '\0';

  for(u=v; *u==' '; u++);
  return (int)(u-v);
}


struct IntuiText *CreateIText(x,y,text)
SHORT x,y;
STRPTR text;
{
  struct IntuiText *it;
  ULONG UserHandle= SetNewLookHandle(PRIVATE_HANDLE);

  if(it= (struct IntuiText *)SmartAllocate(ITEXTSIZE))
  {
    it->FrontPen   = 1;
    it->BackPen    = 0;
    it->DrawMode   = JAM1;
    it->LeftEdge   = x;
    it->TopEdge    = y;
    it->ITextFont  = &Topaz80;
    it->IText      = (UBYTE *)text;
    it->NextText   = (struct IntuiText *)NULL;

    if(text && strchr(text,'_'))
    {
      struct IntuiText *iu;
      STRPTR t,u;  /* text, underscores */
      int n= strlen(text) + 1;  /* plus null-terminal */

      if(t= (STRPTR)SmartAllocate(n*sizeof(char)))
      {
        if(u= (STRPTR)SmartAllocate(n*sizeof(char)))
        {
          if(iu= (struct IntuiText *)SmartAllocate(ITEXTSIZE))
          {
            n= strgen(text,t,u);

            it->IText= (UBYTE *)t;
            iu->IText= (UBYTE *)&u[n];

            iu->FrontPen   = 1;
            iu->BackPen    = 0;
            iu->DrawMode   = JAM1;
            iu->LeftEdge   = x + 8*n;
            iu->TopEdge    = y + 1;
            iu->ITextFont  = &Topaz80;
            iu->NextText   = it;

            MakePrivateHandlePublic(UserHandle);
            return iu;
            /* --- exit point for text w/ underscores --- */
          }
        }
      }
      if(UserHandle != PRIVATE_HANDLE)
      { SmartFreeAll(PRIVATE_HANDLE);
        (void)SetNewLookHandle(UserHandle);
      }
    }
    else /* no text or no underscores in it */
    { MakePrivateHandlePublic(UserHandle);
      return it;
      /* --- exit point for text w/o underscores --- */
    }
  }
  return (struct IntuiText *)NULL;
}


#ifdef TEST
#include <stdio.h>

main(int argc, char **argv)
{
  char t[80],u[80];
  int n;

  while(--argc>0)
  { n= strgen(*++argv,t,u);
    printf("strgen(\"%s\",\"%s\",\"%s\") = %d\n",*argv,t,u,n);
  }
}
#endif /* TEST */
