/*
 * expunge() makes a new copy of the messages file, without any messages
 *    that are flagged as deleted.
 */

void expunge( FILE *old, FILE *temp )
{
  int deleted = 0 ;
  hdr_entry **prev, *header ;
  char inputline[MAXLINELENGTH] ;

  rewind( old ) ;

  prev = &headers ;
      
  /* Loop through all messages */
  while( *prev != NULL )
    {
      header = *prev ;

      event_loop() ;

      if( header->flags.deleted )
	{
	  /* Skip message */
	  do
	    {
	      /* Read a line of message */
	      fgets( inputline, MAXLINELENGTH, old ) ;

	      /* Count deleted characters */
	      deleted += strlen( inputline ) ;
	    }
	  /* Until we get . on it's own */
	  while( strcmp( inputline, ".\n" ) ) ;
	  
	  /* Unlink header */
	  *prev = header->next ;
	  free( header->message_id ) ;
	  free( header->in_reply_to ) ;
	  free( header ) ;
	}
      else
	{
	  /* Copy to temporary file */
	  do
	    {
	      /* Read a line of message */
	      fgets( inputline, MAXLINELENGTH, old ) ;

	      /* Write it to temporary file */
	      fputs( inputline, temp ) ;
	    }
	  while( strcmp( inputline, ".\n" ) ) ;

	  /* Change offset */
	  header->offset -= deleted ;
	}
      prev = &(header->next) ;
    }
}
