/*ProfiPacket - packet radio terminal program
  Copyright (C) 1999  Alexander Feigl

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

  Author:

  Alexander Feigl
  Burachstraße 51

  D-88250 Weingarten

  Mail : Alexander.Feigl@gmx.de
*/


#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "QSO.h"
#include "global.h"

/* QSO_FindMatchChannel : search a free channel which matches a given
   hardware unit - the highest channel of the callset with the most
   free channels is used - this function can be used for gateway connect
   servers or similar to get a free channel */
   
unsigned int QSO_FindMatchChannel(unsigned int hardunit)
 {
  unsigned long i;
  unsigned long CallsetFree[8];
  unsigned long CallsetChannel[8];
  struct QSO *qso;
  unsigned long maxfree,maxfreechan;
  
  /* count free channels of a hardware unit for each callset and remember
     the last channel of this callset */
  
  
  for (i=0;i<8;++i)
   {
    CallsetFree[i]=0;
    CallsetChannel[i]=0;
   }
  qso=QSOs;  
  for (i=1;i<=MaxChannel;++i,++qso)
   {
    if (qso->SkipChannel) continue;
    if (qso->LinkStatus) continue;
    if (qso->Server!=NULL) continue;
    if (qso->SelfConnect) continue;
    if (qso->HardwareUnit!=hardunit) continue;
    ++CallsetFree[qso->CallSet];
    CallsetChannel[qso->CallSet]=i; 
   }

  
  /* chose the callset with the most free channels */
  maxfree=0;
  maxfreechan=0;
  for (i=0;i<8;++i)
   {
    if (CallsetFree[i]>=maxfree)
     {
      maxfree=CallsetFree[i];
      maxfreechan=CallsetChannel[i];
     }
   } 
    
  return(maxfreechan);
 }
 

/* QSO_FindFreeChannel : search a free channel which matches a given callset
   and a given hardware unit - the first matching channel is taken */ 
 
unsigned int QSO_FindFreeChannel(unsigned int hardunit,unsigned int callset)
 {
  unsigned long i;
  struct QSO *qso;
  
  qso=QSOs;
  for (i=1;i<=MaxChannel;++i,++qso)
   {
    if (qso->SkipChannel) continue;
    if (qso->LinkStatus) continue;
    if (qso->Server) continue;
    if (qso->SelfConnect) continue;
    if (qso->HardwareUnit!=hardunit) continue;
    if (qso->CallSet!=callset) continue;
    return(i);
   } 
  return(0);
 }

